text string | size int64 | token_count int64 |
|---|---|---|
from tensorflow.keras.callbacks import Callback
from poem_generator.word_generator import generate_poem
class PoemCallback(Callback):
def __init__(self, poems, seed_length, dictionary, single=True):
super(PoemCallback, self).__init__()
self.poems = poems
self.dictionary = dictionary
... | 715 | 211 |
import numpy as np
from scipy.spatial import ConvexHull
from core.optimizers import SMLAOptimizer
class LinearShatterBFOptimizer(SMLAOptimizer):
def __init__(self, X, buffer_angle=5.0, has_intercept=False, use_chull=True):
self._samplef = self.get_linear_samplef(X, buffer_angle, has_intercept, use_chul... | 1,456 | 672 |
# encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, division,... | 13,464 | 4,193 |
from unittest.mock import patch
from dependent import parameter_dependent
@patch('math.sqrt')
def test_negative(mock_sqrt):
assert parameter_dependent(-1) == 0
mock_sqrt.assert_not_called()
@patch('math.sqrt')
def test_zero(mock_sqrt):
mock_sqrt.return_value = 0
assert parameter_dependent(0) == 0
... | 820 | 300 |
import pytest
from world_rowing import dashboard
def test_dashboard_main():
dashboard.main(block=False)
def test_dashboard_predict():
dash = dashboard.Dashboard.load_last_race()
live_data, intermediates = dash.race_tracker.update_livedata()
dash.update(
live_data.loc[:300],
inte... | 416 | 153 |
"""Tests a package installation on a user OS."""
import pathlib
import subprocess
import unittest
class TestPlErrPackage(unittest.TestCase):
def test_plerr_error_getter(self):
# Given: a command to get a description of a pylint error by an
# error code.
command = ['python3', '-m', 'plerr',... | 1,665 | 467 |
import os
_lab_components = """from api2db.ingest import *
CACHE=True # Caches API data so that only a single API call is made if True
def import_target():
return None
def pre_process():
return None
def data_features():
return None
def post_process():
return None
if __name__ == "__main__":
... | 2,826 | 723 |
from collections.abc import Sequence
class SliceView(Sequence):
def __init__(self, sequence, start=None, stop=None, step=None):
self.sequence = sequence
self.range = range(*slice(start, stop, step).indices(len(sequence)))
def __len__(self):
return len(self.range)
def __getitem__(... | 485 | 145 |
import torch
class LossScaler:
def __init__(self, scale=1):
self.cur_scale = scale
# `params` is a list / generator of torch.Variable
def has_overflow(self, params):
return False
# `x` is a torch.Tensor
def _has_inf_or_nan(x):
return False
# `overflow` is boolean ind... | 2,348 | 743 |
#-*- coding: utf-8 -*-
"""Forms for the django-shop app."""
from django import forms
from django.conf import settings
from django.forms.models import modelformset_factory
from django.utils.translation import ugettext_lazy as _
from shop.backends_pool import backends_pool
from shop.models.cartmodel import CartItem
from... | 3,172 | 965 |
import datetime
import unittest
from conflowgen.domain_models.arrival_information import TruckArrivalInformationForPickup, \
TruckArrivalInformationForDelivery
from conflowgen.domain_models.container import Container
from conflowgen.domain_models.data_types.container_length import ContainerLength
from conflowgen.d... | 6,298 | 1,897 |
from src.access import UserRemoveAccess
from generate_access_data import generate_access_data
def test_remove_user_access():
sessions = generate_access_data()
user = sessions['user'].users.get('user')
useraccess = UserRemoveAccess(sessions['user'], user)
manageraccess = UserRemoveAccess(sessions['mana... | 591 | 161 |
# -*- python2 -*-
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from gdb_test import AssertEquals
import gdb_test
def test(gdb):
# The second superfluous call to LoadManifestFile. This is a... | 541 | 193 |
# Universal Power Supply Controller
# USAID Middle East Water Security Initiative
#
# Developed by: Nathan Webster
# Primary Investigator: Nathan Johnson
#
# Version History (mm_dd_yyyy)
# 1.00 03_24_2018_NW
#
######################################################
# Import Libraries
import Config
import time
import sql... | 1,403 | 647 |
import re
import unicodedata
# Remove empty brackets (that could happen if the contents have been removed already
# e.g. for citation ( [3] [4] ) -> ( ) -> nothing
def remove_brackets_without_words(text: str) -> str:
fixed = re.sub(r"\([\W\s]*\)", " ", text)
fixed = re.sub(r"\[[\W\s]*\]", " ", fixed)
... | 4,054 | 1,381 |
#!/usr/bin/env python3
#
# Import built in packages
#
import logging
import platform
import os
import time
import socket
import subprocess
import signal
import psutil
from .util import setup_logger
from .util import PylinxException
import re
# Import 3th party modules:
# - wexpect/pexpect to launch... | 17,887 | 5,498 |
lookup = [
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i"),
]
def to_roman(integer):
#
"""
"""
for decimal, roman in lookup:
if decimal <= integer:
return roman + to_roman(integer - decimal)
return ""
def main():
print(to_roman(1))
print(to_ro... | 532 | 229 |
from .service import *
import multiprocessing
import threading
__recognizer = None
def init_session(*args) -> None:
global __recognizer
# __recognizer = LiveSpeech()
# daemon = multiprocessing.Process(target=__recognizer.daemon(), args=(), )
# daemon.start()
# r = threading.Thread(target=shell... | 1,781 | 562 |
from behave import *
import requests
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
use_step_matcher("re")
@given("that I am a registered host of privilege walk events and exists events on my username")
def step_impl(context):
context.username = "12thMan"
conte... | 3,618 | 1,143 |
class Stack:
def __init__(self):
self.items = []
def is_empty(self): # test to see whether the stack is empty.
return self.items == []
def push(self, item): # adds a new item to the top of the stack.
self.items.append(item)
def pop(self): # removes the top item from the sta... | 1,011 | 346 |
"""soft_encoder.py: Encoding sentence with LSTM.
It encodes sentence with Bi-LSTM.
After encoding, it uses all tokens for sentence, and extract some parts for trigger.
Written in 2020 by Dong-Ho Lee.
"""
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn as nn
import torch
from ... | 4,422 | 1,401 |
import matplotlib.pyplot as plt
import numpy as np
import math
angle = float(input("Enter angle (degree): "))
velocity = float(input("Enter Velocity (m/s): "))
g = 9.81
cos_theta = math.cos(math.radians(angle))
sin_theta = math.sin(math.radians(angle))
v_x = velocity * cos_theta
v_y = velocity * sin_theta
time_of_... | 1,040 | 457 |
from django.urls import include,path
from remiljscrumy import views
app_name = 'remiljscrumy'
urlpatterns = [
path('',views.index,name='index'),
path('<int:goal_id>/', views.move_goal, name = "move_goal"),
path('accounts/', include('django.contrib.auth.urls')),
]
| 305 | 125 |
from typing import Dict
from django.conf import settings
from django.core.cache import DEFAULT_CACHE_ALIAS
from idom.core.proto import ComponentConstructor
IDOM_REGISTERED_COMPONENTS: Dict[str, ComponentConstructor] = {}
IDOM_BASE_URL = getattr(settings, "IDOM_BASE_URL", "_idom/")
IDOM_WEBSOCKET_URL = IDOM_BASE_URL... | 914 | 391 |
"""Forms for ox_herd commands.
"""
from wtforms import StringField
from ox_herd.core.plugins import base
class BackupForm(base.GenericOxForm):
"""Use this form to enter parameters for a new backup job.
"""
bucket_name = StringField(
'bucket_name', [], description=(
'Name of AWS bucke... | 496 | 139 |
from unittest import TestCase
from unittest.mock import patch, Mock, DEFAULT, call
from dexterity.infrastructure.electromagnetGPIO import ElectromagnetGPIO
class TestElectromagnetGPIO(TestCase):
def setUp(self) -> None:
led_patcher = patch('dexterity.infrastructure.electromagnetGPIO.Led')
self.Le... | 1,455 | 523 |
def cog():
return "Cog is alive."
| 35 | 15 |
from pydantic import BaseModel
class ReadyResponse(BaseModel):
status: str
| 81 | 25 |
"""
RandomBot -- A simple strategy: enumerates all legal moves, and picks one
uniformly at random.
"""
# Import the API objects
from api import State
import random
class Bot:
def __init__(self):
pass
def get_move(self, state):
# type: (State) -> tuple[int, int]
"""
Function ... | 1,087 | 279 |
import datetime
from django.db import models
class TransferRequest(models.Model):
"""转库申请单"""
STR_STATUS_CHOICES = (
(0, '草稿'),
(1, '已审批')
)
id = models.AutoField(primary_key=True)
str_identify = models.CharField(max_length=15, verbose_name='转库申请单编号')
str_serial = models.CharFi... | 8,252 | 3,444 |
from auctions.models import Category, Listing
from django.utils.timezone import now as tz_now
def footer_ctx(request):
listings = Listing.objects.filter(is_active=True, published_date__lte=tz_now(),
expiry_date__gt=tz_now())[:5]
categories = Category.objects.all()[:5]
... | 401 | 118 |
import numpy as np
import operator
# TODO: Make Mutation Operator.
class TerminationCriteria:
@staticmethod
def _convergence_check(convergence_ratio, population_fitness):
if abs((np.max(population_fitness) - np.mean(population_fitness)) / np.mean(
population_fitness)) <= convergence_... | 4,237 | 1,323 |
__author__ = 'paulo.rodenas'
| 29 | 14 |
from distutils.core import setup
setup(
name = 'niu',
packages = ['niu'],
version = '0.2',
description = 'A grouping and pairing library',
author = 'Gabriel Abrams',
author_email = 'gabeabrams@gmail.com',
url = 'https://github.com/gabeabrams/niu',
download_url = 'https://github.com/gabeabrams/niu/archi... | 443 | 160 |
from .client import Client
class Stats(Client):
def __init__(self, api_key='YourApiKeyToken'):
Client.__init__(self, address='', api_key=api_key)
self.url_dict[self.MODULE] = 'stats'
def get_total_ether_supply(self):
self.url_dict[self.ACTION] = 'ethsupply'
self.build_url()
... | 544 | 180 |
import pandas as pd
import numpy as np
import calendar
import datetime
import plotly as py
import plotly.graph_objs as go
class Gantt(object):
def __init__(self, data):
self.data = data
def get_gantt(self, df, less, index):
color = 0
n = 1
for j in less.index:
d... | 2,842 | 890 |
class Book:
def __init__(self, title, author, location):
self.title = title
self.author = author
self.location = location
self.page = 0
def turn_page(self, page):
self.page = page
| 229 | 67 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Evan K. Irving-Pease"
__copyright__ = "Copyright 2020, University of Copenhagen"
__email__ = "evan.irvingpease@gmail.com"
__license__ = "MIT"
import os
import sys
from math import log
import click
import pysam
import yaml
sys.path.append(os.getcwd())
from... | 8,530 | 2,883 |
import logging
from datetime import timedelta
from flask import Flask, render_template, redirect, request, url_for, flash
from flask_login import LoginManager, login_user, logout_user, current_user
from preston.crest import Preston as CREST
from preston.xmlapi import Preston as XMLAPI
from auth.shared import db, evea... | 5,773 | 1,873 |
# Copyright (c) 2018, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of ... | 3,891 | 1,365 |
from typing import (
Dict,
Sequence,
Tuple,
Type,
)
from eth2.beacon.on_startup import (
get_genesis_block,
get_initial_beacon_state,
)
from eth2.beacon.state_machines.configs import BeaconConfig
from eth2.beacon.types.blocks import (
BaseBeaconBlock,
)
from eth2.beacon.types.deposits imp... | 4,141 | 1,397 |
# Minimal settings file to allow the running of tests, execution of migrations,
# and several other useful management commands.
SECRET_KEY = 'abcde12345' # nosec
# Needs to point to something to allow tests to perform url resolving. The file
# doesn't actually need to contain any urls (but does need to define "urlpa... | 1,525 | 508 |
import MiniNero
import ed25519
import binascii
import PaperWallet
import cherrypy
import os
import time
import bitmonerod
import SimpleXMR2
import SimpleServer
message = "send0d000114545737471em2WCg9QKxRxbo6S3xKF2K4UDvdu6hMc"
message = "send0d0114545747771em2WCg9QKxRxbo6S3xKF2K4UDvdu6hMc"
sec = raw_input("sec?")
print... | 360 | 177 |
# Atharv Kolhar (atharv)
import logging
import warnings
warnings.filterwarnings("ignore")
jamalogger = logging.getLogger("JAMALIB")
jamalogger.setLevel(logging.DEBUG)
handle = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',
... | 599 | 209 |
import os
import requests
import logging
from tqdm import tqdm as tq
import zipfile
import tarfile
def download_file(url: str, path: str, verbose: bool = False) -> None:
"""
Download file with progressbar
Usage:
download_file('http://web4host.net/5MB.zip')
"""
if not os.path.exists(path):... | 1,851 | 583 |
from vedacore.misc import registry, build_from_cfg
def build_loss(cfg):
loss = build_from_cfg(cfg, registry, 'loss')
return loss
| 139 | 48 |
# -*- coding: UTF-8 -*-
"""
Created by Régis Eduardo Crestani <regis.crestani@gmail.com> on 19/06/2016.
"""
import os
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from django_rest_scaffold.settings import DJANGO_REST_SCAFFOLD_SETTINGS as SETTINGS
class Command(B... | 6,667 | 2,065 |
"""social_api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | 3,066 | 1,147 |
import itertools
import logging
import socket
import time
from collections import deque
from contextlib import contextmanager
from typing import Callable, Deque, Generator, NamedTuple, Optional
from meta_memcache.base.memcache_socket import MemcacheSocket
from meta_memcache.errors import MemcacheServerError
from meta_... | 5,186 | 1,419 |
#
# derl: CLI Utility for searching for dead URLs <https://github.com/tpiekarski/derl>
# ---
# Copyright 2020 Thomas Piekarski <t.piekarski@deloquencia.de>
#
from time import perf_counter
from derl.model.stats import Stats
class Singleton(type):
_instances = {}
def __call__(cls: "Singleton", *args: tuple, ... | 1,599 | 541 |
import random
import copy
rr = random.Random ( 22 )
def readNameList(fn):
f = open(fn,"r")
if f == None:
print ( f"Invalid file {fn} - failed to open" )
return None
dt = f.readlines()
f.close()
for i in range (len(dt)):
s = dt[i].rstrip()
dt[i] = s
return dt
... | 1,813 | 680 |
# ---license-start
# eu-digital-green-certificates / dgc-api-tests
# ---
# Copyright (C) 2021 T-Systems International GmbH and all other contributors
# ---
# 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 ... | 3,641 | 1,063 |
import numpy as np
import torch
import anndata
from celligner2.othermodels.trvae.trvae import trVAE
from celligner2.trainers.trvae.unsupervised import trVAETrainer
def trvae_operate(
network: trVAE,
data: anndata,
condition_key: str = None,
size_factor_key: str = None,
n_epoch... | 4,503 | 1,423 |
import datetime
import remi
import core.globals
connected_clients = {} # Dict with key=session id of App Instance and value=ws_client.client_address of App Instance
connected_clients['number'] = 0 # Special Dict Field for amount of active connections
client_route_url_to... | 2,519 | 680 |
import os
import pytest
from django.urls import reverse
from seahub.options.models import (UserOptions, KEY_FORCE_2FA, VAL_FORCE_2FA)
from seahub.test_utils import BaseTestCase
from seahub.two_factor.models import TOTPDevice, devices_for_user
TRAVIS = 'TRAVIS' in os.environ
@pytest.mark.skipif(TRAVIS, reason="")
cl... | 2,111 | 655 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
from saucenao.exceptions import *
PREVIOUS_STATUS_CODE = None
STATUS_CODE_OK = 1
STATUS_CODE_SKIP = 2
STATUS_CODE_REPEAT = 3
def verify_status_code(request_response: requests.Response) -> tuple:
"""Verify the status code of the post request to the sear... | 1,495 | 445 |
import time
from os import system
from django.http import HttpResponse
from django.template import Context, loader
from django.views.decorators.csrf import csrf_exempt # Pour des formulaires POST libres
from jla_utils.utils import Fichier
from .models import ElementDialogue
class Tunnel:
def __init__(self, long... | 6,711 | 2,356 |
#!/usr/bin/env python
from unittest import TestCase
from boutiques.bosh import bosh
from boutiques.bids import validate_bids
from boutiques import __file__ as bofile
from jsonschema.exceptions import ValidationError
from boutiques.validator import DescriptorValidationError
import os.path as op
import simplejson as jso... | 1,294 | 392 |
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class OutgoingReceiptProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = OutgoingReceiptProto... | 425 | 114 |
from __future__ import print_function
import pathlib
from builtins import object, str
from typing import Dict
from empire.server.common import helpers
from empire.server.common.module_models import PydanticModule
from empire.server.utils import data_util
from empire.server.utils.module_util import handle_error_messag... | 2,769 | 746 |
from django.urls import path
from .views import game_detail, make_move
urlpatterns = [
path(r'detail/<int:id>/', game_detail, name="gameplay_detail"),
path(r'make_move/<int:id>', make_move, name="gameplay_make_move")
]
| 230 | 85 |
from setuptools import setup
def load_pip_dependency_list():
with open('./requirements.txt', 'r', encoding='utf-8') as file:
return file.read().splitlines()
def load_readme_desc():
with open("README.md", "r", encoding="utf-8") as readme_file:
return readme_file.read()
setup(
name="sc2sim"... | 740 | 253 |
from collections import defaultdict
from itertools import permutations
import networkx as nx
def air_duct_spelunking(inp, part1=True):
max_y = len(inp)
max_x = max(len(line) for line in inp)
grid = defaultdict(lambda: '#')
numbers = defaultdict(lambda: '')
route_list = defaultdict(lambda: 0)
... | 1,906 | 658 |
"""
Contains Angebotsteil class
and corresponding marshmallow schema for de-/serialization
"""
from typing import List, Optional
import attr
from marshmallow import fields
from bo4e.bo.marktlokation import Marktlokation, MarktlokationSchema
from bo4e.com.angebotsposition import Angebotsposition, AngebotspositionSche... | 3,889 | 1,236 |
import os
import shutil
import ast
import sys
import time
import re
from datetime import datetime as dt
import pytz
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import random
from random import shuffle
from biokbase.workspace.client import Workspace as workspaceService
#fro... | 63,926 | 19,832 |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version May 29 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
impor... | 1,723 | 538 |
import unittest2
from openerp.osv.orm import except_orm
import openerp.tests.common as common
from openerp.tools import mute_logger
class TestServerActionsBase(common.TransactionCase):
def setUp(self):
super(TestServerActionsBase, self).setUp()
cr, uid = self.cr, self.uid
# Models
... | 20,121 | 6,711 |
#!/usr/bin/env python
import os
import sys
import abc
import StringIO
from ansible import errors
def duplicateattr(output, attr, dattr):
new_output = []
for group in output:
if attr in group:
new_group = group
new_group[dattr] = group[attr]
new_output.append(new_grou... | 506 | 140 |
"""Gameboy memory.
Cartridge
---------
[0000-3FFF] Cartridge ROM, bank 0: The first 16,384 bytes of the cartridge program are always available at this point in the memory map. Special circumstances apply:
[0000-00FF] BIOS: When the CPU starts up, PC starts at 0000h, which is the start of the 256-byte GameBoy BIOS code... | 3,564 | 1,053 |
""" gradient and hessian readers
"""
import numpy
import autoread as ar
import autoparse.pattern as app
def gradient(output_string):
""" read gradient from the output string
"""
grad = ar.matrix.read(
output_string,
start_ptt=app.padded(app.NEWLINE).join([
app.padded(app.escape... | 1,127 | 395 |
from Language.Grammar.grammar import Production, Symbol, Terminal
class LR1Item:
def __init__(self, production: Production, dot_index: int, lookahead: Terminal = None):
self._repr = ''
self.production = production
self.dot_index = dot_index
self.lookahead = lookahead
self._... | 1,072 | 343 |
# -*- coding: utf-8 -*-
"""
Created on 2021-03-11 18:53:58
---------
@summary:
抓糗事百科的案例
---------
@author: Administrator
"""
import feapder
class Spider(feapder.AirSpider):
def start_requests(self):
for page_num in range(1, 2):
url = "https://www.qiushibaike.com/8hr/page/{}/".format(page_... | 1,402 | 568 |
# coding=utf-8
import turtle
t = turtle.Turtle()
t.goto(-50, 0)
for j in range(3):
t.forward(180)
t.right(120)
t.reset() # 清空窗口,重置turtle状态为起始状态
t2 = turtle.Turtle()
t2.speed(50)
for i in range(5):
t2.forward(150)
t2.right(144)
turtle.exitonclick() # 保持图案,直到鼠标点击才退出
# ### 标准库turtle... | 613 | 365 |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 10:26:55 2021
@author: hp
"""
import importlib
import prediction
import numpy as np
dataframe_instance = []
msg = ["marital status","age","hypertension","heart","glucose"]
for i in range(13):
read = (float(input()))
dataframe_instance.append(read)
#data_np = n... | 519 | 197 |
import signal
import os
import time
def receive_signal(signum, stack):
print 'Received:', signum
signal.signal(signal.SIGUSR1, receive_signal)
signal.signal(signal.SIGUSR2, receive_signal)
signal.signal(signal.SIGINT, receive_signal)
print 'My PID is:', os.getpid()
while True:
print 'Waiting...'
time.sl... | 327 | 117 |
import torch
import torch.nn.functional as F
from maskrcnn_benchmark.structures.bounding_box import BoxList
# the next two functions should be merged inside Masker
# but are kept here for the moment while we need them
# temporarily gor paste_mask_in_image
def expand_boxes(boxes, scale):
w_half = (boxes[:, 2] - box... | 5,211 | 2,075 |
"""Fixtures for tests."""
import json
import boto3
from moto import mock_dynamodb2
import pytest
from fixtures import LambdaContextMock
import payloads
@pytest.fixture
def event():
"""Return parsed event."""
with open('tests/payloads/success.json') as json_data:
return json.load(json_data)
@pytest... | 2,047 | 674 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# Ozer Ozkahraman (ozero@kth.se)
import py_trees as pt
import py_trees_ros as ptr
import time
import numpy as np
import rospy
import tf
import actionlib
# from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from smarc_msgs.msg import GotoWaypo... | 51,450 | 16,651 |
from __future__ import annotations
import logging
import os
import os.path
from ..util import gcs
logger = logging.getLogger(os.path.basename(__file__))
class Image:
def __init__(self, url) -> None:
self.url = url
def __str__(self) -> str:
return self.url
def delete(self):
gcs... | 464 | 154 |
from diofant.utilities.decorator import no_attrs_in_subclass
__all__ = ()
def test_no_attrs_in_subclass():
class A:
x = 'test'
A.x = no_attrs_in_subclass(A, A.x)
class B(A):
pass
assert hasattr(A, 'x') is True
assert hasattr(B, 'x') is False
| 285 | 119 |
import argparse
from ccc_client.app_repo.AppRepoRunner import AppRepoRunner
from ccc_client.utils import print_API_response
def run(args):
runner = AppRepoRunner(args.host, args.port, args.authToken)
r = runner.upload_image(args.imageBlob, args.imageName, args.imageTag)
print_API_response(r)
if args... | 921 | 314 |
class Entity(object):
'''
An entity has:
- energy
- position(x,y)
- size(length, width)
An entity may have a parent entity
An entity may have child entities
'''
def __init__(
self,
p,
parent=None,
children=None):
... | 1,781 | 571 |
from .dataloader import CellsProductionData | 43 | 13 |
#!/usr/bin/python2.6
#-*- coding: utf-8 -*-
import signal
import subprocess
from glob import glob
from os import listdir
from os.path import basename, dirname
label = 'CentOS_6.9_Final'
def listifaces():
ethernet = []
for iface in listdir('/sys/class/net/'):
if iface != 'lo':
ethernet.app... | 4,586 | 1,798 |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021 Ashwin Rajesh
#
# 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 ... | 6,023 | 2,380 |
import re
import sre_constants
from fileIO import *
from moveTasks import MoveTasks, MoveTaskIface
import logging
def get_matching_files(move_task: MoveTaskIface) -> list:
matches = []
try:
pattern = re.compile(move_task.filename_regex)
for root, dirs, files in get_all_files(move_task.search... | 2,096 | 770 |
from ckan_cloud_operator import kubectl
def get(what, *args, required=True, namespace=None, get_cmd=None, **kwargs):
return kubectl.get(what, *args, required=required, namespace=namespace, get_cmd=get_cmd, **kwargs)
| 222 | 76 |
""" Converts some lyx files to the latex format.
Note: everything in the file is thrown away until a section or the workd "stopskip" is found.
This way, all the preamble added by lyx is removed.
"""
from waflib import Logs
from waflib import TaskGen,Task
from waflib import Utils
from waflib.Configure import conf
def ... | 2,121 | 838 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Dusan Klinec, ph4r05, 2018
import operator
import sys
# Useful for very coarse version differentiation.
PY3 = sys.version_info[0] == 3
if PY3:
indexbytes = operator.getitem
intlist2bytes = bytes
int2byte = operator.methodcaller("to_bytes", 1, "big")... | 492 | 190 |
import os.path as osp
from argparse import ArgumentParser
from mmcv import Config
from pytorch_lightning import Trainer, seed_everything
from pytorch_lightning.callbacks import ModelCheckpoint
from torch.utils.data import DataLoader
from datasets import build_dataset
from models import MODELS
import torch
def parse... | 2,324 | 689 |
""" This Script contain the different function used in the framework
part1. Data processing
part2. Prediction and analisys
part3. Plotting
"""
import numpy as np
import librosa
import matplotlib.pyplot as plt
from sklearn import metrics
import os
import pickle
import time
import struct
""" Data processing """
def g... | 11,327 | 4,019 |
"""
jb2.py
~~~~~~
Use JBIG2, and an external compressor, for black and white images.
"""
import os, sys, subprocess, struct, zipfile, random
from . import pdf_image
from . import pdf_write
from . import pdf
import PIL.Image as _PILImage
_default_jbig2_exe = os.path.join(os.path.abspath(".."), "agl-jbig2enc", "jbig2.... | 15,067 | 4,775 |
#!/usr/bin/env python3
import argparse
import sys
from mpopt import ct, utils
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='ct_jug', description='Optimizer for *.jug cell tracking models.')
parser.add_argument('-B', '--batch-size', type=int, default=ct.DEFAULT_BATCH_SIZE)
parser.add_... | 1,581 | 551 |
import os
from setuptools import setup, find_packages
# For development and local builds use this version number, but for real builds replace it
# with the tag found in the environment
package_version = "4.0.0.dev0"
if 'BITBUCKET_TAG' in os.environ:
package_version = os.environ['BITBUCKET_TAG'].lstrip('v')
elif '... | 1,436 | 452 |
"""
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters.
"""
class Solution:
def lengthOfLongestSubstring(self, s):
longest = 0
longest_substr = ""
for ch in s:
if... | 695 | 202 |
# Automatically generated by pb2py
# fmt: off
import protobuf as p
from .TransactionType import TransactionType
class TxAck(p.MessageType):
MESSAGE_WIRE_TYPE = 22
def __init__(
self,
tx: TransactionType = None,
) -> None:
self.tx = tx
@classmethod
def get_fields(cls):
... | 388 | 130 |
import os
import tarfile
import time
import pickle
import numpy as np
from Bio.Seq import Seq
from scipy.special import expit
from scipy.special import logit
import torch
import torch.nn.functional as F
""" Get directories for model and seengenes """
module_dir = os.path.dirname(os.path.realpath(__file__))
model_dir ... | 12,476 | 4,550 |
import abc
class AbstractAnnotator(abc.ABC):
@abc.abstractmethod
def annotate(self, unlab_index, unlabeled):
raise NotImplementedError() | 154 | 49 |
import board, time
import neopixel
# Define Neopixels
LED7_PIN = board.D0 # pin that the NeoPixel is connected to
# Most Neopixels have a color order of GRB or GRBW some use RGB
LED7_ORDER = neopixel.GRB # pixel color channel order
# Create NeoPixel object
LED6 = neopixel.NeoPixel(board.D1, 1, pixel_order=neopixel.R... | 1,046 | 465 |
N = int(input())
A = list(map(int, input().split()))
d = {}
for i in range(N - 1):
if A[i] in d:
d[A[i]].append(i + 2)
else:
d[A[i]] = [i + 2]
for i in range(1, N + 1):
if i in d:
print(len(d[i]))
else:
print(0)
| 263 | 124 |