text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-30 15:45
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependenc... | 2,707 | 808 |
from utils.discord import help_me, DiscordInteractive
from utils.osu.utils import CalculateMods
from utils.utils import Log
interact = DiscordInteractive.interact
class Command:
command = "cs"
description = "Calculate Circle Size value with mods applied."
argsRequired = 1
usage = "<cs> [+mods]"
e... | 1,481 | 475 |
"""Support for MAX! Home Automation Thermostats Sensors."""
import logging
from homeassistant.helpers.entity import Entity
from homeassistant.const import TEMP_CELSIUS
from .consts import *
from .__init__ import MaxHomeAutomationDeviceHandler
from .__init__ import MaxHomeAutomationCubeHandler
_LOGGER = logging... | 8,523 | 2,764 |
def contain_all_unique_characters(s):
letter_count = {}
for i in range(0, len(s)):
key = s[i]
if(key in letter_count): letter_count[key] += 1
else: letter_count[key] = 1
if(letter_count[key] > 1):
return False
return True
s1 = 'gofreetech' #false
print(contain_a... | 760 | 267 |
from zeep.client import Client
# RPC style soap service
client = Client('http://www.soapclient.com/xml/soapresponder.wsdl')
print(client.service.Method1('zeep', 'soap'))
| 171 | 56 |
from __future__ import annotations
import typing
from django.http import HttpRequest
from django.template import loader
from django.utils.translation import gettext_lazy as _
import hexa.ui.datacard
from hexa.ui.utils import get_item_value
from .base import DatacardComponent
class Action(DatacardComponent):
d... | 2,348 | 702 |
# -*- coding: utf-8 -*-
#
# Scimitar: Ye Distributed Debugger
#
# Copyright (c) 2016 Parsa Amini
# Copyright (c) 2016 Hartmut Kaiser
# Copyright (c) 2016 Thomas Heller
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)... | 480 | 181 |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Testing helpers related to the module system.
"""
from __future__ import division, absolute_import
__all__ = ['NoReactor']
import twisted.internet
from twisted.test.test_twisted import SetAsideModule
class NoReactor(SetAsideModule):
"... | 1,175 | 351 |
# https://www.youtube.com/watch?v=Gt0_BuJmJeI&list=PLCC34OHNcOtpz7PJQ7Tv7hqFBP_xDDjqg&index=10
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
Builder.load_file('codemy_7_Cor_BackGround_Labels.kv')
class MyLayout(Widget):
pass
class Codemy_Tutorial_App(App):
def b... | 419 | 179 |
from pydantic.error_wrappers import ValidationError
from db.database import Database
from models.base_record_manager import BaseRecordManager
from models.user.user_model import (USER_MODEL_NAME, User, UserCreate,
UserPartial)
class UserManager(BaseRecordManager):
"""UserManage... | 1,871 | 497 |
# This module tries to achieve disaggregation by using an autoencoder to
# find the main influences in the powerflow.
# Based on CNTK
#
# Realization on the basis of the
# - Autoencoder example: For the model
# - The financial example: How to load from pandas
# - The CNN example: Because the financial example create... | 7,132 | 2,029 |
import logging
import sys
def get_stdout_logger(name='root',level='INFO'):
# if get_stdout_logger.is_initialized:
# return logging.getLogger()
logging_level = getattr(logging, level.upper(), None)
if not isinstance(logging_level, int):
raise ValueError(f'invalid log level {level}')
s... | 1,239 | 373 |
from torchvision import datasets, transforms
import torch
import copy
import numpy as np
def download_data(path, transformer, datatype, batch_size):
# Download and load the training data
dataset = datasets.FashionMNIST(path, download=True, train=datatype, transform=transformer)
dataloader = torch.utils.da... | 3,930 | 1,137 |
import inspect
import logging
import re
import networkx as nx
from pyvis.network import Network
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
# does not match to any symbol
REGEX_NEVER_MATCH = '(?!x)x'
NON_EXECUTABLE = "save|write|remove|delete|duplicate"
def getmembers(ob... | 4,845 | 1,411 |
#! /usr/bin/python3
#
# rubb.py
import os
import os.path
import pwd
import shutil
import signal
import stat
import subprocess
import sys
from sys import stderr
import traceback
# system
ETC_DIR = "/etc/russ"
RUN_DIR = "/var/run/russ"
CONF_DIR = "%s/conf" % RUN_DIR
PIDS_DIR = "%s/pids" % RUN_DIR
SERVICES_DIR = "%s/ser... | 23,773 | 7,061 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 28 05:39:18 2019
@author: ladvien
"""
from time import sleep, time
"""
MOTOR_NUM:
X = 0
Y = 1
Z = 2
E0 = 3
E1 = 4
PACKET_TYPES
0x01 = motor_write
0x02 = motor_halt
DIRECTIO... | 6,100 | 2,124 |
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from matplotlib import colors
import matplotlib.pyplot as plt
def _scale_images(img_tensor):
return torch.true_divide((img_tensor - img_tensor.min()), (img_tensor.max() - img_tensor.min()))
def _clip_image(img_tensor):
res = i... | 2,890 | 1,003 |
from redis import Redis
from redis_natives import Dict
from tests import RedisWrapper
class TestDict(object):
def setup_method(self, method):
self.redis = RedisWrapper(Redis())
self.redis.flushdb()
self.test_key = 'test_key'
self.dict = Dict(self.redis, self.test_key)
def test... | 4,454 | 1,594 |
# -*- coding: utf-8 -*-
"""Adjustment API.
Adjustment classes are attached to ``data`` attribute of
:py:class:`~psd_tools.user_api.layers.AdjustmentLayer`.
Example::
if layer.kind == 'adjustment':
adjustment = layer.data
"""
from __future__ import absolute_import
import inspect
import logging
from psd_t... | 10,436 | 3,381 |
from h_matchers import Any
from h_api.enums import DataType
from h_api.model.json_api import JSONAPIData, JSONAPIError, JSONAPIErrorBody
class TestJSONAPIErrorBody:
def test_create(self):
meta = {"metadata": 1}
body = JSONAPIErrorBody.create(
KeyError("message"),
title="ti... | 2,605 | 758 |
import os
from Parameters.aqueous import Aqueous
from Preparation.WaterInputUser import WaterInputUser
class PreparationUser(object):
"""
This class provides methods that prepares the solver for its calculations
"""
def __init__(self, dest, database, water_species=None, gas_species=None, minerals=N... | 2,152 | 626 |
from statuspageio.version import VERSION
from statuspageio.errors import ConfigurationError
import warnings
class Configuration(object):
def __init__(self, **options):
"""
:param str api_key: Personal access token.
:param str page_id: The page_id you wish to manage
:param str o... | 2,583 | 676 |
"""Handles converting FLAC files to MP3."""
| 44 | 15 |
import pytest
from grappa.operators.callable import CallableOperator
def test_should_callable(should):
test_should_callable | should.be.callable
(lambda x: x) | should.be.callable
CallableOperator | should.be.callable
CallableOperator.match | should.be.callable
with pytest.raises(AssertionError):... | 1,981 | 631 |
from tqdm import tqdm
import pickle
from sys import path
path.append("..")
import numpy as np
import math
from uncertainty_solver import UncertaintySimulatedAnnealingSolver, UncertaintyRandomSolver
import map_converter as m
solutions = {}
state = [(113, 128), (4, 112), (132, 105), (108, 64), (62, 42), (4, 140), (22, ... | 1,471 | 704 |
"""Wrap a path in the default media root. This is only needed for photos
managed outside of the CMS"""
from django.conf import settings
from django_jinja import library
@library.global_function
def media(url):
return getattr(settings, 'MEDIA_URL', '') + url
| 264 | 76 |
from astexport.version import __version__
__prog_name__ = "astexport"
__version__ = __version__
| 97 | 32 |
from enforce_typing import enforce_types # type: ignore[import]
import warnings
from web3tools import web3util, web3wallet
@enforce_types
class DTFactory:
def __init__(self):
name = self.__class__.__name__
abi = web3util.abi(name)
web3 = web3util.get_web3()
contract_address = web3u... | 1,211 | 368 |
from http import server
import os
from plumbum import local, ProcessExecutionError
import sys
from webbrowser import open_new_tab
from .utils import M
sphinx = local['sphinx-build']
sphinx_args = ["-d", "_build/doctrees"]
apidoc = local['sphinx-apidoc']
@M.command()
def build(format="html"):
if format == "latex... | 797 | 290 |
import sys
import numpy as np
def main(argv):
file_prefix = argv[1]
num_files = int(argv[2])
output_filename = argv[3]
matrix = []
for idx in range(num_files):
filename = '{}.{}.rwr'.format(file_prefix, idx)
try:
fp = open(filename, 'r')
except IOError:
... | 533 | 186 |
from __future__ import print_function
# vim: set fileencoding= UTF-8
#!usr/bin/python
"""Word Spot
ENG: Enter string. Output. All world in order they came in, if any word have appired more then once, print index in (paranthesise)
input: qwe sdf tyu qwe sdf try sdf qwe sdf rty sdf wer sdf wer
output:qwe(7) sdf(12) ... | 1,097 | 385 |
load("@bazel_federation//:repositories.bzl", "bazel")
def skydoc_internal_deps():
bazel()
| 95 | 40 |
from .population_engine import PopulationEngine
from .simulation_day import SimulationDay
from .settings import SimfectionSettings
from .logger import SimfectionLogger
from .path import SimfectionPath
from .arguments import _get_parser, simfection_args
import pickle
import time
import os
simfection_logger = Simfectio... | 3,346 | 942 |
# Logger
import logging
import os
LOG_FILE_NAME = 'faro-community.log'
LOG_LEVEL = os.getenv('FARO_LOG_LEVEL', "INFO")
logging.basicConfig(
level=LOG_LEVEL,
format="%(levelname)s: %(name)20s: %(message)s",
handlers=[logging.StreamHandler()]
) | 272 | 104 |
from abc import ABC, abstractmethod
from multiprocessing import Value
from numpy.core.multiarray import ndarray
from yaaf import Timestep
from yaaf import mkdir, isdir
from yaaf.policies import action_from_policy
class Agent(ABC):
"""
Base agent class.
Represents the concept of an autonomous agent.
... | 4,764 | 1,228 |
import os
from functools import partial
import check_manifest
from .base import Tool, Issue
IGNORE_MSGS = (
'lists of files in version control and sdist match',
)
class CheckManifestIssue(Issue):
tool = 'manifest'
pylint_type = 'W'
class CheckManifestTool(Tool):
"""
Uses the check-manifest... | 1,694 | 487 |
from string import ascii_lowercase
class Solution:
def freqAlphabets(self, s: str) -> str:
keys = [str(i) for i in range(1,10)] + [str(i)+'#' for i in range(10,27)]
values = ascii_lowercase
mapping = dict(zip(keys, values))
ans = []
if len(s) == 1: return mapping[s]
i... | 619 | 214 |
from os import system, name
from time import sleep
from RhythmPy.internal.constants import *
from RhythmPy.parser import Parser
class Interface:
def __init__(self, symbol: str = ">"):
self.symbol = symbol
def prompt(self):
print(f"{self.symbol}", end=" ")
def welcome_menu(self):
... | 1,362 | 390 |
from .interactive import *
from visuals.cube import *
from display import *
import random
def parse_colour(input):
parts = input.split(',')
if len(parts) != 3:
return None
return Colour((int(parts[0]), int(parts[1]), int(parts[2])))
def parse_input(input):
lines = input.split('|')
if len(lines) != SIZE:... | 1,229 | 424 |
from .dataprep import Generator, GeneratorFeatExtraction, make_gen_callable
from .template_models import cnn_classifier, autoencoder_denoise, resnet50_classifier, \
cnnlstm_classifier
from .modelsetup import setup_callbacks, setup_layers
from . import plot
from . import builtin
from .builtin import denoiser_train, ... | 900 | 303 |
__version__ = "0.1.0a0"
from pgquery.builder.actor import BuildingActor
from pgquery.builder.impl.column import Integer, Serial, Text, Varchar
from pgquery.builder.impl.literal import literal
from pgquery.builder.impl.table import Table
| 238 | 72 |
import sys,os
from django.core.management.base import BaseCommand, CommandError
from cdadmap.models import *
import csv
"""
Loads original CDAD data from CSV
"""
class Command(BaseCommand):
def load_data_contact(self):
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file... | 13,509 | 3,759 |
# Copyright © 2021 Adam Kovacs <adaam.ko@gmail.com>
# Distributed under terms of the MIT license.
from ply import lex
from ply.lex import TOKEN
import ply.yacc as yacc
import sys
import getopt
import argparse
import os
import re
BINARIES = []
with open(os.path.join(os.path.dirname(os.path.realpath(__fi... | 13,585 | 4,924 |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | 8,929 | 3,043 |
"""
Contains the webhook handler class
containing the handlers required
to process payments from stripe
"""
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django... | 3,928 | 1,099 |
import unittest
from datetime import date, datetime
from decimal import Decimal
from try_parse.utils import ParseUtils
class Tests(unittest.TestCase):
def test_try_parse_date(self):
status, target = ParseUtils.try_parse_date('2018-11-23')
self.assertTrue(status)
self.assertIsInstance(targ... | 3,003 | 1,002 |
from typing import Any, List, Literal, TypedDict
from .FHIR_boolean import FHIR_boolean
from .FHIR_Element import FHIR_Element
from .FHIR_ExampleScenario_ContainedInstance import (
FHIR_ExampleScenario_ContainedInstance,
)
from .FHIR_markdown import FHIR_markdown
from .FHIR_string import FHIR_string
# Example of ... | 3,432 | 871 |
from django.shortcuts import render, render_to_response, redirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect,... | 34,694 | 9,812 |
import os
from dirs import PROJECT_ROOT
logs_folder = PROJECT_ROOT / "logs"
os.makedirs(logs_folder, exist_ok=True)
DICT_CONFIG = {
"version": 1,
"formatters": {"standard": {"format": "%(asctime)s %(name)-8s %(levelname)-8s %(message)s"}},
"handlers": {
"stderr": {"class": "logging.StreamHandler"... | 1,042 | 334 |
__author__ = 'Anowar J. Shajib'
__email__ = 'ajshajib@gmail.com'
__version__ = '0.0.0'
from .coloripy import MshColorMap, get_msh_cmap, skew_scale | 147 | 67 |
######################################
## save_and_check_Phase1.py ##
## Marika Asgari ##
## Version 2020.04.21 ##
######################################
# This is based on Linc's save_and_check_twopoint.
# It has been adapted to make .fits files for the P... | 22,186 | 8,649 |
from .scheduler import ray_dask_get, ray_dask_get_sync
from .callbacks import (
RayDaskCallback,
local_ray_callbacks,
unpack_ray_callbacks,
)
__all__ = [
"ray_dask_get",
"ray_dask_get_sync",
"RayDaskCallback",
"local_ray_callbacks",
"unpack_ray_callbacks",
]
| 292 | 118 |
from . import activations
from . import initializers
from . import layers
from . import models
from .models.model_registry import list_models, load_model
| 154 | 40 |
import datetime
import unittest.mock as mock
real_datetime_class = datetime.datetime
def mock_datetime_now(target: real_datetime_class, datetime_module):
"""
Override ``datetime.datetime.now()`` with a custom target value.
This creates a new datetime.datetime class, and alters its now()/utcnow()
meth... | 1,284 | 373 |
# Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, 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 applicabl... | 4,077 | 1,233 |
from __future__ import print_function
import datetime
import os
import shutil
import subprocess
import sys
from os.path import join
try:
from click.termui import secho
except ImportError:
warn = note = print
else:
def warn(text):
for line in text.splitlines():
secho(line, fg="white", b... | 5,269 | 1,483 |
import torch
from torch import nn as nn
from torch.autograd import Variable
from torch.nn import functional as F
from railrl.pythonplusplus import identity
from railrl.torch import pytorch_util as ptu
from railrl.torch.core import PyTorchModule
from railrl.torch.rnn import BNLSTMCell, LSTM
class FeedForwardDuelingQF... | 10,112 | 3,439 |
import pandas as pd
from database_construction import insert_information
from Database_creator import create_database
from Database_creator import create_table
from config import CSV_PATH
def add_from_database(csv_file_path):
df = pd.read_csv(csv_file_path)
for i in range(len(df)):
print(df.loc[i])
... | 629 | 206 |
import turtle
import time
def drawKochSide(length, level):
if (level == 1):
turtle.forward(length)
else:
drawKochSide(length/3, level-1)
turtle.left(60)
drawKochSide(length/3, level-1)
turtle.right(120)
drawKochSide(length/3, level-1)
turtle.... | 927 | 404 |
import requests
import json
import sys
import matplotlib.pyplot as plt
# get count
url = 'http://localhost:5000/count'
headers = {'content-type': 'application/json'}
response = requests.get(url, headers=headers)
print('number of items in summary: ',int(response.content))
# get summary
url = 'http://localhost:5000/s... | 1,112 | 378 |
import pylext
from pylext import exec_macros
def test_exception():
res = 0
try:
exec_macros("""
def f(x)):
return
""", {})
except SyntaxError as err:
res = 1
assert res == 1
def test_simple_import():
import macros.romb_import as m
res = m.run_test(len(m.validation)-1)
... | 620 | 238 |
import tempfile
import shutil
from unittest import TestCase
from unittest import mock
from lineflow import download
from lineflow.datasets.cnn_dailymail import CnnDailymail, get_cnn_dailymail
class CnnDailymailTestCase(TestCase):
def setUp(self):
self.default_cache_root = download.get_cache_root()
... | 1,881 | 665 |
from tests.test_actions import *
from ltk import actions
from io import StringIO
import unittest
class TestConfig(unittest.TestCase):
def setUp(self):
create_config()
self.action = actions.Action(os.getcwd())
def tearDown(self):
cleanup()
self.action.close()
def test_conf... | 2,187 | 701 |
"""This script tests whether matmul or einsum is faster at multipliying a collection of matrices with a another
collection (same length) of matrices of the same dimension. In biomechanics this operation is used when expressing
a segment in the coordinate system of its proximal segment.
"""
import numpy as np
import ... | 1,842 | 734 |
'''
note: pypdf2 is a pdf manipulation library,
we will read, extract text, count pages etc. different
works can be done using pypdf2. this is a simple project
where we will do the followings:
1. extract text from a pdf
2. pass the text into pyttsx3
3. read it
that is how we will make our own audiobook.
'''
import PyP... | 819 | 283 |
# Copyright © 2019, Massachusetts Institute of Technology
#
# 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 ... | 2,257 | 779 |
# richard -- video index system
# Copyright (C) 2012, 2013, 2014, 2015 richard contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | 2,375 | 753 |
# -*- coding: utf-8 -*-
import os
import math
import unittest
import tempfile
from buffalo.misc import aux
from buffalo.data.mm import MatrixMarket, MatrixMarketOptions
class TestPrepro(unittest.TestCase):
@classmethod
def setUpClass(cls):
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f... | 4,333 | 1,576 |
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
import secret_santa.config as config
import traceback
from secret_santa.response import ErrorException
class EmailSender():
def __init__(sel... | 2,095 | 603 |
"""
Data base to save and recall motor positions
Author: Friedrich Schotte
Date created: 2019-05-24
Date last modified: 2019-05-31
"""
__version__ = "1.3" # monitor
from logging import debug,info,warn,error
class Configuration_Property(property): pass
class Motor_Property(property): pass
from classproperty import cl... | 12,066 | 3,483 |
#!/usr/bin/env python3
import json
import os
import re
import subprocess
def run_in_dir(working_dir, cmdline):
old_working_dir = os.getcwd()
os.chdir(working_dir)
try:
completed = subprocess.run(cmdline, capture_output=True)
return completed.stdout.decode("utf-8")
finally:
os.ch... | 2,643 | 966 |
# Copyright 2017-2020 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" fil... | 9,287 | 2,525 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
__author__ = 'CodeFace'
"""
from enum import IntEnum
from PyQt5.QtCore import Qt, QPersistentModelIndex, QPoint
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QFont
from PyQt5.QtWidgets import QAbstractItemView, QMenu
from electrum.i18n import _
from ele... | 4,764 | 1,475 |
# -*- coding: utf-8 -*-
# Copyright © 2015 Tiger Computing Ltd
# This file is part of pytiger and distributed under the terms
# of a BSD-like license
# See the file COPYING for details
from __future__ import absolute_import
import logging
import logging.config
import os.path
import sys
import syslog
import textwrap
... | 6,726 | 2,182 |
import os, glob
from PIL import Image
# Creats dark icons
icon_folder = 'icons'
new_folder = 'dark_icons'
if not os.path.exists(new_folder):
os.mkdir(new_folder)
for icon in glob.glob(icon_folder + '/*.png'):
im = Image.open(icon)
icon_name = os.path.split(icon)[-1]
print(icon_name)
r, g, b, a = ... | 539 | 219 |
import requests
from lifedb import Config
# Documentation: https://www.rescuetime.com/anapi/setup/documentation
class RescueTime():
def __init__(self):
self.baseURL = 'https://www.rescuetime.com/anapi/data'
self.apiKey = Config().get('RESCUETIME_API_KEY')
print self.apiKey
def get(... | 517 | 161 |
import numpy as np
import matplotlib.pyplot as plt
from analysis.getdata import Wave
from analysis.tremor import Tremor
from analysis.earthquake import Event
a = Tremor(chn=4)
b = Wave()
index = 102
a_tremor = a.tremor[index]
data = []
a_tremor['station'].sort(key=lambda x: x[1], reverse=True)
print(a_tremor)
durati... | 1,244 | 531 |
import os
import sys
import random
import subprocess
import time
import turicreate as tc
####### Training
# Run app_image_classif_create.py first
######################
tracker='sudo /home/icalciu/ccfpga/peaberry/src/pbsim-ptrace/tracker'
######################
tc.config.set_runtime_config('TURI_DEFAULT_NUM_PYLAM... | 682 | 253 |
'''
People's Rectified [[T:Coord|Coordinates]]
@file Utils for inserting valid WGS-84 coords from GCJ-02/BD-09 input
@author User:Artoria2e5
@url https://github.com/Artoria2e5/PRCoords
@see [[:en:GCJ-02]]
@see https://github.com/caijun/geoChina (GPLv3)
@see https://github.com/googollee/eviltransform (MIT)
@see https:/... | 7,036 | 2,829 |
#!/usr/bin/env python3
# Author: Gilberto Agostinho <gilbertohasnofb@gmail.com>
# https://github.com/gilbertohasnofb/mosaic-generator
from PIL import Image, ImageDraw, ImageFont
import os
import random
def get_images(input_folder):
"""Reads input images
"""
source_images = []
if not input_folder.ends... | 2,527 | 773 |
from typing import Any, Protocol
from pydantic import BaseModel
from pydantic.fields import ModelField
from pydantic.fields import UndefinedType as _PydanticUndefinedType
from arti.internal.type_hints import lenient_issubclass
from arti.types import Struct, Type, TypeAdapter, TypeSystem, _ScalarClassTypeAdapter
from ... | 3,586 | 1,087 |
'''
NetPyNE version of Potjans and Diesmann thalamocortical network
cfg.py -- contains the simulation configuration (cfg object)
'''
from netpyne import specs
############################################################
#
# SIMULATION CONFIGURATION
#
#############################################... | 4,355 | 1,494 |
# hackerrank - Algorithms: Is Fibo
# Written by James Andreou, University of Waterloo
import math
def perfect_square(n):
r = math.sqrt(n)
return int(r + 0.5) ** 2 == n
T = int(raw_input())
for t in range(0, T):
N = int(raw_input())**2 * 5
if perfect_square(N+4) or perfect_square(N-4):
print 'IsFi... | 350 | 148 |
import torch
from torch import nn
from .testproblems_modules import net_wrn
from ..datasets.svhn import svhn
from .testproblem import TestProblem
class svhn_wrn164(TestProblem):
"""DeepOBS test problem class for the Wide Residual Network 16-4 architecture\
for SVHN.
Details about the architecture can be fo... | 2,523 | 806 |
import os
from joblib import load
from envs import envs
from utils import load_data
MODEL_DIR = envs['MODEL_DIR']
MODEL_FILE = envs['MODEL_FILE']
METADATA_FILE = envs['METADATA_FILE']
S3_BUCKET = envs['S3BUCKET']
MODEL_PATH = os.path.join(MODEL_DIR, MODEL_FILE)
METADATA_PATH = os.path.join(MODEL_DIR, METADATA_FILE)
S... | 976 | 372 |
from visual import *
from visual.graph import *
import wx
import os
import json
import request as r
version = '0.1a'
cor_ID = 26400
def translate(X,Y,Z):
t_x = X + 114.78125
t_y = Y - 80.71875
t_z = Z + 4.875
return (t_x,t_y,t_z)
# ---------- Request latest JSON digest from EliteBGS API ----------
folder = './da... | 3,045 | 1,276 |
from hashlib import sha224
import django
from django.http import HttpResponse
from oidc_provider import settings
if django.VERSION >= (1, 11):
from django.urls import reverse
else:
from django.core.urlresolvers import reverse
def redirect(uri):
"""
Custom Response object for redirecting to a Non-H... | 3,642 | 1,105 |
from lazylawyer.database import database as db
def write_appeals(appeals):
"""Stores all appeals reference to the database.
"""
db.batch_insert_check('appeals', appeals, attrs=['orig_case_id'])
| 213 | 70 |
#-- coding: utf-8 --
#@Time : 2021/3/21 15:33
#@Author : HUANG XUYANG
#@Email : xhuang032@e.ntu.edu.sg
#@File : LDA_Two_Classifier.py
#@Software: PyCharm
import numpy as np
import matplotlib.pyplot as plt
import sklearn.datasets as sk_dataset
class LDATwoClassifier:
"""A LDA two classifier
Only be used in... | 4,363 | 1,508 |
import sqlite3
conn = sqlite3.connect('Data.db')
c = conn.cursor()
class DataBase:
def __init__(self,username,uID,send):
self.username = username
self.uID = uID
self.send = send
@classmethod
def GetFromDB(self):
with conn:
c.execute("SELECT * FROM Users")
... | 1,505 | 457 |
from PowerScriptexec import run_code
from PowerScriptenv import Env
# Read & Open PowerScript files.
with open("examples/name.ps") as f:
code = f.read()
env = Env()
run_code(env, code)
| 192 | 70 |
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(Block, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNor... | 2,134 | 871 |
if '__file__' in globals():
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from lunchjet import GoogleDrive
import time
import tarfile
from argparse import ArgumentParser
import re
import pathlib
def unlink_files_in(dir_path):
for file in dir_path.glob('**/*'):
if f... | 2,165 | 686 |
import numpy as np
import math
height = 0.0
upper_arm_length = 0.334
forearm_length = 0.288
hand_length = 0.12
ee_location = np.matrix([0., -upper_arm_length-forearm_length-hand_length, height]).T
bod_color = [[0.4, 0.4, 0.4, 1], [0.8, 0.8, 0.8, 1], [0.33, 0.33, 0.33, 1]]
bod_num_links = 3
bod_mass = [2.3, 1.32, 0... | 1,688 | 830 |
from food import Food
def foraging_step(bee):
"""
This type of bee goes to a given food location and takes the food.
If the bee is loaded it returns to the hive.
"""
if bee.is_carrying_food:
bee.move_to_hive()
else:
bee.move(bee.food_location)
# Check if arrived, then ... | 842 | 274 |
from evaluation_framework.DocumentSimilarity.documentSimilarity_model import (
DocumentSimilarityModel,
)
from evaluation_framework.DocumentSimilarity.documentSimilarity_taskManager import (
DocumentSimilarityManager,
)
| 228 | 60 |
# The MIT License (MIT)
#
# Copyright (c) 2018-2022 Yury Gribov
#
# Use of this source code is governed by The MIT License (MIT)
# that can be found in the LICENSE.txt file.
"""Error handling APIs."""
import sys
import os.path
from typing import NoReturn
from gaplan.common.location import Location
_print_stack = ... | 1,447 | 522 |
from phns import Phn
from phns.utils import transcribe
def test_transcribe_simple_word():
transcriptions = transcribe.word("that^is")
assert transcriptions == {
(Phn("dh"), Phn("ae1"), Phn("t"), Phn("ih1"), Phn("z")): ["that", "is"],
(Phn("dh"), Phn("ae1"), Phn("t"), Phn("s")): ["that's"],
... | 403 | 159 |
from flask import json, jsonify, url_for
from tests.conftest import create_authorization_header
from app.comms.encryption import encrypt
from app.models import Member
from tests.db import create_member
class WhenGettingMembers:
def it_returns_all_members(self, client, db_session, sample_member):
member... | 5,041 | 1,532 |
import unittest
import os
import logging
from models.client import ClientDAO, Client
from models.db import DbDAO, DB
from models.insurance import InsuranceDAO, Insurance
from models.invoice import InvoiceDAO, Invoice
from models.profile import ProfileDAO, Profile
from models.quotation.quotation import QuotationDAO, Quo... | 22,426 | 7,427 |