text stringlengths 3.07k 12.6k |
|---|
"""
Math utility functions based on lectures from Prof. <NAME>' Multiple View Geometry course.
"""
import math
import numpy as np
import sympy
def radians(angleDegrees):
return angleDegrees / 180.0 * np.pi
def rotationMatrixToEuler(R):
"""
Compute the Euler angles from a rotation matrix
http://eecs... |
# encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: <NAME> (<EMAIL>)
#
from __future__ import absolute_import, division, unicode_literals
f... |
import json
import pywikibot
import sys
import re
import time
from pathlib import Path
# Regular expressions copied from http://tinyurl.com/yb37xlu7
item_or_property_re = re.compile('^[PQ]\d+$', re.IGNORECASE)
item_re = re.compile('^Q\d+$', re.IGNORECASE)
property_re = re.compile('^-?P\d+$', re.IGNORECASE)
string_re =... |
import inspect
from six.moves.urllib.parse import urlparse
from pyoslc.resources.models import ServiceProvider, Service, QueryCapability, CreationFactory, Dialog
from pyoslc.vocabularies.config import OSLC_CONFIG
class ServiceProviderFactory(object):
@classmethod
def create_service_provider(cls, base_uri, t... |
#!/usr/bin/python3
#
# Copyright (C) 2011 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list o... |
'''Analysis of sample files
'''
import sys
import os
import numpy as np
import pandas as pd
from fjarrsyn.core.helper_funcs import sigmoid_10
AGENT_PREFIX = 'agent_sample'
GRAPH_PREFIX = 'graph_sample'
ENV_PREFIX = 'env_sample'
PHENO_ARCHETYPES = {'ctp' : {'pheno:share' : 1.0,
'pheno:g... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math, copy
import numpy as np
from torch.autograd import Variable
def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout, max_len=... |
#
# 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... |
"""
Perform test automation with nox.
For further details, see https://nox.thea.codes/en/stable/#
"""
from hashlib import sha256
import os
from pathlib import Path
from shutil import rmtree
from urllib.request import urlretrieve
from zipfile import ZipFile
import nox
#: Default to reusing any pre-existing nox env... |
import argparse
import json
import logging
import math
import os
from rapidstream.BE.UniversalWrapperCreater import addAnchorToNonTopIOs
from rapidstream.BE.Utilities import loggingSetup
loggingSetup()
def getAnchorWrapperOfSlot(hub, slot_name):
"""
Top-level ports will be directly connected
All other IOs wil... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 23 16:36:02 2016
@author: noore
"""
import os, sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import imp
import json
import inspect
import urllib
from contextlib import closing
SCRIPT_DIR = os.path.dirname(os.path.abspath(inspect.getfile(insp... |
#External Libraries
import json, csv
import os,sys
import logging
import argparse
#internal libraries
sys.path.insert(0, './lib')
from scraperlibrary import (
soupedUp,
cleanHeader,
cleanData,
)
from etllibrary import ETL
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output",
... |
import json
import logging
import os
import time
from uuid import uuid4
import base64
import ast
import boto3
from boto3.dynamodb.conditions import Attr
_logger = logging.getLogger()
_logger.setLevel(logging.INFO)
# Lambda environment vars
JOB_STATUS_TABLE = os.environ["job_status_table_name"]
SLACK_ALERT_ARN = os.en... |
"""
Module for computing the vector form factor for pi+pi.
"""
from dataclasses import dataclass
from typing import Union
import numpy as np
import numpy.typing as npt
from scipy.special import gamma # type:ignore
from hazma.vector_mediator.form_factors.utils import (
MPI_GEV,
breit_wigner_fw,
breit_wign... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 02:05:24 2016
@author: tunoat
"""
from __future__ import absolute_import
from __future__ import print_function
sentences = [
'fred loves pizza',
'marie loves noodle'
]
# 1. create dictionary
i = 0
vocab = dict()
for sentence in sentences:
wordList = sentence.split... |
# -*- coding: utf-8 -*-
"""
Matching partition files via kD-tree. Given two files, an indexed partition file
and a plain partition file, match the observations in the second to the observations in the first
and create an indexed file.
Created on Thu Jul 20 10:25:12 2017
@author: vcn81216
"""
import argparse
import s... |
"""Contains functionality related to retrieving the content to check against
certain rules.
This module includes content providers, which are classes that know how to
look for information from Github, that is necessary for performing checks.
Ideally this should be abstracted so that it does not depend on Github,
but ... |
"""Main entry point for running discord-hero
discord-hero: Discord Application Framework for humans
:copyright: (c) 2019-2020 monospacedmagic et al.
:license: Apache-2.0 OR MIT
"""
import asyncio
import io
import os
import sys
import django
from django.db import OperationalError, ProgrammingError
from django.core i... |
#
# 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... |
from asyncio.exceptions import CancelledError
from asyncio.tasks import create_task
import os
import time
import asyncio
import itertools
import sys
sudoku = [
"39 2 ",
" 7 48 ",
" 4 5 196",
"6721 84",
" 3194 ",
" 4 7 61 ",
"92 4 356 ",
" 35 14 9",
" 69 "
]
sudo... |
## Copyright 2019
##
## 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, soft... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
from torchvision import datasets, transforms, models
import json
from collections import OrderedDict
from data_helper import process_image
from data_helper import imshow
from collections impo... |
import numpy as np
from matplotlib import pyplot as plt
class BlackJack:
def __init__(self, disc_factor, iters):
# User sum(Max 21), Dealers showing card(Max 10), Usable Ace or not
self.state_value = np.zeros(shape=(22, 11, 2))
self.state_visit = np.zeros(shape=(22, 11, 2))
self.ite... |
import copy
import heapq
from collections import defaultdict
from itertools import product
DESTINATIONS = {
"A": [(3, 2), (3, 3)],
"B": [(5, 2), (5, 3)],
"C": [(7, 2), (7, 3)],
"D": [(9, 2), (9, 3)],
}
# The entrances to the different rooms
BLOCKED_COORDS = [(3, 1), (5, 1), (7, 1), (9, 1)]
MAX_X = 0
M... |
"""
MIT License
Copyright (c) 2019 <NAME>
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, distri... |
import multiprocessing
import os
import pickle
import numpy as np
import pandas as pd
import torch
from torch.nn import functional as F
from analysis import correlations
from experiments import spec_util
from models import infogan, load_checkpoint
from morphomnist import io, measure
DATA_ROOT = "/vol/biomedic/users/... |
#!/usr/bin/python
import glob
import multiprocessing
import os
import shutil
import subprocess
import sys
from argparse import ArgumentParser
from threading import Timer
import itertools
def get_immediate_subdirectories(a_dir):
return [(os.path.join(a_dir, name)) for name in os.listdir(a_dir)
if os.pat... |
import asyncio
import subprocess
import concurrent
import click
import aiohttp
from pyartcd.cli import cli, click_coroutine, pass_runtime
from pyartcd.runtime import Runtime
BASE_URL = 'https://api.openshift.com/api/upgrades_info/v1/graph?arch=amd64&channel=fast'
ELLIOTT_BIN = 'elliott'
async def is_ga(version: st... |
"""
.. module:: sflow
:platform: Unix
:synopsis: A source module which provides an sflow collector
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import time
from zope.interface import implementer
from twisted.internet import reactor
from duct.interfaces import IDuctSource
from duct.objects import Source
from duct i... |
from Utils.miscellaneous import *
#from KMeans.kmeans import KMeans
from EM.em import ExpectationMaximization
import numpy as np
from matplotlib import pyplot
import os
def run_gaussian_test(theta):
file_no = theta[0]
num_clusters = theta[1]
samples = load_gaussian_file_as_samples(file_no=file_no, k=num_cl... |
from sktimeline import db, GithubAPI
from datetime import datetime
import dateutil.parser
class GithubFeedSetting(db.Model):
__tablename__ = 'feed_setting_github'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.uid'))
username = db.Column( db.String(12... |
"""
RL online training Part
"""
import tensorflow as tf
import math
import numpy as np
import warnings
import os
warnings.filterwarnings('ignore')
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
gpu_options = tf.GPUOptions(allow_growth=True)
class Actor:
def __init__(self, n_features, n_actions, lr):
self.... |
import socket, struct
from time import sleep
class Conn:
def __init__(self, host, port):
self.host = host
self.port = port
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connected = False
def connect(self):
# try:
self.soc.connect((self.... |
import tensorflow as tf
from keras import Model, Input
from keras.layers import Conv2D, Concatenate, Lambda
"""
Attention transfer network (layer)
"""
def resize(x, scale=2, to_shape=None, align_corners=True, dynamic=False,
func=tf.compat.v1.image.resize_bilinear, name='resize'):
r""" resize feature m... |
from flask import request, make_response, render_template
from msg_handler import app, redis
from msg_handler.menu import menu
import json
import datetime, time
from msg_handler import logger
from msg_handler.vumi_go import VumiMessage
from mixpanel import Mixpanel
mp = Mixpanel(app.config['MIXPANEL_PROJECT_TOKEN'])
... |
"""Run comparison tests against configured Tesserae versions"""
import argparse
import json
import os
import urllib.request as request
import tesserae_tester as tess
def _parse_args():
"""Parses arguments"""
parser = argparse.ArgumentParser(
description='Run Tesserae version comparison tests')
pa... |
import logging
import warnings
import appdaemon.utils
import mock
from appdaemon.plugins.hass.hassapi import Hass
from packaging.version import Version
CURRENT_APPDAEMON_VERSION = Version(appdaemon.utils.__version__)
def is_appdaemon_version_at_least(version_as_string):
expected_appdaemon_version = Version(vers... |
# coding=utf-8
import wx
import wx.grid as gridlib
from crm import service, customerwin, idnumbervalidator
class CustomerPanel(wx.Panel):
"""
客户面板
"""
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.grid = None
self.edit_win = None
self.id_number_sea... |
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import sys
import celery
import psutil
import pytest
import wrapt
from webtest import TestApp
from scout_apm.core.agent import socket as scout_apm_core_socket
from scout_apm.core.agent.manager i... |
from typing import List
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class InputEmbedding(nn.Module):
def __init__(self, input_channels=3, output_channels=64):
super().__init__()
self.embeding = nn.Sequential(
nn.Conv1d(input_channe... |
#!/usr/bin/env python3
# 1. lists where the numbers are stored
# 2. the collection of documents
import re # regex library
import argparse # this library allows us to give arguments in the form of `python3 <script> --flags arguments`
# You need two files and run the script in the following way
# python3 add_tags_by_n... |
# ------------------------------------------------------------------------------
# Copyright (c) 2018 <NAME>
# Licensed under the MIT License.
# Written by: <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
from sixd import SixdToolkit
from transform import *
fro... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
import json
import random
import re
from ..compat import (
compat_parse_qs,
compat_str,
)
from ..utils import (
js_to_json,
strip_jsonp,
urlencode_postdata,
)
class WeiboIE(InfoExtractor):
_VALID_URL =... |
from discord.ext import commands
from Utils import Field, create_async_database
from dataclass import write_blacklist, write_reaction_messages_to_file
from typing import Union, Optional
import discord
import psutil
class Moderation(commands.Cog):
def __init__(self, client):
self.client: discord.Client = ... |
#!/usr/bin/python
# Classification (U)
"""Program: run_program.py
Description: Unit testing of run_program in rmq_2_isse.py.
Usage:
test/unit/rmq_2_isse/run_program.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import u... |
from __future__ import absolute_import
from __future__ import print_function
import json
import mock
from django.test import TestCase
from django.contrib.auth.models import User
from django.utils import six
from ajax.endpoints import ModelEndpoint
from ajax.exceptions import AJAXError
from ajax.signals import ajax_d... |
# encoding: utf-8
'''
Align paralogous contigs with reference sequence
'''
import os
import sys
import glob
import logging
import argparse
import numpy as np
import pandas as pd
from secapr.helpers import is_dir, is_file, FullPaths
import shutil
from numpy import genfromtxt
from Bio import SeqIO
from Bio.Align.Applic... |
import six
import sys
import sqlalchemy
from flask import current_app, request, abort, Blueprint, g
from itsdangerous import TimedSerializer, BadData
from decimal import Decimal
from .models import Transaction, Payout, TradeRequest
from .utils import Benchmark
from . import db
rpc_views = Blueprint('rpc_views', __n... |
import os.path
import sys
import inspect
import copy
fail_instantly = False
class Error(object):
def __init__(self, key, name):
self.__key = key
self.__name = name
def __add__(self, other):
return self
def __call__(self, wildcards=None):
sys.exit(
"""
... |
import cv2
import numpy as np
faceClassif = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def moviment(x_inicial, y_incial, x_final, y_final):
if (y_incial > y_final): # puja ma
if (x_inicial > x_final):
print("Direcció adalt i esquerra")
elif (x_inicial < x_final):
... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from layers import EncoderLayer, DecoderLayer
import common
from const import *
import const
class CrossEntropy(nn.Module):
def __init__(self):
super().__init__()
def forward(self, props, tgt):
tg... |
import urllib
import sys
import sqlalchemy
from sqlalchemy.orm.session import sessionmaker
sys.path.append('bot')
from database.classes.cDB import engine, Users, Channels, Posts
# СОЗДАНИЕ СЕССИИ
session = sessionmaker(bind=engine)()
async def create_new_user(userid, username, onoff):
try:
session.add(Use... |
import os
import pathlib
import re
from typing import Union, List
import json
from urllib import request
import sqlite3 as db
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
import pandas as pd
from ezgoogleapi.bigquery.base import check_keyfile
DIR = str(pathlib.Path(... |
import asyncio, concurrent.futures
import sys
import os
import oneai
from typing import Awaitable, Dict, Iterable, List, Union
from oneai.classes import Input, Output, Skill
from oneai.segments import *
class Pipeline:
"""
Language AI pipelines allow invoking and chaining multiple Language Skills to process ... |
#!/usr/bin/env python3
import sys
import time
import json
import os, signal, re
import logging, logging.config
import threading
import importlib
from watchdog.observers import Observer
from watchdog.events import RegexMatchingEventHandler
from imageai.Detection import ObjectDetection
from queue import Queue
from mod... |
""" Contains `PieceDataset` class and related utilities to cut the chessboard photograph into 64
images for each chessboard piece or square.
"""
import random
import cv2 as cv
import numpy as np
from rookowl.calibration import CHESSBOARD_CROSS_POINTS, project_points
from rookowl.global_var import PIECE_INPUT_IMA... |
# puredb.py
import mmap
import os
import struct
import tempfile
__all__ = ['CdbReader', 'CdbWriter', 'PasswdWriter']
def cdb_hash(buf):
"""CDB hash function"""
h = 5381 # cdb hash start
for c in buf:
h = (h + (h << 5)) & 0xFFFFFFFF
h ^= c
return h
def uint32_unpack(buf):
"""Un... |
import os
import sys
PROJECT_ROOT = os.path.abspath(
".."
if os.path.abspath(".").split("/")[-1]
in [
"lib",
"api",
"helpers",
"scripts",
"tests",
"extensions",
"docs",
"frontend",
]
else "."
)
sys.path.append(PROJECT_ROOT)
import ti... |
#!/usr/bin/env python
import yt
from yt.units import dimensions
from yt import derived_field
import yt.visualization.volume_rendering.api as vr
from yt.visualization.volume_rendering.transfer_function_helper import TransferFunctionHelper
from yt.visualization.volume_rendering.api import Scene, VolumeSource, Camera, Col... |
import pandas as pd
import numpy as np
import subprocess
import re
from psutil import process_iter
from signal import SIGTERM
import h2o
from h2o.automl import H2OAutoML
import os
import random
import socket
import yaml
from .models import ModelData
from .publish_model import publish_model
def run_auto_analyse(tr... |
import discord, random
from discord.ext import commands
from Scrapers import UD, YT
import datetime, requests
from youtube_search import YoutubeSearch
from Helpers import emoji
import asyncio
class scrapers(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.cooldo... |
import smtplib
from email.message import Message
from os.path import isfile
from json.decoder import JSONDecodeError
import keyring
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from ihatefacebook.logger import Logger
from ihatefacebook.facebook.event import FacebookEven... |
"""Definition and setup of the Space Launch Live Sensors for Home Assistant."""
import datetime
import logging
import dateutil
import time
from homeassistant.util.dt import as_local, as_timestamp
from homeassistant.components.sensor import ENTITY_ID_FORMAT
from homeassistant.const import LENGTH_KILOMETERS, SPEED_KILO... |
from tkinter import *
import tkinter.filedialog
from tkinter.ttk import Progressbar
from os.path import expanduser
import os
import platform
import sys
from os import path, popen
import asyncio
import threading
import platform
bundle_dir = path.abspath(path.dirname(__file__))
path_to_dist = path.join(bundle_dir, 'dis... |
import pytz
import pandas as pd
import dateutil.parser
from enum import IntEnum
from datetime import datetime
from ..defines.column_names import *
from ..defines.enums import RuleType
class DateFormatter:
"""日期格式处理"""
@staticmethod
def convert_local_date_to_timestamp(date):
"""Date -> Timestamp(m... |
import frappe
import razorpay
import six
import json
from frappe.integrations.utils import get_payment_gateway_controller, make_post_request
from frappe.utils import getdate, add_months, add_years
def get_client():
controller = get_payment_gateway_controller("Razorpay")
controller.init_client()
return controller.cl... |
import json
import time
from copy import deepcopy
class NotificationNameNotUnique(Exception):
pass
class NotificationApi:
"""Uses the Api to create an actual notification object."""
def __init__(self, session=None, api=None):
self.session = session
self.factory = api
def getByName(... |
#!/usr/bin/env python3
"""
Class MeasureOutput
"""
import logging
import utils.load_yaml
from utils.load_yaml import yaml_register_class
from utils.output import FormatOutput
import jsonpickle
import utils.logging
from utils.keymaster import get_column_name_for_key
logger = logging.getLogger(utils.logging.getLoggerNa... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# Copyright 2014-2020 Scalyr Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
from random import random
import numpy as np
from sklearn.metrics import mean_squared_error
from logging import getLogger
from dataclasses import dataclass
logger = getLogger(__name__)
@dataclass
class ImageEIT(object):
data:np.ndarray=np.array([])
label:str=''
fwd_model:dict=None
@dataclass
class ImageDa... |
import pygame, sys
import numpy as np
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]
wrongDir = {0: 2, 1: 3, 2: 0, 3: 1}
class Snake:
def __init__(self, x = 0, y = 0, blockSize = 20):
self.position = [[x, y]]
self.tail = [[x, y]]
self.blockSize = blockSize
self.directi... |
# Standard package import:
import os
import sys
import base64
from tkinter import *
from tkinter import messagebox
# From packages import:
from openpyxl import *
from pyautogui import press
from PIL import Image, ImageTk
# Directories declaration:
root_directory = os.path.dirname(os.path.abspath(__file__))
binaries_d... |
import math
import threading
import LTDrop
import LTDecodedFile
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
class DecodeSession:
canvas_width = 500
canvas_h... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from datetime import date
import os
import datetime
import pandas as pd
# although not explicitely used, we need to import s3fs for pandas to interface
# properly with AWS S3
# pylint: disable-next=W0611
import s3fs
from download_decks import make_search_pay... |
from config import nDep as gen_ls
import torch
import torch.nn as nn
import sys
import gc
nUp_n = 2 ** gen_ls ##noise and image tensor relation
nUp = 2**(gen_ls+1) ##for buffer ovelap calculation, >=nUp_n
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def splitH(Im_tri, noise,te,f,sH):
... |
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, ConversationHandler, Filters
import html
import re
from config import CONFIG
from database import DBHelper
import deadline
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
... |
# Authors: <NAME>, <NAME>
import tensorflow as tf
from collections import namedtuple
BACKEND_NAME = 'tensorflow'
class Pad(object):
def __init__(self, pad_size, input_size, pre_pad=False):
"""Padding which allows to simultaneously pad in a reflection fashion
and map to complex.
... |
import math
import torch
import torch.nn as nn
class IOULoss(nn.Module):
def __init__(self, loc_loss_type, box_type='lrtb'):
super(IOULoss, self).__init__()
self.loc_loss_type = loc_loss_type
self.box_type = box_type
def forward(self, pred, target, weight=None):
if self.box_t... |
from __future__ import print_function
from requests import post
import discord
from discord.ext import commands
import misc
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying t... |
import os
import subprocess
import re
import time
from . import wblib as wb
err_str = 'cannot find the path of stanford parser! \n' \
'Please download the stanford parser from ' \
'\"https://nlp.stanford.edu/software/lex-parser.shtml\" \n' \
'Then set environment variable STANFORD_PARSER... |
import config
import re
import os
import time
import smtplib
import logging
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.keys... |
import json
import discord
import asyncio
from discord.ext import commands
from emojis import emojis, numeric_emojis, num_emojis
from page import Page
years = ["2015-2016", "2016-2017", "2017-2018", "2018-2019", "2019-2020"]
@commands.command()
async def grade(ctx, *, msg: str = " "):
prof_and_class = msg.split... |
#!/usr/bin/env python3
# Assumption: Input SVD has only absolute addresses--and those are in <addressOffset>
from lxml import etree
import sys
import settings
import logging
from logging import debug, info, warning, error, critical
def eval_int(element):
""" Given a SVD node, extracts the integer from its text. ... |
#!/bin/python2
import logging
def parser(subparser):
subparser.add_argument('--flavour', help='Flavour name')
subparser.add_argument('--dsize', help='Disk maximum size in GB')
def getFlavourDiskSize(flavour):
from sh import nova, tail, grep, awk
return int(awk(grep(nova("flavor-show", flavour), '| d... |
# IMPORTING LIBRARIES
import os
import shutil
from tqdm import tqdm
import csv
import random
import matplotlib.pyplot as plt
import numpy as np
import time
# Adding Datapaths
datapath = 'data/Dataset'
extra = 'data/extras'
train_path = 'data/data_train'
test_path = 'data/data_test'
validation_path = 'data/data_valida... |
import torch
import torch.nn as nn
def compute_matching_accuracy(eval_loader, device, encode_discrete=None,
distance_metric='hamming', num_retrieve=100,
chunk_size=100, binary=True):
encodings_X, encodings_Y = encode_related_articles(eval_loader, device,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.6.0-bd605d07 (http://hl7.org/fhir/StructureDefinition/Communication) on 2018-12-20.
# 2018, SMART Health IT.
from . import domainresource
class Communication(domainresource.DomainResource):
""" A record of information transmitted from a se... |
# -*- coding:utf-8 -*-
'''
Created on 2017年3月29日
@author: Jin
'''
import xlsxwriter
import time
from core import TestAllRunner
TestReport = TestAllRunner.hthreads()#调用测试结果
hpassnum = 0
def get_format(wd, option={}):
return wd.add_format(option)
# 设置居中
def get_format_center(wd,num=1):
return wd.add_format... |
import random
class TerrainMaker(object):
def __init__(self, width=100, height=100):
self.Width = width
self.Height = height
self.StoredTerrainsDict = {}
def storeTerrain(self, Terrain):
self.StoredTerrainsDict[Terrain.Name] = Terrain
def writeToCSV(self, Terrain, ... |
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression, LinearRegression
from math import log
from causallib.estimation import IPW
def check_input(A, Y, X):
if not isinstance(A, pd.Series):
if not np.max(A.shape) == A.size:
raise Exception(f'A must be one di... |
from app import app, db
from flask import render_template, redirect, url_for, session
from flask_login import login_required, current_user, login_user, logout_user
from app.src.signup import signupValidation
from app.src.login import loginValidation
from app.src.user_tree import user_tree
from app.forms import LoginFor... |
import threading
from pathlib import Path
import cv2
import depthai
import numpy as np
from imutils.video import FPS
nnPathPeople = str((Path(__file__).parent / Path('models/people.blob')).resolve().absolute()) #544x320 NN
nnPathMask = str((Path(__file__).parent / Path('models/facemask.blob')).resolve().absolu... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018-2021 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test email notifications."""
import pytest
from flask import url_for
from jinja2.exceptions import Templa... |
import subprocess
import os
import requests
from gidgethub import sansio
from . import exceptions
def exec_command(cmd):
subprocess.check_output(cmd)
def checkout_branch(branch_name):
cmd = ["git", "checkout", "-b", branch_name, "origin/master"]
try:
subprocess.check_output(cmd)
except sub... |
""" does mkdocs things """
from difflib import unified_diff
from io import BytesIO
import json
from typing import Tuple
from loguru import logger
from ruyaml import YAML
from github_linter.repolinter import RepoLinter
from github_linter.exceptions import NoChangeNeeded
from github_linter.utils import get_fix_file_pa... |
from typing import Tuple
from django.contrib.auth.models import User
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework.authtoken.models import Token
from rest_framework import status
from ..models import Account, Follow, FollowerPetition
class AccountTest(TestCase):
... |
from nltk.parse import CoreNLPParser
from .hr_time import *
from itertools import combinations
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
import re
from fuzzysearch import find_near_matches
def get_nertag(text):
ner_tagger = StanfordNERTagger('english.muc.7class.distsim... |
import math
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as graysca... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created in June 2017 in ComplexCity Lab
@author: github.com/fpfaende
what it does
clean roads graph created from osm file
parameters
graph
how it works
return
'''
import matplotlib.pyplot as plt
import networkx as nx
import colorlover as cl
from shapely.geometry impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.