filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_7960 | # User role
ADMIN = 0
STAFF = 1
USER = 2
ROLE = {
ADMIN: 'admin',
STAFF: 'staff',
USER: 'user',
}
# User status
INACTIVE = 0
LOGOUT = 1
LOGIN = 2
PLAY = 3
STATUS = {
INACTIVE: 'inactive',
LOGOUT: 'logout',
LOGIN: 'login',
PLAY: 'play',
}
|
the-stack_0_7961 | import math
def fibonacciIterative(n):
if(n == 0):
return 0
if(n == 1):
return 1
first = 0
second = 1
for i in range(1,n):
tmp = first + second
first = second
second = tmp
return second
def main():
n = int(input("Enter a number: "))
if... |
the-stack_0_7963 | #!/usr/bin/python3
import os
import sys
import time
import shutil
import hashlib
projectRoot = "https://www.sansay.co.uk/jamstack"
# Parse any options set by the user on the command line.
validBooleanOptions = []
validValueOptions = ["-domainName", "-contentFolderPath", "-jekyllFolderPath", "-buildPassword"]
userOpt... |
the-stack_0_7964 | from socket import *
serverName = '0-pc'
serverPort = 12001
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
sentence = input("input lowercase sentence")
clientSocket.send(sentence.encode())#字符串转化为字节类型
modifiedSentence = clientSocket.recv(1024)
print("from server:", modifiedSen... |
the-stack_0_7965 | import json
import os
from torch.utils.data import Dataset
from config import global_config
from pipeline.actor import Actor
class EvalDataset(Dataset):
def __init__(self, dataset_file, memory, controller):
with open(dataset_file, "r") as f:
self.dataset = json.load(f)
self.folder = ... |
the-stack_0_7966 | from datasette.plugins import DEFAULT_PLUGINS
from datasette.utils import detect_json1
from datasette.version import __version__
from .fixtures import ( # noqa
app_client,
app_client_no_files,
app_client_with_hash,
app_client_shorter_time_limit,
app_client_larger_cache_size,
app_client_returned... |
the-stack_0_7968 | """Additional in template functions for the lattedb module
"""
from django import template
register = template.Library() # pylint: disable=C0103
@register.inclusion_tag("progress-bar.html")
def render_progress_bar(danger, warning, info, success, total):
if total > 0:
context = {
"danger": d... |
the-stack_0_7969 | from fastapi import APIRouter, Request, HTTPException, Depends, Query
from fastapi.responses import StreamingResponse
import aiohttp
import csv
import io
router = APIRouter()
@router.get("/battlefy/{tournament_id}")
async def battlefy_seed_csv(request: Request, tournament_id: str):
"""Returns a CSV of teams and ... |
the-stack_0_7970 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sphinx_py3doc_enhanced_theme
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
'sphinx.ext.doctest',
'sphinx.ext.extlinks',
'sphinx.ext.ifconfig',
'sphinx.ext.napoleon',
'sphinx.e... |
the-stack_0_7972 | # coding: utf-8
from __future__ import division
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import data
def _get_shape(i, o, keepdims):
if (i == 1 or o == 1) and not keepdims:
return [max(i,o),]
else:
return [i, o]
def _slice(tensor, size, i):
"""Gets s... |
the-stack_0_7973 | # #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# <HTTPretty - HTTP client mock for Python>
# Copyright (C) <2011-2020> Gabriel Falcão <gabriel@nacaolivre.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to ... |
the-stack_0_7974 | # Copyright 2012 OpenStack 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 required b... |
the-stack_0_7975 | """HTTP/1.1 client library
A backport of the Python 3.3 http/client.py module for python-future.
<intro stuff goes here>
<other stuff, too>
HTTPConnection goes through a number of "states", which define when a client
may legally make another request or fetch the response for a particular
request. This diagram detail... |
the-stack_0_7977 | from scipy.spatial.transform.rotation import Rotation
from alitra import Euler, Quaternion
def quaternion_to_euler(
quaternion: Quaternion, sequence: str = "ZYX", degrees: bool = False
) -> Euler:
"""
Transform a quaternion into Euler angles.
:param quaternion: A Quaternion object.
:param sequenc... |
the-stack_0_7978 |
## 这里我们用逻辑回归来判断手写数字的扫描图像来判断数字是多少。
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
## 导入数据
digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target
n_samples = len(X_digits)
## 拆分训练集和测试集
X_train = X_digits[:.9 * n_samples]
y_train = y_digits[:.9 * n_samples]
X... |
the-stack_0_7980 | from __future__ import division
import chainer
import chainer.functions as F
from chainercv.links import Conv2DBNActiv
from chainercv.links import SeparableConv2DBNActiv
class SeparableASPP(chainer.Chain):
"""Atrous Spatial Pyramid Pooling with Separable Convolution.
average pooling with FC layer
... |
the-stack_0_7981 | from setuptools import setup
import sys
if not sys.version_info[0] == 3 and sys.version_info[1] < 5:
sys.exit('Python < 3.5 is not supported')
version = '0.74'
setup(
name='steampy',
packages=['steampy', 'test', 'examples', ],
version=version,
description='A Steam lib for trade automation',
a... |
the-stack_0_7982 | """Moses tests."""
from typing import ClassVar, Type
import pytest
from gt4sd.algorithms.conditional_generation.guacamol import (
AaeGenerator,
MosesGenerator,
OrganGenerator,
VaeGenerator,
)
from gt4sd.algorithms.core import AlgorithmConfiguration
from gt4sd.algorithms.registry import ApplicationsRe... |
the-stack_0_7983 | """
Copyright (c) 2019 Imperial College London.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
import torch.nn as nn
from . import net_utils
class _Residual_Block(nn.Module):
def __init__(self, num_chans=64):
super(... |
the-stack_0_7984 | # Copyright 2017 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 applicable ... |
the-stack_0_7985 | import datetime
from django.test import TestCase
from django.utils import timezone
from django.urls import reverse
from .models import Question
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns False for question... |
the-stack_0_7986 | import os
import re
import shutil
import sys
import ctypes
from pathlib import Path
from colorama import Fore, Back, Style
from .settings import *
if sys.version_info[0] < 3 or sys.version_info[1] <= 5:
print("\nPlease restart with Python 3.6+\n")
print("Current Python version:", sys.version_info)
exit(-1)... |
the-stack_0_7988 | import json
import botsdk.Bot
import botsdk.BotRequest
from botsdk.tool.MessageChain import MessageChain
from botsdk.tool.BotPlugin import BotPlugin
from botsdk.tool.Cookie import *
class plugin(BotPlugin):
def __init__(self):
super().__init__()
self.listenType = []
#[["type1",func],["type2"... |
the-stack_0_7992 | import copy
site = {
'html': {
'head': {
'title': 'Куплю/продам телефон недорого'
},
'body': {
'h2': 'У нас самая низкая цена на iPhone',
'div': 'Купить',
'p': 'Продать'
}
}
}
def f(n,data=site, new_list =list()):
if n == 0:
... |
the-stack_0_7996 | from unittest.mock import Mock, patch
from urllib.parse import urlencode
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from django.utils import translation
from phonenumber_field.phonenumber import PhoneNumber
from two_factor.gateways.fake import Fake... |
the-stack_0_7997 | """This module contains the general information for LsbootUsbFlashStorageImage ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class LsbootUsbFlashStorageImageConsts:
TYPE_EMBEDDED_LOCAL_JBOD = "embedded-local-jbod"
TYP... |
the-stack_0_7998 | from typing import Dict, List
from allennlp.common.checks import ConfigurationError
# from allennlp.common.params import Params
from allennlp.common.util import pad_sequence_to_length
from allennlp.data.tokenizers.token import Token
from allennlp.data.token_indexers.token_indexer import TokenIndexer
from allennlp.data... |
the-stack_0_8001 | from flask import render_template, Blueprint
from flask_login import login_required, current_user
import datetime
from project import app, db, localSystem
from project.models import *
home_blueprint = Blueprint(
'home', __name__,
template_folder = 'templates'
)
@home_blueprint.route('/')
def home():
loca... |
the-stack_0_8003 | #!/usr/bin/env vpython
# Copyright 2020 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.
import logging
import os
import subprocess
import sys
import tempfile
import time
import unittest
import mock
from parameterized impo... |
the-stack_0_8006 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from django.http import JsonResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators import csrf
# from django.contrib.auth.decorators import login_required
from tool.tools impo... |
the-stack_0_8007 | from dataclasses import asdict
from functools import wraps
import json
from protobuf_to_dict import protobuf_to_dict
from dacite import from_dict
from schemes.graph import GraphNode, GraphRelation
from configs.config import logger
def raise_customized_error(capture, target):
def _raise_customized_error(func):
... |
the-stack_0_8008 | import multiprocessing as mp
import os
from glob import glob
from subprocess import run
import pandas as pd
def ensure_file(file):
"""Ensure a single file exists, returns the full path of the file if True or throws an Assertion error if not"""
# tilde expansion
file_path = os.path.normpath(os.path.expand... |
the-stack_0_8009 | import asyncio
from aiogram import types, Dispatcher
from aiogram.dispatcher import DEFAULT_RATE_LIMIT
from aiogram.dispatcher.handler import CancelHandler, current_handler
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.utils.exceptions import Throttled
class ThrottlingMiddleware(BaseMiddlewar... |
the-stack_0_8010 | #!/usr/bin/env python
from common.dbconnect import mongo_connect, find_session
from common.hashmethods import *
from common.entities import pcapFile
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from canari.maltego.entities import EmailAddress
from canari.maltego.mes... |
the-stack_0_8011 | import pandas as pd
import numpy as np
import itertools as it
import functools as ft
from numpy import zeros, arange
from collections import defaultdict
try:
from numba import jit, njit
except ImportError:
print('Install numba')
def multi_args(function, constants, variables, isProduct=False, maxLimit=None):
... |
the-stack_0_8012 | # Copyright (c) 2014 Spotify AB
#
# 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... |
the-stack_0_8013 | # Warning
import warnings
import sklearn.exceptions
warnings.filterwarnings('ignore', category=DeprecationWarning)
warnings.filterwarnings('ignore', category=FutureWarning)
warnings.filterwarnings("ignore", category=sklearn.exceptions.UndefinedMetricWarning)
# Python
import numpy as np
import pandas as pd
import tqdm
... |
the-stack_0_8016 | """Core classes and exceptions for Simple-Salesforce"""
# has to be defined prior to login import
DEFAULT_API_VERSION = '29.0'
import logging
import warnings
import requests
import json
try:
from urlparse import urlparse, urljoin
except ImportError:
# Python 3+
from urllib.parse import urlparse, urljoi... |
the-stack_0_8017 | import statistics
import numpy as np
import logging
# ### self defined class
from carViewLibV2 import runWithFPS
class landMark():
def __init__(self, id):
self.markVaildCount = 4
self.markPosXList = []
self.markPosYList = []
self.frameTimeList = []
self.id = id
def addPo... |
the-stack_0_8018 | #!/usr/bin/python
# Classification (U)
"""Program: rabbitmqadmin_list_vhost_topic_permissions.py
Description: Unit testing of RabbitMQAdmin.list_vhost_topic_permissions in
rabbitmq_class.py.
Usage:
test/unit/rabbitmq_class/rabbitmqadmin_list_vhost_topic_permissions.py
Arguments:
"""
... |
the-stack_0_8019 | import numpy
import scipy.linalg
import time
from pauxy.estimators.mixed import (
variational_energy, variational_energy_ortho_det, local_energy
)
from pauxy.estimators.greens_function import gab, gab_spin, gab_mod, gab_mod_ovlp
from pauxy.estimators.ci import get_hmatel, get_one_body_matel
from pauxy.u... |
the-stack_0_8020 | # Standard libraries
import logging
import random
import re
import time
# third party libraries
import tweepy
class RetweetGiveaway:
def __init__(self, api, user):
"""
RetweetGiveaway class constructor, requires api object and user object
:param api tweepy.API: api object from tweepy lib... |
the-stack_0_8023 | # 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
# distributed under the... |
the-stack_0_8026 | from kubernetes import client as k8s_client
from kubernetes.client import rest as k8s_rest
from kubernetes import config as k8s_config
import boto3
from botocore.client import Config
from botocore.exceptions import ClientError
import argparse
import os
import tarfile
class MinioUploader(object):
def __init__(sel... |
the-stack_0_8027 | # 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... |
the-stack_0_8028 |
#Example case how to write a se file
#We write 3 cycles in a newly created file example.se.h5
import sewrite
#create the h5 output file
file_sewrite = sewrite.startfile('example.se.h5')
cycles=[1,2,3]
#writing global parameters:
#Make sure that you write the right units to ensure that MPPNP compute with th... |
the-stack_0_8030 | # -*- coding: utf-8 -*-
from urllib.parse import quote, quote_plus, unquote, urlencode
from plexapi import X_PLEX_CONTAINER_SIZE, log, utils
from plexapi.base import PlexObject
from plexapi.exceptions import BadRequest, NotFound
from plexapi.media import MediaTag
from plexapi.settings import Setting
class Library(Pl... |
the-stack_0_8034 | """
Day 2: 1202 Program Alarm
"""
from itertools import product
from utils import get_int_list
from intcode.cpu import IntcodeCpu
def puzzle1():
prog = get_int_list('day2')
prog[1] = 12
prog[2] = 2
cpu = IntcodeCpu(prog)
cpu.run()
print(cpu[0])
def puzzle2():
prog = get_int_list('day2')... |
the-stack_0_8035 | # This file is part of the MapProxy project.
# Copyright (C) 2011 Omniscale <http://omniscale.de>
#
# 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... |
the-stack_0_8036 | # -*- coding: utf-8 -*-
# @Time : 2020/9/26
# @Author : Benny Jane
# @Email : 暂无
# @File : command.py
# @Project : Flask-Demo
import os
import logging
from logging.handlers import RotatingFileHandler
from flask import request
basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
project_name = os.path... |
the-stack_0_8037 | """
References:
[1] E. Branlard, M. Gaunaa - Cylindrical vortex wake model: skewed cylinder, application to yawed or tilted rotors - Wind Energy, 2015
[2] E. Branlard - Wind Turbine Aerodynamics and Vorticity Based Method, Springer, 2017
"""
#--- Legacy python 2.7
from __future__ import division
from __future__... |
the-stack_0_8039 | #Except for the pytorch part content of this file is copied from https://github.com/abisee/pointer-generator/blob/master/
from __future__ import unicode_literals, print_function, division
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import os
import time
import argparse
from datetime import datetime
impor... |
the-stack_0_8040 | #!/usr/bin/env python
from setuptools import setup, find_packages
desc = ''
with open('README.rst') as f:
desc = f.read()
setup(
name='wheelify',
version='0.1.4',
description=('Simple manylinux wheel builder utility'),
long_description=desc,
url='https://github.com/jmvrbanac/wheelify',
au... |
the-stack_0_8041 | from setuptools import setup
from setuptools import find_packages
import os
this_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_dir, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='megnet',
version='0.3.5',
description='MatErials Graph Netw... |
the-stack_0_8042 | """Message Flags class."""
import logging
import binascii
from insteonplm.constants import (MESSAGE_FLAG_EXTENDED_0X10,
MESSAGE_TYPE_ALL_LINK_BROADCAST,
MESSAGE_TYPE_ALL_LINK_CLEANUP,
MESSAGE_TYPE_ALL_LINK_CLEANUP_ACK... |
the-stack_0_8043 | # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
the-stack_0_8045 | #Crie um programa onde 4 jogadores um dado e tenham
#resultados aleatórios.
##Guarde esse resultados em um dicionário. No final, coloque esse
#dicionário em ordem ,sabendo que o vencedor tirou o maior número na dado.
from random import randint
from time import sleep
from operator import itemgetter
jogadores = {'Jogado... |
the-stack_0_8046 | # -*- coding: utf-8 -*-
import os
import click
from matplusc3d import combine_files
@click.command()
@click.argument('c3dfile', metavar='[filename.c3d]', required=False, type=click.Path())
@click.option('--overwrite', is_flag=True, help="Overwrite existing c3dfiles. "
"If not set, a file new file 'fil... |
the-stack_0_8047 | #
# MIT License
#
# Copyright (c) 2020 Pablo Rodriguez Nava, @pablintino
#
# 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
# t... |
the-stack_0_8048 | from django.urls import path, include
from .viewsets.numbers import (
NumbersViewset,
DetailNumbersViewset,
StartNumber,
StopNumber,
StatusNumber,
LoginNumber,
)
from .viewsets.messages import (
WhatsappChatAllViewset,
WhatsappChatViewset,
WhatsappChatDetailViewset,
WhatsappMedia... |
the-stack_0_8049 | # Copyright (c) 2019 The Johns Hopkins University/Applied Physics Laboratory
# 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/LICEN... |
the-stack_0_8050 | """
Project: SSITH CyberPhysical Demonstrator
Name: component.py
Author: Ethan Lew
Date: 02 October 2020
an object to establish communication and messaging between services
pub/sub approach -- establish service subscribers and publishers at
initialization. register topics and callbacks for service components.
"""
fro... |
the-stack_0_8051 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and Contributors
# See license.txt
from frappe.core.doctype.user_permission.user_permission import add_user_permissions, remove_applicable
from frappe.permissions import has_user_permission
from frappe.core.doctype.doctype.test_doctype import new_doctype... |
the-stack_0_8052 | # 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 may ... |
the-stack_0_8053 | from math import floor
from tweepy import API, OAuthHandler
from data_analysis.database import session, Tweet
consumer_key = 'dGx62GNqi7Yaj1XIcZgOLNjDb'
consumer_secret = 'ZCE896So7Ba1u96ICwMhulO2QO3oeZ5BeVyfUw1YbIYELzVyJs'
access_token = '1121993185-hGOTr3J40FlKGwWkiNWdeNVrcD4bqqW38SPiM3s'
access_token_secret = 'BAo... |
the-stack_0_8054 | import clr
import System
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
def DesignOptionIsPrimary(item):
if hasattr(item, "IsPrimary"): return item.IsPrimary
else: return False
items = UnwrapElement(IN[0])
if isinstance(IN[0], list): OUT = [DesignOptionIsPrimary(x) for x in items]
else: OUT = DesignO... |
the-stack_0_8061 | """ conver arff to csv format"""
import csv
import pandas as pd
def function_arfftocsv(source: str, dest: str = 'processed.csv'):
"""this function deletes @ and empty lines so that produce a no-header csv"""
fp = open(source)
rdr = csv.reader(filter(lambda row: row[0]!='@' and len(row)>1, fp))
with ope... |
the-stack_0_8062 | from django.shortcuts import render, get_object_or_404, HttpResponseRedirect
from treasure_hunt.models import Level, UserProfile
from django.contrib.auth.decorators import login_required
import django
django.setup() #Hack to fix Models not ready error
def index(request):
return render(request, 'treasurehunt/trea... |
the-stack_0_8063 | """Test the API's checkout process over full digital orders."""
import graphene
import pytest
from ....account.models import Address
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.models import Checkout
from ....checkout... |
the-stack_0_8064 | from apodeixi.controllers.util.manifest_api import ManifestAPI
from apodeixi.util.a6i_error import ApodeixiError
from apodeixi.util.formatting_utils import StringUtils
from apodeixi.controllers.util.skeleton_controller import SkeletonController
from apodeixi.knowledge_ba... |
the-stack_0_8065 | #
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by ... |
the-stack_0_8070 | from django.db import migrations
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "to-the-point-29960.botics.co"
site_params = {
"name": "To the point",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_o... |
the-stack_0_8075 | # 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 ... |
the-stack_0_8077 | """
Get Line Intersection
Get's intersection of 2 lines
TESTED REVIT API: 2017
Author: Gui Talarico | github.com/gtalarico
This file is shared on www.revitapidocs.com
For more information visit http://github.com/gtalarico/revitapidocs
License: http://github.com/gtalarico/revitapidocs/blob/master/LICENSE.md
"""
impo... |
the-stack_0_8079 | #####DONORSCHOOSE FUNCTIONS
import datetime
from datetime import timedelta, date #for time duration calculations
from dateutil.parser import parse #for fuzzy finding year
def elapseddays(posted, completed):
formatuse = '%Y-%m-%d %H:%M:%S' # The format: see down this page:https://docs.python.org/3/library/datet... |
the-stack_0_8085 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2016 Timothy Dozat
#
# 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 ... |
the-stack_0_8086 | from simple_rest_client.api import API
from simple_rest_client.resource import Resource
class FileUploadResource(Resource):
actions = {"create": {"method": "POST", "url": "post.php?dir=example"}}
# http://blog.henrycipolla.com/2011/12/testing-multipartform-data-uploads-with-post-test-server/
files = {"file": op... |
the-stack_0_8088 | """Container for creating and displaying diffs."""
import copy
import difflib
import json
import pygments
from pygments import formatters, lexers
DIFF_LEXER = lexers.get_lexer_by_name('diff')
DIFF_FORMATTER = formatters.get_formatter_by_name('terminal16m')
class DiffText:
"""Generic text diffs."""
def __in... |
the-stack_0_8089 | # -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# RCACondition
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019, The NOC Project
# See LICENSE for details
# ------------------------------------------------------------------... |
the-stack_0_8091 | import rudra.utils.helper as helper
import requests
import pytest
def test_get_github_repo_info():
gh_repo1 = 'https://github.com/fabric8-analytics/f8a-hpf-insights'
gh_repo2 = 'https://github.com/fabric8-analytics/f8a-hpf-insights.git'
gh_repo3 = 'git+https://github.com/fabric8-analytics/f8a-hpf-insights... |
the-stack_0_8092 | #
def SortCharacters(s):
order = [0] * len(s)
count = {'$': 0, "A": 0, 'C': 0, 'G': 0, 'T': 0}
for char in s:
count[char] += 1
symb = ['$', 'A', 'C', 'G', 'T']
for i in range(1, 5):
count[symb[i]] += count[symb[i-1]]
for j in range(len(s) - 1, -1, -1):
c = s[j]
c... |
the-stack_0_8095 | # visualization functions
import matplotlib as mpl
import matplotlib.pyplot as plt
def plot_arrays(sample, output):
"""
Create a figure with two plots: the original sample, and a corresponding
prediction.
"""
assert len(sample.shape) == 2 and len(output.shape) == 2
cmap = mpl.colors.ListedCol... |
the-stack_0_8097 | from django.conf import settings
from rest_framework.routers import DefaultRouter, SimpleRouter
from app.users.api.views import UserViewSet
if settings.DEBUG:
router = DefaultRouter()
else:
router = SimpleRouter()
router.register("users", UserViewSet)
app_name = "api"
urlpatterns = router.urls
|
the-stack_0_8098 | #!/usr/bin/env python
# Copyright 2017 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 require... |
the-stack_0_8102 | from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone
def k_fold_cross_validation(sgd_clf, X_train, y_train_nb):
skfolds = StratifiedKFold(n_splits=3, random_state=42)
for train_index, test_index in skfolds.split(X_train, y_train_nb):
clone_clf = clone(sgd_clf)
X_... |
the-stack_0_8104 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
import ray.cloudpickle as cloudpickle
import copy
from datetime import datetime
import logging
import json
import uuid
import time
import tempfile
import os
from numbers impor... |
the-stack_0_8106 | import tkinter as tk
from tkinter import ttk
import numpy as np
from itertools import product
from display_track import OIdisplay, CMdisplay, Cdisplay, ROIdisplay, MainDisplay
class ImageOriginal():
def create_window(self):
try: self.iot_Window.destroy()
except AttributeError: pass
self.iot_... |
the-stack_0_8107 | import unittest
from jupytervvp.variablesubstitution import VvpFormatter, NonExistentVariableException, VariableSyntaxException
class VariableSubstitutionTests(unittest.TestCase):
def test_substitute_user_variables_works(self):
input_text = """
INSERT INTO {{ namespace }}_{resultsTable}
... |
the-stack_0_8108 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
the-stack_0_8109 |
from django import forms
from api.models import JournalEntry, JournalEntryLine, Period, Account
class NewJournalEntryForm(forms.ModelForm):
period = forms.ModelChoiceField(
queryset=Period.objects.all(), required=True, to_field_name="slug")
class Meta:
model = JournalEntry
fields = ... |
the-stack_0_8111 | import sys
from datetime import datetime
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from awsglue.context import GlueContext
from awsglue.dynamicframe import DynamicFrame
from awsglue.job import Job
from pyspark.sql.functions import *
from pyspark.context import SparkContext
from pyspa... |
the-stack_0_8112 | """
https://github.com/tomchristie/django-rest-framework/issues/944
"""
import re
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')
def camelcase_to_underscore(name):
s1 = first_cap_re.sub(r'\1_\2', name)
return all_cap_re.sub(r'\1_\2', s1).lower()
def underscore_t... |
the-stack_0_8113 | """
This file offers the methods to automatically retrieve the graph Vibrio palustris.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein assoc... |
the-stack_0_8114 | # (C) Copyright 2020 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmenta... |
the-stack_0_8115 | import datetime
import gc
import numpy as np
import os
import pandas as pd
os.environ['KMP_DUPLICATE_LIB_OK']='True' # MacOS fix for libomp issues (https://github.com/dmlc/xgboost/issues/1715)
import lightgbm as lgb
import xgboost as xgb
from sklearn.metrics import log_loss, roc_auc_score
from sklearn.model_selectio... |
the-stack_0_8116 | # Copyright 2017 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 ag... |
the-stack_0_8120 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2019 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#... |
the-stack_0_8122 | from .utils import *
from .QFunction import *
import torch
from torch import nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
class MLP_SquashedGaussianActor(nn.Module):
def __init__(self,
observation_dim,
action_dim,
hidden_sizes,
activation,
act_limit):
super().__init__... |
the-stack_0_8123 | import fnmatch
import string
class Match:
ACCEPT = 1
REJECT = 2
UNKNOWN = 3
class PathFilter(object):
class Rule(object):
def __init__(self, pattern, match_action):
assert match_action in (Match.ACCEPT, Match.REJECT)
self.pattern = pattern
self.match_acti... |
the-stack_0_8124 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class NRLTVIE(InfoExtractor):
_VALID_URL = r"https?://(?:www\.)?nrl\.com/tv(/[^/]+)*/(?P<id>[^/?&#]+)"
_TEST = {
"url": "https://www.nrl.com/tv/news/match-highlights-titans-v-knights-862805/",
"info_dict... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.