text stringlengths 1 927k |
|---|
import csv
from collections import Counter
import emoji
from emoji import unicode_codes
import pickle
import re
import pandas
import string
from num2words import num2words
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatize... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'DatenbankEditManoever.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 impor... |
from datetime import datetime
from urllib.parse import urlparse
from transformer.request import HttpMethod, Header, Request
from transformer.task import Task2
from .sanitize_headers import plugin
def test_its_name_is_resolvable():
from transformer.plugins import resolve
assert list(resolve("transformer.plug... |
"""Utilities for ImageNet data preprocessing & prediction decoding.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import warnings
import numpy as np
# from . import get_keras_submodule
# backend = get_keras_submodule('backend')
# keras_ut... |
#ip camera openCV streamer for DLink DCS-932L
import cv2
import urllib
import numpy as np
import sys
#stream=urllib.urlopen('http://admin:CmasQp123@192.168.1.46:8088/mjpeg.cgi?user=admin&password=CmasQp123&channel=0&.mjpg')
stream=urllib.urlopen('http://admin:CmasQp123@192.168.1.46/mjpeg.cgi?user=admin&password=... |
# -*- coding: utf-8 -*-
"""
ITU-R BT.1886
=============
Defines *Recommendation ITU-R BT.1886* electro-optical transfer function
(EOTF / EOCF) and its inverse:
- :func:`colour.models.eotf_inverse_BT1886`
- :func:`colour.models.eotf_BT1886`
See Also
--------
`RGB Colourspaces Jupyter Notebook
<http://nbviewer.jup... |
import random
from toontown.suit import DistributedBossCogAI
from toontown.suit import DistributedSuitAI
from toontown.suit import SuitDNA
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.ClockDelta import *
from direct.fsm import FSM
from otp.ai.AIBaseGlobal import *
from toontown.battle impo... |
"""
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of thei... |
#
# Binary operator classes
#
import pybamm
import numpy as np
import numbers
from scipy.sparse import issparse, csr_matrix
def is_scalar_zero(expr):
"""
Utility function to test if an expression evaluates to a constant scalar zero
"""
if expr.is_constant():
result = expr.evaluate_ignoring_er... |
# encoding: utf-8
from django.db import models
# Create your models here. |
import urllib
def _raw_urlretrieve(url, target_file, context=None):
handle = urllib.urlopen(url)#, context=context)
if handle.getcode() >= 300:
raise IOError("HTTP Error " + str(handle.getcode()))
with open(target_file, 'wb') as output:
while True:
data = handle.read(1024*1024)
... |
# GRPC GYP build file
# This file has been automatically generated from a template file.
# Please look at the templates directory instead.
# This file can be regenerated from the template by running
# tools/buildgen/generate_projects.sh
# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0... |
# encoding: utf-8
from libs.configs import cfgs
from libs.box_utils import bbox_transform
from libs.box_utils import nms_rotate
import tensorflow as tf
import numpy as np
from libs.box_utils.coordinate_convert import coordinate_present_convert, coords_regular
def postprocess_detctions(rpn_bbox_pred, rpn_cls_prob, rp... |
from __future__ import unicode_literals
import collections
import copy
import datetime
import decimal
import inspect
import json
import re
import uuid
from collections import OrderedDict
from django.conf import settings
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.excep... |
# -*- coding: utf-8 -*-
"""
Test xform2json module.
"""
import os
from xml.etree.ElementTree import ParseError
from unittest2 import TestCase
from pyxform.builder import create_survey_from_path
from pyxform.tests import utils
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
from pyxform.xform2json impor... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python3 -u
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Implements adapter for pmdarima forecasters to be used in sktime framework."""
__author__ = ["mloning", "hyang1996", "kejsitake", "fkiraly"]
__all__ = ["_PmdArimaAdapter"]
import pandas as pd
... |
#################################
##### Tests for otter grade #####
#################################
import os
import unittest
import subprocess
import json
import re
import pandas as pd
from unittest import mock
from subprocess import PIPE
from glob import glob
from otter.argparser import get_parser
from otter.gra... |
#!/usr/bin/env python3
"""
Return Kth to Last: Implement an algorithm to find the kth to last element
of a singly linked list.
"""
from singly_linked_list import Node, SinglyLinkedList
# Time complexity: O(n).
# Space complexity: O(1).
def kth_to_last(lst, k):
"""This solution implies that the singly linked ... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('metadata', '0006_auto_20150820_0616'),
]
operations = [
migrations.AlterField(
model_name='metadatatype',
name='parser',
... |
import pygame
import random
class Bos(pygame.sprite.Sprite):
def __init__(self, screen, lvl):
super(Bos, self).__init__()
self.lvl = lvl
self.screen = screen
if lvl == 1:
self.image = pygame.image.load("дизайн/инопланетяни, бонцсы и т.д/bos_1_.png")
if lvl == 2... |
"""
Tests for sulfur.
"""
import unittest
from armi.materials.tests.test_materials import _Material_Test
from armi.materials.sulfur import Sulfur
class Sulfur_TestCase(_Material_Test, unittest.TestCase):
MAT_CLASS = Sulfur
def setUp(self):
_Material_Test.setUp(self)
self.mat = Sulfur()
... |
#/usr/bin/env python
import QtTesting
import QtTestingImage
object1 = 'pqClientMainWindow/menubar/menuSources'
QtTesting.playCommand(object1, 'activate', 'SphereSource')
object2 = 'pqClientMainWindow/objectInspectorDock/objectInspector/Accept'
QtTesting.playCommand(object2, 'activate', '')
object3 = 'pqClientMainWind... |
#! /usr/bin/env python3
# four_to_two is a little script that takes markdown text with 4-space indents on stdin and writes 2-space indented
# markdown on stdout
import math
import re
import sys
BEGINNING_WHITESPACE_RE = re.compile(r'^(\s+)(.*)')
def four_to_two(line):
match = BEGINNING_WHITESPACE_RE.match(line... |
"""
Escreva um programa que leia a velocidade de um carro.
se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado.
A multa vai custar R$7,00 por cada km acima do limite.
"""
velocidade = float(input('Qual a velocidade atual do carro? '))
if velocidade > 80:
print('MULTADO! você excedeu o limite... |
from rest_framework import pagination
class Pagination(pagination.PageNumberPagination):
"""The default pagination class
"""
page_size = 30
page_size_query_param = 'pagesize'
max_page_size = 100 |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... |
from azure.durable_functions.models.actions.WhenAnyAction import WhenAnyAction
from azure.durable_functions.models.ReplaySchema import ReplaySchema
from ..models.TaskSet import TaskSet
def task_any(tasks, replay_schema: ReplaySchema):
"""Determine whether any of the given tasks is completed.
Parameters
-... |
import setuptools
setuptools.setup(
name = "either",
version = "0.1",
url = "https://github.com/kennknowles/python-either",
maintainer = "Kenneth Knowles",
maintainer_email = "kenn.knowles@gmail.com",
packages = setuptools.find_packages()) |
import json
from copy import deepcopy
from hashlib import sha256
from plenum.common.constants import TARGET_NYM, NONCE, RAW, ENC, HASH, NAME, \
VERSION, FORCE, ORIGIN, OPERATION_SCHEMA_IS_STRICT, OP_VER
from plenum.common.messages.client_request import ClientMessageValidator as PClientMessageValidator
from plenum.... |
# The MIT License (MIT)
#
# Copyright (c) 2015 Leon Jacobs
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... |
begin_unit
comment|'# Copyright 2011 OpenStack Foundation'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
co... |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
from paprika.repositories.Repository import Repository
from paprika.connectors.Helper import Helper
class FilePropertyRepository(Repository):
def __init__(self, connector):
Repository.__init__(self, connector)
def get_property(self, file, name):
connection = self.get_connection()
curs... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import Authenticati... |
# -*- coding: utf-8 -*-
# Django imports
from django.apps import AppConfig
class DevilryQualifiesForExamPointsAppConfig(AppConfig):
name = 'devilry.devilry_qualifiesforexam_plugin_points'
verbose_name = 'Devilry qualifies for exam plugin points'
def ready(self):
from devilry.devilry_qualifiesfo... |
import os
base_dir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLE = True
SECRET_KEY = os.environ['SECRET_KEY']
API_URL = os.environ['API_URL']
class TestingConfig(Config):
TESTING = True
class DevelopmentConfig(Config):
DEVE... |
# Copyright 2021 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" file acco... |
"""
Management of PostgreSQL users (roles)
======================================
The postgres_users module is used to create and manage Postgres users.
.. code-block:: yaml
frank:
postgres_user.present
"""
import datetime
import logging
# Salt imports
from salt.modules import postgres
log = logging.get... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('email_user', '0003_emailuser_activation_key'),
]
operations = [
migrations.AddField(
model_name='emailuser',
... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"module_name": "Double Ledger Management",
"category": "Modules",
"label": _("Double Ledger Management"),
"color": "blue",
"icon": "octicon octicon-book",
"type": "module",
"onboard_present": 1
}
] |
from pyrogram import Client, filters
import asyncio
import os
from pytube import YouTube
from pyrogram.types import InlineKeyboardMarkup
from pyrogram.types import InlineKeyboardButton
from youtubesearchpython import VideosSearch
from TamilBots.TamilBots import ignore_blacklisted_users, get_arg
from TamilBots import ap... |
# Copyright 2015 The TensorFlow Authors. 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 applica... |
# Copyright 2015 Adobe. All rights reserved.
# TODO:
# add support for ligatures
# add support for accents with multiple anchors
# - this will require significant changes to the WriteFeaturesMarkFDK module
from itertools import product
from mojo.roboFont import CurrentFont, CurrentGlyph, RGlyph, AllFonts
from mojo.ro... |
import tensorflow as tf
import tensorflow.keras as ks
from kgcnn.layers.casting import ChangeTensorType
from kgcnn.layers.conv.attention import AttentionHeadGAT
from kgcnn.layers.keras import Concatenate, Dense, Average, Activation
from kgcnn.layers.mlp import MLP
from kgcnn.layers.pool.pooling import PoolingNodes
fro... |
from typing import Optional, Any
from .data_class import StaticData
from pathlib import Path
from ruamel.yaml import YAML
yaml = YAML(typ="safe")
class ConfigsManager(StaticData):
"""
插件配置 与 资源 管理器
"""
def __init__(self, file: Path):
self.file = file
super().__init__(file)
se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import cv2
if __name__ == '__main__':
import sys
try:
fn = sys.argv[1]
except:
fn = '../temp/cat.jpg'
img = cv2.imread(fn)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
def nothing(x):
pass
cv2.namedW... |
"""
:mod:`zsl.interface.task`
-------------------------
.. moduleauthor:: Peter Morihladko <morihladko@atteq.com>,
Martin Babka <babka@atteq.com>
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import * # NOQA
from functools import wraps
import j... |
""" This module contains the logic for specifying and validating the top-level
DC/OS configuration from user arguments
The data structure called 'entry' is what defines which validation checks
should be run, how arguments should be calculated, which arguments should have
set defaults, which arguments should be user sp... |
from copy import copy
from itertools import cycle, islice
import numpy as np
import pandas as pd
import pytest
from vispy.color import get_colormap
from napari._tests.utils import check_layer_world_data_extent
from napari.layers import Points
from napari.layers.points._points_utils import points_to_squares
from napar... |
from fltk import *
import copy
import os.path
from cPickle import load
# import time
import numpy as np
import sys
if ".." not in sys.path:
sys.path.append("..")
from PyCommon.modules.ArticulatedBody import hpBipedFeedback as hbf
from PyCommon.modules.Math import mmMath as mm
from PyCommon.modules.Math import ys... |
"""
Threaded programming is used by developers to improve the performance of
an application. This module shows a simple multiplication operation with
some delay can be parallelized using `ThreadPoolExecutor`. A good grasp of
operating systems and CPUs is recommended before reading the code below.
"""
import time
from c... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: proto/clarifai/auth/util/extension.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import s... |
import os
import sys
from decimal import *
import unittest
_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _path not in sys.path:
sys.path.append(_path)
import market_cap
class TestMarketCap(unittest.TestCase):
def test_bitstamp_price(self):
prc = market_cap.get_bitstamp_pric... |
import torch
# f = w * x
# f = 2 * x
X = torch.tensor([1,2,3,4], dtype=torch.float32) # training sample
Y = torch.tensor([2,4,6,8], dtype=torch.float32) # testing sample
w = torch.tensor(0.0, dtype=torch.float32, requires_grad=True)
#model prediction
def forward(x):
return w * x
# loss = MSE
def loss(y, y_pred... |
import csv
import os
import copy
import shutil
from scrapy import log
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse, FormRequest
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.http.co... |
# *_* coding:utf-8 *_*
# 开发人员:烈焰
# 开发时间:2019/12/16 15:16
# 文件名称:page10
# 开发工具:PyCharm
# flask-script扩展命令行
"""
python page10.py --help
positional arguments:
{shell,runserver}
shell Runs a Python shell inside Flask application context.
runserver Runs the Flask development server i.e. app.run... |
import torch
import torch.nn.functional as F
from rlpyt.models.conv2d import Conv2dHeadModel
from rlpyt.utils.collections import namedarraytuple
from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims
RnnState = namedarraytuple(
"RnnState", ["h", "c"]
) # For downstream namedarraytuples to work
... |
# -*- coding: utf-8 -*-
# Copyright 2021 Google 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 applicable law o... |
# -*- coding: utf-8 -*-
"""
##########
# Fields #
##########
Each Field class does some sort of validation. Each Field has a clean() method,
which either raises django.forms.ValidationError or returns the "clean"
data -- usually a Unicode object, but, in some rare cases, a list.
Each Field's __init__() takes at least... |
sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert t... |
from pathlib import Path
import environ
env = environ.Env()
env.read_env('.env')
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto... |
"""Support for getting statistical data from a Pi-hole system."""
import logging
from homeassistant.helpers.entity import Entity
from .const import (
ATTR_BLOCKED_DOMAINS,
DOMAIN as PIHOLE_DOMAIN,
SENSOR_DICT,
SENSOR_LIST,
)
LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, ... |
"""
lokalise.collections.teams
~~~~~~~~~~~~~~~~~~~~~~~~~~
Module containing teams collection.
"""
from .base_collection import BaseCollection
from ..models.team import TeamModel
class TeamsCollection(BaseCollection):
"""Describes teams.
"""
DATA_KEY = "teams"
MODEL_KLASS = TeamModel |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
""" TensorFlow Http Archive
Modified http_archive that allows us to override the TensorFlow commit that is
downloaded by setting an environment variable. This override is to be used for
testing purposes.
Add the following to your Bazel build command in order to override the
TensorFlow revision.
build: --action_env T... |
"""
Django settings for hello_django project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pa... |
import rpy2.robjects as robjects
robjects.r('install.packages("BiocManager", '
'repos="http://cran.r-project.org")')
robjects.r('BiocManager::install("WGCNA")')
robjects.r('library(WGCNA)') |
#!/usr/bin/env python
# coding=utf-8
from __future__ import print_function, unicode_literals
import os
import os.path
import nose.tools as nose
from tests.utils import run_filter
def test_query_ignore_case():
"""should ignore case when querying songs in an album"""
results = run_filter('playsongin', 'beat... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from .gcp import GCP # noqa
from .config import GCPConfig # noqa
from .storage import GCPStorage # noqa
from .function import GCPFunction # noqa |
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an emai... |
async def cooldown(bot, message, one_result, guild_result, connection, cursor, unix_time_millis, ru_RU, en_US):
await message.add_reaction(emoji="⌛") |
"""
MIT License
Sugaroid Artificial Intelligence
Chatbot Core
Copyright (c) 2020-2021 Srevin Saju
Copyright (c) 2021 The Sugaroid Project
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 r... |
#!/usr/bin/env python
import re
import optparse
import cryptutils
class CheckerBoard(object):
Block = ['ET AON RIS','BCDFGHJKLM','PQ/UVWXYZ.']
Columns = [0,1,2,3,4,5,6,7,8,9]
Rows = ['',2,6]
Adds = [8,18]
key = None
UPPERA = 65
def getNumber(self,ch):
return(ord(ch)-self.UPPERA)
... |
from django.core.management.base import BaseCommand, CommandError
from django.urls import reverse
from django.core.mail import send_mail
from django.template.loader import get_template, render_to_string
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils import timezone
from... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
TOPIC: Crossfield auditing two fields with one field.
In this problem set you work with cities infobox data, audit it, come up with a
cleaning idea and then clean it up.
If you look at the full city data, you will notice that there are couple of
values that seem to pr... |
import time
from bibliopixel.animation.circle import Circle
from bibliopixel.colors import COLORS
class ArcClock(Circle):
def __init__(self, layout, **kwds):
super().__init__(layout, **kwds)
self.hands = [
{
'rings': [0, 1],
'color': COLORS.Red,
... |
# -*- coding: utf-8 -*-
"""
Data types provided by plugin
Register data types via the "aiida.data" entry point in setup.json.
"""
'''
# You can directly use or subclass aiida.orm.data.Data
# or any other data type listed under 'verdi data'
from aiida.orm import Dict
from voluptuous import Schema, Optional
# A subs... |
# Copyright 2019 Contributors to Hyperledger Sawtooth
#
# 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 ... |
"""
sundial.py
This file contains code to run an indoor sundial
Developed on Python 3.7.3 / Raspberry Pi 4
Nathaniel Schmucker
"""
from busio import I2C
from board import SCL, SDA
from adafruit_pca9685 import PCA9685
from adafruit_motor import servo
from pysolar.solar import get_altitude, get_azimuth
from scipy.optim... |
#!/usr/bin/env python3
import logging
import subprocess
import os
from tempfile import NamedTemporaryFile as NTF
from cblaster import helpers
from cblaster.classes import Hit
LOG = logging.getLogger(__name__)
def parse(results, min_identity=30, min_coverage=50, max_evalue=0.01):
"""Parse a string containing... |
# Copyright 2019 DeepMind Technologies Limited.
#
# 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 agr... |
import pdf_to_json as p2j
import json
url = "file:data/multilingual/Latn.GJN/Serif_12/udhr_Latn.GJN_Serif_12.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... |
from django import template
from myshop_mail.models import Order
register = template.Library()
@register.filter
def cart_item_count(user):
if user.is_authenticated:
qs = Order.objects.filter(user=user)
if qs.exists():
return qs[0].items.count()
return 0 |
# import celery
from .celery import app as celery_app |
import unittest
from monty.fractions import gcd, lcm, gcd_float
class FuncTestCase(unittest.TestCase):
def test_gcd(self):
self.assertEqual(gcd(7, 14, 63), 7)
def test_lcm(self):
self.assertEqual(lcm(2, 3, 4), 12)
def test_gcd_float(self):
vs = [6.2, 12.4, 15.5 + 5e-9]
... |
# Generated by Django 2.0.8 on 2018-12-01 12:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cases', '0006_auto_20181105_0419'),
]
operations = [
migrations.AddField(
model_name='case',
name='identification_nu... |
#!/usr/bin/env python
#
# DiNgoeS: Compare anti-malware and phishing filtering DNS services
# Author: https://twitter.com/gszathmari
#
import os
import time
import argparse
import signal
from pyfiglet import Figlet
from halo import Halo
from sys import exit
from dingoes.hphosts import HpHostsFeed
from dingoes.report i... |
import numpy as np
import sys
#Usage:
#python thisprog.py threshold numofnetworks
#Will randomly initialize numofnetworks neural networks and train them until the error on a training set is less than threshold
#Will then try to interpolate between these networks while keeping error below that of threshold.
#Will tabula... |
"""
Django settings for ndmanager project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# See: https://docs.python.org/3/library/time.html#time.process_time
# http://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python
import time
initial_time = time.perf_counter()
#do some stuf... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import tarfile
class TarFile(tarfile.TarFile):
def next(self):
"""A copy and modification of the next() method in tarfile module.
Note: this function should stay named next()... |
# -*- coding: utf-8 -*-
"""
EauDouce.utils.aes_cbc
~~~~~~~~~~~~~~
AES加密的实现模式CBC。
CBC使用密码和salt(起扰乱作用)按固定算法(md5)产生key和iv。然后用key和iv(初始向量,加密第一块明文)加密(明文)和解密(密文)。
:copyright: (c) 2017 by Mr.tao.
:license: MIT, see LICENSE for more details.
"""
from Crypto.Cipher import AES
from binascii import b2a_... |
#Datos de entrada
numE=float(input("Ingrese el numero de estudiantes a realizar el viaje:"))
#Proceso
if numE>100:
print("El pasaje por alumno es de $20.00")
elif numE>=50 and numE<=100:
print("El pasaje por estudiante es de $35.00")
elif numE>=20 and numE<50:
print("El pasaje por estudiante es de $40.00")
elif n... |
import collections
import math
import pathlib
import pytest
import tempfile
import demes
from demes import ms
import tests
def N_ref(*, theta, mu, length):
"""
Calculate N0 reference size for an ms command.
"""
return theta / (4 * mu * length)
def N_ref_macs(*, theta, mu):
"""
Calculate N0 ... |
#!/usr/bin/env python
import unittest
import bloom
class BloomTest(unittest.TestCase):
def test_fun(self):
self.assertEqual(bloom.fun(3), 4)
if __name__ == '__main__':
unittest.main() |
import pyximport; pyximport.install()
import gryphon.lib; gryphon.lib.prepare()
import os
import unittest
import sure
import mock
from decimal import Decimal
from gryphon.lib.money import Money
from gryphon.lib.exchange.consts import Consts
from gryphon.lib.models.trade import Trade
import logging
logger = logging.g... |
import torch
import torch.nn as nn
from torch_geometric.nn import MessagePassing
import torch.nn.functional as F
from torch_geometric.nn import global_mean_pool, GCNConv, SAGEConv
from torch_geometric.utils import degree
from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder
### GIN convolution along the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.