text string | size int64 | token_count int64 |
|---|---|---|
class Directory:
SOLUTIONS = 'solutions'
CASES = 'cases'
BUILD = 'build'
TESS = '.tess'
DEBUG_SOLUTIONS = '.tess/debug/src'
DEBUG_BUILD = '.tess/debug/build'
CUSTOM_CONFIG_LINUX = '~/.config/tess'
CUSTOM_CONFIG_MAC = '~/Library/Application\\ Support/Tess'
@staticmethod
def init(... | 460 | 165 |
import os
import pandas as pd
import numpy as np
from io import StringIO
import config
import logging
import pandas as pd
import pymysql
from sqlalchemy import create_engine
class Data_Retreival:
def __init__(self):
self.code_complexity_query = 'SELECT Merge_Scenario_merge_commit_hash, measure1_diff, ... | 16,697 | 4,932 |
from pydantic import BaseModel
class A(BaseModel):
abc: str = '123'
def __init__(self):
pass
A()
class B(BaseModel):
abc: str = '123'
def __init__(self, a: float, b: int):
pass
B(abc='123'<warning descr="null">)</warning>
class C(BaseModel):
abc: str = '123'
def __init__(self... | 977 | 418 |
# coding=utf-8
"""Utility functions for gmusicapi_wrapper.
>>> import gmusicapi_wrapper.utils as gmw_utils
>>> from gmusicapi_wrapper.utils import ...
"""
import logging
import os
import re
import subprocess
import mutagen
from .constants import CHARACTER_REPLACEMENTS, CYGPATH_RE, TEMPLATE_PATTERNS
from .decorat... | 12,948 | 4,376 |
def asdjf ( l,
a):
3
+4
| 46 | 22 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2017 - Anil Lakhman - MIT License
# -----------------------------------------------------------------------------
from pygments.style import Style
from pygments.token import Keyw... | 4,402 | 1,765 |
'''
Author: geekli
Date: 2020-12-28 15:53:18
LastEditTime: 2020-12-28 15:53:19
LastEditors: your name
Description:
FilePath: \QA_MRC\preprocess\__init__.py
'''
| 161 | 88 |
# -*- coding: utf-8 -*-
from numpy import linspace
from ....Methods.Machine import LINE_NPOINT_D
from ....Methods.Geometry.Segment import NbPointSegmentDError
def discretize(self, nb_point=LINE_NPOINT_D):
"""Return the discretize version of the Segment.
Begin and end are always returned
Parameters
-... | 1,225 | 409 |
from model.transit import *
from gtfsdb import GTFSDatabase
import sys
from exporter.timetable3 import export
import exporter.timetable4
from datetime import timedelta, date
MAX_DAYS = 32
def put_gtfs_modes(tdata):
PhysicalMode(tdata,'0',name='Tram')
PhysicalMode(tdata,'1',name='Metro')
PhysicalMode(tdata... | 5,258 | 1,933 |
from flickrapi import FlickrAPI
import config
def get(tags):
flickr = FlickrAPI(config.FLICKR_PUBLIC, config.FLICKR_SECRET, format='parsed-json')
rnd = 1
raw = flickr.photos.search(tags=tags[0:1], text=tags[1], tag_node='all', per_page=rnd, extras=config.extras)
return raw['photos']['photo'][rnd - 1][... | 329 | 139 |
from pyecharts import options as opts
from pyecharts.charts import Bar, Grid, Line
x_data = ["{}月".format(i) for i in range(1, 13)]
bar = (
Bar()
.add_xaxis(x_data)
.add_yaxis(
"蒸发量",
[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
yaxis_index=0,
color... | 2,340 | 978 |
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.core.text import LabelBase
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager
from ketchuporo.const import Files
from ketchuporo.controllers import (
BreakScreen,
BreaksOverScreen,
PomodorosOverScreen,
SettingsScree... | 1,128 | 367 |
from output.models.ms_data.particles.particles_b010_xsd.particles_b010 import (
Doc,
Elem,
)
__all__ = [
"Doc",
"Elem",
]
| 139 | 64 |
# 読書計画用スニペット
from datetime import date
def reading_plan(title, total_number_of_pages, period):
current_page = int(input("Current page?: "))
deadline = (date(int(period[0]), int(period[1]),
int(period[2])) - date.today()).days
print(title, period, "まで残り", deadline, "days",
(t... | 379 | 137 |
# Copyright 2014: Mirantis Inc.
# 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. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | 6,144 | 1,726 |
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.federalreserve.gov/monetarypolicy/discountrate.htm")
bsObj = BeautifulSoup(html.read(), "lxml")
d1 = bsObj.findAll("option")
urls = []
for item in d1:
if "PDF" in str(item.get_text()):
prefix = "http://ww... | 603 | 228 |
import random
import matplotlib
from matplotlib import pyplot as plt
# 显示中文
# Windows/Linus
font = {'family' : 'MicroSoft Yahei', 'weight': 'bold', 'size': '9'}
matplotlib.rc("font", **font)
# 设置图片 大小 20x8
fig = plt.figure(figsize=(20, 8), dpi=80)
y = [random.randint(20, 35) for i in range(120)]
x = range(120)
plt.... | 644 | 341 |
import unittest
import time
from unittest.mock import Mock
from pyats.topology import Device
from genie.metaparser.util.exceptions import SchemaEmptyParserError,\
SchemaMissingKeyError
from genie.libs.parser.sros.show_isis import ShowRouterIsisAdjacency,\
... | 13,846 | 4,036 |
from sys import exit
import argparse
ALL_ARGS = None
# found a free server to execute blindly, will update with CRON if need be
def sanity():
if ALL_ARGS.hour > 23 or ALL_ARGS.hour < 0:
print('Error in hour provided, must be >= 0 and <= 23')
exit(0)
if ALL_ARGS.min > 59 or ALL_ARGS.min < 0:... | 935 | 327 |
import numpy as np
import os
import pickle
import random
from algorithms import model as model_algorithm
from utils import data_paths
def test_model_can_create_instance_with_no_arguments():
model_algorithm.Model()
def test_model_load_creates_the_expected_instance():
model = model_algorithm.Model()
mode... | 1,846 | 574 |
from tests.test_base import TestBase
from pathlib import Path
from xd_cwl_utils.helpers.get_paths import get_tool_metadata
from xd_cwl_utils.validate import metadata_validator_factory
from xd_cwl_utils.classes.metadata.tool_metadata import ParentToolMetadata, SubtoolMetadata
class TestValidateMetadata(TestBase):
... | 2,296 | 680 |
import discord
class Alert(discord.Embed):
alert_types = {
"error": "<:error:807799799721230347>",
}
def __init__(self, alert_type, title: str, description: str = discord.Embed.Empty):
super().__init__(
color=discord.Color.blurple(),
title=self.process_title(alert... | 533 | 182 |
from model.project import Project
class ProjectHelper:
def __init__(self, app):
self.app = app
def open_project_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("/manage_proj_create_page.php")):
wd.find_element_by_xpath("//div[@id='main-container']/div[@id='side... | 2,616 | 876 |
#!/usr/bin/env python3
# By Icarus747
# Created 10/11/2020
# Used for converting DCS MGRS grid coordinates to Lat/Long coordinates.
import mgrs
import re
def main():
m = mgrs.MGRS()
# dcs = '38TLN046623'
dcs = input("Enter MGRS cord.\n\r")
dcs = validate_mgrs(dcs)
dd = m.toLatLon(dcs)
lat =... | 773 | 362 |
def test_to_be_removed():
pass
| 35 | 15 |
from django.core.management.base import BaseCommand
from backend.file_manager import build_file_structure
class Command(BaseCommand):
help = 'Sets entry folder to given file path.'
def add_arguments(self, parser):
parser.add_argument('folder', type=str, help='Path to entry folder')
def handle(se... | 637 | 172 |
from math import *
N = 8
V = 4
Z = 2
C = 1
wordSign = 1 << 11
wordMask = (1 << 12) - 1
byteSign = 1 << 7
byteMask = (1 << 8) - 1
def adder(op, a, b, cin, siz=False):
if siz:
sign = wordSign
mask = wordMask
else:
sign = byteSign
mask = byteMask
auL = mask & a
if op == ... | 2,149 | 1,024 |
import numpy as np
import pickle
import os
import glob
import torch
def string_to_num(z_size_data):
z_size_data = str(z_size_data)
z_size_data = [float(i) for i in z_size_data.split(',')]
z_size_data = torch.tensor(z_size_data)
print("Inside Util")
return z_size_data.deta... | 324 | 127 |
from optimism.JaxConfig import *
from optimism import Mesh
from optimism import QuadratureRule
from optimism import Surface
import numpy as onp
def get_current_coordinates_at_quadrature_points(mesh, dispField, quadRule, edge):
fieldIndex = Surface.get_field_index(edge, mesh.conns)
edgeCoords = Surface.ev... | 2,289 | 796 |
import torch
from torch.nn import ParameterList, Parameter
class Elmo(torch.nn.Module):
"""
Computes a parameterised scalar mixture of N tensors, `mixture = gamma * sum(s_k * tensor_k)`
where `s = softmax(w)`, with `w` and `gamma` scalar parameters.
In addition, if `do_layer_norm=True` then apply laye... | 1,970 | 586 |
import smtplib
from email.message import EmailMessage
from os import environ
from time import sleep
from datetime import datetime
"""envio um alerta sobre atualização do relatório
para pessoas próximas, utilizando um gmail bot"""
enderecos_de_usuarios = environ.get("ADRESS_USERS")
emails = enderecos_de_usuarios.spli... | 1,035 | 386 |
from .container import CodeContainer
from .game import Game, GameConstants
from .basicviewer import BasicViewer
| 112 | 27 |
"""
Base classes for USD variants. It's written on Python to be
able to use complex UI and PySide.
"""
# Copyright 2017 Rodeo FX. All rights reserved.
import json
from .Qt import QtWidgets
from walterComplexMenu import ComplexMenu
class VariantSet():
"""Per variantset variants list."""
def __init__(self, na... | 5,082 | 1,399 |
import matplotlib.pyplot as plt
import mahotas
photo = mahotas.demos.load('luispedro')
photo = mahotas.colors.rgb2sepia(photo)
plt.imshow(photo)
plt.axis('off')
plt.show()
| 173 | 71 |
import subprocess
import av
import numpy as np
from av.audio.frame import format_dtypes
from typing import Dict, Generator, Tuple
from logging import Logger
from pathlib import Path
from enum import Enum, auto
from speechless.utils.logging import NULL_LOGGER
class StreamInfo(Enum):
SAMPLE_RATE = auto()
FRAME_SI... | 4,983 | 1,515 |
from kivy.core.audio import SoundLoader
class MultiSound(object): # for playing the same sound multiple times.
def __init__(self, file, num):
self.num = num
self.sounds = [SoundLoader.load(file) for n in range(num)]
self.index = 0
def play(self):
self.sounds[self.index]... | 413 | 127 |
from numpy import genfromtxt
from os.path import join, realpath, dirname
ORANGE_PATH = join(dirname(realpath(__file__)), "orange")
def load_ionosphere(n=None):
"""
Load the ionosphere dataset.
:param n: Maximum number of examples.
:return: Dataset in standard form.
"""
header = genfromtxt(join... | 810 | 279 |
#!/usr/bin/python
"""
Invocation: scripts/initialize_instance .py -t|--type[=] default|demo|test
-r|--heroku[=] <heroku_app>
Use this script to create an instance with different types of configuration:
[default]: includes the basic configuration. The admin needs to creat... | 2,524 | 807 |
#!/usr/bin/env python
print 'Content-type: text/html\n'
from os.path import join, abspath
import cgi, sys
BASE_DIR = abspath('data')
form = cgi.FieldStorage()
filename = form.getvalue('filename')
if not filename:
print 'Please enter a file name'
sys.exit()
text = open(join(BASE_DIR, filename)).read()
print... | 799 | 292 |
# Sean Warlick
# Seattle Housing Project
# XML Parsing Functions
# Date: July 12, 2016
###############################################################################
# Import packages
import xml.etree.ElementTree as et
def location_parse(xml_string):
# Convert the data returned from api to XML
xml_element = et.fro... | 2,608 | 896 |
T = int (raw_input ())
while T :
X, Y = map (long, raw_input ().split ())
T -= 1
neg_X = -X
neg_Y = -Y
if X == 0 and Y == 0 :
print "YES"
elif X < 0 and not (X & 1) and X <= Y and Y <= neg_X :
print "YES"
elif X > 0 and X & 1 and (1 - X) <= Y and Y <= (X + 1) :
print "YES"
elif Y > 0 and not (Y & 1) and... | 462 | 235 |
import pygame
import warnings
from typing import Union, List, Tuple
from .. import ui_manager
from ..core import ui_container
from ..core.ui_element import UIElement
from ..elements.ui_button import UIButton
class UIHorizontalSlider(UIElement):
"""
A horizontal slider is intended to help users adjust values ... | 11,009 | 2,991 |
print("Very well, you can run Python scripts from a Python script.")
input() | 76 | 20 |
from datetime import datetime
import logging
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse, JsonResponse
from django.utils.encoding import force_text
from django.utils.functional import Promise
from django.utils.translation import ugettext as _
from django.utils.cache ... | 2,614 | 740 |
import re
from os import path
def preprocess_file(class_name='MyClass', file_name=None, property_name=None):
if file_name is None:
file_name = class_name.lower() + '.py'
found = [False] * 3
class_info = {
'name': class_name,
'definition': 'class {}:'.format(class_name)
}
if path.exists(fil... | 2,193 | 804 |
#!/usr/bin/python3
# -*- encoding="UTF-8" -*-
#Import Package
import numpy as np
from tkinter.messagebox import *
import parameters
from Functions.string2num import string2num
def getOutTitleDC():
if len(parameters.listDCParam) == 1:
paramName = parameters.listDCParam[0].paramName
WriteString = ... | 28,087 | 8,429 |
import kilojoule.humidair
import kilojoule.realfluid
import kilojoule.idealgas as idealgas
from kilojoule.organization import QuantityTable
from kilojoule.display import Calculations, Summary
from kilojoule.units import units, Quantity
import kilojoule.magics
humidair = kilojoule.humidair.Properties(unit_syste... | 2,086 | 722 |
"""
"""
from sty import RgbFg, Style, ef, fg
from tests import demo, test_ansi_values # isort:skip
from tests.docs import ( # isort:skip
getting_started,
effects,
coloring,
customizing,
muting,
etc,
)
| 229 | 87 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals # for python2 compatibility
from __future__ import division
from __future__ import absolute_import
# created at UC Berkeley 2015
# Authors: Christopher Hench
# This program scans MHG epic poetry, returning data to analyze statistically
import codecs
im... | 7,640 | 2,582 |
# -*- coding: utf-8 -*-
#######################
'''For each energy step, a projection and then a flat field are
acquired. The script calls the move_energy method from the TXM class.
'''
import time
import os
import logging
import warnings
import numpy as np
import h5py
import tqdm
from scanlib.scan_variables import... | 12,084 | 3,813 |
from contextlib import closing
import sqlite3
def query(db_name, sql):
with closing(sqlite3.connect(db_name)) as con, con, \
closing(con.cursor()) as cur:
cur.execute(sql)
print(cur.fetchall())
if __name__ == '__main__':
query("IMDB.db","""SELECT * FROM title_basics LIMIT 200""")
| 308 | 110 |
import tkinter
import tkinter.font
from scripts import General, Parameters, Constants
from scripts.frontend.custom_widgets.CustomLabels import InformationLabel
from scripts.frontend.custom_widgets.WidgetInterface import WidgetInterface
TITLE_FONT_SIZE = 8
class Frame(tkinter.Frame, WidgetInterface):
def __init... | 4,551 | 1,466 |
# 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 applicable law or agreed to... | 2,320 | 787 |
from django import forms
class ModelTestForm(forms.Form):
text = forms.CharField()
| 89 | 26 |
from uuid import uuid4
from sentry.runner import configure
configure()
from clims.models import *
from clims.services import *
from sentry.models import *
from sentry.testutils.fixtures import Fixtures
app = ApplicationService()
ioc.set_application(app)
notebook_plugin, _ = PluginRegistration.objects.get_or_create(
... | 440 | 144 |
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.dates as mdates
from db import DatabaseConnection
from datetime import datetime, timedelta
class Charts:
def __init__(self, db: DatabaseConnection):
self._db = db
# get pie chart of the total cases by continent and ... | 2,747 | 937 |
import binascii
import pytest
from unittest import mock
from mitmproxy import exceptions
from mitmproxy.addons import proxyauth
from mitmproxy.test import taddons
from mitmproxy.test import tflow
from mitmproxy.test import tutils
class TestMkauth:
def test_mkauth_scheme(self):
assert proxyauth.mkauth('u... | 9,452 | 2,781 |
import dataclasses
__all__ = ["ElakshiTrack", "AudioSource"]
@dataclasses.dataclass(frozen=True)
class ElakshiTrack:
eid: str
@dataclasses.dataclass(frozen=True)
class AudioSource:
source: str
identifier: str
uri: str
start_offset: float
end_offset: float
is_live: bool
| 303 | 109 |
"""Randomized LU decomposition."""
import numpy as np
import scipy.linalg as la
from typing import Tuple
PQLU = Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]
def randomized_lu(A: np.ndarray, k: int, l: int, seed: int = 0) -> PQLU:
"""Performs a randomized rank-k LU decomposition of A.
Adapted fr... | 2,340 | 952 |
"""Constants for the HTML5 component."""
DOMAIN = "html5"
SERVICE_DISMISS = "dismiss"
| 86 | 31 |
import torch
import torch.nn as nn
class G(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64):
super(G, self).__init__()
# 128 x 128
self.conv1 = nn.Conv2d(input_nc, ngf, 4, 2, 1)
# 64 x 64 x1
self.conv2 = nn.Conv2d(ngf, ngf*2, 4, 2, 1)
# 32 x 32 x 2
... | 4,045 | 1,845 |
"""
Slotter
Slotter is used to slot elements in buckets
"""
from .version import __version__
__title__ = 'slotter'
__author__ = 'Saurabh Hirani'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 Saurabh Hirani'
from .slotter import Slotter
create = Slotter
| 264 | 104 |
from ..utils import Object
class ChatTypeSupergroup(Object):
"""
A supergroup (i.e. a chat with up to GetOption("supergroup_max_size") other users), or channel (with unlimited members)
Attributes:
ID (:obj:`str`): ``ChatTypeSupergroup``
Args:
supergroup_id (:obj:`int`):
... | 941 | 299 |
import os
import sys
import logging
from typing import Dict
from concurrent_log_handler import ConcurrentRotatingFileHandler
LOG_NAME: str = "service.log"
LOG_LEVEL_INT: int = 20
formatter_dict = {
1: logging.Formatter(
"日志时间【%(asctime)s】 - 日志名称【%(name)s】 - 文件【%(filename)s】 - "
"第【%(lineno)d】行 -... | 12,370 | 4,491 |
import json
import csv
import os
data = {}
line_count = 0
data['rules'] = []
def writeJSON():
with open('automated_json.json', 'w') as outfile:
json.dump(data, outfile)
def createJSON(csvfile,action):
global line_count
with open(csvfile) as file:
csv_reader = csv.reader(fi... | 1,945 | 568 |
from django.db.models import Q
import functools
import operator
def search_filtered_queryset(base_queryset, search_fields, search_value):
filters = []
for key, value in search_fields.items():
field_filter = key
if value != 'equal':
field_filter = field_filter + '__' + value
... | 502 | 148 |
#refer to http://blog.sipeed.com/p/677.html
import sensor,image,lcd,time
import KPU as kpu
lcd.init(freq=15000000)
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_vflip(1)
sensor.run(1)
clock = time.clock()
classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bu... | 1,103 | 519 |
"""
.. todo::
doc
"""
__all__ = [
# "BertModel",
"ConvolutionCharEncoder",
"LSTMCharEncoder",
"ConvMaxpool",
"LSTM",
"StarTransformer",
"TransformerEncoder",
"VarRNN",
"VarLSTM",
"VarGRU",
"MaxPool",
"MaxPoolWithMask",
"AvgPool",
"AvgPoolWithMask",
... | 759 | 271 |
#!/usr/bin/python
# DupLess is a python script to detect and remove artifact duplications in assemblies.
# Assemblies from heterozygous genomes tend to create two contigs instead of
# one in areas of high heterozygosity. DupLess detects these regions based on
# read coverage and sequence similarity.
# Depend... | 14,393 | 4,308 |
import cv2
import numpy as np
import time
import math
import serial
import pickle
LASER_START = (100,100)
arduino = serial.Serial('COM6', 9600, timeout=5)
def clear_leds():
# turn off all leds
data = bytes("C0,0\r\n", "utf8")
arduino.write(data) # write increment to serial port
... | 6,889 | 2,518 |
# todo keras/tesnorflow memory problem when search over network parameters
# currently just deleting EVERY model and retraining the best parameters
# at the end, see **1
__author__ = "Aaron Bostrom, James Large"
import gc
import numpy as np
from sklearn.model_selection import train_test_split
from tensorfl... | 22,984 | 7,106 |
# coffer
# Dataset manager and collection application.
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Thu Oct 08 21:44:00 2015 -0400
#
# Copyright (C) 2015 District Data Labs
# For license information, see LICENSE.txt
#
# ID: __init__.py [] benjamin@bengfort.com $
"""
Dataset manager and ... | 728 | 193 |
# Copy to .venv/lib/python3.6/site-packages/enchant/share/enchant/myspell
# https://github.com/elastic/hunspell/tree/master/dicts/pl
| 133 | 55 |
# -*- coding: utf-8 -*-
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import init
import copy
class fullBGM(torch.nn.Module):
def __init__(self):
super(fullBGM, self).__init__()
self.feat_dim = 2048
self.batch_size = 1
self.c_hidden = 256
s... | 3,280 | 1,251 |
def merge_the_tools(string, k):
substrings = int(len(string)/k)
size_substring = int(len(string)/substrings)
count = 0
frequency = {}
word = ""
for value in string:
count += 1
if not value in frequency:
word += value
frequency[value] = True
... | 508 | 152 |
#!/usr/bin/env python3
import argparse
from collections import Callable
from utils.command import Command
from utils.commands.preprocess import Preprocess
from utils.commands.test import Test
from utils.commands.train import Train
from utils.commands.repair import Repair
from utils.commands.stats import Stats
from ut... | 1,915 | 549 |
import logging
import numpy as np
import cv2
from lanefinder.params import camera_params
from lanefinder.params import perspective_params
# Capture camera model
# 1. calibrate using a set of images of chessboards
# 2. undistort image based on calibration
# 3. warp image to get a bird's eye view of it
class CamModel:... | 3,884 | 1,135 |
import math
import kivy
from kivy.graphics import Line
from kivy.graphics import Color
from kivy.properties import ListProperty, NumericProperty
from kivy.uix.widget import Widget
from kivy.logger import Logger
kivy.require('1.10.0')
class HexTile(Widget):
corners = ListProperty()
sides = ListProperty()
... | 4,446 | 1,450 |
import os
from pathlib import Path
def pytest_generate_tests(metafunc):
"""Source the test environment
"""
for line in open(Path(__file__).absolute().parent.parent / ".env-test"):
k, v = line.split("=", 1)
k = k.strip()
if not os.environ.get(k):
os.environ[k] = v.strip(... | 322 | 106 |
#! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Osman Baskaya"
"""
Split the keys according to target words. Our gold file is merged.
All keys are in the same file. In order to create a development set
in run/gold/twitter|gigaword, we need to split keys in dev set
into separate files.
input_file should be... | 816 | 299 |
from flask_apispec import MethodResource
from flask_apispec import doc
from flask_restful import Resource
from queue import Queue
from flask_jwt_extended import jwt_required
from decorator.catch_exception import catch_exception
from decorator.verify_admin_access import verify_admin_access
class AddWorker(MethodResou... | 857 | 252 |
#! /home/admin/venvs/hcr-2016/bin/python
import sys
print '\n'.join(sys.path)
import naoqi
if __name__ == '__main__':
print "Naoqi Test"
| 139 | 63 |
from tinydb import TinyDB, Query, where
from tinydb.operations import delete, add, set
# import json
from pymongo import MongoClient, ReplaceOne
from bson import json_util, objectid
from pymongo.errors import BulkWriteError
import time
import pprint
class TripDB:
database = None
def __init__(self):
self... | 1,463 | 435 |
from django.core.mail import EmailMessage
from celery.decorators import task
from django.conf import settings
import base64
@task(name='send_email_task')
def send_email_task(email, name):
email_value = email.split('@')[0].encode('utf-8') # 사용자 인증 url로 이메일의 @ 앞부분을 base64 기반으로 인코딩
encoded_email = base6... | 940 | 512 |
# -*- coding: utf-8 -*-
import os
import six
import time
from tests.integration import TestsBase, s3_tests, dynamodb_tests
WRONG_CONTENT_TYPE = 'nasty type'
VALID_KML = '''<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Simple placemark</name>
<descrip... | 11,403 | 4,615 |
import os
import warnings
import numpy as np
import pandas as pd
from .utils import classname_sorted, match_count
class Board(object):
def __init__(self, match_count, keys=None):
"""Initialize match display board.
Args:
match_count (int): Number of matches.
keys (list[st... | 5,703 | 1,689 |
from .pessoa_tests import *
from .unidadeorganizacional_tests import *
| 71 | 23 |
# Generated by Django 2.2.5 on 2019-09-29 21:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('spider_base', '0008_auto_20190817_1815'),
]
operations = [
migrations.AlterField(
model_name='assignedprotection',
n... | 521 | 185 |
__all__ = []
from .rbig import *
from .feature_map import *
from . import rbig
from . import feature_map
__all__ += rbig.__all__
__all__ += feature_map.__all__
del rbig
del feature_map
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester | 283 | 100 |
# 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
#
#
#
# 示例 1:
#
# 输入: [10,2]
# 输出: "102"
# 示例 2:
#
# 输入: [3,30,34,5,9]
# 输出: "3033459"
#
#
# 提示:
#
# 0 < nums.length <= 100
# 说明:
#
# 输出结果可能非常大,所以你需要返回一个字符串而不是整数
# 拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-c... | 641 | 462 |
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details
import base64
import re
import uuid
import os
import os.path
from datetime import datetime
try:
import xml.etree.cElementTree as etree
except ImportError:
from xml.etree.elementtree import ElementTree as etree
import ujson as jso... | 92,549 | 25,512 |
from EasyParser import EasyParser
import re
import datetime
# exe date
# ---
# current date is: 2018-08-01
# exe time
# ---
# current time is: 15:05:43
# last ntp sync:Wed Aug 1 14:58:13 2018
class TZoffset(datetime.tzinfo):
def __init__(self, seconds_from_utc, name):
self.offset = seconds_from_utc
self.name ... | 5,076 | 2,079 |
sys_OS = "A_Free_Cart"
Website = "Afreecart"
My_Name = "Samar_Kant_Saxena"
#A free cart budget calculator
#Budget = "370000"
#Expenditure = "70000"
| 152 | 78 |
import logging
import subprocess
from pathlib import Path
import hydra # type: ignore
from omegaconf import DictConfig
logger = logging.getLogger(__name__)
initialized = False
@hydra.main(config_path="conf/", config_name="ax") # type: ignore
def main(cfg: DictConfig) -> float:
field_wt_list = [f"{k[:-3]}:{v}... | 1,367 | 546 |
class Solution:
"""
@param inputA: Input stream A
@param inputB: Input stream B
@return: The answer
"""
def inputStream(self, inputA, inputB):
resA = ""
resB = ""
for a in inputA:
if a == '<':
resA = resA[:-1]
else:
... | 530 | 156 |
"""
@Time : 202/20/19 09:41
@Author : TaylorMei
@Email : mhy845879017@gmail.com
@Project : iccv
@File : compute_contrast.py
@Function:
"""
import os
import numpy as np
import cv2
import skimage.io
from misc import data_write
# image_path = '/home/iccd/data/2019/msd9_all/all_images/'
# mask_path = '/... | 2,127 | 1,023 |
from datetime import datetime
from angular_flask.core import db
from angular_flask import app
import json
# class Post(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# title = db.Column(db.String(80))
# body = db.Column(db.Text)
# pub_date = db.Column(db.DateTime)
#
# def __init__(self,... | 13,352 | 4,098 |
# encoding=utf-8
"""
create by pymu
on 2021/6/6
at 2:09
"""
from sherry.inherit.component import Component
class BaseBar(Component):
bar_normal = None # 自定义标题栏的最大化最小化及关闭按钮
bar_close = None
bar_mini = None
def __init__(self, master, *args, **kwargs):
super().__init__(master, *arg... | 3,108 | 1,159 |
#!/usr/bin/python3
import sys
import os
if len(sys.argv) < 3:
print("Usage: {} SRC_DIR DST_DIR".format(str(sys.argv[0])))
exit(1)
SRC_DIR = str(sys.argv[1])
DST_DIR = str(sys.argv[2])
if not os.path.isdir(SRC_DIR) or not os.path.isdir(DST_DIR):
print("Usage: {} SRC_DIR DST_DIR".format(str(sys.argv[0])))... | 333 | 154 |
# Copyright (c) 2007 Mikeal Rogers
#
# 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 agre... | 3,970 | 1,156 |