text stringlengths 3.07k 12.6k |
|---|
import concurrent.futures
import itertools
import time
from pathlib import Path
import geopandas as gpd
import jsonlines
import pandas as pd
import requests
from pandas import Timedelta
from searchtweets import ResultStream, gen_request_parameters, load_credentials
from tqdm import tqdm
SEARCH_ARGS = load_credentials... |
from collections import namedtuple
from ..arraystep import Competence
from .base_hmc import BaseHMC
from pymc3.theanof import floatX
from pymc3.vartypes import continuous_types
import numpy as np
import numpy.random as nr
__all__ = ['NUTS']
BinaryTree = namedtuple('BinaryTree',
'q, p, q_gra... |
from PIL import Image
from common import get_file_contents
class Point:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
def __str__(self):
return "Point(x={}, y={})".format(self.x, self.y)
def __repr__(self):
return str(self)
def __eq__(self, other):
return self.x == other.x and self.y == o... |
import sys
import os
import os.path
import shutil
import subprocess
from pathlib import Path
import functools
import re
import click
from doit.doit_cmd import DoitMain
from doit.cmd_base import ModuleTaskLoader
from doit.runner import ERROR
from elm_doc.run_config import Build, Validate
from elm_doc.loader import mak... |
# Copyright 2008 Canonical Ltd.
# This file is part of launchpadlib.
#
# launchpadlib is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ve... |
# This file is part of remsh
# Copyright 2009, 2010 <NAME>
# See COPYING for license information
# -*- test-case-name: test.test_ops -*-
import sys
import os
class ProtocolError(Exception):
"An error in the internal protocol between master and slave"
class NotFoundError(ProtocolError):
"Something was not f... |
import numpy as np
import scipy.sparse
from mpi4py import MPI
from .mpi_kron import (BlockDiagMPI, CompositeMPI, IdentityKronMatMPI,
LinearOperatorMPI, MatKronIdentityMPI,
SparseKronIdentityMPI, SumMPI, TridiagKronIdentityMPI,
TridiagKronMatMPI)
from... |
#!/usr/bin/env python
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLD... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 16:12:32 2020
@author: <NAME>
"""
#%%
# This module contains the general framework of NN Class used for RL
import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from ..rl.utilities import check_WhileTrue_timeout, c... |
"""
Build on the NetworkBuilder.py function:
Workflow inputs:
:param timeseries_list: the list of the subjects timeserie. the columns are the certain ROIs and the rows represents the certain timepoints.
:param SinkDir: where to write important ouputs
:param SinkTag: The output direct... |
import collections
import os
import random
import h5py
import PIL.Image as Image
import torch
import torchvision.transforms as transforms
from torch.utils.data import Dataset
class VisionLanguageDataset(Dataset):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
data_path = kwargs["data_path"]
data... |
import logging
import time
from abc import ABC, abstractmethod
from os import path, makedirs
from typing import List, Optional
from pypapi import papi_high, events as papi_events
from pypapi.exceptions import PapiNoEventError
class IterativeMonitor(ABC):
@abstractmethod
def before_iteration(self) -> None:
... |
import pandas as pd
import numpy as np
from utils import loading
def calculate_top_words(series, relative=False):
'''calculate word frequencies from a series of strings
Arguments: series - a series containing strings, relative - If true calculate proportion of word frequency by number of observation, if False ... |
##############################################################################
#
# Copyright (c) 2008,2019 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... |
from bs4 import BeautifulSoup, SoupStrainer
import urllib.request
from elections_app.models import Person, Info, Election
from datetime import datetime, timedelta
import json
import django
import logging
logger = logging.getLogger('elections')
def get_soup(url):
response = urllib.request.urlopen(url)
html = resp... |
import os
import datetime
import numbers
import shutil
import stat
import glob
import json
from pathlib import Path
from codar.cheetah import exc
def make_executable(path):
current_mode = os.stat(path).st_mode
os.chmod(path, current_mode | stat.S_IEXEC)
def swift_escape_string(s):
"""
Escape backs... |
#==================================================================================
# Copyright (c) 2018-2019 AT&T Intellectual Property.
#
# 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 Li... |
#!/usr/bin/python3
#
# Program objective - generate images from recipes
#
from PIL import Image
from os import listdir
from os.path import isfile, join, isdir
itemsList = {}
def getImageSize(filename):
img = Image.open(filename)
return img.size
def generateItemsList():
for x in listdir("img/items"):
... |
import numpy as np
###########################################################################################
#Mid-point rooting
###########################################################################################
def MP_root(tree):
"""
This function implements a mid-point rooting algorithm that is lin... |
""" Implements an abstract class that represents an object in the game.
"""
from __future__ import annotations
import math
from typing import Literal, Optional
from abc import ABC
from dataclasses import dataclass
import pyg
import numpy as np
_MAX_VEL = 0.5
class GameObject(ABC):
""" Abstract class represen... |
# Create your models here.
from multiprocessing.dummy import Array
from django.db import models
from dcd.bucket.thing import Thing
import environ
import threading
import time
import requests
env = environ.Env()
environ.Env.read_env(env_file=".env")
STUDY_ID = env("STUDY_ID")
PROLIFIC_API = env("PROLIFIC_API")
PROLIFI... |
import argparse
import datetime
import sys
from supporters.settings import Settings
from supporters.database import Database
import supporters.tasks_common as task_action
from supporters.taskitem import TaskItem
# TODO: parser.add_argument("-tom", "--tomorrow", help="tomorrow")
def initialization(breefkase_dir):
... |
"""Basic utilities to manages shape objects and determine target
location."""
__author__ = "<NAME>, <NAME>, and <NAME>"
import io
import math
import time
from typing import Tuple
from hawk_eye.inference import types
from messages import interop_pb2
EARTH_RADIUS = 6378137
EARTH_ECCEN = 0.0818191
def curr_time() -... |
'''
MIT License
Copyright (c) 2020 <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 numpy as np
import math
import random
class Position():
def __init__(self, x, y):
self.xPos = x
self.yPos = y
def __str__(self):
return '(' + str(self.xPos) + ',' + str(self.yPos) + ')'
surface = np.zeros((5,5))
coordinatesZero = []
coordinatesOne = []
dim= np.shape... |
from qm import SimulationConfig
from qm.qua import *
from qm.QuantumMachinesManager import QuantumMachinesManager
from configuration import *
t = int(1e3) # Sensing duration
def init_nuclear_spin(qubit, target_state):
SSR(qubit, state, 1000)
with while_(state != target_state):
save(state,... |
import torch
import math
import scipy.stats
import numpy
import statsmodels.stats.proportion
from torch.autograd import Variable
device = torch.device('cuda:2')
print('use cuda ==> {}'.format(device))
def random_mask_batch_one_sample(batch, keep_per_image, mean_val=0.1307, reuse_noise=False):
flat = ... |
#!/usr/bin/env python
"""
Tile a given wire network pattern according to a grid or hex mesh.
"""
import argparse
import json
import numpy as np
import os.path
import pymesh
from pymesh.wires import WireNetwork, Tiler, Parameters, Inflator
from find_file import find_file
def parse_config_file(config... |
# -*- coding: utf-8 -*-
try:
import numpy as np
except ImportError:
np = None
try:
import matplotlib.pyplot as plt
except ImportError:
plt = None
from .. import ReactionSystem, Equilibrium
from ..units import get_derived_unit, to_unitless, default_units as u
def _dominant_reaction_effects(substance... |
from abc import ABC, abstractmethod
from typing import Optional
from django.db import models, transaction
from django.contrib.auth.hashers import check_password, make_password
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
fro... |
'''
from math import pi
class Circel(object):
def __init__(self,radius):
self.radius = radius
def getRadius(self):
return self.radius
def setRadius(self,value):
if not isinstance(value,(int, float) ): #python3 没有long
raise ValueError('wrong type')
self.radius = float(value)
def getArea(self):
retu... |
import pandas as pd
import numpy as np
import pyranges as pr
from pyranges.multithreaded import pyrange_apply
from pyranges.methods.statistics import _relative_distance
import numpy as np
def fdr(p_vals):
from scipy.stats import rankdata
ranked_p_values = rankdata(p_vals)
fdr = p_vals * len(p_vals) / r... |
# -*- coding: utf-8 -*-
"""
FY-4A标称(NOM)全圆盘(DISK)数据的行列号经纬度互转
参考国家卫星气象中心FY-4A数据行列号和经纬度的互相转换方法
Created on 2018/11/08 21:25:32
"""
from numpy import deg2rad, rad2deg, arctan, arcsin, tan, sqrt, cos, sin
ea = 6378.137 # 地球的半长轴[km]
eb = 6356.7523 # 地球的短半轴[km]
h = 42164 # 地心到卫星质心的距离[km]
λD = deg2rad(104.7) # 卫星星下点所在... |
import os
from django.http import HttpResponse
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import LineBotApiError
from linebot.models import *
from .models import *
# Init
file_host = 'https://app.whattoeat.work/File/Store/'
line_bot_api = LineBotApi(os.getenv('LINE_CHANNEL_ACCESS_LONG_TOKEN... |
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
from sklearn.mixture import GaussianMixture
from math import sqrt, exp
from scipy.special import erf
from scipy.stats import gaussian_kde
import torch
# (12, 168, n, 2)
# (12 ,168, 2)
# Fit a GMM on the n samples try 100 and 1000. If no difference pick 1... |
import argparse
from tqdm import tqdm
import jsonlines
import numpy as np
import random
import spacy
import math
import re
from tfidf.doc_db import DocDB
class PreTrainDataGenerator:
def __init__(self, \
db_file, \
output_file):
self.db = DocDB(db_file)
self.ner_m... |
"""
pypenumbra.api
~~~~~~~~~~~~~~
Defines the API for pypenumbra.
:copyright: 2019 <NAME>
:license: MIT
"""
import os
from . import sinogram
from skimage import io
from skimage import exposure
from skimage.exposure import equalize_adapthist
from skimage import img_as_ubyte, img_as_float64
from skim... |
import random
import pygame
width = 500
rows = 25
class Cube(object):
rows = rows
w = width
def __init__(self, start, dirx=1, diry=0, color=(255, 0, 0)):
self.pos = start
self.dirx = 1
self.diry = 0
self.color = color
def move(self, dirx, diry):
self.dirx = di... |
import os
from tqdm import tqdm
import numpy as np
import json
from PIL import Image
import matplotlib.pyplot as plt
def compute_convolution(I, T, stride=None):
'''
This function takes an image <I> and a template <T> (both numpy arrays)
and returns a heatmap where each grid represents the output produced ... |
# -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2014 PyBuilder Team
#
# 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/l... |
import pytest
import sidekick as sk
from numpy.testing import assert_almost_equal
from sidekick import X, Y
from pydemic.formulas import sir, seir, seair, formula
class TestFormulaDecorator:
def test_positional(self):
@formula((), positional=1)
def fn(f, gamma, sigma):
return f(gamma,... |
from typing import Optional
import httpx
from ...types import Response
Client = httpx.Client
import datetime
from typing import Dict, List, Optional, Union
from dateutil.parser import isoparse
from ...models.an_enum import AnEnum
from ...models.http_validation_error import HTTPValidationError
from ...models.model... |
# reddit bot for sharing mmd from nicovideo.jp for r/mikumikudance subreddit
# by u/pke1029
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import praw
import datetime
import time
import os
def make_soup(url):
while True:
try:
respond = requests.get(url)
... |
# Copyright 2015 Catalyst IT Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
import sys
import random
from django.http import HttpResponse
from django.db.models import Count
from django.template.loader import get_template
from django.template import Context
from api.models import User, Zipcode, Store, Competitor
from bugreport.helpers.distance import haversine
#constants
epsilon = 0.05
pric... |
import pytest
import uuid
from fastapi import status
#
# INVALID TESTS
#
@pytest.mark.parametrize(
"key,value",
[
("expires_on", ""),
("expires_on", "Monday"),
("expires_on", "2022-01-01"),
("for_detection", 123),
("for_detection", None),
("for_detection", "T... |
#!/usr/bin/env python
import sys, os
import json
import argparse
from multiprocessing import Pool
#
# Convert a Wikipedia corpus previously processed by a wikiextractor (https://github.com/attardi/wikiextractor)
# It tries to limit each chunk to have at most given number of BERT tokens while keeping
# original sentenc... |
# Copyright 2018,2019,2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# 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
#... |
"""Implements a sample BlockChain.
"""
import datetime
import hashlib
class Node:
"""A node for the BlockChain Linked List.
"""
def __init__(self, block):
self.block = block
self.prev = None
class Block:
"""A Block that goes onto the BlockChain.
"""
def __init__(self, time... |
from __future__ import print_function
import sys
import errno
import shutil
import os
import traceback
import subprocess
import io
import glob
import re
import git
import yaml
DEBUG = False
REFRESH_TEMPLATE = False
WORK_OFFLINE = False
def eprint(*args, **kwargs):
'''
Print to std error.
'''
print(*a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
nmrstarlib.bmrblex
~~~~~~~~~~~~~~~~~~
This module provides :func:`~nmrstarlib.bmrblex.bmrblex` lexical analyzer for
BMRB NMR-STAR format syntax. It is implemented as Python generator-based
state machine which generates (yields) token one at a time when
:py:func:`next... |
from FIAT.reference_element import LINE
import gem
from finat.finiteelementbase import FiniteElementBase
from finat.tensor_product import TensorProductElement
class WrapperElementBase(FiniteElementBase):
"""Common base class for H(div) and H(curl) element wrappers."""
def __init__(self, wrappee, transform):... |
#!/usr/bin/python
import boto3
import botocore
import os
import sys
import errno
import ast
from optparse import OptionParser
args=None
parser = OptionParser()
parser.add_option("--transfer-info", dest="transfer_info", help="Detailed Transfer Information")
parser.add_option("--out-file", dest="out_file", help="Output... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... |
"""Define DataNode"""
import numpy
import torch
import inspect
import functools
import abc
from typing import Callable, Tuple, List, Union
from idrlnet.variable import Variables
from idrlnet.node import Node
from idrlnet.geo_utils.sympy_np import lambdify_np
from idrlnet.header import logger
class DataNode(Node):
... |
# coding: utf-8
# In[48]:
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import os
def create_df_hand(game_file):
with open(game_file) as json_file:
data = json.load(json_file)
df_game = pd.DataFrame(data['datasLis... |
from . import config as c
from . import sprites
import pygame as pg
import math
class Game_Object():
def __init__(self, rect):
self.rect = rect
def __getattr__(self, name):
"""Makes lines shorter by not having to type rect.pos when retrieving position"""
if name == 'pos':
r... |
##############################################################################
#
# Copyright (c) 2017, 2018 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.
# TH... |
import re
from xml.dom.minidom import parseString
from six.moves.urllib.parse import parse_qs
from django.db import models
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
from .the3rdman import signals
def prettify_xml(xml_str):
xml_str = re.sub(r'\s*\n\s*', '', xm... |
# plots.py
from __future__ import division
import matplotlib
matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')
import numpy as np
from numpy import array as arr
from scipy.interpolate import interp1d
from scipy.linalg import solve
import matplotlib.pyplot as plt
from matplotlib.axis import Axi... |
import GPopt as gp
import time
import sys
import numpy as np
import matplotlib.pyplot as plt
from os import chdir
from scipy.optimize import minimize
# branin
def branin(x):
x1 = x[0]
x2 = x[1]
term1 = (x2 - (5.1*x1**2)/(4*np.pi**2) + (5*x1)/np.pi - 6)**2
term2 = 10*(1-1/(8*np.pi))*np.cos(x1)
... |
"""
motifscan.scanner
-----------------
Module for core motif scanner.
"""
import logging
import os
from collections import namedtuple
from motifscan.motif.cscore import c_scan_motif
logger = logging.getLogger(__name__)
MotifSite = namedtuple("MotifSite", ['start', 'score', 'strand'])
class Scanner:
"""
... |
from rest_framework.generics import (
GenericAPIView,
CreateAPIView,
RetrieveAPIView,
UpdateAPIView,
)
from rest_framework.permissions import AllowAny, IsAuthenticated
from .permissions import (
IsOwnerDeliver,
IsDeliverGroup,
IsOrderedCustomer
)
from django.contrib.auth.models import U... |
import sys
import copy
from collections import defaultdict, deque
import json
from utils import read_problem
from solve import check_partial_solution, compute_inside_points, is_edge_inside
problem_id = sys.argv[1]
spec = read_problem(problem_id)
def check_distance(spec, orig_dist, new_dist):
if abs(1.0 * new_d... |
"""SSL client/server certificates verification for `urllib2`.
It works on Python 2.6, 2.7, 3.1, 3.2
It also works on Python 2.4, 2.5 if `ssl` is installed (``pip install ssl``)
Example::
>>> import urllib2, urllib2_ssl
>>> opener = urllib2.build_opener(urllib2_ssl.HTTPSHandler(
... key_file='clientkey.p... |
#!/usr/bin/python3
##--<NAME>
##--AVWX-Engine : AutoTester.py
##--Constantly test the Metar parser against a list of all possible stations
##--2015-06-19
from avwx import *
import time , csv , smtplib , os , sys , io , requests
timeoutStations = []
notFoundStations = []
parseErrorStations = []
foundMissing = []
know... |
"""
Copyright 2018 Johns Hopkins University (Author: <NAME>)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from ..utils.list_utils import list2ndarray
def compute_confusion_matrix(
y_true... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`test_client`
==================
.. module:: test_client
:platform: Unix, Windows
:synopsis:
.. moduleauthor:: hbldh <<EMAIL>>
Created on 2015-08-07, 12:00
"""
from __future__ import division
from __future__ import print_function
from __future__ import u... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import compas
from compas import _iotools
class OFF(object):
"""Class for working with OFF files.
Parameters
----------
filepath : path string | file-like object | URL string
A path, ... |
import json
import pytest
import re
import requests
from urllib.parse import parse_qs
from .common import get_message, controlled_responses
from plugins.bamboo import BambooBot
with open('tests/test_bamboo_data.json') as data_file:
data = json.load(data_file)
server = {'host': 'http://host', 'username': 'user', ... |
# Noughts and crosses
# Reinforcement Learning - simple training.
# This records the history of moves and updates the value function at
# all visited positions at the end of every game, starting at the end and
# looping back through the positions with:
# prior = player.value[state]
# reward = prior + player.le... |
import ESMF
import numpy as np
import os, glob
import re
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from matplotlib import cm, gridspec, rcParams
import matplotlib.pyplot as plt
from readers import read_grid, get_coords, get_mask
from regrid import get_ease_coords, ESMF_GenRegridWeights
def write... |
#!/usr/bin/env python
import sys
import threading
import time
import numpy as np
import rospkg
import rospy
from cv_bridge import CvBridge, CvBridgeError
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog
# import some common detectron2 utilities
from detectron2.engine import DefaultPre... |
import tensorflow as tf
from tensorflow import einsum
from tensorflow.keras import Model
from tensorflow.keras.layers import Layer
from tensorflow.keras import Sequential
import tensorflow.keras.layers as nn
from einops import rearrange, repeat
from einops.layers.tensorflow import Rearrange
class PreNorm(Layer):
... |
#
# This file is part of PyFOPPL, an implementation of a First Order Probabilistic Programming Language in Python.
#
# License: MIT (see LICENSE.txt)
#
# 19. Jan 2018, <NAME>
# 31. Jan 2018, <NAME>
#
import ast
from . import Options, foppl_ast
from .distributions import distributions_map
_bin_op = {
ast.Add: '+',
... |
from fairseq.models.nat.levenshtein_transformer import LevenshteinTransformerModel
from fairseq.models import register_model, register_model_architecture
from fairseq.models import (
FairseqEncoder,
)
from fairseq.models.nat import (
FairseqNATEncoder
)
from fairseq.modules.transformer_sentence_encoder import ... |
#!/usr/bin/env python
"""models.py
Udacity conference server-side Python App Engine data & ProtoRPC models
$Id: models.py,v 1.1 2014/05/24 22:01:10 wesc Exp $
created/forked from conferences.py by wesc on 2014 may 24
"""
__author__ = '<EMAIL> (<NAME>)'
import httplib
import endpoints
from protorpc import message... |
import ipaddress
import subprocess
import enum
from itertools import groupby
import json
import datetime
def flatten(i, separator):
return str(i).replace('\r','\\r').replace('\n','\\n').replace(separator,' ')
def h2bin(x):
data = x.replace(' ', '').replace('\n', '').replace('\t', '').replace('\r', '')
return bytea... |
import json
import os
import pathlib
import tempfile
# get relevant paths
from typing import Optional, Dict, Tuple
from solcx import compile_standard
from solcx.exceptions import SolcError
from zkay.config import zk_print, cfg
from zkay.zkay_ast.ast import get_code_error_msg
class SolcException(Exception):
""" ... |
"""
Implementation notes:
For 1.1 I've introduced support for multiline rules,
and I think this makes the grammar non-LALR(1). Therefore,
additonal parsing step is needed.
After lexing, a hand-written parser splits input stream
into separate rule definitions, which are then fed to the LALR parser.
I'm clearly not a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 <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... |
from __future__ import absolute_import
from __future__ import unicode_literals
# Copyright 2016,2017 <NAME>nsic Pty Ltd. 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
... |
"""
All non-neural data preprocessing.
Technical indicators:
MA - moving average
EMA - exponential moving average
MOM - momentum
ROC - rate of change
ATR - average true range
BBands - bollinger bands
RSI - relative strength index
MACD - Moving Average Convergence Divergencew
william_r_% - Williams Percent Range
k% - ... |
#!/usr/bin/env python
"""
A library and command-line tool for generating a RAPID-style CommandConstants.idl
file from an XPJSON schema.
"""
import os
import sys
import re
import logging
# hack to ensure xgds_planner2 submodule is at head of PYTHONPATH
ffroot = os.path.dirname(os.path.dirname(os.path.dirname(os.path.... |
#!/usr/bin/env python3
import re
import os
import sys
import hashlib
import base64
import subprocess as sub
BINDIR = sys.argv[1]
def sha256_checksum(filename, otype='V', block_size=65536):
sha256 = hashlib.sha256()
size = 0
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_s... |
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.autograd import Variable
import math, random, string, os, sys
from submodels.context_feature_extractor import CNN_Embedding
from DAMIC import DAMIC as basemodel
torch.manual_seed(1)
device = torch.device("cuda" if torch.cuda.is_availab... |
import re
from typing import Optional, Tuple, Dict, Callable, Any
from datetime import datetime, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
from scapy.all import Packet, Raw, IP, TCP, NoPayload
from util.misc import add_space_and_encode_to_bytes
passive_mode_response_regex = re.compil... |
#!/usr/bin/env python
# coding: utf-8
# ## Sample GAIA DR2
#
# To search for specific data in DR2. <br>
# Note that gaia-on-tap is by default for DR1 <br>
import sys, os
rootdir = os.environ.get("GAIA_ROOT")
sys.path.append("%s/run/src"%(rootdir))
import astropy.coordinates as coord
from astropy.coordinates import... |
from instance import Instance
import virtualbox
from contextlib import contextmanager
from ..tools import waituntil
import logging
log = logging.getLogger(__name__)
@contextmanager
def boot_image(name, image):
instance = VirtualBoxInstance(name, image)
try:
instance.create()
try:
instance.boot()
yield ins... |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import jax.numpy as jnp
from jax.experimental import stax
from jax.experimental.stax import Dense, Relu, Dropout, Sigmoid
from jax.experimental import optimizers
from jax import jit, grad
from jax import random
import numpy.random as npr
import itertools
from sklearn.preprocessing import Normalizer
from test_utils.data... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
# a public static method
def toBlocky(ast):
t = PseudoCodeTranslator()
return t.toPseudoCode(ast)
# Class: Psuedo Code Translator
# ------------------------
# Can turn an AST into psuedo code.
class P... |
import logging
import re
import aiohttp
from dango import dcog, Cog
import discord
from discord.ext.commands import command, group, errors, Converter, UserConverter
from pachimari import BattleTag, OverwatchProfile, Platform, PCRegion, CONRegion
log = logging.getLogger(__name__)
def battle_tag(value):
try:
... |
import numpy as np
import open3d, os
import torch
from visualization_utils import get_hand_geometry
import transforms3d
torch.set_printoptions(precision=8)
def inv_transform_grasp(grasp_trans):
'''
Input:
grasp_trans:[B, 8] (center[3], axis_y[3], grasp_angle[1], score[1])
Output:
matrix... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
import requests
from .exceptions import APIError, DoesNotExist
class Struct:
def __init__(self, **attrs):
self.__dict__.update(attrs)
def _requests_g... |
import Queue as q
import contextlib
import functools
import json
import requests
import select
import signal
import socket
import subprocess as sp
import tempfile
import threading as t
import yaml
import sys
MAIN_CLASS = "com.spotify.heroic.HeroicService"
DEV_NULL = open("/dev/null")
BASE_PORT = 12345
PING_PORT = 1202... |
from fooster.web import web
import mock
test_request = 'GET / HTTP/1.1\r\n' + '\r\n'
def bad_read(self):
raise Exception()
def run(request, handler=None, timeout=None, keepalive=True, initial_timeout=None, read_exception=False, close=True, skip=False):
if not isinstance(request, bytes):
request ... |
#%% Imports
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping
import optuna
from optuna.integration import PyTorchLightningPruningCallback
import warnings
warnings.simplefilter("... |
import numpy as np
import os
from gbmgeometry import PositionInterpolator, gbm_detector_list
from astropy.coordinates import SkyCoord
from cosmogrb.utils.package_utils import get_path_of_data_file
from cosmogrb.response.response import Response
from cosmogrb.instruments.gbm.gbm_orbit import gbm_orbit
from cosmogrb.... |
from re import error
from unittest import TestCase as _TestCase
from lib.easyre import (
Text,
Or,
Group,
Many,
CharacterSet,
CharacterRange,
NegativeCharacterSet,
NegativeCharacterRange,
NumericRange,
)
class TestCase(_TestCase):
def set(self, re):
self.re = re
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.