content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""
Tatoeba (https://tatoeba.org/) is a collection of sentences and translation, mainly aiming for language learning.
It is available for more than 300 languages.
This script downloads the Tatoeba corpus and extracts the sentences & translations in the languages you like
"""
import os
import sentence_transformers
impo... | python |
from django.test import TestCase
from unittest2 import skipIf
from django.db import connection
import json
import re
from sqlshare_rest.util.db import get_backend
from sqlshare_rest.test import missing_url
from django.test.utils import override_settings
from django.test.client import Client
from django.core.urlresolver... | python |
from rest_framework import status
from rest_framework.test import APITestCase
from .. import models
from .. import serializers
class DocumentTopicTestCase(APITestCase):
URL = '/v1/m2m/document/topic/'
DOCUMENT_URL = '/v1/document/'
def test_create_document_topic(self):
topic_data = {
... | python |
#!/usr/bin/env python
import sys
import numpy
from numpy import matrix
class Policy(object):
actions = None
policy = None
def __init__(self, num_states, num_actions, filename='policy/default.policy'):
try:
f = open(filename, 'r')
except:
print('\nError: unable to open file: ' + filename)
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Credits: Benjamin Dartigues, Emmanuel Bouilhol, Hayssam Soueidan, Macha Nikolski
import pathlib
from loguru import logger
import constants
import plot
import numpy as np
import helpers
from image_set import ImageSet
from helpers import open_repo
from path import global_r... | python |
import matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import networkx as nx
import numpy as np
import sklearn.metrics as metrics
import torch
import torch.nn as nn
from torch.a... | python |
#!/usr/bin/env python3
import pandas as pd
def cyclists():
df = pd.read_csv('src/Helsingin_pyorailijamaarat.csv', sep=';')
# [Same as line below]: df = df[df.notna().any(axis=1)]
df = df.dropna(how='all')
df = df.dropna(how='all', axis=1)
return df
def main():
print(cyclists())
if __name... | python |
def calc_fitness(pop):
from to_decimal import to_decimal
from math import sin, sqrt
for index, elem in enumerate(pop):
# só atribui a fitness a cromossomos que ainda não possuem fitness
# print(elem[0], elem[1])
x = to_decimal(elem[0])
y = to_decimal(elem[1])
# x = ... | python |
import os
from typing import Tuple, List
from tokenizers import BertWordPieceTokenizer, Tokenizer
import sentencepiece as spm
from enums.configuration import Configuration
from services.arguments.pretrained_arguments_service import PretrainedArgumentsService
from services.file_service import FileService
class Bas... | python |
#!/usr/bin/env python3
import fileinput
import hashlib
salt = ''
for line in fileinput.input():
salt = line.strip()
def md5(i):
return hashlib.md5((salt + str(i)).encode('utf-8')).hexdigest()
def checkNple(s, n):
i = 0
while i < len(s):
char = s[i]
consecutive = 0
while i < ... | python |
txt = ''.join(format(ord(x), 'b') for x in 'my foo is bar and baz')
print txt
from collections import Counter
secs = {
'60': '111100',
'30': '11110',
'20': '10100',
'12': '1100',
'10': '1010',
'6': '110',
'5': '101',
'3': '11',
'2': '10',
'1': '1',
'0': '0',
... | python |
#############################################
# --- Day 8: I Heard You Like Registers --- #
#############################################
import AOCUtils
class Instruction:
def __init__(self, inst):
inst = inst.split()
self.reg = inst[0]
self.mul = {"inc": 1, "dec": -1}[inst[1]]
s... | python |
import datetime
import geospacelab.express.eiscat_dashboard as eiscat
dt_fr = datetime.datetime.strptime('20201209' + '1800', '%Y%m%d%H%M')
dt_to = datetime.datetime.strptime('20201210' + '0600', '%Y%m%d%H%M')
# check the eiscat-hdf5 filename from the EISCAT schedule page, e.g., "EISCAT_2020-12-10_beata_60@uhfa.hdf5"... | python |
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib.auth.models import User
from django.conf import settings
from postgresqleu.util.fields import LowercaseEmailField
from postgresqleu.countries.models import Country
from postgresqleu.invoices.models ... | python |
import numpy as np
def readLine(line):
return [ int(c) for c in line.split(' ') ]
def schedule(activities):
lastC = 0
lastJ = 0
sortedSchedule = ''
sortedActivities = sorted(activities, key=lambda a: a[1])
for a in sortedActivities:
if a[1] >= lastC:
sortedSchedule += 'C'... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
# slim主要是做代码瘦身-2016年开始
slim = tf.contrib.slim
# 5 x Inception-Resnet-A
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
"""Build the 35 x 35 resnet b... | python |
# -------------------------------------------------------------------------
# function: classes,type = dbscan(x, k, Eps)
# -------------------------------------------------------------------------
# Objective:
# Clustering the data with Density - Based Scan Algorithm with Noise (DBSCAN)
# -------------------------... | python |
# form test
| python |
# -*- coding: utf-8 -*-
"""
测试方法:
1. 执行 s1, s2, s3 确保 document 被创建, 并且 value = 0
2. 打开两个 terminal 输入 python e3_concurrent_update.py
3. 快速在两个 terminal 按下 enter 运行. 效果是对 value 进行 1000 次 +1, 由于有两个
并发, 所以互相之间会争抢
4. 执行 s4, 查看 value 是否是 2000
ES 中处理并发的策略详解 https://www.elastic.co/guide/en/elasticsearch/reference/current... | python |
# -*- coding: utf-8 -*-
import numpy as np
from skued import azimuthal_average, powdersim
from crystals import Crystal
import unittest
from skimage.filters import gaussian
np.random.seed(23)
def circle_image(shape, center, radii, intensities):
""" Creates an image with circle or thickness 2 """
im = np.ze... | python |
# Copyright 2018 Luddite Labs 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 or agreed to in writing... | python |
import os
import io
import sys
import time
import string
import random
import pstats
import unittest
import cProfile
import itertools
import statistics
from unittest.mock import patch, MagicMock
import bucky3.statsd as statsd
class RoughFloat(float):
def __eq__(self, other):
if not isinstance(other, flo... | python |
import os
import cv2
import numpy as np
import torch
# from utils import cropping as fp
from csl_common.utils import nn, cropping
from csl_common import utils
from landmarks import fabrec
from torchvision import transforms as tf
from landmarks import lmvis
snapshot_dir = os.path.join('.')
INPUT_SIZE = 256
transfo... | python |
from django.shortcuts import render
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
class NewFatpercentageView(LoginRequiredMixin, TemplateView):
template_name = "new_fatpercentage.html"
class FatpercentageView(LoginRequiredMixin, TemplateView):
temp... | python |
import sys
from io import StringIO
def io_sys_stdin():
"""标准输入流
Ctrl + D 结束输入
"""
for line in sys.stdin: # 按行分割输入
s = line.split() # 该步返回一个 list,按空格分割元素
print(s)
def io_input():
"""使用 input() 读取输入,会将输入内容作为表达式
以换行符为结束标志
Python 3 没有 raw_input() 方法,以 input() 代替
"""
... | python |
#
# Copyright 2014 Thomas Rabaix <thomas.rabaix@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | python |
from Jumpscale import j
def test():
"""
to run:
kosmos 'j.data.rivine.test(name="sia_basic")'
"""
e = j.data.rivine.encoder_sia_get()
# you can add integers, booleans, iterateble objects, strings,
# bytes and byte arrays. Dictionaries and objects are not supported.
e.add(False)
e... | python |
from nose.tools import *
from ..app import address_parts
@raises(TypeError)
def test_address_parts_no_address():
expected = []
actual = address_parts()
def test_address_parts_with_address():
expected = ['AddressNumber', 'StreetName']
actual = address_parts('123 main')
assert actual == expected
| python |
from sys import *
def parse_weights(numberExpectedParams, filename):
f = open(filename, 'r')
contents = f.readlines()
params = []
linenumber=0
for i in contents:
linenumber = linenumber + 1
i = i.strip()
if i == "":
continue
try... | python |
from flask import current_app as app
from flask import jsonify, request
from director.api import api_bp
from director.builder import WorkflowBuilder
from director.exceptions import WorkflowNotFound
from director.extensions import cel_workflows, schema
from director.models.workflows import Workflow
@api_bp.route("/wo... | python |
nome = input('Digite seu nome:')
if nome == 'Cristiano':
print('Sou eu')
else:
print('Não sou seu')
| python |
from django.db import models
from bitoptions import BitOptions, BitOptionsField
TOPPINGS = BitOptions(
('pepperoni', 'mushrooms', 'onions', 'sausage', 'bacon', 'black olives',
'green olives', 'green peppers', 'pineapple', 'spinach', 'tomatoes',
'broccoli', 'jalapeno peppers', 'anchovies', 'chicken', 'bee... | python |
print(["ABC","ARC","AGC"][int(input())//50+8>>5]) | python |
from __future__ import print_function
import sys
if sys.version_info < (3, 8):
print(file=sys.stderr)
print('This game needs Python 3.8 or later; preferably 3.9.', file=sys.stderr)
exit(1)
try:
import moderngl
import pyglet
import png
except ImportError:
print(file=sys.stderr)
print('Y... | python |
#!/usr/bin/python2
#Dasporal
import swiftclient
import os, sys, mimetypes
import requests
import json
import pprint
data = file(os.path.join(sys.path[0], "../tokens.json"))
tokens = json.load(data)
if len(sys.argv) != 2 or len(sys.argv) != 3:
print ("Usage: podcast_upload.py [audio file name]")
exit(1)
# ... | python |
DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
SPECIAL_CASES = {
'ee': 'et',
}
LANGUAGES = {
'af': 'afrikaans',
'sq': 'albanian',
'ar': 'arabic',
'be': 'belarusian',
'bg': 'bulgarian',
'ca': 'catalan',
'zh-CN': 'chinese_simplified',
'zh-TW': 'chinese_traditional',... | python |
from keras.engine import InputSpec
from keras.layers import Dense
from keras.layers.wrappers import Wrapper, TimeDistributed
class Highway(Wrapper):
def __init__(self, layer, gate=None, **kwargs):
self.supports_masking = True
self.gate = gate
super(Highway, self).__init__(layer, **kwargs... | python |
import tensorflow as tf
import tqdm
from one_shot_learning_network import MatchingNetwork
class ExperimentBuilder:
def __init__(self, data):
"""
Initializes an ExperimentBuilder object. The ExperimentBuilder object takes care of setting up our experiment
and provides helper functions such... | python |
from __future__ import annotations
from typing import TYPE_CHECKING
from os import chdir, path
from asdfy import ASDFProcessor, ASDFAccessor
if TYPE_CHECKING:
from obspy import Trace, Stream
if not path.exists('traces.h5') and path.exists('tests/traces.h5'):
chdir('tests')
def func1(stream: Stream):
#... | python |
import numpy as np
from starfish.core.expression_matrix.concatenate import concatenate
from starfish.core.expression_matrix.expression_matrix import ExpressionMatrix
from starfish.types import Features
def test_concatenate_two_expression_matrices():
a_data = np.array(
[[0, 1],
[1, 0]]
)
... | python |
"""The plugin module implements various plugins to extend the behaviour
of community app.
The plugins provided by this module are:
SketchsTab - additional tab to show on the profile pages
LiveCodeExtension - injecting livecode css/js into lesson page
"""
import frappe
from community.plugins import PageExtensi... | python |
# -*- coding: utf-8 -*-
"""
@description: 分类器
@author:XuMing
"""
import re
import jieba
from jieba import posseg
class DictClassifier:
def __init__(self):
self.__root_path = "data/dict/"
jieba.load_userdict("data/dict/user.dict") # 自定义分词词库
# 情感词典
self.__phrase_dict = self.__get... | python |
import discord
import logging
import os
class ValorantBot(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.BOT_LOG = os.getenv('BOT_LOG')
if self.BOT_LOG == 'INFO' or self.BOT_LOG is None or self.BOT_LOG == '':
logging.getLogger().s... | python |
import unittest
from typing import List, Text
INPUT_FILE = "input.txt"
TEST_INPUT_SHORT = "test_input_short.txt"
TEST_INPUT_LONG = "test_input_long.txt"
def getJolts(inputFile: Text):
jolts: List[int] = []
with open(inputFile, "r") as inputFile:
lines = inputFile.readlines()
for line in lines... | python |
from resolwe.process import IntegerField, Process, StringField
class PythonProcessDataIdBySlug(Process):
"""The process is used for testing get_data_id_by_slug."""
slug = "test-python-process-data-id-by-slug"
name = "Test Python Process Data ID by Slug"
version = "1.0.0"
process_type = "data:pyth... | python |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import pandas as pd
style.use('fivethirtyeight')
fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
de... | python |
import os
from src.MarkdownFile import MarkdownFile
class Parser:
def __init__(self, folderPath='.', ignoredDirectories=['.obsidian', '.git']):
self._folderPath = folderPath
self._ignoredDirectories = ignoredDirectories
self.mdFiles = list[MarkdownFile]
self._retrieveMarkdownFiles()... | python |
# Created byMartin.cz
# Copyright (c) Martin Strohalm. All rights reserved.
import pero
class DrawTest(pero.Graphics):
"""Test case for text properties drawing."""
def draw(self, canvas, *args, **kwargs):
"""Draws the test."""
# clear canvas
canvas.fill(pero.color... | python |
# 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 writing, software
# distributed under the Li... | python |
########################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
AutoStartWaitHeartbeatSetting = Enum(
'no',
'systemDefault',
'yes',
)
| python |
"""
Vulnerability service interfaces and implementations for `pip-audit`.
"""
from .interface import (
Dependency,
ResolvedDependency,
ServiceError,
SkippedDependency,
VulnerabilityResult,
VulnerabilityService,
)
from .osv import OsvService
from .pypi import PyPIService
__all__ = [
"Depend... | python |
#!/usr/bin/env python
import sys
from shutil import rmtree
from os.path import abspath, dirname, join
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
media_root = join(abspath(dirname(__file__)), 'test_files')
rmtree(media_root, igno... | python |
import lightgbm as lgbm
from sklearn.model_selection import StratifiedKFold
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
def load_data():
real_df = pd.read_csv(
"feat/real.txt",
delimiter=" ",
header=None,
names=["a", "b", "c", "d", "e", "f"],
... | python |
class BudgetFiscalYear():
'''Class to describe the federal fiscal year'''
__base = None
__bfy = None
__efy = None
__today = None
__date = None
__startdate = None
__enddate = None
__expiration = None
__weekends = 0
__workdays = 0
__year = None
__month = None
__day ... | python |
# import os
# import shutil
# from django.test import TestCase
# from django_dicom.data_import.local_import import LocalImport
# from django_dicom.models.image import Image
# from tests.fixtures import TEST_FILES_PATH, TEST_IMAGE_PATH, TEST_ZIP_PATH
# TESTS_DIR = os.path.normpath("./tests")
# TEMP_FILES = os.path.jo... | python |
import os
import joblib
import pandas as pd
import numpy as np
from dataclasses import dataclass
from sklearn.preprocessing import RobustScaler
from sklearn.feature_selection import VarianceThreshold
from rdkit import Chem
from rdkit.Chem import MACCSkeys
from rdkit.Chem import MolFromSmarts
from mordred import Calc... | python |
import torch.nn as nn
import functools
import torch
import functools
import torch.nn.functional as F
from torch.autograd import Variable
import math
import torchvision
class Bottleneck(nn.Module):
# expansion = 4
def __init__(self, inplanes, outplanes, stride=1, downsample=None):
super(... | python |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Benjamin Kiessling
#
# 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 ... | python |
hello = 'hello world'
print(hello) | python |
# -*- coding: utf-8 -*-
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1 + nota2) / 2
print('A média foi de {:.2f}!'.format(media)) | python |
import unittest
import sys
undertest = __import__(sys.argv[-1].split(".py")[0])
maioridade_penal = getattr(undertest, 'maioridade_penal', None)
class PublicTests(unittest.TestCase):
def test_basico_1(self):
assert maioridade_penal("Jansen Italo Ana","14 21 60") == "Italo Ana"
if __name__ == '__m... | python |
#!/usr/bin/python3
import json
def stringToInt(origin_string):
result = 0
temp_string = origin_string.strip()
for c in temp_string:
if c >= '0' and c <= '9':
result = result * 10 + (ord(c) - ord('0'))
else:
return -1
return result
def getString(hint, default_value... | python |
import sys
import zipfile
import shutil
import commands
import os
import hashlib
import re
import traceback
import json
from lib.dexparser import Dexparser
from lib.CreateReport import HTMLReport
from lib.Certification import CERTParser
import lib.dynamic as dynamic
dexList = [] #dexfile list
#program usage
def usag... | python |
#!/usr/bin/env python
import setuptools
setuptools.setup(
author='Bryan Stitt',
author_email='bryan@stitthappens.com',
description='Mark shows unwatched on a schedule.',
long_description=__doc__,
entry_points={
'console_scripts': [
'plex-schedule = plex_schedule.cli:cli',
... | python |
"""A class using all the slightly different ways a function could be defined
and called. Used for testing appmap instrumentation.
"""
# pylint: disable=missing-function-docstring
from functools import lru_cache, wraps
import time
import appmap
class ClassMethodMixin:
@classmethod
def class_method(cls):
... | python |
# Copyright 2014 Google 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 by applicable law or ag... | python |
from unittest import TestCase
from gui_components import parser
from math import tan
class ParserTestCase(TestCase):
def test_ctan(self):
self.assertEqual(parser.ctan(0.5), 1 / tan(0.5))
def test__check_res(self):
self.assertEqual(parser._check_res('2*x+3', 1), (True, 5))
self.assertE... | python |
import random
whi1 = True
while whi1 is True:
try:
print("Selamat Datang Di Game Batu, Gunting, Kertas!")
pilihanAwal = int(input("Apakah Kau Ingin Langsung Bermain?\n1. Mulai Permainan\n2. Tentang Game\n3. Keluar\nPilihan: "))
whi2 = True
while whi2 is True:
if pil... | python |
# Generated by Django 2.0.13 on 2020-10-10 16:05
import ddcz.models.magic
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ddcz', '0024_skills_name'),
]
operations = [
migrations.AlterField(
model_name='commonarticle',
na... | python |
# Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# 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/... | python |
from .calibration import Calibration
from .capture import Capture
from .configuration import Configuration, default_configuration
from .device import Device
from .image import Image
from .imu_sample import ImuSample
from .transformation import Transformation | python |
# some comment
""" doc string """
import math
import sys
class the_class():
# some comment
""" doc string """
import os
import sys
class second_class():
some_statement
import os
import sys
| python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Pizza Project - main.py - started on 8 November 2021
# Written by Garret Stand licensed under a MIT license for academic use.
# This file contains shell formatting and other output modification/redirections functions for the program. It is a non-executable library.
# Please ... | python |
#!/usr/bin/env python
# encoding: utf-8
# 把str编码由ascii改为utf8(或gb18030)
import random
import sys
import time
import requests
from bs4 import BeautifulSoup
file_name = 'book_list.txt'
file_content = '' # 最终要写到文件里的内容
file_content += '生成时间:' + time.asctime()
headers = [
{'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Li... | python |
import numpy as np
from scipy.ndimage import map_coordinates
import open3d
from PIL import Image
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import functools
from multiprocessing import Pool
from utils_eval import np_coor2xy, np_coory2v
def xyz_2_coorxy(xs, ys, zs, H, W):
us... | python |
import pytest
from openeye import oechem
from openff.recharge.aromaticity import AromaticityModel, AromaticityModels
from openff.recharge.utilities.openeye import smiles_to_molecule
@pytest.mark.parametrize(
"smiles",
[
"c1ccccc1", # benzene
"c1ccc2ccccc2c1", # napthelene
"c1ccc2c(c... | python |
import pygame, math, os, time
from .Torpedo import Torpedo
from .Explosion import Explosion
FRICTION_COEFF = 1 - 0.015
class Spaceship(pygame.sprite.Sprite):
def __init__(self, colour, img_path, bearing, torpedo_group, explosion_group):
super().__init__()
self.torpedo_group = torpedo_group
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from datetime import datetime
class SyncModel:
""" Implements common methods used by the models for syncing data into database.
currently following models use this: Companies, Contacts, Departments, Events,
Invoices, Projects, Users."""
def ... | python |
class InvalidBrowserException(Exception):
pass
class InvalidURLException(Exception):
pass
| python |
import os
import time
import json
import string
import random
import itertools
from datetime import datetime
import numpy as np
import pandas as pd
from numba import jit
from sklearn.metrics import mean_squared_error
from contextlib import contextmanager, redirect_stdout
import matplotlib.pyplot as plt
N_TRAIN = 20216... | python |
"""
Configurations for Reserved Virtual Machines simulations:
"""
###################################
### Don't touch this line - import
import numpy
###################################
################################################
### General configurations, for all simualtions
START_TIME = 0 # Seconds - NOT IMP... | python |
#!/usr/bin/python
#
## @file
#
# Collection of classes that control the establish the basic operation of dave
# as it issues various types of commands to HAL and Kilroy
#
# Jeff 3/14
#
# Hazen 09/14
#
from xml.etree import ElementTree
from PyQt4 import QtCore
import sc_library.tcpMessage as tcpMessage... | python |
"""
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
import asyncio
import loggi... | python |
# Not used
# Author : Satish Palaniappan
__author__ = "Satish Palaniappan"
import os, sys, inspect
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
from twokenize import *
import re
Code = r"\\[... | python |
import json
import cv2.aruco as aruco
import numpy as np
with open("config.json", "r") as json_file:
data = json.load(json_file)
arucoDictionary = aruco.Dictionary_get(data["arucoDictionary"])
timeStep = data["timeStep"]
isLogEnabled = bool(data["logEnabled"])
markerWidth = data["markerWidth"]
... | python |
import unittest
import younit
# @unittest.skip("skipped")
class CommonTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
async def async_setUp(self):
pass
async def async_tearDown(self):
pass
def setUp(self):
pass
def tearDown(self):
... | python |
# -*- coding: utf-8 -*-
import os
import pathlib
from .Decorators import Decorators
from ...Exceptions import AsyncyError
def safe_path(story, path):
"""
safe_path resolves a path completely (../../a/../b) completely
and returns an absolute path which can be used safely by prepending
the story's tmp ... | python |
# Generated by Django 3.1.2 on 2020-10-30 18:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0002_auto_20201030_1417'),
]
operations = [
migrations.RemoveField(
model_name='book... | python |
import logging
from application.utils import globals
from application.utils.helpers import Singleton
from pymongo import MongoClient, ASCENDING, DESCENDING
@Singleton
class Connection:
_client = None
db = None
def __init__(self):
try:
self._client = MongoClient(globals.configuration.m... | python |
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... | python |
# Generated by Django 2.2.5 on 2019-11-21 01:48
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Search',
fields=[
('id', mo... | python |
import os
import sys
import tempfile
import mimetypes
import webbrowser
# Import the email modules we'll need
from email import policy
from email.parser import BytesParser
# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser
# In a real program you'd get the filename f... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
My first warp!
Using scikit-image piecewise affine transformation,
based on manual node assignment with stable corners.
A midpoint morph (halfway between the key frames) is generated.
http://scikit-image.org/docs/dev/auto_examples/plot_piecewise_affine.html
"""
####... | python |
# Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
import os
import sys
import re
import traceback
# This is the global namespace.
# 2011.04.19: g.log is the only member of the global namespace. I think there
# were bigger plans for g.py, but i... | python |
# -*- coding: utf-8 -*-
""" contest forms: HTTP form processing for contest pages
:copyright: Copyright (c) 2014 Bivio Software, Inc. All Rights Reserved.
:license: Apache, see LICENSE for more details.
"""
import decimal
import re
import sys
import flask
import flask_mail
import flask_wtf
import paypalrest... | python |
import sqlite3
import os
import urllib.request
from urllib.error import *
DATABASE_PATH = 'database/card_image_database.db'
def create_card_image_database(print_function):
print_function('Creating Database.')
if os.path.exists(DATABASE_PATH):
try:
os.remove(DATABASE_PATH)
except O... | python |
/home/runner/.cache/pip/pool/37/a3/2b/4c0a8aea5f52564ead5b0791d74f0f33c3a5eea3657f257e9c770b86c6 | python |
'''
Largest Palindrome of two N-digit numbers given
N = 1, 2, 3, 4
'''
def largePali4digit():
answer = 0
for i in range(9999, 1000, -1):
for j in range(i, 1000, -1):
k = i * j
s = str(k)
if s == s[::-1] and k > answer:
return i, j
def largePali3dig... | python |
import os
import tempfile
from os import makedirs
from os.path import join, exists
from sys import platform
def get_home_folder():
from pathlib import Path
home_folder = f"{Path.home()}"
return home_folder
def get_temp_folder():
temp_folder = None
if platform == "linux" or platform == "linux2... | python |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def addTwoNumbers(list1, list2, node, digit):
n = digit
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.