text stringlengths 3.07k 12.6k |
|---|
"""
Turn a merged corpus into tfrecord files.
NOTE: You will want to do this using several processes. I did this on an AWS machine with 72 CPUs using GNU parallel
as that's where I had the deduplicated RealNews dataset.
"""
import argparse
import json as json
# from sample.encoder import get_encoder, tokenize_for_grov... |
'''
This module has two classes for splitting time series data temporally - where train/test or fold
splits are created within each of the time series' in the time series data. This splitting approach
is for evaluating how well the algorithm performs on segments drawn from the same time series but
excluded from the tra... |
import os
import random
import json
import xmltodict
import pandas as pd
import numpy as np
from itertools import chain
DATASET = "WGISD"
def invert_dictionary(dictionary):
new_dict = {}
for k,v in dictionary.items():
for x in v:
new_dict.setdefault(x,[]).append(k)
return new_dict
def... |
#!/bin/bash python
# -*- coding: utf-8 -*-
"""
Copyright 2020-present Works Mobile Corp.
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 requi... |
from util import Context
from storage import json_data
import random
import discord
from discord.ext import commands
import alakazam as zz
import re
async def good_bot(message: discord.Message) -> None:
json_data.good += 1
await message.channel.send("You have voted this bot as a good bot. :robot:")
async de... |
from abc import ABCMeta, abstractmethod
from random import randint, randrange
class Fighter(object, metaclass=ABCMeta):
"""战斗者"""
# 通过__slots__魔法限定对象可以绑定的成员变量
__slots__ = ('_name', '_hp')
def __init__(self, name, hp):
"""初始化方法
:param name: 名字
:param hp: 生命值
... |
import logging
from pyramid.view import view_config
import dbas.review
import dbas.review.queue
from dbas.handler.language import get_language_from_cookie
from dbas.helper.decoration import prep_extras_dict
from dbas.review.history import get_ongoing_reviews, get_review_history
from dbas.review.mapper import get_titl... |
#!/usr/bin/env python
"""
train.py
"""
from __future__ import division
from __future__ import print_function
import sys
import argparse
import ujson as json
import numpy as np
from time import time
import torch
from torch.autograd import Variable
from torch.nn import functional as F
from models import GSSuperv... |
__license__ = "MIT"
__copyright__ = r"""
MIT License
Copyright (c) 2017 <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... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import doctest
import io
import bits
import encode
import lazy
import model
import strings
import tycheck
SIGNATURE ... |
import pytest
from list_utils import *
from oracle import ColumnRecommendation, ColumnClassification
def test_find_one():
needle = 1
none = [0, 0, 5, 's']
beginning = [1, None, 9, 6, 0, 0]
end = ['x', '0', 1]
several = [0, 0, 3, 4, 1, 3, 2, 1, 3, 4]
assert find_one(none, needle) == False
... |
import pytest
from collections import OrderedDict
from test_plus import APITestCase
from tests.profile.factories import ProfileFactory, IndicatorCategoryFactory, IndicatorSubcategoryFactory, ProfileIndicatorFactory
from tests.datasets.factories import DatasetFactory, IndicatorFactory, IndicatorDataFactory, GroupFacto... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created on 1/12/19 by <NAME>
"""
.. currentmodule:: elastalk.client
.. moduleauthor:: <NAME> <<EMAIL>>
Start a conversation with Elasticsearch!
"""
import base64
import binascii
import json
import logging
from typing import Any, Dict
import elasticsearch
from .config im... |
import logging
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django_fsm import TransitionNotAllowed
from rest_framework import decorators, exceptions, response, status, views
from waldur_core.core import views as core_views
from waldur_core.structure import permissions ... |
# TODO (True): currently only supporting one texture and no materials
import panda3d as p3d
import numpy as np
import os
from renderer_util import compute_vertex_normals, convert_polygon_to_triangles
#-------------------------------------------------------------------------------
class OBJNode(p3d.core.GeomNode):
... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# 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... |
# Modified by Microsoft Corporation.
# Licensed under the MIT license.
# Various math calculations used by algorithms
import numpy as np
import torch
# general math methods
def normalize(v):
'''Method to normalize a rank-1 np array'''
v_min = v.min()
v_max = v.max()
v_range = v_max - v_min
v_ran... |
import numpy as np
import CNN_utils
# ref :https://blog.csdn.net/Daycym/article/details/83826222
class Convolution:
def __init__(self, ch_in, ch_out, kernel_size=(5, 5), stride=1, pad=0):
# Init parameters
self.W = np.random.random(size=(ch_out, ch_in, kernel_size[0], kernel_size[1])) - 0.5
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OptExp (c) University of Manchester 2019
OptExp is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>
Created on Tue Nov 27 16:01:46 2018
@author: <NAME>
@description: Basic routines common to several doe scr... |
# -*- coding: utf-8 -*-
"""This module contains the Contents object."""
from __future__ import unicode_literals
from base64 import b64decode, b64encode
from json import dumps
from .. import models
from ..decorators import requires_auth
from ..git import Commit
class Contents(models.GitHubCore):
"""A representa... |
"""
UBC Eye Movement Data Analysis Toolkit (EMDAT), Version 3
Created on 2011-08-25
Commonly used helper methods.
Authors: <NAME> (creator), <NAME>.
Institution: The University of British Columbia.
"""
from EMDAT_core.data_structures import Fixation
import params
import math
def point_inside_polygon(x,y,poly):
... |
import featuretools as ft
from featuretools.primitives import (
AddNumeric,
AddNumericScalar,
Count,
DivideByFeature,
DivideNumeric,
DivideNumericScalar,
Equal,
EqualScalar,
GreaterThan,
GreaterThanEqualTo,
GreaterThanEqualToScalar,
GreaterThanScalar,
LessThan,
Le... |
# Standard library
from itertools import groupby
from operator import (
attrgetter,
itemgetter,
)
from typing import (
NamedTuple,
Tuple,
)
# Local libraries
from tracers.containers import (
Frame,
LoopSnapshot,
)
from tracers.constants import (
CHAR_BROKEN_BAR,
CHAR_CHECK_MARK,
CHA... |
from dataclasses import dataclass
from typing import List, get_type_hints, get_args
import typing_utils
from google.protobuf.message import Message
from enum import Enum
from modela.util import TrackedList
def isPrimitive(obj):
return not hasattr(obj, '__dict__')
def convert_case(attr):
return attr[0].lower... |
import datetime
import logging
import os
import random
from tor import __root__, __version__
from tor.core import __HEARTBEAT_FILE__
# Load configuration regardless of if bugsnag is setup correctly
try:
import bugsnag
except ImportError:
# If loading from setup.py or bugsnag isn't installed, we
# don't wa... |
#!/usr/bin/env python3
#
# Copyright 2022 Graviti. Licensed under MIT License.
#
"""Paging list related class."""
from itertools import repeat
from math import ceil
from typing import Any, Callable, Iterator, List, Optional, Tuple
import pyarrow as pa
from graviti.paging.lists import PagingList, PyArrowPagingList
... |
"""Building blocks."""
from datetime import datetime
import pickle
STATUS_BACKSPACE = 1
STATUS_CORRECT = 2
STATUS_WRONG = 3
class Action:
"""Representation of one keypress.
Parameters
----------
pressed_key : str
What key was pressed. We define a convention that pressing
a backspac... |
#!/usr/bin/env python
"""
Converts the jams2 files to the 0.2.0 version of JAMS.
jams2 was initially contained in MSAF and is deprecated and should not be
confused with 2.0 or above JAMS version (sorry for the confusion!).
If you're new to MSAF, you probably don't need this.
"""
from __future__ import print_function
... |
"""
File: for2py_arrays.py
Purpose: Code to handle array manipulation in the Python code generated
by for2py.
Usage:
"""
import sys
import copy
import itertools
_GET_ = 0
_SET_ = 1
################################################################################
# ... |
# encoding:utf-8
import os
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from ...nn import BasicBlock, AttGate1, AttGate2, AttGate3
# RFUNet: Res U-Net
__all__ = ['RUNet', 'get_runet']
class RUNet(nn.Module):
def __init__(self, n_classes=21, ... |
import rbn
from collections import defaultdict
from operator import add
import reaction
class Atom:
"""
Represents an Atom in the Frozen-Node Spiky RBN Chemistry.
"""
id = 0
def __init__(self):
"""
The Atom class constructor.
Parameters:
id = An id numb... |
from datetime import datetime, timezone
from enum import Enum
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%f%z'
DATE_FORMAT_WITH_OFFSET = '%Y-%m-%dT%H:%M:%S.%f%z'
class IssueType(Enum):
STORY = 'Story'
TASK = 'Task'
SUB_TASK = 'Subtask'
BUG = 'Bug'
class Sprint:
def __init__(self, sprint_dict):
se... |
import os
from collections.abc import Mapping, Sequence, Callable
from torch.utils.tensorboard import SummaryWriter
import boardom as bd
from .util import _create_state_dict_element, _prepare_cfg
class AverageTracker:
def __init__(self, engine, size_key, fields):
self.trackers = {}
self.engine = e... |
# -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function
import argparse
import math
import os
import pickle
import sys
import numpy as np
import progressbar as pb
from util.distance import get_distance
def find_threshold_sort(pos, neg):
pos_list = sorted(pos, key=lambda x: x[0])... |
import unittest
class Election:
def __init__(self, processes):
abstract
def initElection(self, process):
abstract
def getElectedLeader(self):
abstract
def getMsgCnt(self):
abstract
def updateProcesses(self, processes):
... |
#!/usr/bin/env python3
#
# Copyright (c) 2019, The OpenThread Authors.
# 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
# ... |
import chess
import json
import time
import datetime
import random
# Bots
import random_bot
import basic_bot_1_2
class ChessArena(object):
def __init__(self, bot1, bot2, seed=None):
'''Initialize the chess arena with bot modules bot1 and bot2'''
self.arena_start_time = (datetime.datetime.fromti... |
# Date: 11/03/2019
# Author: Mohamed
# Description: Generate a decryptor
import os
import sys
import shlex
import shutil
import tempfile
from os import path
from lib.file import File
from argparse import ArgumentParser
from agent.lib.crypto import CryptoRSA
try:
from PyInstaller import __main__ as pyi, is_win
ex... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 1999-2015, <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 limitation ... |
import re
import os
from xdg import XDG_DATA_HOME
import sqlalchemy
from . import models
DB_PATH_ENV = 'TELEGRAM_BRIDGE_DB_PATH'
if os.getenv(DB_PATH_ENV, None) is None:
# Support old environment variable
DB_PATH_ENV = 'PLAZA_TELEGRAM_BRIDGE_DB_PATH'
if os.getenv(DB_PATH_ENV, None) is None:
_DATA_DIRE... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright (c) 2012 Samsung SDS Co., LTD
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you m... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021 <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, co... |
import os
import numpy as np
from data_types import Contact, Finger
from grasp_functions import (
get_H_and_l,
get_S,
check_equal_vectors,
block_diag,
list_to_vertical_matrix,
is_nullspace_trivial,
)
np.set_printoptions(suppress=True)
class Jacobian:
def __init__(self, fingers, contact_po... |
import nacl.utils
import base64
import nacl.signing
import nacl.encoding
import nacl.secret
from nacl.signing import VerifyKey
from mnemonic import Mnemonic
def print_info_about_seed_phrase(entropy_bytes):
entropy_hex = entropy_bytes.hex()
entropy_base64 = base64.b64encode(entropy_bytes).decode()
public... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2015 Kitware 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 cop... |
"""
Copyright 2020 The OneFlow 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 law or agr... |
import sys
sys.path.append('/data/AV-speech-separation/LipNet')
sys.path.append('/data/AV-speech-separation/models')
sys.path.append('/data/AV-speech-separation1/models/classification_models-master/')
import tensorflow as tf
import keras
from keras.layers import *
from keras import Model, Sequential
import keras.backe... |
import os
import argparse
from tqdm import tqdm
from datetime import datetime
from torch.utils.tensorboard import SummaryWriter
import torch
from dataset import MultimodalDataset
from torch.utils.data import DataLoader
from utils import rng_init, init_weights
import char_cnn_rnn as ccr
def sje_loss(feat1, feat2):... |
# pytorch dataset for SL learning
# matlab code (line 26-33):
# https://github.com/hellbell/ADNet/blob/master/train/adnet_train_SL.m
# reference:
# https://github.com/amdegroot/ssd.pytorch/blob/master/data/voc0712.py
import os
import cv2
import numpy as np
import torch
import torch.utils.data as data
from datasets.get... |
import tensorflow as tf
from tensorflow.python.training import moving_averages
def variable_weight(name, shape, initializer, trainable=True):
return tf.get_variable(name, shape=shape, dtype=tf.float32,
initializer=initializer, trainable=trainable)
def conv_layer(x, num_outputs, kernel_... |
"""The Discriminators."""
import functools
import itertools
import torch
from torch import nn
from torch.nn import functional as nnf
from torch.autograd import Variable
import environ
TYPES = ('cnn', 'rnn')
CNN, RNN = TYPES
def _l2_reg(mod, l=1e-4):
def _reg(var, grad):
return grad + l*var
mod.wei... |
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator, BranchPythonOperator
from airflow.operators.dummy_operator import DummyOperator
from airflow.hooks.postgres_hook import PostgresHook
from airflow.utils.trigger_rule import Trigg... |
import numpy as np
from numba import njit
@njit(nogil=True, fastmath=True)
def logsumexp(a):
a_max = np.max(a)
out = np.log(np.sum(np.exp(a - a_max)))
out += a_max
return out
@njit(parallel=True, error_model='numpy')
def normalize_to_probability(distribution):
'''Ensure the distribution integrat... |
# coding: utf-8
# # sat - Summed Area Table (integral image)
# ## Synopse
# The `sat` function is used to calculate from a given grayscale image, the summed area table (integral image).
#
# - **g = iasat(f)**
# - **Output**
# - **g**: ndarray with the summed area table.
#
# - **Input**
# ... |
import bittensor
from unittest.mock import MagicMock
import os
import shutil
import unittest.mock as mock
import pytest
# Init dirs.
if os.path.exists('/tmp/pytest'):
shutil.rmtree('/tmp/pytest')
def test_create():
keyfile = bittensor.keyfile (path = '/tmp/pytest/keyfile' )
mnemonic = bittensor.Keypa... |
import numpy as np
import sklearn.decomposition as skl_decomposition
try:
from orangecontrib.remote import aborted, save_state
except ImportError:
def aborted():
return False
def save_state(_):
pass
import Orange.data
from Orange.data.util import SharedComputeValue
from Orange.data impo... |
import csv
from collections import defaultdict
import pandas as pd
pd.set_option('display.max_columns', 60)
import munch
from IPython.display import display, HTML
import pybedtools as pbt
import sh
import tabulate
tbl = tabulate.tabulate
from spartan.utils.annotations.ensembl.gff3 import parse_gff3
from spartan... |
import pandas as pd
from pathlib import Path
# import matplotlib.pyplot as plt
# added by Pierre
import matplotlib as mpl
mpl.use('TkAgg') # or whatever other backend that you want
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import os
import argparse
from stable_baseli... |
import inquirer, subprocess, os, time, pdb
def select_wireless_interface():
'''
Select the Wireless Network Interface to be used to crack the wireless Access Points
'''
p1 = subprocess.Popen(('sudo', 'iw', 'dev'), stdout=subprocess.PIPE)
p2 = subprocess.Popen(('grep', 'Interface'), stdout=subproces... |
import torch
import numpy as np
import cv2
import math
import random
from torch.utils.data import Dataset
from configuration import Config
from utils.iou import IoU
class YoloDataset(Dataset):
def __init__(self, annotation_dir, transform=None):
self.annotation_dir = annotation_dir
self.max_boxes_... |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
# Copyright 2015 and onwards Google, 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/license... |
import unittest
import numpy as np
import pandas as pd
import xarray as xr
from test.sampledata import create_highroc_dataset
from xcube.core.update import update_dataset_var_attrs, update_dataset_attrs
class UpdateVariablePropsTest(unittest.TestCase):
def test_no_change(self):
ds1 = create_highroc_data... |
import codecs
import copy
import mimetypes
import os
import pathlib
import tempfile
from email.message import EmailMessage
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from io import BytesIO
from os.path import basename, splitext
from datetim... |
#
# Copyright 2012 New Dream Network, LLC (DreamHost)
# Copyright 2013 IBM Corp.
# Copyright 2013 eNovance <<EMAIL>>
# Copyright Ericsson AB 2013. All rights reserved
# Copyright 2014 Hewlett-Packard Company
# Copyright 2015 Huawei Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"... |
#!/usr/bin/env python
import csv
import datetime
from http.client import HTTPException, IncompleteRead
import logging
import os
import re
import string
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.request import urlopen
from bs4 import BeautifulSoup
from deco import concurrent, sync... |
from register import Register
from protocol.smart7e_protocol import *
from tools.converter import u16tohexstr
class Validator(Register):
def __init__(self):
self.ack = False
pass
def __call__(self, data):
raise NotImplementedError
class NoMessage(Validator):
def __init__(self, a... |
import os
import json
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
year_join=2015
month_join=10
def timeAddition(df,timestamp):
year=[timeConversion(x).split("-")[0] for x in df[str(timestamp)]]
month=[timeConversion(x).split("-")[1] for x in df[str(timestamp)]]
... |
import re
import math
import hashlib
import sqlite3
import unicodedata
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from collections import Counter
from cStringIO import Stri... |
import os, subprocess
import os.path as path
import time
from ...database.models import AudioGrab, Mix, Music, Stem
from .base_fittings import CPU_Fitting
class Transcode_To_MP3(CPU_Fitting):
def fitting(self):
if 'audio_db' in self.fso.props:
audio_db = self.fso.props.audio_db
if ... |
from banal import is_mapping, as_bool
from typing import TYPE_CHECKING, Any, List, Optional, TypedDict
from followthemoney.exc import InvalidModel
from followthemoney.types import registry
from followthemoney.rdf import NS, URIRef
from followthemoney.util import gettext, get_entity_id
if TYPE_CHECKING:
from follo... |
#!/usr/bin/env python
# coding: utf-8
# # Introduction
# This notebook presents couple examples of **graph visualization** in **pytorch**.
# **NOTE**: graph vizualization code was originally copied from https://github.com/szagoruyko/pytorchviz. Subsequenty modified by me.
# Contents:
# * [Imports](#Imports)
# * [Gr... |
# Copyright 2016 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... |
import ctypes
import ctypes.util
import sys
import os
dlls = list()
platform = sys.platform
if platform == "darwin":
dlls.append(ctypes.cdll.LoadLibrary("libssl.32.dylib"))
elif "win" in platform:
for d in ("libcrypto-1_1-x64.dll",):
try:
dlls.append(ctypes.cdll.LoadLibrary(d))
exc... |
# -*- coding: utf-8 -*-
# @Author : pengj <<EMAIL>>
# @Time : 2019/6/27 23:09
# @File : backtesting.py
import itertools
import matplotlib.pyplot as plts
from pyalgotrade import strategy, plotter
from pyalgotrade.optimizer import local
from pyalgotrade.stratanalyzer import returns, sharpe, drawdown, trades
fr... |
"""Real time bus arrival timings from LTA DataMall"""
from datetime import datetime, timedelta, timezone
import logging
import async_timeout
from dateutil import parser, tz
from ltapysg import get_bus_arrival
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const... |
# This file is part of gnome-tweak-tool.
# Copyright (c) 2012 Red Hat, Inc.
#
# gnome-tweak-tool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... |
#!/usr/bin/env python
'''
Analyzer for iPhone backup made by Apple iTunes
(C)opyright 2011 <NAME> <<EMAIL>>
Released under MIT licence
callhistory.py provides the code to show a TK window to browse through
the SQLite file which holds the call history data in the iPhone Backup.
'''
# IMPORTS ------------------... |
import heapq
import sys
# 1. Each character occurence counting:
def occurence(data_string):
char_occurence = dict()
string = data_string
for i in string:
if i in char_occurence:
char_occurence[i]+=1
else:
char_occurence[i]=1
return char_occurence
# 2. Build t... |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
"""
Coinmarketcap scraper.
Scrape data from https://coinmarketcap.com and populate the database.
"""
# Import standard modules
import json
import logging
import datetime
from time import sleep
from typing import Any, Dict, List, Optional, Union
# Import third-party modules
import requests
# Import local modules
fro... |
import datetime
from django.db.models import Q
from django.utils import timezone
import stripe
from .. import hooks, models, utils
def cancel(subscription, at_period_end=True):
"""
Cancels a subscription
Args:
subscription: the subscription to cancel
at_period_end: True to cancel at th... |
#!/usr/bin/env python3
"""
main() for OrbitX. Can launch one of several OrbitX programs.
Look in the submodules of orbitx.programs for different programs.
"""
import argparse
import logging
import sys
import time
import warnings
from pathlib import Path
import vpython
from orbitx import logs
from orbitx import pro... |
import argparse
import random
import re
class UnsupportedOperation(Exception):
"""
Exception class for unsupported operations.
"""
pass
def extract_alphanumeric(value):
"""
Extract alphanumeric values from given string.
:param value:
:return:
"""
pattern = re.compile(r"[\W_... |
from sphinx.application import TemplateBridge
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.highlighting import PygmentsBridge
from pygments import highlight
from pygments.lexer import RegexLexer, bygroups, using
from pygments.token import *
from pygments.filter import Filter, apply_filters
from py... |
command_names = [
"Lazy",
"Forward",
"Left",
"Right",
"Synthesise",
"MakeMinerals",
"EatFront",
"GiveEnergy",
"GiveMinerals",
"SendMsg",
"MakeNewBot",
"IfGEq",
"IfEq",
"IfLe",
"RelativeJump",
"AbsoluteJump",
"Store",
"StoreAbs",
"IncStore",
... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... |
import os
import shutil
import time
import logging
import argparse
import homie
from homie_hue_bridge.HueSSDP import SSDP
from homie_hue_bridge.HueBridgeEmulator import (
HueBridgeEmulator,
get_mac,
get_ip_address,
)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
# Devic... |
from ngrammer.Ngrammer import *
from ngrammer import CorpusHandler
def generate(trie, sos="[Start]", eos="[End]"):
import random
word = sos
sentence = [sos]
while word != eos:
temp = sentence[-(trie.n - 1):]
node = trie.get(temp)
children = list(node.children.keys())
wo... |
#!/usr/bin/env python3
# -----------------------------------------------------------------------------
# Copyright 2014 if(we)
#
# 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://ww... |
import discord
import random
import pandas as pd
async def order_not_available(message):
await message.channel.send('Cette fonction n\'est pas encore disponible. Peut-être dans la prochaine version du bot. :thinking: ')
await message.channel.send(file=discord.File('inputs/images/work.gif'))
return
def rank_to_emot... |
#-*- coding: utf-8 -*-
from __future__ import print_function
import re
import os
import time
import sys
sys.path.append("python")
import data_parser
import config
from gensim.models import KeyedVectors
from rl_model import PolicyGradient_chatbot
import tensorflow as tf
import numpy as np
#=========================... |
##############################################################################
#
# Copyright (c) 2001-2007 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THI... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, <EMAIL> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.desk.form.load import get_attachments, get_versions, get_badge_info, get_view_logs, get... |
"""Tests of the base module."""
import numpy as np
import nibabel as nb
import pytest
import h5py
from ..base import SpatialReference, SampledSpatialData, ImageGrid, TransformBase
from .. import linear as nitl
def test_SpatialReference(testdata_path):
"""Ensure the reference factory is working properly."""
o... |
import numpy as np
import scipy
from scipy import ndimage
import scipy.sparse
import matplotlib.pyplot as plt
def running_ccorr(
arr1,
arr2,
avg1=None,
avg2=None,
lags=10,
kernel_width=20,
order=0,
edge_mode="reflect",
cut_incomplete=True,
):... |
import tensorflow as tf
from PIL import Image
import xml.etree.ElementTree as ET
import glob, os, tqdm
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(value):
"""Returns a float_list from a flo... |
"""
Functions for generating vectorized spark UDFs
to distribute the prediction of sklearn model predictions
with PySpark DataFrames
"""
import pandas as pd
import numpy as np
class PysparkRequired(ImportError):
pass
class PyarrowRequired(ImportError):
pass
_PYSPARK_INSTALLED = None
_PYARROW_INSTALLED = Non... |
# coding: utf-8
"""
Logic module for management of languages
"""
import collections
import typing
from .. import db
from . import errors, settings, locale
from .. import models
class Language(collections.namedtuple(
'Language', ['id', 'lang_code', 'names', 'datetime_format_datetime', 'datetime_format_moment', '... |
from pytest import raises as assert_raises
from bundlebuilder.constants import (
DESCRIPTION_MAX_LENGTH,
REVISION_MIN_VALUE,
SHORT_DESCRIPTION_LENGTH,
TLP_CHOICES,
SCHEMA_VERSION,
)
from bundlebuilder.exceptions import ValidationError
from bundlebuilder.models import (
Bundle,
Sighting,
... |
# Allow user to move the current selection.
# Author: <NAME> (<EMAIL>), Jan 2011.
import golly as g
# set edges of bounded grid for later use
if g.getwidth() > 0:
gridl = -int(g.getwidth()/2)
gridr = gridl + g.getwidth() - 1
if g.getheight() > 0:
gridt = -int(g.getheight()/2)
gridb = gridt + g.getheig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.