content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 14:37:57 2020
"""
from gensim import models
#import pymysql
import pandas as pd
#import MeCab
#from progressbar import ProgressBar
#import time
#from pandas import Series,DataFrame
#from gensim import corpora,matutils
#from gensim.models import word2ve... | python |
import random
import string
from collections import namedtuple
from unittest.mock import patch
from uuid import uuid4
from django.test import TestCase
from django.utils import timezone
from requests.exceptions import ConnectionError
from corehq.apps.accounting.models import SoftwarePlanEdition
from corehq.apps.accou... | python |
from performance_tests import generate_problem
from Drawing import draw_problem_configuration
import matplotlib.pyplot as plt
for name in ['barriers', 'hallway', 'narrow', 'split', 'maze']:
environment, robot, start, goal = generate_problem(name)
plt.close()
draw_problem_configuration(environment, robot, ... | python |
'''input
6
red
red
blue
yellow
yellow
red
5
red
red
yellow
green
blue
1
1
voldemort
10
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
0
3
apple
orange
apple
5
apple
apple
apple
apple
apple
1
6
red
red
blue
yellow
... | python |
import urllib
import requests
import json
import datetime
import os
import argparse
import pandas as pd
if __name__ == '__main__':
from Code.cdi_class import CDI_Dataset
from Code.cdi_validator import CDI_Masterlist_QA, Extra_Data_Gov
from Code.tag_validator import Climate_Tag_Check, Export_Retag_Request
... | python |
import maya.cmds as cmds
import re
import rsTools.utils.openMaya.dataUtils as dUtils
import maya.OpenMayaAnim as OpenMayaAnimOld
import maya.OpenMaya as OpenMayaOld
import maya.api.OpenMaya as om
import maya.api.OpenMayaAnim as oma
def isDeformer(deformer):
if not cmds.objExists(deformer):
return False
... | python |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2018-present MagicStack Inc. and the EdgeDB authors.
#
# 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... | python |
# flake8: noqa F401
from ask_cfpb.models.django import (
ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG, Answer, Audience, Category,
NextStep, SubCategory, generate_short_slug
)
from ask_cfpb.models.pages import (
ABOUT_US_SNIPPET_TITLE, CONSUMER_TOOLS_PORTAL_PAGES,
ENGLISH_ANSWER_SLUG_BASE, ENGLISH_DISCLAIME... | python |
"""
Test cases for customers Model
"""
import logging
import unittest
import os
from service.models import Customer, DataValidationError, db
from service import app
from service.models import Customer, DataValidationError, db
from werkzeug.exceptions import NotFound
DATABASE_URI = os.getenv(
"DATABASE_URI", "po... | python |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2021] 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/LICENSE-2.0
Unless required by... | python |
#--------------------------------------------
# calculate auc, tpr, tnr with n bootstrap
#-------------------------------------------
import os
import numpy as np
import pandas as pd
import glob
from sklearn.utils import resample
import scipy.stats as ss
from utils.mean_CI import mean_CI
from sklearn.metrics import ro... | python |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2022 all rights reserved
#
# externals
import re
# the framework
import pyre
# my superclass
from .ProjectTemplate import ProjectTemplate
# declaration
class React(ProjectTemplate, family='pyre.smith.projects.react'):
"""
Encapsulation... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# TCP
import socket
# Client
# # create
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# # connect
# s.connect(('www.sina.com.cn', 80))
#
# # AF_INET IPV4
# # AF_INET6 IPV6
# # SOCK_STREAM 使用面向流的TCP协议
# # connect 参数是tuple 包含ip和port
#
# # send
# s.send(b'GET / ... | python |
import random
from bos_consensus.common import Ballot, BallotVotingResult
from bos_consensus.consensus import get_fba_module
IsaacConsensus = get_fba_module('isaac').Consensus
class DivergentVotingConsensus(IsaacConsensus):
faulty_frequency = None
faulty_ballot_ids = None # store the ballot to be fault
... | python |
'''
I was given this problem in an interview. How would you have answered?
Design a data structure that offers the following operations in O(1) time:
insert
remove
contains
get random element
Consider a data structure composed of a hashtable H and an array A. The hashtable keys are the elements in the data structur... | python |
import time
import board
import busio
import adafruit_adxl34x
i2c = busio.I2C(board.SCL, board.SDA)
# For ADXL343
accelerometer = adafruit_adxl34x.ADXL343(i2c)
# For ADXL345
# accelerometer = adafruit_adxl34x.ADXL345(i2c)
accelerometer.enable_freefall_detection()
# alternatively you can specify attribut... | python |
import abc
from .card import CardType, Icons
class Tableau(abc.ABC):
def __init__(self, player_name, cash=0, thugs=None, holdings=None, hand=None):
self.player_name = player_name
self._cash = cash
self.thugs = thugs if thugs else []
self.holdings = holdings if holdings else []
... | python |
from Bio import SeqIO
import os
from utils import batch_iterator, create_dir
import csv
import collections
class DeepLocExperiment:
"""
Class to set up DeepLoc experiments:
1) convert fasta -> csv for Pytorch
2) split csv -> train and test
"""
def __init__(self, fasta_path, domains_path, output_path, label_na... | python |
class DependenciesMatrixError(Exception):
def __init__(self, msg, desc=None):
super().__init__(self, msg)
self.msg = msg
self.desc = desc
def __str__(self):
return f"DependenciesMatrixError: {self.msg}\nDescription: {self.desc}"
class PropabilityMatrixError(Exception):
def... | python |
import math
from functools import reduce
import aiger
import funcy as fn
from aigerbv import atom, UnsignedBVExpr
from aiger_coins import utils
def coin(prob, input_name=None):
# TODO: reimplement in terms of common_denominator_method.
prob = utils.to_frac(prob)
mux, is_valid = mutex_coins({'H': prob, '... | python |
"""
MIT License
Copyright (c) 2022 VincentRPS
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, modify, merge, publish, di... | python |
# -------------------------------------------------------------------------------
#
# Copyright (C) 2017 Cisco Talos Security Intelligence and Research Group
#
# PyREBox: Python scriptable Reverse Engineering Sandbox
# Author: Xabier Ugarte-Pedrero
#
# This program is free software; you can redistribute it and/... | python |
from unittest import TestCase
import numpy as np
import pandas as pd
from fireant.queries.pandas_workaround import df_subtract
class TestSubtract(TestCase):
def test_subtract_partially_aligned_multi_index_dataframes_with_nans(self):
df0 = pd.DataFrame(
data=[
[1, 2],
... | python |
"""Keras Sequence for running Neural Network on graph edge prediction."""
from typing import List
import numpy as np
import tensorflow as tf
from ensmallen import Graph # pylint: disable=no-name-in-module
from keras_mixed_sequence import Sequence
from embiggen.utils.tensorflow_utils import tensorflow_version_is_highe... | python |
from django.utils import timezone
from django.conf import settings
from rest_framework import serializers
from apps.todos.models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = (
'pk', 'author', 'title', 'description',
'de... | python |
import pygame
class Sprite(pygame.sprite.Sprite):
def __init__(self, image, spawn_x, spawn_y):
super().__init__()
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.rect.center = [spawn_x, spawn_y]
def update(self):
pass
def ... | python |
# -*- coding: utf-8 -*-
from .player import BagPlayer
from .reader import BagReader
from .recorder import BagRecorder
from .writer import BagWriter
| python |
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(path, ".."))
sys.path.append(os.path.join(path, "../../../common/"))
sys.path.append(os.path.join(path, "../../../common/acllite"))
import numpy as np
import acl
import base64
imp... | python |
"""Gordon Ramsay shouts. He shouts and swears. There may be something wrong with him.
Anyway, you will be given a string of four words. Your job is to turn them in to Gordon language.
Rules:
Obviously the words should be Caps, Every word should end with '!!!!',
Any letter 'a' or 'A' should become '@', Any other vow... | python |
# Copyright 2022 The jax3d Authors.
#
# 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 wr... | python |
import numpy as np
from forge.blade.action import action
from forge.blade.systems import skill, droptable
class Entity():
def __init__(self, pos):
self.pos = pos
self.alive = True
self.skills = skill.Skills()
self.entityIndex=0
self.health = -1
self.lastAttacker = None
def a... | python |
from django.db import models
class Student(models.Model):
firstname = models.CharField(max_length=64)
lastname = models.CharField(max_length=64)
olsclass = models.ForeignKey('OLSClass')
family = models.ForeignKey('Family')
def __unicode__(self):
return self.name()
def name(self, lastn... | python |
from django.core.management.base import BaseCommand
from exampleapp.models import FieldUpdate
from exampleapp.tests import EXAMPLE, FIELDS
from time import time, sleep
from django.db import transaction, connection
def tester(f, n=10):
runs = []
for _ in range(n):
# some sleep to put db at rest
... | python |
#List items are indexed and you can access them by referring to the index number:
#Example
#Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
| python |
import keyboard, time
from map import *
from inventory import Inventory
class Player():
x = 0
y = 0
direction = "UP"
costume = "@"
def spawn(pos_x, pos_y):
Map.generate()
Player.x = pos_x
Player.y = pos_y
Map.replaceObject(Player.x, Player.y, Player.costume, True)
... | python |
# -*- coding: UTF-8 -*-
import io
from distutils.core import setup
# http://stackoverflow.com/a/7071358/735926
import re
VERSIONFILE='freesms/__init__.py'
# In Python 2.x open() doesn't support the encoding keyword parameter.
verstrline = io.open(VERSIONFILE, encoding='utf-8').read()
VSRE = r'^__version__\s+=\s+[\'"]... | python |
import torch.nn as nn
from torchvision.models.alexnet import AlexNet
import torch.utils.model_zoo as model_zoo
from torch.nn.parameter import Parameter
import math
def init_network(model):
print('==> Network initialization.')
if isinstance(model, AlexNet) and hasattr(model, 'classifier100'): # fine tune alex... | python |
from django.conf import settings
def pusher(request):
return {
"PUSHER_KEY": getattr(settings, "PUSHER_KEY", ""),
}
| python |
from enhancer import enhance
startingtable = []
with open("data.txt", "r") as fh:
lookup = fh.readline().strip()
for thing in [i.strip() for i in fh.readlines()]:
if len(thing):
startingtable.append(list(thing))
enhance(startingtable, lookup, 50) | python |
import collections as abc_collection
from .. import abc
from .adjacency_graph import AdjacencyGraph
class Bounded(abc.Graph):
"""
Wrapper to make the values of :py:class:`~.abc.Graph` instances bounded
:param value_bound: bound for all values
The ``value_bound`` must be compatible with all values s... | python |
class PaintIt:
"""
Simple utility to easily color a text printed in the console.
Usage: print(ColorMe("green")("Hello World!"))
"""
colors = {
'unchanged': "{0}",
'yellow': "\033[93m{0}\033[00m",
'sea': "\033[96m{0}\033[00m",
'red': "\033[91m{0}\033[00m",
'g... | python |
# Copyright 2018 Open Source Robotics Foundation, 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... | python |
from django.test import TestCase
from core.forms import RITSForm
from core.models import get_rits_choices
class RITSFormTestCase(TestCase):
def test_python_prohibited(self):
test_body = {
'name': 'Test RITS',
'transformation_type': 'python',
}
form = RITSForm(test_... | python |
import distributions
import numpy as np
def gen_hmm(pi, A, obs_distr, T):
K = len(obs_distr)
seq = np.zeros(T, dtype=int)
X = np.zeros((T,obs_distr[0].dim))
seq[0] = np.argmax(np.random.multinomial(1, pi))
for t in range(T-1):
seq[t+1] = np.argmax(np.random.multinomial(1, A[seq[t]]))
... | python |
import subprocess
import json
creds = subprocess.check_output(['pass', 'gcloud/ansible@dlang-ci.iam.gserviceaccount.com'])
GCE_PARAMS = ('ansible@dlang-ci.iam.gserviceaccount.com', json.loads(creds)['private_key'])
GCE_KEYWORD_PARAMS = {'project': 'dlang-ci', 'datacenter': 'us-east1'}
| python |
# Copyright 2021 The TensorFlow Ranking Authors.
#
# 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 ag... | python |
import pandas as pd
import numpy as np
abnb = pd.read_csv('Airbnb_U4.csv',
usecols=[1, 2, 3, 5, 6, 7, 8, 27, 28],
)
print(abnb.shape)
# abnb.info()
# print("\nNULL :\n", abnb.isnull().sum())
abnb['price'] = round(np.exp(abnb['log_price']),1)
print(abnb.dtypes)
... | python |
from unet_ddpm import *
class EncResBlock(nn.Module):
def __init__(
self, in_channel, out_channel, dropout=0, group_norm=32,
):
super().__init__()
norm_affine = True
self.norm1 = nn.GroupNorm(group_norm, in_channel)
self.activation1 = Swish()
self.conv1 = c... | python |
#!/usr/bin/env python
### generate prior file from h5py file directly ###
### generate_h2_pT generates two prior files from the results of LDSC and a fixed annotation file ###
### generate_h2_from_user generates one prior file from the user provided prior file ###
import h5py
import os
from collections import Counter
... | python |
import logging
import os
def initLogger() -> object:
"""
Initialize the logger.
"""
logger_level = logging.INFO
if 'APP_ENV' in os.environ:
if os.environ['APP_ENV'] == 'dev':
logger_level = logging.DEBUG
logging.basicConfig(level=logger_level,
form... | python |
import numpy as np
import torch
import torchvision
import torch.utils.data as data
import torchvision.transforms as transforms
import pandas as pd
import h5py
import os
import sys
import json
import time
from scaler import *
from opts import parse_opts
from loss_funcs import *
# lightweight GAN model
from lwgan.lig... | python |
"""
NLP Sandbox Date Annotator API
# Overview The OpenAPI specification implemented by NLP Sandbox Annotators. # noqa: E501
The version of the OpenAPI document: 1.0.2
Contact: thomas.schaffter@sagebionetworks.org
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
impo... | python |
# Enter your code here. Read input from STDIN. Print output to STDOUT
phonebook = dict()
n = int(input())
for i in range(n):
inp = input()
inp_command = inp.split()
#print(inp_command)
phonebook[inp_command[0]] = int(inp_command[1])
#print(phonebook)
while True:
try:
name = input()
... | python |
from typing import Any, List, Optional
from antarest.study.storage.rawstudy.model.filesystem.factory import FileStudy
from antarest.study.storage.variantstudy.model.model import CommandDTO
from antarest.study.storage.variantstudy.model.command.common import (
CommandOutput,
CommandName,
)
from antarest.study.s... | python |
#!/usr/bin/env python
# EQUAL PARTS VINEGAR AND WATER
#
# https://www.goodhousekeeping.com/home/cleaning/tips/a26565/cleaning-coffee-maker/
#
# Fill the reservoir with equal parts vinegar and water, and place a paper filter
# into the machine's empty basket. Position the pot in place, and "brew" the solution
# halfway... | python |
"""
# Copyright 2022 Red Hat
#
# 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 agr... | python |
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
import factory
from datetime import date
from ggrc_workflows import models
fro... | python |
import shutil
def terminal_width():
"""
Return the current width of the terminal screen.
"""
return shutil.get_terminal_size().columns
| python |
# jsb/tick.py
#
#
""" provide system wide clock tick. """
## jsb imports
from jsb.lib.threadloop import TimedLoop
from jsb.lib.eventbase import EventBase
from jsb.lib.callbacks import callbacks
from jsb.lib.config import getmainconfig
## TickLoop class
class TickLoop(TimedLoop):
def start(self, bot=None):
... | python |
# -*- coding: utf8 -*-
"""`dsklayout.cli.cmdext_`
"""
from . import cmdbase_
__all__ = ('CmdExt',)
class CmdExt(cmdbase_.CmdBase):
__slots__ = ('_parent',)
@property
def parent(self):
"""A parent command which contains this extension"""
return self._parent
@parent.setter
def p... | python |
#!/usr/bin/env python
import os
import codecs
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-compose-settings',
version=codecs.open(os.path.join(here, 'VERSION'), encoding='utf-8').read().strip(),
description='Django composable settings loader.',
... | python |
typeface = {
'font': 'Gotham',
"foundry": "Hoefler",
"designer": "tobias frere-jones",
"cassification": "geometric sans-serif",
"default-size": 12.0,
'weights': [
{'name': "bold", 'weight': 600},
{'name': "medium", 'weight': 500},
{'name': "light", 'weight': 350}
],
... | python |
import numpy as np
import pyautogui
import time
import cv2
from game_frame_detector import GameFrameDetector
from scrollbar_detector import ScrollbarDetector
from kai_recognizer import KaiRecognizer
from rarity_recognizer import RarityRecognizer
from common import Point, Size, Rect
def takeScreenshot():
raw_captur... | python |
from passlib.hash import pbkdf2_sha256
def encrypt_psw(psw):
return pbkdf2_sha256.hash(psw)
def compare_psw(current, saved):
return pbkdf2_sha256.verify(current, saved)
| python |
from .task import Task
class TaskObserver:
def __init__(self):
self.__tasks = {}
def add_task(self, task: Task):
delivery_tag = task.delivery_tag
if delivery_tag in self.__tasks.keys():
raise ValueError(f"Delivery tag {delivery_tag} is already exists")
self.__tasks... | python |
# -*- coding: utf-8 -*-
import os
import pytest
def test_env_absent():
# Even if the env var is not initially set, the environ
# variables should not be affected.
assert "PYGAME_HIDE_SUPPORT_PROMPT" not in os.environ
import pygamesilent
assert "PYGAME_HIDE_SUPPORT_PROMPT" not in os.environ
| python |
#-*- codeing = utf-8 -*-
import bs4 #Web page parsing
import re #Text extraction, regular expressions
import urllib.request,urllib.error #Get web page data
import xlwt #Excel
import sqlite3 #Database operations
def main():
baseurl="https://movie.douban.com/top250?start="
datalist = getData(baseurl)
def getDa... | python |
from django.utils.encoding import smart_str
from test_plus import TestCase
from touchtechnology.common.tests import factories
class SitemapNodeTests(TestCase):
def setUp(self):
self.object = factories.SitemapNodeFactory.create()
def test_string_representation(self):
self.assertEqual(self.obj... | python |
from threading import Thread, Event
import time
# Code to execute in an independent thread
def countdown(n, started_evt):
print("countdown starting")
started_evt.set()
while n > 0:
print("T-minus", n)
n -= 1
time.sleep(5)
# Create the event object that will be used to signal start... | python |
# A script to copy positions using Interactive Brokers because SierrChart does
# not support adaptive market orders
import asyncio
import json
import logging
import typing as t
import datetime as dt
from asyncio.tasks import ensure_future
from contextlib import suppress
import click
from ib_insync import ContFuture, ... | python |
from typing import Optional, List, Dict, Any
from collections import OrderedDict
import timm
from timm.models.layers import SelectAdaptivePool2d
import torch
import torch.nn as nn
from theseus.utilities.loading import load_state_dict
from theseus.utilities.loggers.observer import LoggerObserver
LOGGER = LoggerObserve... | python |
import mock
import pytest
from py_zipkin import Encoding
from py_zipkin import Kind
from py_zipkin import logging_helper
from py_zipkin.encoding._encoders import get_encoder
from py_zipkin.encoding._helpers import create_endpoint
from py_zipkin.encoding._helpers import Endpoint
from py_zipkin.encoding._helpers import ... | python |
import nddata
import numpy as np
def ones(shape, dtype = None):
'''
'''
values = np.ones(shape, dtype = dtype)
coords = []
dims = []
for ix in range(len(shape)):
dims.append(str(ix))
coords.append(np.arange(shape[ix]))
return nddata.nddata_core(values, dims, coords)
def o... | python |
# this deals with setting a custom prefix and writing it to a json file
# (not the best way, but works)
# Imports
from discord.ext import commands
import discord
import json
# config
from config import DEFAULT_PREFIX
# cog class
class Prefix(commands.Cog):
def __init__(self, bot):
self.bot = bot
@c... | python |
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '12/21/2020 5:37 PM' | python |
squares = []
for x in range(10):
squares.append(x**2)
print(squares)
squares = list(map(lambda x : x** 2, range(10)))
print('lambda:', squares)
squares = [x ** 2 for x in range(10)]
print('for: ', squares)
squares = [(x,y) for x in [1,2,3] for y in [3,1,4] if x != y ]
print(squares) | python |
from django.dispatch import Signal
product_viewed_signal = Signal(providing_args=['instance', 'request']) | python |
from apero.core.constants import param_functions
from apero.core.core import drs_recipe
from apero import lang
from apero.core.instruments.default import file_definitions as sf
# =============================================================================
# Define variables
# =========================================... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import check_call, call, Popen, PIPE
from ansible.module_utils.basic import *
LAIN_VIP_PREFIX_KEY = "/lain/config/vips"
module = AnsibleModule(
argument_spec=dict(
ip=dict(required=True),
port=dict(required=True),
container_app=... | python |
# Generated by Django 2.0 on 2018-08-17 09:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('humanist_app', '0004_incomingemail_log'),
]
operations = [
migrations.AlterField(
model_name='incomingemail',
name='lo... | python |
from rest_framework import routers
from talentmap_api.language import views
router = routers.SimpleRouter()
router.register(r'', views.LanguageListView, base_name="language.Language")
urlpatterns = []
urlpatterns += router.urls
| python |
"""
A prototype application of the distributed cross-entropy method to the wind optimization problem.
In this basic implementation, the number of turbines is fixed and the generative distribution is uncorrelated.
TODO:
+ Add boundary constraints / penalties
+ Add proximity constraints
+ Better order turbine locatio... | python |
from __future__ import unicode_literals
def file_args_to_stdin(file_args):
return '\0'.join(list(file_args) + [''])
def run_hook(env, hook, file_args):
return env.run(
' '.join(['xargs', '-0', hook['entry']] + hook['args']),
stdin=file_args_to_stdin(file_args),
retcode=None,
)
... | python |
import os
import subprocess
import time
from .exceptions import InterfaceNotFoundError
from .abstract_readers import TcIpQueueLimitsStatsReader
from .utils.available_interfaces import AvailableInterfaces
class QueueLimitsStatsReader(TcIpQueueLimitsStatsReader):
@staticmethod
def _interface_exists(interface_n... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tags', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='tag',
options={'verbose... | python |
import numpy as np
import cvxopt as cvx
import math
from Env.opter import CvxOpt
class Env:
REWARD_NEG = 0
STATE_ON = 1
STATE_OFF = 0
def __init__(self, name, configure):
self.name = name
if configure.random_seed >= 0:
np.random.seed(configure.random_seed)
self... | python |
import warnings
from copy import deepcopy
import pygromos.files.blocks.pertubation_blocks
from pygromos.files._basics import _general_gromos_file, parser
from pygromos.files.blocks import pertubation_blocks as blocks
class Pertubation_topology(_general_gromos_file._general_gromos_file):
_block_order = ["TITLE"]... | python |
from base import BaseTest
import requests
import json
class Test(BaseTest):
def test_root(self):
"""
Test / http endpoint
"""
self.render_config_template(
)
proc = self.start_beat(extra_args=["-E", "http.enabled=true"])
self.wait_until(lambda: self.log_co... | python |
from uuid import UUID
from typing import Dict, Optional
from dataclasses import dataclass, field
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from source.domain.entities import Profile
from source.ports.repositories import ProfileRepository
from source.infrastructure.tables import... | python |
## emotionProcessor-threaded.py
## This is a variation of the emotionProcessor class.
## The main difference between the two classes is that this
## class utilizes python's threading module to collect the
## audio metrics.
## Since this proved to offer little to no performance gains
## while still expending ex... | python |
import json
ID1 = "3a569cbc-49a3-4772-bf3d-3d46c4a51d32"
TEST_JSON_1 = {
"name": "some_name",
"values": [
"value1", "value2"
]
}
SHARED_ID = "2d34bed8-c79a-4f90-b992-f7d3b5bc1308"
SHARED_JSON = {
"shared_value": "psx"
}
EXPANSION_JSON = {
"services": {
"starsky": {
... | python |
import os
import subprocess
import sys
import re
from joblib import Parallel, delayed
from tqdm import tqdm
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Align.Applications import PrankCommandline
from Bio.Align.Applications import MafftCommandline
from Bio.Align.Applicat... | python |
from pyrevit.framework import List
from pyrevit import revit, DB
import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
clr.AddReference("System")
from Autodesk.Revit.DB import FilteredElementCollector
from Autodesk.Revit.DB import BuiltInCategory, ElementId, XYZ, ExternalFileReference,FamilyInstance,E... | python |
#!/usr/bin/python3
def max_integer(my_list=[]):
"""
finds the largest integer of a list
"""
if len(my_list) == 0:
return (None)
my_list.sort()
return (my_list[-1])
| python |
'''OpenGL extension EXT.blend_minmax
This module customises the behaviour of the
OpenGL.raw.GL.EXT.blend_minmax to provide a more
Python-friendly API
Overview (from the spec)
Blending capability is extended by respecifying the entire blend
equation. While this document defines only two new equations, the
Blen... | python |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2015 Baifendian 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 required by applicable law o... | python |
import json
jf = open('test.json', 'r')
f = json.load(jf)
l = [ ]
for item in f:
try:
loc = item['location']
except:
l.append(item['Empresa'])
out = open('test_no_found.txt', 'w')
out.write(str(l))
| python |
#!/usr/bin/python
from __future__ import division
import sys
import collections
import math
def percentile(N, percent):
k = (len(N)-1) * percent
f = math.floor(k)
c = math.ceil(k)
if f == c:
return N[int(k)]
d0 = N[int(f)] * (c-k)
d1 = N[int(c)] * (k-f)
return int(d0+d1)
outputResults = sys.argv[1]
outputfil... | python |
from setuptools import setup
import elife_bus_sdk
setup(
name='elife_bus_sdk',
version=elife_bus_sdk.__version__,
description='This library provides a Python SDK for the eLife Sciences Bus',
packages=['elife_bus_sdk',
'elife_bus_sdk.publishers',
'elife_bus_sdk.queues'],
... | python |
"""
The Swift-Hohenberg equation
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
from typing import Callable
import numpy as np
from ..fields import ScalarField
from ..grids.boundaries.axes import BoundariesData
from ..tools.docstrings import fill_in_docstring
from ..tools.numba import jit, nb
from .ba... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.