text stringlengths 3.07k 12.6k |
|---|
"""
Code for generating Phy input files:
http://phy-contrib.readthedocs.io/en/latest/template-gui/
"""
from datetime import datetime
import os.path as path
import numpy as np
from yass.util import load_asset, load_yaml
from yass.geometry import n_steps_neigh_channels
def params(path_to_config):
"""
Generat... |
"""
Filtering authors and tokens to keep only the 20k most common of each. Uncommon
authors/tokens are set to UNK_author or UNK.
"""
import csv
import json
from operator import itemgetter
import ast
import pandas as pd
import numpy as np
from tqdm import tqdm, trange
from seq2cite import config, utils
UNK = 0
CITE ... |
#
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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, pu... |
import os
import numpy as np
import pandas as pd
from qharv.reel import mole
# ======================== level 0: paths and inputs =========================
def get_pcdirs(
tmp_dir='inp_text',
pd_name='proj_dir.dat',
fdl_name='folder_list.dat'
):
""" read project dir and calc dirs from inputs
defaul... |
from copy import deepcopy
from eolearn.core import EOTask
import xarray as xr
import numpy as np
import dask.array as da
# These exceptions should translate to the list of OpenEO error codes:
# https://open-eo.github.io/openeo-api/errors/#openeo-error-codes
class ExecFailedError(Exception):
def __init__(self, m... |
# pylint: disable=too-many-locals, too-many-branches, duplicate-code, R0101
"""Management command that saves locale .po files from database."""
from __future__ import unicode_literals
from os import mkdir
from os.path import join, isdir, exists
from wagtail.core.blocks.stream_block import StreamValue
from django.cor... |
""" Module responsible for calculating advantages given a dataset of games """
import numpy as np
from tools.metadata import get_last_patch
def _update_dicts(game, synergy, counter):
""" Updates the synergy and counter games given the game given as input
Args:
game: row of a mined pandas DataFrame
... |
from math import gamma
import torch.nn as nn
import torch
import torch.optim as optim
from torchvision import datasets
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader, random_split
import time
import torch.optim.lr_scheduler as lr_s
import torchvision.transforms as transforms
from Bl... |
from numpy import diff, sqrt, sum, array, corrcoef
import numpy as np
from scipy.misc import comb
from scipy.signal import periodogram
__all__ = ['shocklikeGaussian', 'GaussianPulse', 'rect', 'squarepulse']
def shocklikeGaussian(time, t0, m0, sigma, noise = 0.0):
"""Generates a signal that resembles a shoc... |
"""
Implements a signalling message as a structured dataclass. Used to pass signaling
message between the Django Message Broker clients and server.
"""
from __future__ import annotations
from asyncio.futures import Future
from dataclasses import dataclass, field
from msgspec.core import encode, decode
from typing imp... |
from skimage.data import imread
import numpy as np
from enum import Enum
import math
import matplotlib.pyplot as plt
class Img:
@staticmethod
def load_image(path, as_grey = False, to_float = True):
# Load image
image = imread(path, as_grey)
if to_float:
# Convert to floati... |
from django.shortcuts import render,redirect
from Book.models import BookInfo
from django.http import HttpResponse
from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO
from django.core.urlresolvers import reverse
# Create your views here.
def login3(request):
"""重定向到fan3"""
# ret... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
import numpy as np
class MaxPoolStride1(nn.Module):
""" maxpooling without changing size """
def __init__(self):
super (MaxPoolStride1, self).__init__()
def forward(self, x):
x = F.ma... |
"""This module contains the general information for EquipmentPciDef ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class EquipmentPciDefConsts():
DEVICE_TYPE_BROADCOM57712_NIC = "Broadcom57712Nic"
DEVIC... |
#!/usr/bin/env python
# coding: utf-8
# Extraction des certificats ISCC https://www.iscc-system.org/certificates/all-certificates/
import argparse
import requests
import urllib.request
from bs4 import BeautifulSoup
import json
import pandas as pd
from datetime import date # Pour le nom du fichier sauvegardé
from os ... |
import os
import pickle
import pandas as pd
import numpy as np
import pickle5 as pickle
from typing import Optional, Dict, Any, List
import spacy
from spacy import displacy
from spacy.tokens import Doc
from spacy.matcher import DependencyMatcher
import streamlit as st
from spacy_streamlit.util import load_model, proc... |
from __future__ import print_function #pylint bug workaround
import argparse
import os
import pandas
import re
import obj_tools
import neuralnets.grammar as grammar
import neuralnets.shape_graph as shape_graph
from neuralnets.shape_graph import smiles_variations
SMILES_COL_NAME = "structure"
CATEGORIES_COL_NAME = "edg... |
# Copyright (c) 2011 OpenStack, 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 wr... |
import numpy as np
import colorsys
import random
import cv2
def get_n_hls_colors(num):
hls_colors = []
i = 0
step = 360.0 / num
while i < 360:
h = i
s = 90 + random.random() * 10
l = 50 + random.random() * 10
_hlsc = [h / 360.0, l / 100.0, s / 100.0]
hls_colors.a... |
import random
import re
import copy
ASSIGNMENT = "assignment"
FORMULA = "formula"
ID = "id"
REFERENCE = "reference"
SYMBOL = "symbol"
TYPE = "type"
WEIGHT = "weight"
LEVEL = "level"
class Grammar:
def __init__(self, grammar_file):
self.grammar = self.build_grammar(grammar_file)
self.variable_nam... |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #
# All rights reserved. #
# This file is part of the AiiDA-FLEUR package. ... |
"""Defines bridges to MAX! devices.
- Thermostat ``Accessory`` interfacing with a MAX! thermostat.
- MaxBridge, which discovers and bridges MAX! devices.
"""
import logging
import socket
from maxcube.connection import MaxCubeConnection
from maxcube.cube import MaxCube
from maxcube.device import (MAX_THERMOSTAT,
... |
import torch
from nff.utils.scatter import compute_grad
from nff.nn.modules import ConfAttention
EPS = 1e-15
def update_boltz(conf_fp, weight, boltz_nn):
"""
Given a conformer fingerprint and Boltzmann weight,
return a new updated fingerprint.
Args:
conf_fp (torch.Tensor): molecular finerprint... |
import subprocess
import json
import os
import os.path
import sqlite3
from os import path
import base64
from Crypto.Cipher import AES
import redis
import time
r = redis.StrictRedis(host='localhost', port=6370, db=0, charset="utf-8", decode_responses=True)
global Xcount
Xcount = 0
class AutoConf:
def __init__(self... |
from pathlib import Path
from invoke import Collection
from invoke import task
from invoke.exceptions import Failure
GITHUB_USERNAME = "midwatch"
GITHUB_SLUG = "sphinx-notebook"
SOLUTION_SLUG = "sphinx_notebook"
CC_VERSION = "0.0.0"
ROOT_DIR = Path(__file__).parent
SOURCE_DIR = ROOT_DIR.joinpath("sphinx_notebook")
T... |
import datetime
import os
import smtplib
import time as ti
import webbrowser as we
from email.message import EmailMessage
from time import sleep
import clipboard
import psutil
import pyautogui
import pyjokes
import pyttsx3
import pywhatkit
import requests
import speech_recognition as sr
from newsapi import NewsApiClie... |
import re
import time
from datetime import datetime
import pexpect
PROMPT_LIST = ["R1>", "R1#", "R1(config)#", "R1(config-if)#", "R1(config-router)#", "R1(config-line)#", ]
_ACCESS_CONFIG_CMD = "configure terminal\r"
_COPIED_MSG = "bytes copied in"
_ENCRYPT_CONFIG_CMD = "service password-encryption\r"
_EXIT_CMD = "e... |
#
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
#
# 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 a... |
import sys
from enum import Enum
from typing import Callable, List, Optional, Sequence, Tuple, Union
import pytest
from hermes.typeo import spoof, typeo
@typeo
def func(a: int, b: int = 10):
return a + b
@typeo("named-program")
def named(a: int, b: int):
return a + b
@typeo
def lists_func(a: List[str]):... |
import nonebot
import json
import aiohttp
import os
from ..tools.get_user_info import GetUserInfo
from ... import config
from ...utils import read_file, write_file
from nonebot.adapters.onebot.v11.exception import NetworkError
scheduler = nonebot.require("nonebot_plugin_apscheduler").scheduler
@scheduler... |
""" Utilities to build models.
Including -
- basic building blocks, e.g., conv3x3, conv1x1, etc.
"""
import functools
import os
import numpy as np
import torch
import torch.nn as nn
from thop import profile
from gumi.ops import GroupConv2d, MaskConv2d, MMPointwiseConv2d, SparseGroupConv2d
__all__ = ["conv3x3", "... |
#!/usr/bin/env python3
import sys
import argparse
import json
import requests
from bs4 import BeautifulSoup
import progressbar as pb
from termcolor import colored
BASE_URL = "https://www.studentska-prehrana.si/"
RESTAURANT_EXT = "sl/restaurant"
class Restaurant():
def __init__(self):
self.name = ""
... |
import base64
import configparser
import os
import pytest
import requests
def b64encode(message):
"""
This function encodes a string to base64.
:param message: String to encode.
:return: Base64 encoded string.
"""
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(mess... |
import dataclasses
import enum
import typing
import regex
from amino.schema_parser import Schema, SchemaType
whitespace_regex = regex.compile(r"[\s]+")
name_regex = regex.compile(r"[A-Za-z_]+")
parenthesis_open_regex = regex.compile(r"[(]+")
parenthesis_close_regex = regex.compile(r"[)]+")
int_literal_regex = regex.... |
#!/usr/bin/env python3
# Copyright 2021 <NAME> <<EMAIL>>
#
# 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 l... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import ElementNotVisibleException, NoSuchElementException
import time, re, collections, itertools, math, random
import numpy as np
import pandas as pd
import argparse
parser = argparse.ArgumentParser(descript... |
import os
import random
from typing import Any, List, Tuple, Union
import gym
import numpy as np
import torch
import torch.nn as nn
from ...environments import VecEnv
def get_model(type_: str, name_: str) -> Union:
"""
Utility to get the class of required function
:param type_: "ac" for Actor Critic, "... |
from lxml import etree
import os
import datetime
import shutil
import collections
import posixpath
import zipfile
import sys
# Global variables for silent mp3s and Score Sheet
audio_folder = r'PATH/TO/Quiz Cue Music and 4 Second Silent MP3'
score_sheet = r'PATH/TO/GWD OFFICIAL _____ Scoresheet.xxx'
# Locates 4 second... |
import xml.etree.ElementTree as ET
import xml.dom.minidom
import sys, os, itertools
import random
COLOR_BLACK = 0x000000
COLOR_WHITE = 0xffffff
COLOR_RED = 0xff0000
COLOR_GREEN = 0x00ff00
COLOR_BLUE = 0x0000ff
COLOR_YELLOW = COLOR_RED ^ COLOR_GREEN
def offset_coords(list_of_coords, offset):
minx, miny, minz = offset... |
'''
Copyright (c) 2020. IIP Lab, Wuhan University
'''
import os
import argparse
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import models
from tensorflow.keras import backend as K
from data import *
from train import *
from layers import ProductOfExpertGaussian... |
import keras
import math
import numpy as np
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers import Conv2D, Dense, Input, add, Activation, AveragePooling2D, GlobalAveragePooling2D
from keras.lay... |
# -*- coding: utf-8 -*-
import os
import re
import json
from flask import Flask, request, render_template, url_for, make_response
from uploader import Uploader
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload/', methods=['GET', 'POST', 'OPTIONS'])
d... |
######################################
# EASY THAUMCRAFT RESEARCH GENERATOR #
######################################
import os
import json
import copy
import re
# Made to remove duplicate contents for Thaumcraft researches.
################################################################################
##############... |
import os
import re
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy.numarray as na
import asmtypes
import shock
class ArastJob(dict):
"""
"""
def __init__(self, *args):
dict.__init__(self, *args)
self['pipelines'] = [] # List of ArastPipeline
... |
import psycopg2
from psycopg2.extensions import AsIs
from psycopg2.extras import RealDictCursor
from app.config import connect, close_conn, no_commit_close_conn
from datetime import date, datetime, time
import time as t
def create_schema(cur, sch_name):
""" Given a cursor and a name,
makes a schema with that name.""... |
from django.db import models
from django.contrib.postgres.fields import JSONField
from django.utils import timezone
import uuid
class AGVenue(models.Model):
"""Store the venue where events happens, including name, description, latitude and
longtitude.
"""
uuid = models.UUIDField(primary_key=True, def... |
# (c) Copyright IBM Corporation 2020.
# LICENSE: Apache License 2.0 (Apache-2.0)
# http://www.apache.org/licenses/LICENSE-2.0
import abc
import functools
import logging
import os
from enum import Enum
from typing import Dict, Mapping, Sequence
import lrtc_lib.definitions as definitions
from lrtc_lib.train_and_infer... |
from dataclasses import dataclass
from typing import Tuple, Union
import numpy
@dataclass(frozen=True)
class EllipseParams:
"""
Represent an ellipse by the following form:
c_xx x^2 + 2 c_xy x y + c_yy y^2 + 2 c_x x + 2 c_y y + c = 0
Methods below follow the notation in:
https://en.wiki... |
import json
from io import BytesIO
import cv2 as cv
import requests
from PIL import Image
def get_personId_name_mappings():
name2personId = dict()
name2personId['a-yuhu'] = 'f1dfd6a7-85e4-4b83-94ea-63ae96e6bf6a'
name2personId['abelch'] = 'e2c15b40-7d7b-4372-97cc-206a53840085'
name2personId['bekimd'] ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ['log', 'register', 'register_all', 'Event']
from collections import namedtuple
from cloghandler import ConcurrentRotatingFileHandler
from tcloghandler import ConcurrentTimeRotatingFileHandler
import logging
import logging.handlers
import os
import re
import st... |
# Copyright 2020 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, ... |
import click
import pandas
from pathlib import Path
from matplotlib import pyplot as plt
import numpy as np
import seaborn as sns
@click.command()
@click.option(
'--report', '-r', type=str, help='Path or file glob to tax report files'
)
@click.option(
'--prefix', '-p', type=str, help='Output pr... |
from keras.models import model_from_json
from keras.utils import multi_gpu_model
import numpy as np
from sklearn.metrics import accuracy_score
from keras.callbacks import Callback, CSVLogger
from keras import backend as K
import tensorflow as tf
def score_binary_logistic_regression_error(y_true, y_pred):
"""
... |
from queue import Empty, Queue
from unittest.mock import call
import pytest
from uptimer.helpers.threads import ProcessingThread
from uptimer.plugins import ShutdownMarker
def test_processing_thread_init(mocker):
mock_callback = mocker.MagicMock()
processor = ProcessingThread(mock_callback)
assert proc... |
# -*- coding: utf-8 -*-
# Author: XuMing <<EMAIL>>
# Data: 17/8/29
# Brief:
import sys
import os
import re
StopWordtmp = ['。', ',', '!', '?', ':', '“', '”', '‘', '’', '(', ')', '【', '】', '{', '}', '-', '-', '~',
'[', ']', '〔', '〕', '.', '@', '¥', '•', '.']
# StopWordtmp = [' ', u'\u3000', u'\x30fb', u... |
import os
from collections import defaultdict
import dicom
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
from skimage import measure
def load_by_type(path, file_type, contains=""):
return [
dicom.read_file(os.path.join(path, s))
for s i... |
# We will use EfficientNetV2L as it should fit on the EdgeTPU and result in a reasonable accuracy with a low-enough latency
from pathlib import Path
import tensorflow as tf
import tensorflow_model_optimization as tfmot
from keras.applications.mobilenet_v2 import MobileNetV2
import numpy as np
from PIL import Image
impo... |
import os
import datetime
import random
import pandas as pd
import numpy as np
from calendar import monthrange
from dateutil.easter import easter
from utilities import get_path, get_config
DAYS = {"MON": 0, "Mon": 0, "Mo": 0, "Montag": 0, "Monday": 0,
"TUE": 1, "Tue": 1, "Di": 1, "Dienstag": 1, "Tuesday": 1,
... |
import torch.nn as nn
from .initialization import initialize_resnet
def conv3x3(in_planes, out_planes, stride=1, groups=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False)
def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_pla... |
from __future__ import unicode_literals
import pytest
from django.core.urlresolvers import reverse
from saleor.dashboard.order.forms import MoveItemsForm
from saleor.order.models import Order, OrderHistoryEntry, OrderedItem, DeliveryGroup
from saleor.product.models import Stock
from tests.utils import get_redirect_loc... |
# encoding: utf-8
from __future__ import unicode_literals
import json
from .ssh import SSHClient
from . import k8s
from .ocboot import GROUP_PRIMARY_MASTER_NODE, GROUP_MASTER_NODES, GROUP_WORKER_NODES
A_OCBOOT_UPGRADE_CURRENT_VERSION = 'upgrade.ocboot.yunion.io/current-version'
def construct_cluster(primary_maste... |
import unittest
from ..base import NoteException, ScoreException, StaffException
from ..chord import Chord
from ..note import Note, Rest, Message
from ..staff import Clef, Staff
class TestClef(unittest.TestCase):
def test_property_setters(self):
t = Clef('Treble')
b = Clef('Bass')
p = Cl... |
import numpy as np
import os
import time
import matplotlib
import matplotlib.pyplot as plt
def statistics(pkl_data, times, mode):
data = pkl_data["human_monitor"]
data = sorted(data.items(), key=lambda x: x[0])
start_date = data[0][0]
data = [((k - start_date).days, v) for k, v in data]
human2sy... |
# coding: utf-8
# # Importing libraries
# In[14]:
from contraction import CONTRACTION_MAP
import re
import pickle
import math
import re
import time
import tensorflow as tf
from tensorflow import keras
import pandas as pd
import nltk
from contraction import CONTRACTION_MAP # Its a py file contain expanded word ... |
import pytest
from testfixtures import compare
from firestore_odm import schema, fields
from firestore_odm.context import Context as CTX
from firestore_odm.config import Config
from firestore_odm.firestore_object import FirestoreObject, \
FirestoreObjectClsFactory
from firestore_odm.primary_object import PrimaryOb... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2021 <NAME> <<EMAIL>>
#
# 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 l... |
"""Shared pieces for the test suite."""
from typing import Tuple
import flax.core.frozen_dict as frozen_dict
import jax
import jax.numpy as jnp
import numpy as np
import vmcnet.mcmc as mcmc
import vmcnet.models as models
import vmcnet.train.default_config as default_config
from vmcnet.utils.typing import Array, PRNGK... |
import os # Zugriff auf Systembefehle
import re # Regulaere Ausdruecke
from pathlib import Path # Zugriff auf Systempfade
from random import shuffle # Zufaelliges Anordnen von Listenelementen
from playsound import playsound # Einzige Funktion: Audiodateien abspiel... |
import os,sys
import numpy as np
import numpy.linalg as npl
import matplotlib.pyplot as plt
import cv2
path2file = os.path.dirname(os.path.realpath(__file__))
from test_directions_permutohedral import get_permutohedral_basis
def simpdesc(name,arr):
print(str(name))
print(str(arr))
print(" ")
from test_util... |
import requests
import re
import threading
import os
import random
import socket
import struct
import time
#API接口初始化,按照手机号生成不同的网址
def initAPI(phone):
# 短信接口API 请求间隔时间 备注 请求方式 请求参数 需要SESSION的先决请求URL以及Referer
APIList = [
["https://login.ceconline.com/thirdPartLogin.do", 60, "世界经理人", "POST",
{"mo... |
import requests
import time
from requests.models import Response
from django.utils import timezone
import pytz
from meetup_data_scraper.meetup_scraper.models import (
EventPage,
GroupPage,
HomePage,
)
from meetup_data_scraper.meetup_scraper.meetup_api_client.exceptions import (
HttpNoSuccess,
HttpN... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Copyright 2020 <NAME>
#
# 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 ap... |
import os
import sys
import tensorflow as tf
import argparse
from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard, LearningRateScheduler
sys.path.append(os.path.dirname(__file__))
from modules.models import ArcFaceModel
from modules.losses import SoftmaxLoss
from modules.utils import set_memory_growth, ... |
""" Author: <NAME>
NCU CSIE 3B, Taiwan
Run through all of the testing data by calling televid for best parameter
testing.
"""
import csv
import itertools
import logging
import multiprocessing as mp
import pathlib
import pickle
import platform
import time
import televid
logging.basicConfig(level=logging.INFO)
... |
"""
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 License ... |
import time
import json, requests
import socket
import smtplib
import random, string
import argparse
from tqdm import tqdm
from multiprocessing import Pool
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests... |
import pandas as pd
from . import date_util as d
from . import type_util as t
import dolphindb.date_util as dd
from dolphindb.date_util import *
from dolphindb.pair import Pair
# python data type to xxdb data type mapping
DBTYPE = dict()
DBTYPE[bool] = DT_BOOL
DBTYPE[int] = DT_INT
DBTYPE[float] = DT_DOUBL... |
import os
import re
import json
import copy
from datetime import datetime
import pytz
from src.flags import FLAGS
def get_packages(gs_client):
print("Getting packages...")
# Find a spreadsheet by key and open the content sheet
book = gs_client.vfxpy_book
worksheet = book.worksheet("content")
p... |
import datetime
import re
from dimagi.ext.jsonobject import (
JsonObject,
StringProperty,
DictProperty,
BooleanProperty,
DateTimeProperty,
ListProperty,
IntegerProperty,
)
from jsonobject.base import DefaultProperty
from casexml.apps.case import const
from couchforms.jsonobject_extensions i... |
"""
Contains classes that describe Viper's Abstract Syntax Tree.
"""
from enum import Enum
class BinaryOpKind(Enum):
"""
The different kinds of binary operators
"""
POWER = 0
MUL = 1
MATMUL = 2
DIV = 3
MOD = 4
INTEGER_DIV = 5
PLUS = 6
MINUS = 7
SHIFT_LEFT = 8
SHIF... |
from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
from itertools import chain, combinations
import numpy as np
# Bringing back the SAUCE
model = KeyedVectors.load("models/glove.6B.100d.kv")
# Load stop words
with open("... |
from django.test import TestCase
from model_mommy import mommy
from cpovc_main.models import FacilityList
from cpovc_main.models import SchoolList, SetupGeography
from cpovc_main.models import SetupGeography
from cpovc_main.models import SetupList
from cpovc_main.models import Forms
class TestSchoolListModel(TestC... |
from lexermod.cft_token import Token, TokenTypes
from cft_errors_handler import ErrorsHandler
from cft_namehandler import NameHandler
LBOOL_OPS = ['not']
"""Left operators that are always return type `bool`"""
LOPS = ['+', '-', '*', '~', *LBOOL_OPS]
"""Left operators: <op> <expr>"""
MIDDLE_BOOL_OPS = ['or', 'and', ... |
import tensorflow as tf
import tools
from collections import OrderedDict
def focal_loss(logits, targets, alpha, gamma, normalizer,mask_flat):
"""Compute the focal loss between `logits` and the golden `target` values.
Focal loss = -(1-pt)^gamma * log(pt)
where pt is the probability of being classified to t... |
# -*- coding: utf-8 -*-
import re
from opensextant.gazetteer import DB, DataSource, get_default_db, as_place, SCRIPT_CODES
from opensextant.utility import get_csv_reader
"""
Name Variant Generator: create as many valid name variants for popular
abbreviated phrases in names.
"<NAME>" (instead of San Pedro)
... |
import io
import math
import os
import random
import shutil
import tensorflow as tf
import time
from lxml import etree
import dataset_util
import util
# Configurations (in most cases you don't need to change them)
ratio = 0.2 # Percentage of the total images used for testing, between 0~1
labelMapFilename = "label_ma... |
import cv2
import time
import numpy as np
import torch
import torch.nn as nn
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet,self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1,32, 5, 1, padding = 2),
torch.nn.ReLU(),
nn.MaxPool2d(kernel_size... |
import asyncio
import io
import traceback
import sys
import textwrap
from contextlib import redirect_stdout
from discord.ext import commands
import discord
from cogs.utils import paste
async def run_cmd(cmd: str) -> str:
"""Runs a subprocess and returns the output."""
process = await asyncio.create_subprocess_... |
import sys
import time
import argparse
import logging
import threading
import queue
import statistics
import cv2
import numpy as np
from tf_pose import common
from tf_pose.common import CocoPart
from tf_pose.estimator import TfPoseEstimator, BodyPart, Human
from tf_pose.networks import get_graph_path
# This work is ... |
import json
from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls impo... |
# -*- coding: utf-8 -*-
# Author: <NAME>
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.firefox_binary impo... |
import sys, os, subprocess, logging, json, requests, shutil, boto3, json, tabulate, urllib.request, re, math
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from dku_utils.access import _has_not_blank_property
def dataiku_recommended_instance_type(instance_type, gpu_ind=0):
i... |
import numpy as np
import h5py
# Normalized between 0-1
def rescale(rmat):
min_x = np.min(rmat)
max_min_x = np.max(rmat) - min_x
norm_rmat = (rmat - min_x)/ max_min_x
return norm_rmat
# Shifting to non-negative by adding the minimum number
def shifting_min(rmat):
min_x = np.min(rmat)*-1
norm_r... |
# Copyright 2021 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
import json
import time
import requests
from pyecharts.charts import Map, Timeline
from pyecharts import options as opts
def update_news():
url = 'https://lab.isaaclin.cn/nCoV/api/news?num=5'
news_data = []
res = requests.get(url)
while res.status_code != 200:
res = requests.get(url)
data =... |
'''
Database models
'''
from datetime import datetime
from sqlalchemy.dialects.postgresql import JSONB
from .database import db
from .settings import BOOK_TYPE, BOOK_SOURCE_NAME, BOOK_STATUS, UNKNOWN
class User(db.Model):
'''用户'''
__tablename__ = 'reader'
id = db.Column(db.Integer, primary_key=True, c... |
import argparse
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from helpers.utils import print_flags, load_mnist
BATCH_SIZE = 50
LEARNING_RATE = 1e-2
EPOCHS = 10
class ConvolutionalAutoencoder(object):
def __init__(self, learning_rate=1e-2):
self.learning_rate = learning_rate
def inf... |
from .AAA3A_utils.cogsutils import CogsUtils # isort:skip
from redbot.core import commands # isort:skip
from redbot.core.i18n import Translator, cog_i18n # isort:skip
from redbot.core.bot import Red # isort:skip
import discord # isort:skip
import typing # isort:skip
from .helpers import embed_from_msg
... |
from __future__ import unicode_literals, print_function
import os
import fnmatch
import bible_books
from general_tools.file_utils import write_file, read_file
from distutils.dir_util import copy_tree
class Preprocessor(object):
def __init__(self, manifest, source_dir, output_dir, quiet=False):
self.mani... |
import cv2
import numpy as np
import scipy.io as sio
def get_annotation_dict_in_day(annotation_fp):
annotation_dict = {}
with open(annotation_fp, 'r') as f:
annotation = f.readlines()
for idx, line in enumerate(annotation):
line = line.strip()
line = line.split(' ')
img_nam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.