content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/env python
'''Tools for modifying halo data output files.
@author: Zach Hafen
@contact: zachary.h.hafen@gmail.com
@status: Development
'''
import copy
import glob
import numpy as np
import os
import pandas as pd
import galaxy_dive.galaxy_linker.linker as galaxy_linker
import galaxy_dive.analyze_data.halo_... | nilq/baby-python | python |
import typing
from django.core.paginator import Paginator
class Pagination:
result_list: typing.Iterable
can_show_all: bool
show_all: bool
multi_page: bool
paginator: Paginator
page_num: int
list_per_page = 20
list_max_show_all = 2000
def __init__(self, object_list: typing.Iterab... | nilq/baby-python | python |
import spotipy
from spotipy import util
from spotipy.oauth2 import SpotifyClientCredentials
import os
from dotenv import load_dotenv
from pprint import pprint
# load_dotenv()
#
# os.environ['SPOTIPY_CLIENT_ID'] = os.getenv('client_id')
# os.environ['SPOTIPY_CLIENT_SECRET'] = os.getenv('client_secret')
client_id = '... | nilq/baby-python | python |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/odd-even-level-difference/1
def getLevelDiff(root):
h = {0: 0, 1: 0}
level = 0
populateDiff(root, level, h)
return h[0]-h[1]
def populateDiff(root, level, h):
if root == None:
return
l = level%2
h[l] += root.... | nilq/baby-python | python |
############################################################################
# #
# Copyright (c) 2019 Carl Drougge #
# #
# Licensed u... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request
import re
import os
import sqlite3
from bs4 import BeautifulSoup
from datetime import datetime
from loc_code import LOC_CODE
def jp_sqlite3_init(conn, cursor):
cursor.execute('''CREATE TABLE IF NOT EXISTS realestate (district text, dong text, a... | nilq/baby-python | python |
#
# This is a dummy class to illustrate the use of cvui in a project
# that contains multiple files.
#
# Copyright (c) 2018 Fernando Bevilacqua <dovyski@gmail.com>
# Licensed under the MIT license.
#
import cvui
class Class1:
def __init__(self):
self.checked = [False]
def renderInfo(self, frame):
cvui.window(f... | nilq/baby-python | python |
# from subtlepatterns.com
bg = """\
iVBORw0KGgoAAAANSUhEUgAAABIAAAANCAMAAACTkM4rAAAAM1BMVEXy8vLz8/P5+fn19fXt7e329vb4+Pj09PTv7+/u7u739/fw8PD7+/vx8fHr6+v6+vrs7Oz2LjW2AAAAkUlEQVR42g3KyXHAQAwDQYAQj12ItvOP1qqZZwMMPVnd06XToQvz4L2HDQ2iRgkvA7yPPB+JD+OUPnfzZ0JNZh6kkQus5NUmR7g4Jpxv5XN6nYWNmtlq9o3zuK6w3XRsE1pQIEGPIsdtTP3m2cYwlPv6... | nilq/baby-python | python |
#!/usr/bin/env python
# PNG2PDF - Graphic interface related class and methods.
from gi.repository import Gtk, Gio
from gi.repository.GdkPixbuf import Pixbuf, InterpType
from wand.image import Image
from wand.exceptions import BlobError
class GuiWindow(Gtk.Window):
"""
PNG2PDF main window class, derivates fro... | nilq/baby-python | python |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
METRIC_MAP = {
'consul_client_rpc': 'client.rpc',
'consul_client_rpc_failed': 'client.rpc.failed',
'consul_memberlist_degraded': 'memberlist.degraded',
'consul_memberlist_gossip': 'memberli... | nilq/baby-python | python |
import os as os
import numpy as np
import pandas as pd
import re
import botutils
zx=pd.read_csv('./recipies_full_v2.csv',index_col=0)
def Recuperador(ingredientes,df=zx,Criterio='Ingredientes'):
len_ing=[]
match=[]
qw=0
for i in range(len(df)):
len_ing.append(len(df.Ingredientes.iloc[i].split(... | nilq/baby-python | python |
from flask import render_template, session, flash, request, redirect
import tags
import awstools
import contestmode
import language
from datetime import datetime, timedelta
def home():
if contestmode.contest():
return redirect(f'/contest/{contestmode.contestId()}')
userinfo = awstools.getCurrentUserIn... | nilq/baby-python | python |
import socket
import sys
import traceback
import random
def upper_monitor():
examples = ["Normal#ru-RU#Здраствуйте, меня зовут Жулдз, я робот гид", "Happy#ru-RU#Я так рада что вы тут",
"Sad#ru-RU#Простите, я вас не поняла, можете, пожалуйста, перефразировать",
"Angry#ru-RU#Алё, тупо... | nilq/baby-python | python |
"""
https://tinkerpop.apache.org/docs/current/reference/
"""
from typing import Hashable, Generator, Iterable
import time
import pandas as pd
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __, GraphTraversalSource
from gremlin_python.driver.driver_remote_connection... | nilq/baby-python | python |
import time
from django.db import connections
from django.db.utils import OperationalError
from django.core.management import BaseCommand
class Command(BaseCommand):
"""Djanho commandf to pause executuoin until datbase is availane"""
def handle(self, *args, **options):
self.stdout.write('Waiting for... | nilq/baby-python | python |
import csv
import requests
def getArray():
# To use a local file, comment out this part, and uncomment the next part
r = requests.get('https://github.com/HeardLibrary/digital-scholarship/raw/master/code/pylesson/challenge4/cartoons.csv')
fileText = r.text.split('\n')
if fileText[len(fileText)-1] == '':... | nilq/baby-python | python |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import logging
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip(... | nilq/baby-python | python |
import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path... | nilq/baby-python | python |
# library to do some animations
# assumes you want to do a x/y plot and an energy plot
# empty placeholders for different plots
def plot_animations(fig, ax, t, E, r):
nFrames = len(t) #number frames in our animation
n_part = r.shape[0] #number particles
# initialize our plots with empty data
trajs =... | nilq/baby-python | python |
import os
import pathlib
import enum
import warnings
import colorama
import requests
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
import invoke
class MoleculeDriver(enum.Enum):
docker = 1
lxd = 2
vagrant = 3
class TestPlatform(enum.Enum):
linux... | nilq/baby-python | python |
# Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.FileHandler.FileReader import FileReader
from typing import Optional
class WorkspaceReader(FileReader):
def __init__(self) -> None:
super().__init__()
self._workspace_name = None # type: Op... | nilq/baby-python | python |
import jetson.inference
import jetson.utils
import time
import cv2
import numpy as np
timeStamp=time.time()
fpsFilt=0
#Importing custom dataset and using ssd-mobilenet-v2 model
net=jetson.inference.detectNet('ssd-mobibilenet-v2',['--model=models/YOUR MODEL/ssd-mobilenet.onnx','--input-blob=input_0','--output-cvg=scores... | nilq/baby-python | python |
import os
from flask import Flask, jsonify
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
app = Flask(__name__)
if 'APP_CONFIG_FILE' in os.environ:
app.config.from_envvar('APP_CONFIG_FILE')
else:
app.config.from_pyfile('config/production.py')
db = ... | nilq/baby-python | python |
import os
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', hours=2)
def main():
print('[!] Starting crawling.')
os.system('python -m scrapy crawl imdnews')
print('[!] Ending crawling.')
print('[!] Sending messages.')
os.sy... | nilq/baby-python | python |
# coding: utf-8
from setuptools import setup, find_packages
import os
# not so bad: http://joebergantine.com/blog/2015/jul/17/releasing-package-pypi/
version = __import__('filer_addons').__version__
def read(fname):
# read the contents of a text file
return open(os.path.join(os.path.dirname(__file__), fname... | nilq/baby-python | python |
from distutils.core import setup
setup(
name="pinax.checkers",
version="1.1",
author="Pinax",
author_email="development@eldarion.com",
url="https://github.com/pinax/pinax-checkers",
description="Style checker for Pinax and Eldarion OSS",
license="BSD",
packages=[
"pinax",
... | nilq/baby-python | python |
#!/usr/bin/python3
import copy
import random
with open('tiles.txt') as fh:
lines = fh.readlines()
tilestrs = ''.join(lines).split('\n\n')
tilestrs = {int(t.split('\n')[0][5:9]):'\n'.join(t.strip().split('\n')[1:]) for t in tilestrs}
tiles = {}
for tilekey,tilestr in tilestrs.items():
tile = []
for rowstr... | nilq/baby-python | python |
import model as mo
import view as vi
custlist=[]
page=-1
view = vi.viewer()
model = mo.model()
while True:
choice = view.hello()
if choice=="I":
custlist, page = model.inputI(custlist, page)
elif choice=="C":
custlist, page = view.inputC(custlist, page)
elif choice == 'P':
cust... | nilq/baby-python | python |
def add_time(start, duration, start_day=''):
days = 0
real_duration = 0
days_of_week = [
'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday',
'saturday'
]
hours_in_day = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 2... | nilq/baby-python | python |
import json
from flask import request, send_file
from flask_restplus import Namespace, Resource, marshal
from .utils import *
from polylogyx.utils import require_api_key
from polylogyx.dao import carves_dao as dao
from polylogyx.dao import nodes_dao as nodedao
from polylogyx.wrappers import parent_wrappers as parentw... | nilq/baby-python | python |
#!/usr/bin/python3
import re
with open("sar.txt") as fp:
reading = False
for l in fp:
s = l.split()
if len(s) == 0:
continue
m = re.match("[\d]{3,5}", s[0])
if (s[0] != "TOTAL") and (s[1] != "DO") and (m is None):
continue
if m is not No... | nilq/baby-python | python |
#Jackknife reduction templates for NIRC2 and OSIRIS pipelines.
#Author: Sean Terry
def jackknife():
"""
Do the Jackknife data reduction.
"""
##########
#
# NIRC2 Format
#
##########
##########
# Ks-band reduction
##########
# Nite 1
target = 'MB07192'
sci_file... | nilq/baby-python | python |
"""
This module contains helper functions for handling manipulation
of atom geometries
"""
import numpy as np
def _correct_vec(vec):
''' correct vectors in fractional coordinates
(assuming vectors minimal connection between 2 points)
'''
vec[np.where(vec >= 0.5)] -= 1.0
vec[np.where(vec < ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
from src.gui.configtool.connectionControl import ConnectionControlGroupBox
from src.gui.configtool.controlLoopConfig import ControlLoopGroupBox
from src.gui.configtool.deviceJoggingControl import DeviceJoggingControl
from src.gui.configtool.droD... | nilq/baby-python | python |
from protocols.video_protocols.UCSDProtocol import UCSDProtocol
from protocols.video_protocols.AvenueProtocol import AvenueProtocol
from protocols.video_protocols.ShanghaiTechProtocol import ShanghaiTechProtocol
from protocols.video_protocols.SubwayProtocol import SubwayProtocol
| nilq/baby-python | python |
import logging
import re
from html import unescape
from urllib.parse import quote
from dvtag.utils import create_request_session
session = create_request_session()
class DoujinVoice():
def __init__(self, rjid: str) -> None:
self.rjid = rjid
self.dl_count = 0
self.url = ""
self.w... | nilq/baby-python | python |
# vim: set tabstop=4 shiftwidth=4 expandtab
##############################################################################
# Written by: Ray Wang <rawang@novell.com>
# Date: 01/13/2008
# Description: Application wrapper for datetimepicker_dropdown.py
# be called by ../datetimepicker_dropdown_ops.py... | nilq/baby-python | python |
from malcolm.yamlutil import check_yaml_names, make_block_creator
ADAndor3_driver_block = make_block_creator(__file__, "ADAndor3_driver_block.yaml")
ADAndor3_runnable_block = make_block_creator(__file__, "ADAndor3_runnable_block.yaml")
__all__ = check_yaml_names(globals())
| nilq/baby-python | python |
import torch
import torch.nn as nn
import embeddings
from torch.autograd import Variable
import pdb
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class RNNEncoder(nn.Module):
def __init__(self, ninp, nhid, nlayers, bsz):
super(RNNEncoder, self).__... | nilq/baby-python | python |
# Generated by Django 3.0.7 on 2020-08-22 19:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('staff', '0007_auto_20200820_2133'),
]
operations = [
migrations.AlterField(
model_name='staff',
name='mname',
... | nilq/baby-python | python |
from flask_sqlalchemy import SQLAlchemy
from models import ProductArea
#This file contians the functions that compose the Product Area API
"""
The getProductAreas function, doesn't take any parameters.
the ProductArea.query.all() returns a list of all the ProductAreas in the ProductArea table
the serialize func... | nilq/baby-python | python |
# Copyright 2015 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 |
#-*-coding:utf-8-*-
# date:2020-03-28
# Author: xiang li
import numpy as np # 加载 Numpy 库
import torch # 加载 Torch 库
'''
思考这一节的用法与实际项目的使用方式结合
'''
if __name__ == "__main__":
x = torch.tensor(3.1415)
print(x.floor())# tensor 向上取整
print(x.ceil())# tensor 向下取整
print(x.trunc())# tensor 取整数部分
... | nilq/baby-python | python |
from __future__ import absolute_import
import numpy as np
from pydci import DCI
from ann_benchmarks.algorithms.base import BaseANN
class PYDCIKNN(BaseANN):
def __init__(self, dim, num_simple=10, num_composite=10):
self.name = 'PYDCIKNN(d=%d, num_simple=%d, num_composite=%d' % (
dim, num_simple... | nilq/baby-python | python |
from .commands import (
MODULES, SYSTEMS, args
)
__all__ = ["args", "MODULES", 'SYSTEMS'] | nilq/baby-python | python |
# -*- coding: utf8 -*-
from pathlib import Path
HOME = str(Path.home())
# BASE_URL = 'http://localhost'
BASE_URL_BACKEND = 'http://130.211.114.2'
BASE_API_SERVER = 'http://34.122.87.173'
PORT = 80
# PORT1 = 5000
# PORT2 = 5001
API_URL_BASE = "{}:{}".format(BASE_API_SERVER, PORT)
API_BACKEND = "{}:{}".format(BASE_UR... | nilq/baby-python | python |
from mxnet.gluon import HybridBlock
import mxnet as mx
class SigmoidCrisp(HybridBlock):
def __init__(self, smooth=1.e-2,**kwards):
super().__init__(**kwards)
self.smooth = smooth
with self.name_scope():
self.gamma = self.params.get('gamma', shape=(1,), init=mx.init.One())
... | nilq/baby-python | python |
from __future__ import unicode_literals
from django.db import models
from adventures.models import Adventure
class Picture(models.Model):
adventure = models.ForeignKey(Adventure)
img = models.ImageField(upload_to='pictures')
description = models.CharField(max_length=50)
funny_facts = models.TextField(max_length=25... | nilq/baby-python | python |
import subprocess
import os
class Pythuby:
def __init__(self, code = False, file = False):
if code:
self.code = code
self.pythuby()
if file:
self.file = file
def pythuby(self):
with open("Temp.rb", "w") as temp_rb_script:
temp_rb_script.... | nilq/baby-python | python |
import time
from typing import Optional, List
import graphene as g
from graphql.execution.base import ResolveInfo
from graphql_jwt.decorators import login_required, superuser_required
from contak import models
from contak.graphql.object_types import Contact
LOAD_DELAY = 0.5
class Query:
contact = g.Field(Contac... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""The preg front-end."""
import logging
from dfvfs.helpers import file_system_searcher
from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver import resolver as path_spec_resolver
from plaso.dfwinreg import definitions a... | nilq/baby-python | python |
from .tracker import Tracker
class Rifle:
def __init__(self , display_width , display_height , triggerHandler):
# openCV tracer
self.tracker = Tracker('orange')
# variables to scale the cursor to desired screen width and height
self.display_width = display_width
self.displa... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
* This is a script file to associate images and IMU data.
* Copyright 2018 Nanjing University of Science and Technology
* Author: Zhixing Hou <zxhou@njust.edu.cn>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with ... | nilq/baby-python | python |
# Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to each element x in the array.
# The returned array must be in sorted order.
# Expected time complexity: O(n)
# Example:
# nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5,
# Result: [3, 9, 15, 33]
# nums ... | nilq/baby-python | python |
import numpy as np
import warnings
def into_patches(image, patch_shape, patch_n):
"""
Process a 2D image into evenly spaced-out 2D patches.
Arguments:
image: image to process into patches as a 2D numpy array.
patch_size: target size of patches: (height, width).
patch_n: number... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
# Copyright 2019 Huawei Technologies Co.,Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | nilq/baby-python | python |
from typing import List
from datetime import datetime
from pydantic import BaseModel
from model.Schema.word import Word
class init_module(BaseModel):
module_name: str
publisher: str
word: List[Word]
class Module(init_module):
created_at: datetime
module_id: int
class Response_module(BaseMod... | nilq/baby-python | python |
from ...Colors import *
from ..BaseControlClass import GradientTypesEnum
from copy import copy
from json import dump, load
class StyleHintsEnum(object):
Flat = 'Flat'
Raised = 'Raised'
Sunken = 'Sunken'
Hover = 'Hover'
Image = 'Image'
# Custom = 'Custom'
class DefaultStyle(object):
def ... | nilq/baby-python | python |
lista1 = []
lista2 = []
exp = str(input('Digite a expressão: '))
for c in exp:
if c == '(':
lista1.append('(')
if c == ')':
lista2.append(')')
if len(lista1) == len(lista2):
print('Sua expressão está correta!')
else:
print('Sua expressão está errada!')
| nilq/baby-python | python |
import argparse
import logging
import sys
from . import config
from . import gerrit
from . import jenkins
from . import output
def run():
parser = argparse.ArgumentParser(
description='A command line tool for working with Ovirt CI')
parser.add_argument(
'--debug',
help="Show noisy de... | nilq/baby-python | python |
# exceptions.py -- custom exception classes for this module
class PayloadException(Exception):
'''
Something went wrong with the payload from the GitHub API.
'''
pass
class WorkerException(Exception):
'''
Something went wrong in the worker process.
'''
pass
class QueueException(Exc... | nilq/baby-python | python |
import os
from http import HTTPStatus
from pathlib import Path
from typing import Union
from restit._response import Response
from restit.internal.suffix_media_type_mapping import SUFFIX_MEDIA_TYPE_MAPPING
class StaticFileResponse(Response):
def __init__(
self, file_path: Union[str, Path],
... | nilq/baby-python | python |
#
# PySNMP MIB module SNMP-REPEATER-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-REPEATER-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:28:55 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:5... | nilq/baby-python | python |
import os
import unittest
import numpy as np
from pyfluka.utils import PhysicsQuantities as PQ
from pyfluka.plugins.PlotMaker import PlotMaker as PM
from pyfluka.utils.Plotter import PlotConfig as PC
class TestPlotMaker(unittest.TestCase):
def setUp(self):
plotConfigDict = {'type': "2D", 'quantity': "Ac... | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function
import sys
from iotbx import reflection_file_editor
if __name__ == "__main__" :
reflection_file_editor.run(sys.argv[1:])
| nilq/baby-python | python |
from unittest.mock import MagicMock, patch
import pytest
from geniust import constants
from geniust.functions import account
@pytest.mark.parametrize("genius_token", [None, "some_token"])
@pytest.mark.parametrize("spotify_token", [None, "some_token"])
def test_login_choices(update_message, context, genius_token, sp... | nilq/baby-python | python |
from insights.parsers import docker_list
from insights.tests import context_wrap
DOCKER_LIST_IMAGES = """
REPOSITORY TAG DIGEST IMAGE ID CREATED VIRTUAL SIZE
rhel6_vsftpd ... | nilq/baby-python | python |
from math import cos
from reclaimer.hek.defs.objs.tag import HekTag
class DeviTag(HekTag):
def calc_internal_data(self):
HekTag.calc_internal_data(self)
devi_attrs = self.data.tagdata.devi_attrs
devi_attrs.inv_power_acceleration_time = 0
devi_attrs.inv_power_transition... | nilq/baby-python | python |
from pepy.domain.model import ProjectName
def test_project_name_strip_spaces():
project = ProjectName(" some-project ")
assert "some-project" == project.name
def test_set_lowercase_to_project_name():
project = ProjectName("Some-Project")
assert "some-project" == project.name
| nilq/baby-python | python |
from sqlalchemy import *
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import *
from sqlalchemy.sql import text
# Hive
engine = create_engine('hive://192.168.10.12:10010/ltv')
sql = text("select * from ltv.rac_grant_credit limit 10")
sql_rst = engine.execute(sql).fetchall()
print sql_rst
| nilq/baby-python | python |
orders_num = int(input())
total = 0
for n in range(orders_num):
price_capsule = float(input())
days = int(input())
capsule_count = int(input())
price = price_capsule * days * capsule_count
total += price
print(f'The price for the coffee is: ${price:.2f}')
print(f'Total: ${total:.2f}') | nilq/baby-python | python |
""" Models for notice app """
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from messaging.tasks import send_email
from condominium.models import Company
class Feedback(models.Model):
New = 'NEW'
Resolved = 'RES'
Ignored = 'IGN'
... | nilq/baby-python | python |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import argparse
import subprocess
import os
import gzip
import feather
def load_pair_data(path):
if path.endswith('.txt.gz'):
return pd.read_csv(path, sep='\t', usecols=['pair_id', 'slope', 'slope_se'], index_col=0, dtype={'pair_id':str, 'slope... | nilq/baby-python | python |
#from nose.plugins.skip import SkipTest
from nose.tools import assert_equal, raises
from mock import Mock, patch
from unittest import TestCase
from JenkinsPluginResolver.JenkinsPluginResolver import JenkinsPluginResolver
from os.path import dirname, realpath
class Test_JekinsPluginResolver(TestCase):
@patch('Jenk... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" Helper for uploading file, takes care of chunking file, create the file schema. """
__author__ = 'Thomas Sileo (thomas@trucsdedev.com)'
import logging
import os
from concurrent import futures
import camlipy
from camlipy.rollsum import Rollsum
from camlipy.schema import Bytes, File
MAX... | nilq/baby-python | python |
# Generated by Django 2.0 on 2017-12-30 16:08
from django.conf import settings
from django.db import migrations, models
import apps.web.validators
class Migration(migrations.Migration):
dependencies = [
('web', '0001_initial'),
]
operations = [
migrations.RemoveField(
model... | nilq/baby-python | python |
"""Generate masks from sum of flurophore channels"""
import os
import pandas as pd
import micro_dl.utils.aux_utils as aux_utils
from micro_dl.utils.mp_utils import mp_create_save_mask
from skimage.filters import threshold_otsu
class MaskProcessor:
"""Generate masks from channels"""
def __init__(self,
... | nilq/baby-python | python |
# Testing
from django.test import TestCase, Client
from django.test.utils import override_settings
# APP Models
from seshdash.models import Sesh_Alert, Alert_Rule, Sesh_Site,VRM_Account, BoM_Data_Point as Data_Point, Daily_Data_Point, Sesh_User
# django Time related
from django.utils import timezone
from time import ... | nilq/baby-python | python |
# Created by Gorkem Polat at 10.02.2021
# contact: polatgorkem@gmail.com
import os
import glob
import json
import shutil
import cv2
import numpy as np
import random
import matplotlib.pyplot as plt
from tqdm import tqdm
def show_image(image):
plt.imshow(image)
plt.show()
def show_image_opencv(image):
if... | nilq/baby-python | python |
import importlib
import imp
import sys
class SettingsWrapper(object):
'''
Wrapper for loading settings files and merging them with overrides
'''
my_settings = {}
ignore = [
'__builtins__',
'__file__',
'__package__',
'__doc__',
'__name__',
]
def _in... | nilq/baby-python | python |
"""
Frame assertion setting.
"""
class Ac:
"""
Set assertion constant.
Const:
eq: Assertion is equal.
nq: Assert inequality.
at: Assertion is True.
af: Assertion is False.
als: Assert a is b.
alst: Assert a is not b.
an: Assertion is None.
an... | nilq/baby-python | python |
from pwn import *
sh = ssh(user='ctf', host='node3.buuoj.cn', port=25102, password='guest', level='debug')
sh.interactive() | nilq/baby-python | python |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.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/L... | nilq/baby-python | python |
import unittest
from elasticsearch import ElasticsearchException
from elasticbatch.exceptions import ElasticBufferFlushError
class TestElasticBufferFlushError(unittest.TestCase):
def test_str(self):
class TestCase:
def __init__(self, msg, err, verbose, expected_str):
self.m... | nilq/baby-python | python |
from domain import Material
from collections import namedtuple
from random import randint
_State = namedtuple('_State', 'player_spawn, world_map, links, players')
def initial_state(player_spawn, world_map, links):
return _State(player_spawn, world_map, links, {})
def handle_command(state, command_name, input_data... | nilq/baby-python | python |
# EXPERIMENTAL: all may be removed soon
from gym.benchmarks import scoring
from gym.benchmarks.registration import benchmark_spec, register_benchmark, registry, register_benchmark_view # imports used elsewhere
register_benchmark(
id='Atari200M',
scorer=scoring.TotalReward(),
name='Atari200M',
view_gr... | nilq/baby-python | python |
#coding: utf-8
from __future__ import division, absolute_import, print_function, unicode_literals
from kasaya.core import exceptions
import msgpack
#
# Warning, msgpack is broken and can't differentiate strings from binary data.
# Under python 3 message pack is unusable to transport data.
#
# More details and useles... | nilq/baby-python | python |
from RPIO import PWM
from sys import stdin,stdout
pin=18
PWM.setup()
PWM.init_channel(13)
PWM.add_channel_pulse(13, pin ,0,0)
while True:
userinput = stdin.readline().rstrip('\n')
if userinput == 'quit':
break
else:
stdout.write("LightValue: " + userinput)
PWM.clear_channel_gpio(13, pin)
PWM.add_channel_p... | nilq/baby-python | python |
import flask
import pickle
import praw
import nltk
nltk.download("stopwords")
nltk.download("punkt")
from nltk.corpus import stopwords
import contractions
import inflect
import pandas as pd
import json
def clean(t):
en_stops = set(stopwords.words('english'))
t_old = str(t)
t_old = t_old.translate({ord(... | nilq/baby-python | python |
"""
Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной
первой буквой. Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит
из латинских букв в ниж... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Distributed under terms of the MIT license.
import os
import datetime
import json
import numpy as np
from numpy.linalg import norm
import math
import argparse
from platt import *
from sklearn.metrics import f1_score
import time
import scipy.stats
from ... | nilq/baby-python | python |
import pandas as pd
import time
import json
from collections import OrderedDict
class RunManager():
def __init__(self):
""" Class constructor """
self.epoch_count = 0
self.epoch_loss = 0
self.epoch_num_correct = 0
self.epoch_start_time = None
self.run_params = None... | nilq/baby-python | python |
__author__ = 'David Moser <david.moser@bitmovin.net>'
from unittest import TestSuite
from .testcase_create_delete_live_stream import CreateLiveStreamTestCase
def get_test_suite():
test_suite = TestSuite()
test_suite.addTest(CreateLiveStreamTestCase())
return test_suite
| nilq/baby-python | python |
#
# PySNMP MIB module Dlink-IMPB-MNG (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dlink-IMPB-MNG
# Produced by pysmi-0.3.4 at Wed May 1 12:58:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | nilq/baby-python | python |
#GAE modules
import webapp2
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
#Application specific Modules
from ExtraModules.gettemplate import gettemplate
from ExtraModules import phonenumbers
from model import Messages
def checkPhoneNumber(number, country_code):
try:
... | nilq/baby-python | python |
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
mc.postToChat("Hello, Minecraft World") | nilq/baby-python | python |
"""
You should not make an instance of the Client class yourself, rather you should listen for new connections with
:meth:`~websocket.server.WebSocketServer.connection`
>>> @socket.connection
>>> async def on_connection(client: Client):
... # Here you can use the client, register callbacks on it or send it messag... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_log_viewer.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObj... | nilq/baby-python | python |
import requests
import json
import re
ig_url = 'https://instagram.com'
ig_username = 'thephotoadventure'
query_url = f'{ig_url}/graphql/query'
all_user_posts = []
r = requests.get(f'{ig_url}/{ig_username}/?__a=1')
all_data = r.json()
user_data = all_data['graphql']['user']
user_posts = user_data['edge_owner_to_timel... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import sys
if __name__ == '__main__':
section, foil, cap = None, None, 9999999
if len(sys.argv) == 3:
section, foil = sys.argv[2], sys.argv[1]
elif len(sys.argv) == 4:
section, foil, cap = sys.argv[2], sys.argv[1], int(sys.argv[3])
else: # len(sys.argv... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.