text stringlengths 1 927k |
|---|
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import os.path
import xml.dom.minidom
import re
XML_TEMPLATE = """<?xml version="1.0" ?>
<mujoco>
<compiler angle="radian" coordinate="local" inertiafromgeom="true" settotalmass="14"/>
<default>
<joint armature=".1" damping=".01" limited="true" solimpl... |
# 本resnet结构选自:https://arxiv.org/pdf/1603.05027.pdf
# 是原作者在resnet上的更新版本(实际用的没有原始版本广,认可度有质疑)
from __future__ import absolute_import
import math
import torch.nn as nn
from .channel_selection import channel_selection
__all__ = ['resnet']
"""
preactivation resnet with bottleneck design.
"""
class Bottleneck(nn.Module):... |
# -*- coding: utf-8 -*-
"""
The purpose of this script is to launch a GUI that prompts the user to select
either an option to APPEND or SPLIT a database. The user will then be prompted
with what inputs and outputs they desire. No data has been provided for this script,
but the user can still run this script to see the... |
from importmagician import import_from
with import_from('./'):
# Data pipeline
from configs.lane_detection.common.datasets.tusimple_seg import dataset
from configs.lane_detection.common.datasets.train_level0_360 import train_augmentation
from configs.lane_detection.common.datasets.test_360 import test_a... |
import contextlib
import ctypes
from rotypes.types import GUID, REFGUID, check_hresult
import json
# import pprint
import logging
logger = logging.getLogger(__name__)
if __name__ == '__main__':
logger.addHandler(logging.StreamHandler(__import__('sys').stderr))
logger.setLevel(logging.DEBUG)
try:
HCS_SYST... |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... |
# Copyright 2018 DeepMind Technologies Limited. 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 ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
The fetcher is the component that talks to external APIs to get and put signals
@see SignalExchangeAPI
"""
import typing as t
from threatexchange.signal_type.pdq import PdqSignal
from threatexchange.signal_type.pdq_ocr import PdqOcrSignal
f... |
#!/usr/bin/env python2.7
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import os
import subprocess
import sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
FUCHSIA_ROOT = os.pa... |
"""cc_toolchain_config rule for configuring CUDA toolchains on Linux, Mac, and Windows."""
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"action_config",
"env_entry",
"env_set",
"feature",
"feature_set",
"flag_group",
"flag_set",
"tool",
"tool_path",
"variable... |
# --------------------------------------------------------------------------
# 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 may cause incor... |
from .core import resource, client
from .util import full_name
from .sqs import (
get_queue as sqs_get_queue
)
from .s3 import (
get_bucket as s3_get_bucket,
get_object as s3_get_object,
put_object as s3_put_object
)
from .dynamodb import (
put_item as dynamodb_put_item,
increment_field as dynam... |
class Vessel:
def __init__(self, name: str):
"""
Initializing class instance with vessel name
:param name:
"""
self.name = name
self.fuel = 0.0
# list of dicts with passenger attributes
self.passengers = []
def __enter__(self):
"""
... |
import functools
import operator
import os
from collections import OrderedDict
from datetime import date, datetime, time
from operator import methodcaller
import numpy as np
import pandas as pd
import pytest
import toolz
import ibis
import ibis.common.exceptions as com
import ibis.expr.analysis as L
import ibis.expr.... |
from typing import List, Tuple
from skmultiflow.data import FileStream
from skmultiflow.drift_detection.base_drift_detector import BaseDriftDetector
from skmultiflow.lazy import KNNClassifier
from tqdm import tqdm
def classify(
detector: BaseDriftDetector, dataset: FileStream, window_size: int
) -> Tuple[Lis... |
import torch
from torch import nn
import torch.optim as optim
import torch.nn.functional as F
import math
import numpy as np
from config import parameters as conf
if conf.pretrained_model == "bert":
from transformers import BertModel
elif conf.pretrained_model == "roberta":
from transformers import RobertaMode... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Colony Framework
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Colony Framework.
#
# Hive Colony Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Found... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class MachineToMachineTestCase(... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import imageio
import skimage
import skimage.io
import skimage.transform
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.lay... |
if __name__ == "__main__":
"""
Wypisz na konsole swoje inicjaly.
"""
print("A.D.")
"""
Wypisz na konsole "witaj swiecie"
"""
print("Witaj swiecie") |
# -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Optimization/OptiSolver.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Optimization/OptiSolver
"""
from os import linesep
from logging import... |
import json
import os
import os.path as osp
#from collections import OrderedDict
import tempfile
import numpy as np
from mmpose.core.evaluation.top_down_eval import (keypoint_nme,
keypoint_pck_accuracy)
from mmpose.datasets.builder import DATASETS
from mmpose.datasets... |
from django.apps import AppConfig
class CategoryConfig(AppConfig):
name = 'poolink_backend.apps.category' |
import pytest
def test_get_sprite_names_nodata(parser):
result = parser.get_sprite_names(dict())
assert result == False
def test_get_sprite(parser, full_sb3):
result = parser.get_sprite_names(full_sb3)
assert type(result) == list
assert result == ["Scratch"] |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
VERSION = '1.3.0' |
# -*- coding: utf-8 -*-
# Copyright 2020 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 or... |
import numpy as np
from skimage.filters import gabor_kernel
import cv2
class KernelParams:
def __init__(self, wavelength, orientation):
self.wavelength = wavelength
self.orientation = orientation
def __hash__(self):
return hash((self.wavelength, self.orientation))
def __eq__(self... |
from kivy_ios.toolchain import PythonRecipe, shprint
from os.path import join
import sh, os
class Pyasn1ModulesRecipe(PythonRecipe):
version = "0.2.1"
url = "https://pypi.python.org/packages/source/p/pyasn1-modules/pyasn1-modules-{version}.tar.gz"
depends = ["python", "pyasn1"]
def install(self):
... |
import os
import pickle
import torch
SPECIAL_WORDS = {'PADDING': '<PAD>'}
def load_data(path):
"""
Load Dataset from File
"""
input_file = os.path.join(path)
with open(input_file, "r") as f:
data = f.read()
return data
def preprocess_and_save_data(dataset_path, token_lookup, creat... |
# encoding: utf-8
import os
from setuptools import setup, find_packages
readme_file = os.path.join(os.path.dirname(__file__), 'README.rst')
README = None
try:
f = open(readme_file, encoding='utf-8')
except TypeError:
f = open(readme_file)
README = f.read()
f.close()
os.chdir(os.path.normpath(os.path.join(os... |
# Generated by Django 2.0.2 on 2018-02-13 11:39
import datetime
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_u... |
from datetime import date, datetime, timedelta
import os
import timeit
import unittest
import moment
import schedule
from functions.date import DTIME
from functions import date as _date
DT = DTIME
TICK = timedelta.resolution
_orig_global_tz_getter = None
class TestSchedule(unittest.TestCase):
def assertDate(self,... |
# 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, overload
from ... import _utilities
fro... |
import sys
import os.path
from setuptools import setup, Extension, find_packages
if sys.version_info[:2] < (3, 6):
raise RuntimeError("Python >= 3.6 required.")
CYTHON_REBUILD = False
CYTHON_ANNOTATE = True
RTD_BUILD = 'READTHEDOCS' in os.environ
# Extra arguments to setup.py install/build/build_ext
# This is ... |
#
# Local postgis database with local user as the same name as the data base
#
import os
import six
# Nothing to define in the settings
globs = globals()
DEFAULT_SETTINGS = {
# Database over a network interface
'POSTGRES_HOST': 'localhost',
'POSTGRES_PORT': 5432,
'POSTGRES_DB': 'db',
'POSTGRES_U... |
"""Xiaomi common components for custom device handlers."""
import asyncio
import binascii
import logging
from zigpy import types as t
from zigpy.quirks import CustomCluster, CustomDevice
from zigpy.zcl.clusters.general import AnalogInput, Basic, PowerConfiguration
from zigpy.zcl.clusters.homeautomation import Electric... |
##-----------------------------------------------------------------------------
## Primitive: Template
##-----------------------------------------------------------------------------
# class Template(BasePrimitive):
# """
# """
# def __init__(self, action, context):
# BasePrimitive.__init__(self, ac... |
# ------------------------------------------------------------------------------------------------
# Copyright (c) 2018 Microsoft Corporation
#
# 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 ... |
import time
class Station:
duration = 100
file = ""
launch_time = 0
special = False
special_active = False
name = ""
def __init__(self, playlist_item):
self.file = playlist_item['file']
self.duration = playlist_item['duration']
self.special = playlist_item['special'] if 'special' in playlist... |
from abc import ABCMeta
from collections import OrderedDict
from collections.abc import Iterable
import hashlib
from itertools import product
from numbers import Real, Integral
from xml.etree import ElementTree as ET
import numpy as np
import pandas as pd
import openmc
import openmc.checkvalue as cv
from .cell import... |
# list(map(int, input().split()))
# int(input())
from itertools import combinations_with_replacement
import copy
def main(lst, K):
original = copy.copy(lst)
# 要するにC>B>Aになればおけ.
comb = combinations_with_replacement([0, 1, 2], K)
for c in comb:
lst = copy.copy(original)
for i in c:
... |
import gevent
import opentracing
import structlog
from eth_utils import is_binary_address
from raiden import waiting
from raiden.api.exceptions import ChannelNotFound, NonexistingChannel
from raiden.constants import BLOCK_ID_PENDING, NULL_ADDRESS_BYTES, UINT64_MAX, UINT256_MAX
from raiden.exceptions import (
Alrea... |
#!/usr/bin/env python
# encoding: utf-8
def loan_calculator(amount, rate, time):
if amount<0:
return "Invalid amount!"
if rate>100:
return "Invalid rate!"
if time>12:
return "Invalid Number of months!"
return amount + (amount*(rate/100)*time) |
import datetime
import typing as tp
from pydantic import Field
from modules.routers.tcd.models import ProtocolStatus
from modules.routers.passports.models import UnitStatus
from ..types import Filter
async def parse_passports_filter(
status: tp.Optional[UnitStatus] = None,
name: tp.Optional[str] = None,
... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
int_or_none,
float_or_none,
mimetype2ext,
parse_iso8601,
remove_end,
update_url_query,
)
class DRTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?dr\.d... |
"""Functions related to user input."""
# Standard Python Libraries
from datetime import datetime
import logging
# Third-Party Libraries
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
import pytz
# cisagov Libraries
from util.validate import BlankInputValidator, BooleanValidator... |
"""
Cubic spline planner
Author: Atsushi Sakai(@Atsushi_twi)
"""
import math
import numpy as np
import bisect
class Spline:
"""
Cubic Spline class for calculte curvature (Author: Atsushi Sakai(@Atsushi_twi)).
Parameters
-x : float
The x coordinate.
-y : float
The y coordinate.
... |
# 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 ... |
# Generated by Django 2.2.16 on 2020-10-10 21:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ebooks', '0122_auto_20201005_2212'),
]
operations = [
migrations.AlterField(
model_name='book',
name='logo_backgrou... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 6
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_1_1.models.namespa... |
from __future__ import annotations
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Tuple
from pathlib import Path
import json
import uuid
from random import randint
class Entity:
@staticmethod
def eid() -> str:
return uuid.uuid4().hex
class Seek... |
from random import randint
print('\033[33m=-=\033[m'*12)
print('JOGO DO PAR OU ÍMPAR')
n = 0
total = 0
derrota = False
resultado = ''
vitoria = 0
while derrota == False:
print('\033[33m=-=\033[m'*12)
n = int(input('Digite um número: '))
jogador = ' '
while jogador not in 'PI':
jogador = str(inpu... |
from __future__ import print_function
import json
import string
from collections import Set, OrderedDict
from SmartAnno.umls.Authentication import *
class UMLSFinder:
version = "current"
uri = "https://uts-ws.nlm.nih.gov"
content_endpoint = "/rest/search/" + version
AuthClient = None
translator ... |
class TenantAdminMixin:
"""
Mixin for Tenant model:
It disables save and delete buttons when not in current or public tenant (preventing Exceptions).
"""
change_form_template = 'admin/django_tenants/tenant/change_form.html' |
#!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from h.services.group_scope import group_scope_factory, GroupScopeService
class TestFetchByScope(object):
def test_it_returns_empty_list_if_origin_not_parseable(
self, svc, scope_util, document_uri
):
scope_util.p... |
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
image = Image.open("../../res/images/man.jpg")
w, h = image.size
image.thumbnail((w // 2, h // 2))
image.save("../res/images/thumbMan.jpg", 'jpeg')
image2 = image.filter(ImageFilter.BLUR)
image2.save("../res/images/blurImage.jpg", 'jpeg')
# 随机字母... |
import os
for module_name in os.listdir("../uptrop"):
if module_name.endswith(".py"):
doc_name = module_name.split('.')[0]
with open("source/" + doc_name + ".rst", 'w') as this_doc:
this_doc.write("="*len(doc_name) + "\n")
this_doc.write(doc_name + "\n")
this_doc... |
import re
import os
from polyglotdb.io.parsers.base import BaseParser # , PGAnnotation, PGAnnotationType, DiscourseData
from .speaker import FilenameSpeakerParser
from .speaker import DirectorySpeakerParser
from .base import DiscourseData
class PartiturParser(BaseParser):
_extensions = ['.par,2']
def __in... |
# Copyright (c) 2016 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 la... |
# Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft 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 b... |
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
"/../../")
import numpy as np
from src.rrt.rrt_star import RRTStar
from src.search_space.search_s... |
import os
from logzero import logger
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from caendr.models.datastore import PipelineOperation, DatabaseOperation, NemascanMapping, IndelPrimer
from caendr.models.error import PipelineRunError
from caendr.services.cloud.datastore impo... |
"""
Discussion: This has got to do with which part of the input current distribution
is transferred to the spiking activity.
Intuitive understanding is difficult but this relationship arises due to non-linearities
in the neuron F-I curve. When F-I curve is linear, output correlation is independent
of the mean and ... |
# coding=utf-8
import logging
from scrapy import FormRequest
from scrapy import Request
from zspider.basespider import BaseSpider
__author__ = "zephor"
logger = logging.getLogger(__name__)
class NewsSpider(BaseSpider):
name = "news"
def __init__(self, *args, **kwargs):
super(NewsSpider, self).__... |
from keras.layers import Input
from keras import backend as K
from keras.engine.topology import Layer
import numpy as np
class NonMasking(Layer):
def __init__(self, **kwargs):
self.supports_masking = True
super(NonMasking, self).__init__(**kwargs)
def build(self, input_shape):
input_sh... |
# Description:
#
# WARNING!!! This file is a critical component of Vorticity Gaia API for seismic imaging
# PLEASE DO NOT MODIFY
#
# (C) Vorticity Inc. Mountain View, CA 2021
# Licence: MIT
import numpy as np
import grpc
import time
import os
import sys
import gaia_pb2
import gaia_pb2_grpc
import dispatch_pb2
import d... |
from geth import LoggingMixin
from geth.process import BaseGethProcess, DevGethProcess
class RinkebyGethProcess(BaseGethProcess):
def __init__(self, geth_kwargs=None):
if geth_kwargs is None:
geth_kwargs = {}
if 'network_id' in geth_kwargs:
raise ValueError(
... |
from django.db import models
# Create your models here.
class Category(models.Model):
class Meta:
verbose_name_plural = 'Categories'
name = models.CharField(max_length=254)
display_name = models.CharField(max_length=254)
# note: did not add null=True and blank=True params to these
# as ... |
import FWCore.ParameterSet.Config as cms
XMLIdealGeometryESSource = cms.ESSource("XMLIdealGeometryESSource",
geomXMLFiles = cms.vstring(
'Geometry/CMSCommonData/data/materials/2021/v1/materials.xml',
'Geometry/CMSCommonData/data/rotations.xml',
'Geometry/CMSCommonData/data/extend/v2/cmsexte... |
import logging
from celery.app import Celery
from celery import shared_task
from sandbox import settings, Sandbox, UnsupportedLanguage, TimeoutError, MemoryLimitExceeded
from sandbox.settings import LANG_CONFIG
logging.basicConfig(filename='worker.log',
level=logging.DEBUG,
fo... |
# Copyright 2015 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 a... |
################################################################################
# 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... |
#!/usr/bin/env python3
"""Simple client for the make jobserver."""
import signal
from . import utils
try:
InterruptedError = InterruptedError
except NameError:
class InterruptedError(BaseException):
pass
class JobServerClient:
def __init__(self, make_flags=None):
self.tokens = []
... |
from Planetoid.PlanetoidDataset import PlanetoidSCDataset
from models import planetoid_GCN, planetoid_GAT, planetoid_SCN, planetoid_SCConv, planetoid_SAN, planetoid_SAT
import torch.nn as nn
import torch
from Planetoid.DGI import DGI
from Planetoid.logreg import LogReg
from constants import DEVICE
2708, 79
dataset = '... |
"""
================
Parametric Curve
================
This example demonstrates plotting a parametric curve in 3D.
"""
import numpy as np
import matplotlib.pyplot as plt
ax = plt.figure().add_subplot(projection='3d')
# Prepare arrays x, y, z
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 1... |
#!/usr/bin/env python3
"""Generate code for an Elm client."""
# pylint: disable=too-many-lines
from typing import Optional, MutableMapping, List, Dict, TextIO, Any # pylint: disable=unused-import
import collections
import swagger_to
import swagger_to.intermediate
INDENT = ' ' * 4
class Typedef:
"""Represent a... |
#!/usr/bin/python3
#
# Checks that the upstream DNS has been set correctly and that
# SSL certificates have been signed, etc., and if not tells the user
# what to do next.
import sys, os, os.path, re, subprocess, datetime, multiprocessing.pool
import dns.reversename, dns.resolver
import dateutil.parser, dateutil.tz
i... |
# flake8: noqa
import os
import time
import numpy
import numpy as np
from skimage.data import camera
from skimage.metrics import peak_signal_noise_ratio as psnr
from skimage.metrics import structural_similarity as ssim
from aydin.features.standard_features import StandardFeatureGenerator
from aydin.io.datasets import... |
import bpy
import bmesh
from inspect import getmembers
from pprint import pprint
class SetupOperator(bpy.types.Operator):
bl_idname = "blendertodayz.setup"
bl_label = "Reset Scene"
def remove_object(self, obj):
if isinstance(obj, bpy.types.Collection):
for child_col in obj.children:
... |
'''
* Copyright 2018 Canaan 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... |
def pattern(n):
count = n
for i in range(n):
for j in range(n - i - 1):
print(' ', end='')
for k in range(2 * i + 1):
print(count, end='')
count = count - 1
print()
print("Enter the number of rows: ")
n = int(input())
patte... |
#
# 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 us... |
# -*- coding: utf-8 -*-
#Import Statements
import pandas as pd
import numpy as np
import nltk
import spacy
import courseToBOK
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
import re
from re import *
from nltk.util import ngrams
from nltk.corpus ... |
from .compare_text_read import compare_text, get_all_possible_mappings
def test_get_all_possible_mappings_1():
orig = [1, 2, 3, 5]
alt = [0, 1, 2, 3, 4, 5, 4, 3, 2]
result = get_all_possible_mappings(orig, alt)
assert len(result) == 4
assert len(result[0]) == 1
assert 1 in result[0]
assert len(result[1]) == 2... |
אוהבים את סופרטולז אבל לא רוצים להיכנס לפייסבוק?!
קבלו את סופרטולז לוואטאפ! 🚀 (beta)
בשבועיים האחרונים פיתחתי פלטפורמה לסרוויסים לוואטסאפ
מה הכוונה? כל רעויון לאפלקיציה שיש לכם יכולה עכשיו להשתמש בוואטספ כinput והoutput שלה!
ומאפשרת whatsapp automation ברמה גבוהה מאוד.
התכוונתי לשתף פה את המערכת וחשבתי מה יהיה יותר ... |
import pytest
from suite.resources_utils import wait_before_test
from suite.custom_resources_utils import (
read_ts,
patch_ts,
)
from settings import TEST_DATA
@pytest.mark.ts
@pytest.mark.parametrize(
"crd_ingress_controller, transport_server_setup",
[
(
{
"type":... |
import random
import string
def generate_codes(number_of_codes: int, code_length: int):
"""Generates X number of random codes based on the provided length.
Pramas:
-------
number_of_codes (int): The number of the random codes that shall be
created which should be unique also.
... |
import os
import torch
import torch.nn as nn
import numpy as np
from pymongo import MongoClient
class Net(nn.Module):
def __init__(self, D_in, D_out):
super(Net,self).__init__()
self.layer_1 = nn.Linear(D_in, D_out*2)
self.layer_out = nn.Linear(D_out*2, D_out)
self.relu = nn.ReLU()... |
# coding: utf8
# try something like
def index():
rows = db((db.sponsor.text!="")&(db.sponsor.active==True)&(db.sponsor.level!=SPONSOR_LEVELS[-3])).select()
if rows:
return dict(sponsors_detail=rows)
else:
return plugin_flatpage()
def prospectus(): return plugin_flatpage()
@auth.requires_lo... |
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, FuncFormatter
import numpy as np
def latexify(fig_width=None, fig_height=None, columns=1):
"""Set up matplotlib's RC params for LaTeX plotting.
Call this before plotting a figure.
Parameters
----------
... |
import os
import sys
from copy import deepcopy
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SERVICES_DIR = os.path.join(os.path.dirname(BASE_DIR), 'services')
ALLOWED_HOSTS = ['localhost', '127.0.0.1',... |
# Tencent is pleased to support the open source community by making GNES available.
#
# Copyright (C) 2019 THL A29 Limited, a Tencent company. 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... |
from . import base_processing
from . import FamilyHistory
from . import HealthAndMedicalHistory
from . import LifestyleAndEnvironment
from . import PsychosocialFactors
from . import SocioDemographics
"""
Pre-processing classes.
Load and select features for each dataset in the UK biobank.
""" |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Hang Zhang
## ECE Department, Rutgers University
## Email: zhang.hang@rutgers.edu
## Copyright (c) 2017
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this sou... |
config = {
'device': 'cuda:0',
'seed': 42,
# config for logging
'logging': {
'log_file': 'run.log',
'fmt': '%(asctime)s: %(message)s',
'level': 'INFO',
},
# config to load and save network
'net': {
'saved_net_path': None,
'net_path': 'models/resnet.p... |
#####################################################################################
# Compression Summary for Error Correction Benchmarking
# zar-lab ucla
# 5/17/18
# supervisor: Serghei Mangul
# author: Keith Mitchell
"""
Functions Contained
check_existence: checks if the filename supplied has already ... |
# -*- coding: utf-8 -*-
"""Contains constants for middleware layer."""
from typing import Tuple, Union
class Text:
"""Contains constants for text parameters."""
@property
def global_font(self) -> str:
"""Used for setting global font for text."""
return "Helvetica"
@property
def... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
num = 10
if num < 0 or num > 10: # 判断值是否在小于0或大于10
print 'hello'
else:
print 'undefine' |
import datetime
import os
import random
import time
import warnings
import hydra
import torch
from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf
from torch.cuda.amp import autocast, GradScaler
from torch.nn import functional as F
from torch.utils.data import DataLoader, WeightedRandomSampl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.