text stringlengths 1 927k |
|---|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# ============================================================================
# Erfr - One-time pad encryption tool
# Executor script
# Copyright (C) 2018 by Ralf Kilian
# Distributed under the MIT License (https://opensource.org/licenses/MIT)
#
# Website: http://www.urb... |
#
# Autogenerated by Thrift Compiler (0.9.1)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from .ttypes import * |
import unittest
from unittest.mock import MagicMock
from scraper.scraper import get_table_with_data, row_not_loaded, \
reload_table_rows, get_coin_name, get_coin_symbol, \
get_coin_price, get_coin_change24h, get_coin_change7d, \
get_coi... |
from .client import client, as_completed
__all__ = ['client', 'as_completed'] |
import os
import sys
from subprocess import Popen, PIPE, STDOUT
from logzero import logger
from dotenv import load_dotenv
from caendr.utils import monitor
from caendr.models.error import EnvVarError
from caendr.services.cloud.storage import upload_blob_from_file
dotenv_file = '.env'
load_dotenv(dotenv_file)
monitor... |
from django.core.management.base import BaseCommand
from dimagi.utils.couch.database import iter_docs
from corehq.apps.domain.models import Domain
class Command(BaseCommand):
def _get_domains_without_last_modified_date(self):
docs = iter_docs(Domain.get_db(), [
domain['id']
for ... |
"""
# install the package
pip install deepctr
# tutorial
https://deepctr-doc.readthedocs.io/en/latest/Quick-Start.html#getting-started-4-steps-to-deepctr
# github
https://github.com/shenweichen/DeepCTR
しかし、これは binary しか出来ないので適応不可能。
binary を無理矢理適応させるばあいは、非クリックデータを何らかの方法で生成する必要がある。
# ---- 次のアイデア ----
# github
https:/... |
# 20893 - [Job Adv] (Lv.100) The Empress' Chief Knight
sm.setSpeakerID(1101000)
sm.sendNext("#h #... what is this?")
sm.setPlayerAsSpeaker()
sm.sendNext("This, milady, is the report from Neinheart about the activities of the Cygnus Knights.")
sm.setSpeakerID(1101000)
sm.sendNext("Haha, is that wat Neinheart said? It... |
import logging
from esphome.const import (
CONF_INPUT,
CONF_MODE,
CONF_NUMBER,
)
import esphome.config_validation as cv
_ESP_32S3_SPI_PSRAM_PINS = {
26: "SPICS1",
27: "SPIHD",
28: "SPIWP",
29: "SPICS0",
30: "SPICLK",
31: "SPIQ",
32: "SPID",
}
_ESP_32_ESP32_S3R8_PSRAM_PINS = {... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="Jati",
version="0.0.2",
author="Janoko",
author_email="janoko@sandhika.com",
description="Jati merupakan modul python untuk restAPI dan websocket",
long_description=long_description,
... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.16
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
"""
Discord Pybot Support
~~~~~~~~~~~~~~~~~
Support File with stuff
:copyright: (c) 2021-2021 M2rsho
:license: MIT, see LICENSE for more details.
"""
if __name__ == "__main__":
print("Huh?")
exit
from datetime import datetime
from colorama import *
import yaml
from random import choice
from PIL import Imag... |
from collections import OrderedDict, namedtuple
from dagster import check
from dagster.core.definitions import (
CompositeSolidDefinition,
InputDefinition,
PipelineDefinition,
Solid,
SolidDefinition,
SolidHandle,
SolidOutputHandle,
solids_in_topological_order,
)
from dagster.core.defini... |
N = int(input())
A = list(map(int, input().split()))
d = {}
for a in A:
if a in d:
d[a] += 1
else:
d[a] = 1
l = [k for k in d if d[k] >= 2]
l.sort(reverse=True)
if len(l) == 0:
print(0)
elif d[l[0]] >= 4:
print(l[0] * l[0])
elif len(l) == 1:
print(0)
else:
print(l[0] * l[1]) |
import socket
def is_connected_to_internet(host="8.8.8.8", port=53, timeout=3):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
... |
import os, sys
try:
from setuptools import setup
from setuptools.command.install import install as _install
from setuptools.command.sdist import sdist as _sdist
except ImportError:
from distutils.core import setup
from distutils.command.install import install as _install
from distutils.command.s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 UT-Battelle, LLC and other Celeritas Developers.
# See the top-level COPYRIGHT file for details.
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""
"""
import json
import subprocess
from os import environ, path
from sys import exit, argv
try:
geometry... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: zkinterface
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
# Witness represents an assignment of values to variables.
#
# - Does not include variables already given in `CircuitHeader.instance_variabl... |
"""
Copyright (C) 2021-2022 Intel Corporation
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... |
#!/usr/bin/env python
# coding=utf-8
# Imports
import h5py
import scipy.io as sio
import os
import requests
import zipfile
import numpy as np
import glob
import shutil
import pickle
def loadmat(matfile):
"""Function to load .mat files.
Parameters
----------
matfile : str
path to `matfile` contai... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Extend numpy's decorators to use nipy's gui and data labels.
"""
from numpy.testing.decorators import *
from nipy.utils import templates, example_data, DataError
def make_label_dec(label, ds=None):
... |
# encoding: UTF-8
# Wide Column Store (Key-Column-Value database) built on top of SQLite
# (c) 2017 by mobarski (at) gmail (dot) com
# licence: MIT
# version: x1m3 (x-experimental, p-preview, r-release, m-modification)
# x1m6 - better test coverage
# x1m5 - tests, limit_str, some comments, set_items<-store, scan_item... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='Cat chaser',
version='0.1.0',
description='Code for the cat chaser.',
long_description=readme,
author='Joakim N... |
__source__ = 'https://leetcode.com/problems/restore-ip-addresses/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/restore-ip-addresses.py
# Time: O(n^m) = O(3^4)
# Space: O(n * m) = O(3 * 4)
# DFS
#
# Description: Leetcode # 93. Restore IP Addresses
#
# Given a string containing only digits, restore it by r... |
# 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... |
import pytest
from hypothesis import settings
@pytest.fixture(params=["petstore_v2.yaml", "petstore_v3.yaml"])
def testdir(request, testdir):
def make_petstore_test(*args, **kwargs):
kwargs["schema_name"] = request.param
testdir.make_test(*args, **kwargs)
testdir.make_petstore_test = make_pet... |
from ariadne import ObjectType
user = ObjectType("User")
game = ObjectType("Game")
#game_event = ObjectType("GameEvent")
#join_game_event = ObjectType("JoinEvent")
object_types = [
user,
game,
#game_event,
#join_game_event,
] |
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
from .base_model import BaseModel
import numpy as np
from . import losses
import shutil
from utils.util import *
from torch.autograd import Variable
from collections import OrderedDict
from tensorboardX import SummaryWriter
import ... |
# flake8: noqa
from aydin.features.standard_features import StandardFeatureGenerator
from aydin.io.datasets import examples_single
from aydin.it.fgr import ImageTranslatorFGR
from aydin.it.transforms.attenuation import AttenuationTransform
from aydin.regression.cb import CBRegressor
from aydin.util.log.log import Log
... |
# Copyright (c) 2020 PaddlePaddle 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 appli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def rot13(message):
import codecs
return codecs.encode(message, 'rot13')
assert rot13("test") == "grfg"
assert rot13("Test") == "Grfg" |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import seaborn as sns
import matplotlib.pylab as plt
import numpy as np
# TODO 所有循环结构应该呈现灵活性,每一层都不能一样!
activation_dict = {"relu" : nn.ReLU,
"leakyrelu" : nn.LeakyReLU,
"prelu" : nn.PRe... |
import os
import sys
import argparse
import json
import logging
import yaml
import hashlib
from filelock import FileLock
from typing import Optional, List, Dict, Any
from pathlib import Path
import ray
from ray._private.conda import (get_conda_activate_commands,
get_or_create_conda_env... |
# 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
# distrib... |
# flake8: noqa: F811, F401
import asyncio
import dataclasses
import logging
import random
import time
from secrets import token_bytes
from typing import Dict, Optional, List
import pytest
from taco.consensus.pot_iterations import is_overflow_block
from taco.full_node.bundle_tools import detect_potential_template_gene... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='netinfo',
version='0.0.2',
description='Client to interact with Netinfo services.',
author="Brandon Dixon",
author_email... |
print("Hola Mundooo")
a=20
b=10
print("Suma:",a+b)
print("Resta:",a-b)
print("Division:",a/b)
print("Multiplicacion:",a*b) |
from brian2.codegen.runtime.cython_rt.extension_manager import cython_extension_manager
code = '''
def f(ns):
#cdef int n = <int> ns['n']
cdef int n = ns['n']
print n
'''
ns = {
'n':3,
}
mod = cython_extension_manager.create_extension(code)
mod.f(ns) |
#!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
from os import path
from time import sleep
def sanitize_path(raw_path):
""" Replace spaces with backslashes+spaces """
return raw_p... |
from urllib import request
from bs4 import BeautifulSoup
from selenium import webdriver
import os
import time
def get_trans_text():
url = 'https://translate.google.cn/#view=home&op=translate&sl=zh-CN&tl=en&text=%3Cdiv%20class%3D%22dpl-box-title%22%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%E8%B4%A7%E5%93%81%E7%B1%BB%E... |
# -*- coding: utf-8 -*-
"""
Neighbor Articles Plugin for Pelican
====================================
This plugin adds ``next_article`` (newer) and ``prev_article`` (older)
variables to the article's context
"""
from pelican import signals
def iter3(seq):
it = iter(seq)
nxt = None
cur = next(it)
for... |
import profiles
"""Calibration Profile"""
class ProfileCalibration(profiles.Profile):
"""Calibration Profile"""
def config(self):
# __name__ msut be the same as the class name
self.__name__ = "ProfileCalibration"
self.title = "Calibration Profile"
self.title_short = "Calibrat... |
from pyswagger import SwaggerApp, primitives, errs
from ..utils import get_test_data_folder
from pyswagger.spec.v2_0 import objects
from pyswagger.utils import jp_compose
import os
import unittest
import datetime
import six
class SchemaTestCase(unittest.TestCase):
""" test for Schema object """
@classmethod
... |
# -*- coding: utf-8 -*-
#
# This class was auto-generated.
#
from onlinepayments.sdk.data_object import DataObject
class CreateHostedTokenizationRequest(DataObject):
__ask_consumer_consent = None
__locale = None
__tokens = None
__variant = None
@property
def ask_consumer_consent(self) -> bool... |
#!/usr/bin/env python3
import torch
import unittest
from gpytorch.kernels import RBFKernelGrad
from gpytorch.test.base_kernel_test_case import BaseKernelTestCase
class TestRBFKernelGrad(unittest.TestCase, BaseKernelTestCase):
def create_kernel_no_ard(self, **kwargs):
return RBFKernelGrad(**kwargs)
d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.core.validators
from aldryn_apphooks_config.fields import AppHookConfigField
from aldryn_categories.fields import CategoryManyToManyField
from aldryn_categories.models import Category
from aldryn_newsblog.utils.utilities import get_valid_la... |
# Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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:... |
import argparse
from readers import generics, facebook, telegram, discord
from visualization import visualization as viz
parser = argparse.ArgumentParser(
description='Reads messages from various social medias and generates plots.'
)
# Add command line parameters
generics.init(parser)
facebook.init(parser)
telegr... |
"""Pyrex.Distutils.build_ext
Implements a version of the Distutils 'build_ext' command, for
building Pyrex extension modules."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id:$"
import sys, os, string, re
from types import *
from distutils.core import Command
from distutils.errors imp... |
import ctypes
from ctypes import (POINTER, c_char_p, c_size_t, c_int, c_long, c_ulong,
c_double, c_void_p)
from ctypes.util import find_library
class _c_gsl_rng_type(ctypes.Structure):
_fields_ = [('name', c_char_p),
('max', c_long),
('min', c_size_t),
... |
from flask.ext.restless import APIManager
from flask.ext.security import SQLAlchemyUserDatastore, Security
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
from flask.ext.cors import CORS
app = Flask(__name__)
app.config.from_pyfile('config.py')
CORS(app)
db = SQLAlchemy(app)
api_manager = APIMan... |
# Numeric Pattern 12
"""
Desired Output:
5 10 15 20 25
4 9 14 19 24
3 8 13 18 23
2 7 12 17 22
1 6 11 16 21
"""
x = 5
for i in range(5, 0, -1):
j = i
for _ in range(5):
print(j, end=" ")
j += x
print() |
# -*- coding:utf-8 -*-
#!/bin/env python
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^manage_file', views.manage_file,name='manage_file'),
url(r'^del_file', views.del_file,name='del_file'),
url(r'^upload_file', views.upload_file,name='upload_file'),
] |
# #######
# Copyright (c) 2016-2020 Cloudify Platform Ltd. 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... |
# make facebank
import warnings
warnings.filterwarnings("ignore")
import os
import torch
from model import Backbone
import argparse
from pathlib import Path
from torchvision import transforms as trans
from PIL import Image
import numpy as np
def prepare_facebank(path_images,facebank_path, model, mtcnn, device , tta = T... |
"""Module to create a XDMF file for a PetIBM field variable."""
import sys
import pathlib
from lxml import etree
from .grid import read_grid_hdf5
def write_xdmf(outpath, datadir, gridpath, name,
nstart=None, nt=None, nsave=None,
states=None, times=None):
"""Write a XDMF file to rea... |
import sys
import numpy as np
import pandas as pd
import itertools
import logging
import inspect
import copy
from .result import AlgoResult, ListResult
from scipy.misc import comb
from . import tools
class Algo(object):
""" Base class for algorithm calculating weights for online portfolio.
You have to subclas... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
# ReCode by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/L... |
from __future__ import absolute_import
from torch import nn
import torchvision
fea_dims_small = {'layer2': 128, 'layer3': 256, 'layer4': 512}
fea_dims = {'layer2': 512, 'layer3': 1024, 'layer4': 2048}
class ResNet(nn.Module):
__factory = {
18: torchvision.models.resnet18,
34: torchvision.models.... |
import numpy as np
""" Dimensional/data reduction methods. """
def average_within_regions(dataset, img, threshold=None, remove_zero=True):
""" Averages over all voxels within each ROI in the input image.
Takes a Dataset and a Nifti image that defines distinct regions, and
returns a numpy matrix of ROIs x map... |
import unittest
from unittest.mock import patch
from PIL import Image
import processor
class ProcessorTest(unittest.TestCase):
def test_normalize_input(self):
img = Image.new("RGB", (400, 400), "#ff0000")
normalized = processor.normalize_input(img)
assert normalized.shape == (224, 224, 3... |
from AES import AES
from AES import unpad
from EncodeDecode import encode
from EncodeDecode import decode
from ImageInsideImage import *
from PIL import Image
if __name__ == '__main__':
print("Enter 1 to Ecrypt a Message Using AES Encryption\nEnter 2 to Decrypt a Message\nEnter 3 to Encrypt a Message and Hide... |
from locust import HttpLocust, TaskSet, between
import json
def login(l):
headers = {'content-type': 'application/vnd.api+json'}
l.client.post(
"/api/v1/realms/PLAYGROUND/auth-session",
data=json.dumps({
"data": {
"type":"auth-session",
"attributes"... |
#%%
import random
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras as keras
import seaborn as sns
import numpy as np
import pickle
from sklearn.model_selection import StratifiedKFold
from math import log2, ceil
import sys
#sys.path.append("../src/")
sys.path.append("../src_sampling/"... |
import os
from reclaimer.hek.handler import HaloHandler
from reclaimer.os_hek.defs import __all__ as all_def_names
from supyr_struct.defs.constants import PATHDIV
class OsHaloHandler(HaloHandler):
frozen_imp_paths = all_def_names
default_defs_path = "reclaimer.os_hek.defs"
tagsdir = "%s%stags%s" % (os.p... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 o... |
"""
Copyright (c) 2016-17 Keith Sterling http://www.keithsterling.com
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, mod... |
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
targetList = []
targetList.append(nums[0])
for i in range(1,len(nums)):
targetList.insert(index[i] , nums[i])
return targetList |
import unittest
from unittest import IsolatedAsyncioTestCase
from unittest.mock import Mock
from pyfreenas.disk import DiskType
from pyfreenas.websockets.disk import CachingDisk
from pyfreenas.websockets.machine import CachingMachine
from tests.fakes.fakeserver import (
FreeNASServer,
TDiskQueryResult,
TDi... |
import defcon
import sys
sys.path.append("..")
from kernFeatureWriter import *
def read_file(path):
'''
Read a file, split lines into a list, close the file.
'''
with open(path, 'r', encoding='utf-8') as f:
data = f.read().splitlines()
return data
def test_WhichApp():
assert WhichA... |
from UI import interface
from Model import confidenceInterval as ci
interface.heading()
answer = interface.menu()
if answer == '1':
mean, deviation, confidence = interface.readDataNormalDistribution()
x1, x2, significancePoint = ci.confidenceIntervalForNormalDistribution(mean, deviation, confidence)
prin... |
#!/usr/bin/env python
# Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
import sys
import os
import os.path
import socket
import thread
import time
import getopt
import httplib
from SocketServer import *
from BaseHTTPServer import *
from SimpleHTTPServer import *
if __n... |
"""
Copyright (C) Microsoft Corporation. All rights reserved.
Microsoft Corporation (“Microsoft”) grants you a nonexclusive, perpetual,
royalty-free right to use, copy, and modify the software code provided by us
("Software Code"). You may not sublicense the Software Code or any use of it
(except to your affiliates... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 4 10:20:35 2021
@author: Administrator
""" |
import asyncio
import logging
import datetime
import aiohttp
from ..web.rest.json import json_response
from ..log import LOG_NOTICE
##
L = logging.getLogger(__name__)
##
class WebApiLoggingHandler(logging.Handler):
def __init__(self, app, level=logging.NOTSET, buffer_size: int = 10):
super().__init__(level... |
from .resnet50 import resnet50 |
# ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2018 www.open3d.org
#
# Permission is her... |
# Copyright [2019] [Christopher Syben]
#
# 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... |
import torch
import hashlib
import os
import re
import shutil
import sys
import tempfile
if sys.version_info[0] == 2:
from urlparse import urlparse
from urllib2 import urlopen
else:
from urllib.request import urlopen
from urllib.parse import urlparse
try:
from tqdm import tqdm
except ImportError:
... |
from itertools import takewhile, repeat
from typing import Iterable, Union
from collections.abc import Sized
from m2data.example import Example
# this is sometimes off by an example or two for very large files, but that probably doesn't matter much
def fast_example_count(filename) -> int:
f = open(filename, 'rb'... |
from sklearn.svm import LinearSVC
import numpy as np
def apply_threshold(data, threshold):
data[np.where(np.abs(data) < threshold)] = 0
def train_one(data, loss, C, verbose, max_iter, threshold, dual, tol):
def _get_features(obj):
# Index samples iff they are required
# Helful in reducing mem... |
from typing import Optional, Any, Dict
import numpy as np
import pandas as pd
from more_itertools import first
from networkx import Graph, to_numpy_matrix
import matplotlib.pyplot as plt
import seaborn as sb
from adam.semantics import Concept, KindConcept, ObjectConcept, ActionConcept
class SemanticsManager:
de... |
from random import randrange
import matplotlib.pyplot as plt
import numpy as np
import cv2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
parser.add_argument("nombre1", help="echo the string you use here")
parser.add_argument("nombre2", help="echo the... |
# Generated by Django 2.0.6 on 2018-07-03 14:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0006_alter_photo_and_photographer'),
]
operations = [
migrations.CreateModel(
name='MonumentType',
fields=... |
# built in library
from abc import ABC
class TAMLoopReceiver(ABC):
def __init__(self, name):
self._name = name
self._running = True
self._receiver_settings = {}
def get_name(self):
"""
info: Will get the receiver name
:return: str
"""
return sel... |
from __future__ import annotations
from datetime import datetime
class RefWarning:
NEVER = datetime(9999, 1, 1)
def __init__(self, user_id: int, timestamp: datetime, mod_name: str, reason: str = "",
expiration_time: datetime = NEVER):
self.user_id = user_id
self.timestamp = t... |
from __future__ import absolute_import, print_function, division
import logging
from nose.plugins.skip import SkipTest
from nose_parameterized import parameterized
import numpy
from itertools import product, chain
import theano
from six import StringIO
import theano.tensor as T
import theano.tests.unittest_tools as u... |
# 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
# "License"); you may not u... |
import jsonlines
import re
import transformers
import torch
from tqdm import trange, tqdm
import argparse
import os, sys
def get_case_insensitive_key_value(input_dict, key):
return next((value for dict_key, value in input_dict.items() if dict_key.lower() == key.lower()), None)
def filter_triples(model, tokenizer,... |
# mysql/cymysql.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
r"""
.. dialect:: mysql+cymysql
:name: CyMySQL
:dbapi: cymysql
:connec... |
from __future__ import absolute_import
from django.conf import settings
from six.moves.urllib.parse import urlparse
import os
import socket
import pytest
_service_status = {}
def cassandra_is_available():
if "cassandra" in _service_status:
return _service_status["cassandra"]
try:
socket.cre... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1',... |
#!/usr/bin/env python
# Copyright 2015-2016 Yelp 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 ... |
import os
from collections import defaultdict
from xml.etree import ElementTree as ET
# Todo: ""
# execute from galaxy root dir
tooldict = defaultdict(list)
def main():
doc = ET.parse("tool_conf.xml")
root = doc.getroot()
# index range 1-1000, current sections/tools divided between 250-750
sectioni... |
import dsfs.neural_networks as under_test
def test_xor_network():
xor_network = [[[20.0, 20, -30], [20.0, 20, -10]], [[-60.0, 60, -30]]]
assert 0.000 < under_test.feed_forward(xor_network, [0, 0])[-1][0] < 0.001
assert 0.999 < under_test.feed_forward(xor_network, [1, 0])[-1][0] < 1.000
assert 0.999 <... |
def divide(num):
for i in xrange(2,num/2) :
if(num%i == 0) :
return i, num/i
return -1, num
def soinsu(num) :
insu = []
if num < 2 :
return num
current = divide(num)
'''print current'''
while current[0] != -1 :
insu.append(current[0])
current = divide(current[1])
print current
insu.append(current... |
"""
循环不变式 就是 : A[0, j-1]
"""
from random_array import random
def insert_sort(arr):
if len(arr) < 2:
raise Exception("array is too short to sort")
for j in range(1, len(arr)):
pivot = arr[j]
i = j - 1
while i >= 0 and arr[i] > pivot:
arr[i+1] = arr[i]
i -= 1
arr[i+1] = pivot
return... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Prettifies 'git diff' output.
prettify_diff() takes a diff string, and returns an HTML string decorating the
diff.
This code doesn't support other diff c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-07.
# 2019, SMART Health IT.
import os
import io
import unittest
import json
from . import composition
from .fhirdate import FHIRDate
class CompositionTests(unittest.TestCase):
def instantiate_from(self, filename... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.