content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
#
# packaging.py
#
# Copyright (C) 2012, 2013 Steve Canny scanny@cisco.com
#
# This module is part of python-pptx and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
'''
The :mod:`pptx.packaging` module coheres around the concerns of reading and
writing p... |
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import *
from Profile.forms import ProfileUpdateForm
from Profile.models import Profile
from .models import Posts,Like,Logins
from django.contrib import messages
from... |
"""
Copyright (c) 2016 Cyrill Jauner
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, modify, merge, publish, distribute, ... |
"""Queries the database for specific genes."""
import sys
from bloom_filter import encode
import database
def main(f=None):
"""Reads in queries from a file and searches for them. If no file present,
reads in quieries from the standard input and searches for them.
Note: queries from standard in have a ma... |
from pathlib import Path
from gpxpy import gpx as gpxpy
import matplotlib.pyplot as plt
import osmnx as ox
class Plotter(object):
FIGSIZE = (15,15)
COLOR_BACKGROUND = '#10627a'
COLOR_FOOTPRINT = '#083440'
COLOR_ROUTE = '#f30c2c'
def __init__(self, walk_id, render_dir):
self._walk_id = wal... |
# -*- coding: utf-8 -*-
# !/usr/bin/python
#
# Copyright (c) Contributors to the Open 3D Engine Project.
# For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
# --------------------------------------------------------------... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Muhammad Bilal Shaikh"
__copyright__ = "Copyright 2021, AR-ResNetX"
__license__ = "GPL"
__version__ = "1.0.1"
__email__ = "mbs.techy@gmail.com"
__status__ = "Production"
import pickle
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
... |
from .dist_utils import (DistOptimizerHook, allreduce_grads, get_dist_info,
init_dist)
from .evaluation import (DistEvalTopKAccuracyHook, mean_class_accuracy,
parallel_test, softmax, top_k_acc, top_k_accuracy,
top_k_hit)
from .fp16 import Fp16Op... |
from django.contrib import admin
from auth.models import InviteCode
@admin.register(InviteCode)
class InviteCodeAdmin(admin.ModelAdmin):
pass |
#!/usr/bin/python
# create database and tables
import sqlite3 as lite
datafile = "sensor_stream.db"
contolFile = "control_stream.db"
con = lite.connect(datafile)
cur = con.cursor()
cur.execute("create table sensor_log(time_stamp date, sensor_id integer, temperature real, humidity real)")
con.close()
con = lite.con... |
import sys, pathlib
sys.path.append(pathlib.Path(__file__).parent.parent / 'src')
from {{filename}} import {{filename}}
import unittest
class {{filename}}Test(unittest.TestCase):
def test_init(self):
ins = {{filename}}()
self.assertEqual({{filename}}, type(ins))
def test_raise(self):
wi... |
import unittest
from datastructure.oop.progression.test_progression import FibonacciProgression
class MyTestCase(unittest.TestCase):
def test_something(self):
p = FibonacciProgression(2, 2)
self.assertEqual(42, [next(p) for i in range(8)][7])
if __name__ == '__main__':
unittest.main()
|
import logging
import boto3
import os
from botocore.exceptions import ClientError
import json
QUEUE_URI = os.getenv("QUEUE_URI")
logger = logging.getLogger()
logging.basicConfig(level=logging.INFO,
format='%(asctime)s: %(levelname)s: %(message)s')
sqs_client = boto3.client("sqs", region_name = os.... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
size:本堆块的长度。长度计算方式:size字段长度+用户申请的长度+对齐。libc以size_T长度*2为粒度对齐。
例如32bit以4*2=8byte对齐,64bit以8*2=0×10对齐。因为最少以8字节对齐,所以size一定是8的倍数,故size字段的最后三位恒为0,libc用这三个bit做标志flag。
比较关键的是最后一个bit(pre_inuse),用于指示相邻的前一个堆块是alloc还是free。如果正在使用,则bit=1。
libc判断当前堆块是否处于free状态的方法就是判断下一个堆块的pre_inuse是否为1。... |
import mock
import pytest
from nose.tools import assert_equal
from addons.forward.tests.utils import ForwardAddonTestCase
from tests.base import OsfTestCase
from website import settings
pytestmark = pytest.mark.django_db
class TestForward(ForwardAddonTestCase, OsfTestCase):
def setUp(self):
super(TestF... |
# -*- coding: utf-8 -*-
"""\
CML Execution Utilities
-----------------------
"""
import os
import shutil
import logging
import glob
from ..utils import osutils
_lgr = logging.getLogger(__name__)
def is_caelus_casedir(root=None):
"""Check if the path provided looks like a case directory.
A directory is dete... |
"""
Referenced from
https://github.com/chainer/chainer/pull/3351
originally made by @himkt
"""
from chainer import reporter
from chainer.training import util
def greater(current_val, best_val):
return current_val > best_val
def less(current_val, best_val):
return current_val < best_val
class EarlyStoppi... |
from django.apps import AppConfig
class NyokaserverConfig(AppConfig):
name = 'nyokaserver'
|
# Find the number of letters "a" or "A" in a string using control flow
counter = 0
string = 'Python is a widely used high-level programming language for general-purpose programming, ' \
'created by Guido van Rossum and first released in 1991. An interpreted language, Python has a design ' \
'philos... |
from typing import Optional
from dataclasses import dataclass
from .InvoiceDataResult import InvoiceDataResult
from .BasicResponse import BasicResponse
@dataclass
class QueryInvoiceDataResponse(BasicResponse):
"""Response type of the POST /queryInvoiceData REST operation
:param invoice_data_result: Invoice d... |
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
from abc import ABC, abstractmethod
from typing import List
import requests
from airbyte_cdk.sources.declarative.types import Record
class HttpExtractor(ABC):
@abstractmethod
def extract_records(self, response: requests.Response) -> List[Record]:
... |
metros = float(input('Digite um valor em metros: '))
centimetros = metros * 100
milimetros = metros * 1000
decimetros = metros * 10
decametro = metros / 10
hectometro = metros / 100
kilometro = metros / 1000
print('A conversão de metro para CM foi {} \n e MM foi {} \n em DM foi {} \n em DAM foi {} \n em HM {} \n e ... |
from django.contrib import admin
from .models import Contact, Invoice, Item, InvoiceItem, Payment
# Register your models here.
class ContactAdmin(admin.ModelAdmin):
list_display = ("contact_type", 'name','email', 'city', 'pincode')
search_fields = ("contact_type", 'name','email', 'city', 'pincode')
admin.site... |
from machinable import Experiment
class TestView(Experiment):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._state = None
def hello(self):
return "there"
def set_state(self, state):
self._state = state
def get_state(self):
return... |
# 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 itasca import UDEC_Connection
udec = UDEC_Connection()
udec.connect()
for i in range(10):
print "sending", i
udec.send(i)
value = udec.receive()
print "got", value, "from UDEC"
udec.send(-1)
udec.end()
|
import math
import sys
import itertools
def strange_multiplication_1225():
case_arr = list(map(int, sys.stdin.readline().split()))
case_1_val = 0
case_2_val = 0
for num1 in str(case_arr[0]):
case_1_val += int(num1)
for num2 in str(case_arr[1]):
case_2_val += int(num2)
sys.stdou... |
import os
import difflib
from labugr import windows
__all__ = ['ayuda']
def __nombre_funciones():
"""
Devuelve una lista de las funciones en el directorio de trabajo
"""
lista = os.listdir()
for i in range(0, len(lista)):
lista[i] = lista[i].split('-')[0]
return lista
def ayuda(funcion):
"""
Muestra en ... |
#!/usr/bin/env python
import sys
import os
import json
import re
from functools import cmp_to_key
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "libs", "pandemia-client-py"))
import pandemia
def get_path(path):
return os.path.join(os.path.dirname(__file__), "..", "..", path)
def ident_4(... |
from datetime import datetime
import random
import sys
# datetime object containing current date and time
now = datetime.now()
dt_string = now.strftime("%Y-%m-%dT%H:%M:%S")
gtws = ['eui-b827ebfffe998292',
'eui-b827ebfffe411ace',
'eui-b827ebfffe13b290',
'eui-b827ebfffe71f386']
ms = [[125300, 1... |
import cv2
img = cv2.imread("../lung_gray.png")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# box filter
res = cv2.boxFilter(img, -1, (3,3))
cv2.imshow("boxfilter", res)
cv2.imwrite("./boxfilter_image.png", res)
# gussian filter
gussian_res = cv2.GaussianBlur(img,(3, 3),1.5)
cv2.imwrite("./gussian_res_image.png", gu... |
""" Provides a CSV interface for sh-style whitespace separated values. """
from contextlib import contextmanager
from subprocess import list2cmdline
from shlex import split as cmdline2list
from .csv2 import csv_open
class WsvValueError(ValueError):
""" Raised when a WSV line cannot be parsed. """
def __init... |
import csv
import nltk.data
import re
from sklearn import feature_extraction
import random
import os
from collections import defaultdict
LABELS = ['agree', 'disagree', 'discuss', 'unrelated']
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
def print_confusion_matrix(cm):
lines = ['CONFUS... |
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import SKU, GoodsCategory, SPU
from meiduo_admin.serializers.categorys import CategoriesSerializer
from meiduo_... |
"""
Simple functions for interacting with coresignal in a progromatic way
"""
# TODO: make these return WH objects
import pandas as pd
import requests
import numpy as np
import os, sys
import json
from pydantic import Json, HttpUrl
from typing import List, Dict, Optional, Any, Union
from WH_Utils.Objects.Company impo... |
import sys
import pandas
import networkx as nx
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from graphframes import *
sc=SparkContext("local", "degree.py")
sqlContext = SQLContext(sc)
''' return the simple closure of the graph as a graphframe.'''
def simple(g):
... |
""" This module contains unit tests for utils-module. """
import sys
sys.path.append('../cloudnetpy')
from dataclasses import dataclass
import numpy as np
import numpy.ma as ma
from numpy.testing import assert_array_almost_equal
import pytest
from cloudnetpy import utils
def test_binvec():
""" Unit tests for unit... |
"""Scraper for the Vermont Environmental
CourtID: vt
Court Short Name: VT
Court Contact: submit form here https://www.vermontjudiciary.org/website-feedback-form
"""
from . import vt
class Site(vt.Site):
def get_backscrape_max(self):
return 1
def get_division_id(self):
return "2"
|
from hypernets.core.ops import HyperInput
from hypernets.core.callbacks import SummaryCallback
from hypernets.core.search_space import HyperSpace, Choice
from hypernets.searchers.random_searcher import RandomSearcher
from hyperts.hyper_ts import HyperTS
from hyperts.utils import consts, get_tool_box
from hyperts.datas... |
## Dependencies
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
import math
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
from FindLaneLine import *
## G... |
"""
* *******************************************************
* Copyright VMware, Inc. 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL ... |
"""Label segments with language and speaker by matching original transcript to CTM."""
from __future__ import annotations # for difflib.SequenceMatcher type annotation
import difflib
from collections import deque
from collections import namedtuple
from itertools import islice
from typing import Any
from typing import... |
#--------------------------------------------#
# 该部分代码用于看网络结构
#--------------------------------------------#
import torch
from torchsummary import summary
from nets.deeplabv3_plus import DeepLab
if __name__ == "__main__":
# 需要使用device来指定网络在GPU还是CPU运行
device = torch.device('cuda' if torch.cuda.is_available(... |
import numpy as np
from utils import matrix_ref, int_face, notation, swap4, colors, corners
class FaceCube:
def __init__(self):
self.color_matrix = matrix_ref.copy()
def swap(self, to_swap, way):
(self.color_matrix[to_swap[0]], self.color_matrix[to_swap[1]],
self.color_matrix[to_swap... |
from abc import ABC, abstractmethod
class MessageConverter(ABC):
"""
Abstract class, which declares methods for converting just single message for specific format.
All important operations of data conversion should be done in this class.
"""
@abstractmethod
def modify_data(self, input_message... |
# pip install fbchat
from fbchat import log
from fbchat import Client
class Bot(Client):
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
log.info("{} from {} in {}".for... |
import os
import codecs
import warnings
import chardet
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def _get_encoding(b):
return chardet.detect(b)['encoding']
def _get_encoding_from_file(path):
with open(path, 'rb') as f:
return _get_encoding(f.read())
def auto_open(path):
encoding =... |
# Author : Achintya Gupta
from .swtlocalizer import SWTLocalizer
__version__ = "1.1.1"
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/flyss/myData/myCode/pythonWorkSpace/pyDownloader/pyResourceGet/uiDefines/SpiderDebugWindow.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, Qt... |
# -*- coding: utf-8 -*-
class ActionInterrupted(Exception):
"""
This exception can be raised by a :ref:`adminaction_requested` or :ref:`adminaction_start`
to prevent action to be executed
"""
class FakeTransaction(Exception):
pass
|
"""
Module: verification_stats_grid.py
Purpose: Process verification statistics generated by LMR_verify_grid.py on
various reconstruction experiments and produce a summary for comparison.
Originator: Greg Hakim | Dept. of Atmospheric Sciences, Univ. of Washington
| January 2017
Revisi... |
from django.contrib import admin
from .models import Perreria
# Register your models here.
admin.site.register(Perreria) |
import pytest
from bioconda_utils import bioconductor_skeleton
from bioconda_utils import cran_skeleton
from bioconda_utils import utils
config = {
'channels': ['conda-forge', 'bioconda', 'defaults']
}
def test_cran_write_recipe(tmpdir):
cran_skeleton.write_recipe('locfit', recipe_dir=str(tmpdir), recursiv... |
# Auto-generated at 2021-09-27T17:12:31.439417+08:00
# from: Justice Iam Service (4.1.0)
# Copyright (c) 2018 - 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
# pylint: disable=duplicate-code
# pylint: ... |
from django.contrib import admin
# Register your models here.
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser, Authority
admin.site.site_header = "Landgate Admin"
admin.site.site_title = "Survey Services Portal"
admin.site... |
from dataclass_factory import Factory
from shazamio.factory import FactorySchemas
from shazamio.models import ArtistInfo
from shazamio.models import SongSection, VideoSection, RelatedSection
from shazamio.models import TrackInfo
from shazamio.models import YoutubeData
from shazamio.models import ResponseTrack
FACTORY... |
from .util import *
from .pyfzf import Pyfzf
from .spinner import Spinner
from .session import BaseSession
from .fileloader import FileLoader
|
# Copyright (c) 2012-2019 Seafile Ltd.
# encoding: utf-8
from datetime import datetime
import logging
import re
import requests
import json
from django.core.management.base import BaseCommand
from django.urls import reverse
from django.utils import translation
from django.utils.translation import ungettext
from seahu... |
"""
Copyright 2021 Janrey "CodexLink" Licas
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, s... |
# from helpers.py.tree_node import Node
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
# from helpers.py.node import Node
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
... |
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
class Metrics:
"""
Methods for computing useful regression metrics
sse: Sum of squared errors
sst: Total sum of squared errors (actual vs avg(actual))
r_squared: Regression coefficient (R^2)
adj_r_squared: Adj... |
class NaZakupy:
def __init__(self,nazwa_produktu,ilosc,jednostka_miary,cena_jed):
self.nazwa_produktu=str(nazwa_produktu)
self.ilosc=int(ilosc)
self.jednostka_miary=str(jednostka_miary)
self.cena_jed=float(cena_jed)
def wyswietl_produkt(self):
print('nazwa : ' +s... |
"""
Dialogflow python requests package
"""
import sys
if 'install' not in sys.argv and 'egg_info' not in sys.argv:
from .dialogflow import Dialogflow
__version__ = '0.0.7'
__author__ = 'Mallikarjunarao Kosuri'
__email__ = 'malli.kv2@gmail.com'
|
import time
import tempfile
import json
import os
import urllib
import numpy as np
import pandas as pd
from selenium import webdriver
from selenium.common.exceptions import (NoSuchElementException,
ElementClickInterceptedException,
StaleEl... |
import pandas as pd
import numpy as np
import cv2
data_file = 'thinking.csv'
"""
labels must be a list of segments where the time serie class is true
(i.e. the list of segments where the drawer has "hands down")
"""
labels = [(29,96),(122,145),(162,185),(209,220),(244,261),(339,454)]
df = pd.read_csv('data/unlabe... |
# coding=utf-8
from lxml import etree
from app.utils.parse_url import parse_url
class SearchMetaclass(type):
"""
add __CrawlFunc__ and __CrawlFuncCount__ attr
"""
def __new__(cls, name, bases, attrs):
count = 0
attrs['__SearchFunc__'] = []
for k in attrs.keys():
if ... |
"""test distutils-related functionality and methods in src/distutils.h"""
import distutils.extension
import distutils.util
import os.path
import subprocess
import sys
import tempfile
import textwrap
import unittest
tests_dir = os.path.dirname(os.path.abspath(__file__))
if __name__ == '__main__':
plat_specifier ... |
#!/usr/bin/env python
import sys
import os
from types import StringType
# get bencode package from http://github.com/fishy/scripts/downloads
from bencode.bencode import bencode, bdecode, BTFailure
try :
torrent = sys.argv[1]
except IndexError :
print "Usage: \"%s <torrent_file> [tracker_url]\" to show torrent info ... |
import json
import sys
def check(flag):
processed = flag[::-1]
processed = processed.decode("base64")
final = json.loads(processed)
if (final['check_code'] != "AK4782"):
return False
if (final['flag_content']['numbers']*2 != 18529313):
return False
if (final['flag_content']['cha... |
from metaflow_test import MetaflowTest, ExpectationFailed, steps, tag
class CardTimeoutTest(MetaflowTest):
"""
Test that checks if the card decorator works as intended with the timeout decorator.
# This test set an artifact in the steps and also set an timeout to the card arguement.
# It will assert t... |
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, A... |
"""Test the smarttub config flow."""
from unittest.mock import patch
from smarttub import LoginFailed
from openpeerpower import config_entries, data_entry_flow
from openpeerpower.components.smarttub.const import DOMAIN
from openpeerpower.const import CONF_EMAIL, CONF_PASSWORD
from tests.common import MockConfigEntry... |
from chain import chain
from copy import deepcopy
import numpy as np
def create(*args,**kwargs):
return CLP(*args,**kwargs)
class CLP(chain):
def __init__(self,
rodLength=15,
rodDiameters=[1.0],
rodBondLength=1.0,
rodBondTypes=[1.0],
rod... |
#!/usr/bin/env python
import unittest
from cogent3 import DNA, make_aligned_seqs
from cogent3.core.annotation import Feature, Variable, _Feature
from cogent3.core.location import Map, Span, as_map
from cogent3.core.sequence import DnaSequence, RnaSequence
__author__ = "Gavin Huttley"
__copyright__ = "Copyright 2007... |
import robosuite as suite
from robosuite.models import MujocoWorldBase
from robosuite.models.robots import UR5e
from robosuite.models.grippers import gripper_factory
from robosuite.models.arenas import EmptyArena
from mujoco_py import MjSim, MjViewer
world = MujocoWorldBase()
ur5 = UR5e()
gripper = gripper_factory("R... |
from unittest import TestCase, main
import os
import dask
import numpy as np
import pandas as pd
import pandas.testing as pdt
from skbio import DNA
from qiime2.plugin.testing import TestPluginBase
from qiime2 import Artifact, Metadata
from q2_types.feature_data import DNAIterator, DNAFASTAFormat
from q2_sidle._tree... |
# 이미지 및 라벨을 생성하기 위한 코드 ( Team. NMSP )
import numpy as np
import cv2
import os
DATA_DIR = "Group_Image" # 데이터(이미지) 생성 경로
LABEL_DIR="Group_Label" # 라벨 생성 경로
if os.path.exists(DATA_DIR) is False:
os.makedirs(DATA_DIR) # 이미지 경로 폴더 생성
if os.path.exists(LABEL_DIR) is False:
os.makedirs(LABEL_DIR) # 라벨 경로 폴더 생성
... |
"""
Unary operations on SomeValues.
"""
from __future__ import absolute_import
from collections import defaultdict
from rpython.tool.pairtype import pair
from rpython.flowspace.operation import op
from rpython.flowspace.model import const, Constant
from rpython.flowspace.argument import CallSpec
from rpython.annotato... |
#!/usr/bin/env python3
# ==============================================================================
#
import freeton_utils
from freeton_utils import *
class SubscriptionDebot(BaseContract):
def __init__(self, tonClient: TonClient, ownerAddress: str, signer: Signer = None):
genSigner = generate... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-1405-Longest-Happy-String.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-02-07
==============================... |
# Generated by Django 2.2.13 on 2020-06-30 21:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('features', '0021_historicalfeaturesegment'),
]
operations = [
# this migration should have no affect but should fix the issues on dev after
... |
"""
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 use this ... |
import datetime
from operator import itemgetter
from babel.core import get_global
from babel.numbers import get_currency_name, get_territory_currencies
from django import forms
from django_file_form.forms import FileFormMixin
from addressfield.fields import AddressField
from hypha.apply.stream_forms.fields import Mul... |
"""
Configuration file for the Python Atmospheric data Community Toolkit (ACT)
The values for a number of ACT parameters and the default metadata created
when reading files, correcting fields, etc. is controlled by this single
Python configuration file.
Examples:
---------
from act.config import DEFAULT_DATASTREAM_NAM... |
"""Attribute Tags for IPP."""
from .enums import IppTag
ATTRIBUTE_TAG_MAP = {
"attributes-charset": IppTag.CHARSET,
"attributes-natural-language": IppTag.LANGUAGE,
"document-number": IppTag.INTEGER,
"printer-uri": IppTag.URI,
"requesting-user-name": IppTag.NAME,
"job-id": IppTag.INTEGER,
"d... |
import numpy as np
from sklearn import preprocessing, neighbors, model_selection, svm
import pandas as pd
import pickle
#import serial
import re
import random
from sklearn.metrics import confusion_matrix, plot_confusion_matrix, plot_precision_recall_curve
import matplotlib.pyplot as plt
from sklearn.metrics import accu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module mainly provides a ``XenaDataset`` class representing one Xena
matrix in a Xena cohort. Three class, ``GDCOmicset``, ``GDCPhenoset``,
``GDCSurvivalset`` and ``GDCAPIPhenoset``are derived from ``XenaDataset``,
representing genomic data, phenotype info of TCGA ... |
import torch.nn as nn
import torchvision.models as models
from .helper import init, make_standard_block
class VGG(nn.Module):
def __init__(self, use_bn=True): # Original implementation doesn't use BN
super(VGG, self).__init__()
if use_bn:
vgg = models.vgg19(pretrained=True)
... |
from abc import abstractmethod
from copy import deepcopy
from hrl.salient_event.SalientEventClass import SalientEvent
import numpy as np
from gym import Wrapper
class GoalConditionedMDPWrapper(Wrapper):
"""
this abstract class is a wrapper that represents a goal conditioned MDP
user must specify a start a... |
from typing import Tuple
import pytest
from hypothesis import given
from dendroid.hints import (Item,
Key)
from tests.utils import (Map,
map_value_to_key)
from . import strategies
@given(strategies.empty_maps_with_keys)
def test_base_case(map_with_key: Tuple[Map,... |
# Copyright (c) 2021 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial.
# Full text can be found in LICENSE.md
import os
import glob
import argparse
import cv2
import tqdm
from utils import *
import subprocess
import sys
module_path = os.path.abspa... |
# Copied from chromium build/.
#
# Copyright 2014 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.
"""Helper functions useful when writing scripts that integrate with GN.
The main functions are ToGNString and FromGNString ... |
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core as _c... |
import time
import sys
from signalrcore.hub_connection_builder import HubConnectionBuilder
def input_with_default(input_text, default_value):
value = input(input_text.format(default_value))
return default_value if value is None or value.strip() == "" else value
server_url = input_with_default('Enter your s... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name="index"),
path('list',views.res_list,name="list"),
path('search',views.res_search,name="search"),
path('restaurants/<int:id>',views.res_detail,name="detail"),
path('create_reservation/<int:id>',views.create_r... |
from django.db.models import Count, Max, F, Value
from codice import settings
from files.models import File
from repos.models import Branch, Repository
hotspot_threshold = settings.CODICE_HOT_SPOTS_THRESHOLD
def max_changes(repo: Repository, branch: Branch):
qs = File.objects.filter(repository=repo, branch=bran... |
from cupyx.scipy.ndimage.filters import correlate # NOQA
from cupyx.scipy.ndimage.filters import convolve # NOQA
from cupyx.scipy.ndimage.interpolation import affine_transform # NOQA
from cupyx.scipy.ndimage.interpolation import map_coordinates # NOQA
from cupyx.scipy.ndimage.interpolation import rotate # NOQA
fr... |
# -*- coding: utf-8 -*-
import os,sqlite3
db_file = os.path.join(os.path.dirname(__file__),'test.db')
if os.path.isfile(db_file):
os.remove(db_file)
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
users = [('A-001', 'Adam', 95),
('A-002', 'Bart', 62),
('A-003', 'Lisa', 78)]
cursor.execute('cre... |
import requests
import re
class GenderResponse:
"""
A class that acts as a wrapper for all responses which classify a name into a gender.
Attributes:
ID (str): The ID of the request
first_name (str): The first name that was classified
last_name (str): The last ... |
import collections
import sys
import pip
import json
import changelogs
import urllib.request
from packaging import version
from urllib.error import HTTPError, URLError
from distutils.version import LooseVersion
SECURITY_NOTICE_KEYWORDS = [
'security', 'vulnerability', 'cve', 'xss', 'sql injection',
]
DISPLAY_TAB... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.