filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_15949 | from network import *
from loss import *
import torch.nn as nn
import torch
class Model(nn.Module):
def __init__(self, opt):
super(Model, self).__init__()
self.opt = opt
self.Darknet = Darknet(opt)
self.Darknet.apply(weights_init_normal).to(device)
self.optimizer = torch.op... |
the-stack_106_15950 | import pytest
from click.testing import CliRunner
from datahub.entrypoints import datahub
from tests.test_helpers import fs_helpers, mce_helpers
from tests.test_helpers.docker_helpers import wait_for_port
@pytest.mark.slow
def test_mysql_ingest(docker_compose_runner, pytestconfig, tmp_path, mock_time):
test_reso... |
the-stack_106_15951 | #!/usr/bin/env python
#
# Copyright (c) 2017, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
#
# All rights reserved.
#
# The Astrobee platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except i... |
the-stack_106_15952 | import numpy as np
import numpy.linalg as linalg
def centering(X):
'''
Removes the mean intensity of the image from each image
:param X: [m,n], image in m dimension, n samples
:return: np.dot(np.identity(m) - np.ones([m,m]) / float(m) , X)
'''
# X: [m,n]
m, n = X.shape
# mathematically... |
the-stack_106_15955 | #!/usr/bin/env python3
import yaml
CONFIG = {
'aws-arm64-quota-slice': {
# Wild guesses. We'll see when we hit quota issues
'us-east-1': 10,
'us-east-2': 8,
'us-west-1': 8,
'us-west-2': 8,
},
'aws-quota-slice': {
# Wild guesses. We'll see when we hit quo... |
the-stack_106_15957 | from pyplan_engine.classes.dynamics.BaseDynamic import BaseDynamic
from pyplan_engine.classes.Helpers import Helpers
import numpy as np
import cubepy
import datetime as dt
import re
class CubepyDynamic(BaseDynamic):
def circularEval(self, node, params):
"""
Used for execute nodes with circular re... |
the-stack_106_15958 | """
1. Clarification
2. Possible solutions
- Recursively
- Iteratively
3. Coding
4. Tests
"""
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
# T=O(n), S=O(n)
class Solution:
def postorder(self, root: 'N... |
the-stack_106_15959 | # -*- coding: utf-8 -*-
def extraNumber(A, B, C):
if A == B: return C
elif A == C: return B
else: return A
extraNumber = lambda A, B, C: C if (A == B) else B if (A == C) else A
"""
Given three integers, two of them are guaranteed to be equal, find the third one.
Example
For A = 2, B = 4 and C = 2, the ... |
the-stack_106_15963 | import glob
import pandas as pd
import os
log_model = {'fisher': 'EWC', 'mas': 'MAS', 'mine3': 'New3', \
'new': 'New', 'retrain': 'Fine-tune', 'regu': 'Fine-tune2', 'selfless': 'Selfless'}
def getPaths(folder, prefix):
txt_files = glob.glob(os.path.join(folder, '{}_*.log'.format(prefix)))
return txt_files
def get_d... |
the-stack_106_15964 | import json
import pulumi_aws as aws
from pulumi import ComponentResource, Output, ResourceOptions
class FileSystem(ComponentResource):
def __init__(self,
name,
security_groups,
subnets,
vpc_id,
opts: ResourceOptions = None):
... |
the-stack_106_15966 | import concurrent.futures
import os
import re
import tempfile
from contextlib import contextmanager
from typing import Iterable, Iterator, List, Optional, Set
import click
from pygitguardian import GGClient
from ggshield.output import OutputHandler
from ggshield.scan import Commit, ScanCollection
from ggshield.text_u... |
the-stack_106_15967 | from aws_cdk.core import Stack, Construct
from aws_cdk.aws_ssm import StringParameter
from b_aws_cdk_parallel_test.integration.infrastructure.infrastructure3.stack1 import Stack1
class Stack2(Stack):
def __init__(self, scope: Construct, stack1: Stack1) -> None:
super().__init__(scope=scope, id='Stack2')
... |
the-stack_106_15968 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
the-stack_106_15970 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
parse_duration,
int_or_none,
ExtractorError,
)
class Porn91IE(InfoExtractor):
IE_NAME = "91porn"
_VALID_URL = r"(?:https?://)(?:www\.|)91porn\.com/.+?\?viewkey=(?P<id>[\w\d]+)"
_TE... |
the-stack_106_15973 | # coding: utf-8
import re
import sys
from guessit import guessit
from requests.utils import quote
class Downloader(object):
header = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)\
AppleWebKit 537.36 (KHTML, like Gecko) Chrome",
"Accept-Language": "z... |
the-stack_106_15977 | import tempfile
import subprocess
import shlex
import os
import numpy as np
import scipy.io
import cv2
script_dirname = os.path.abspath(os.path.dirname(__file__))
np.set_printoptions(threshold='nan')
def get_windows(image_fnames, cmd='edge_boxes_wrapper',alpha=0.6,beta=0.7,minscore=0.01,maxboxes=1e4):
"""
Run... |
the-stack_106_15980 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from discord.ext import commands
app = Flask(__name__)
ENV = 'prod'
if ENV == 'dev':
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = ''
else:
app.debug = False
app.config['SQLALCHEMY_DATABASE_URI'] = ''
app.confi... |
the-stack_106_15981 | import logging
import itertools
import numpy as np
from numpy.linalg import inv
from typing import List, Optional, Tuple
import scipy as sp
try:
import qutip as qtp
except ImportError as e:
logging.warning('Could not import qutip, tomo code will not work')
DEFAULT_BASIS_ROTS = ('I', 'X180', 'Y90', 'mY90', 'X90... |
the-stack_106_15982 | # --
# File: domaintools_iris_connector.py
#
# Copyright (c) 2019-2022 DomainTools, LLC
#
# --
# Phantom App imports
import codecs
import hashlib
import hmac
import json
import sys
from datetime import datetime, timedelta
import phantom.app as phantom
import requests
from phantom.action_result import ActionResult
fr... |
the-stack_106_15983 | #!/usr/bin/env python3
# Copyright (c) 2009 Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Purge pyftpdlib installation by removing pyftpdlib-related files and
directories found in site-packages directories. This is nee... |
the-stack_106_15985 | # -*- coding: utf-8 -*-
"""
Inventory Management
A module to record inventories of items at a locations (sites),
including Warehouses, Offices, Shelters & Hospitals
"""
module = request.controller
resourcename = request.function
if not deployment_settings.has_module(module):
raise HTTP(404, body="Mo... |
the-stack_106_15986 | #! /usr/bin/env python3
from Bio.Seq import Seq
from Bio import SeqIO
from threading import Thread
import re,argparse,time,threading
threading.stack_size(65536)
parser = argparse.ArgumentParser()
parser.add_argument("-b",required ='TRUE',help=".txt with list of barcodes, one per line, overhang listed last")
parser.add_... |
the-stack_106_15987 | from collections import defaultdict
from .models import DisplayCondition, ExtraField
def get_extra_fields():
conditions = defaultdict(list)
for condition in DisplayCondition.objects.all():
conditions[condition.field_id].append({
'key': condition.key,
'values': condition.values... |
the-stack_106_15988 | from ai.player import Player
from ai.train import train
from game.tictactoe import TicTacToe
from sys import argv
from argparse import ArgumentParser
def cmd_train(game, playerType, args):
player = playerType(game)
if args.load:
player.load_weights('./checkpoints/tictactoe')
i = 0
bad = True
while bad:
... |
the-stack_106_15990 | import json
import plotly
import pandas as pd
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import Bar
import joblib
from sqlalchemy import create_engine
app = Flask(__name__)
def to... |
the-stack_106_15991 | from .base import Base, db # noqa
from .bible import BibleVersion, UserPref # noqa
from .confession import ( # noqa
Article,
Chapter,
Confession,
ConfessionNumberingType,
ConfessionType,
ConfessionTypeEnum,
NumberingTypeEnum,
Paragraph,
Question,
)
__all__ = (
'db',
'Base... |
the-stack_106_15995 | """SensiMix: Sensitivity-Aware 8-bit Index & 1-bit Value Mixed Precision Quantization for BERT Compression
Authors:
- Tairen Piao (piaotairen@snu.ac.kr), Seoul National University
- Ikhyun Cho (ikhyuncho@snu.ac.kr), Seoul National University
- U Kang (ukang@snu.ac.kr), Seoul National University
This software may be use... |
the-stack_106_15996 | import sdl2
import sdl2.ext
from Node import Node
import json
import time
jsnode = Node("controls_node.json")
sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
""" For when we want to use multiple joysticks
self.joysticks = []
for i in range(0, sdl2.SDL_NumJoySticks()):
joy = sdl2.SDL_JoystickOpen(i)
self.joysticks.appe... |
the-stack_106_15997 | # -*- coding: utf-8 -*-
from datetime import timezone, datetime, date
import copy
import json
import os
import base64
import sys
from io import BytesIO, BufferedIOBase, TextIOBase
from zipfile import ZipFile
import uuid
from collections import defaultdict
import logging
import hashlib
from pathlib import Path
from typ... |
the-stack_106_15998 | # -*- coding: utf-8 -*-
'''
Work with cron
'''
from __future__ import absolute_import
# Import python libs
import os
import random
# Import salt libs
import salt.utils
import salt.ext.six as six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER =... |
the-stack_106_16000 | import utime as time
from platform import simulator, USB_ENABLED
if not simulator:
import pyb
else:
from unixport import pyb
class USBHost:
def __init__(self, callback=None):
self.callback = callback
self.data = ""
if USB_ENABLED:
self.usb = pyb.USB_VCP()
# alte... |
the-stack_106_16001 | # --------------
import pandas as pd
from sklearn.model_selection import train_test_split
#path - Path of file
# Code starts here
df = pd.read_csv(path)
X = df.drop(labels=['customerID','Churn'], axis=1)
y = df['Churn']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3, random_state=0)
# -----... |
the-stack_106_16002 | import os
import tempfile
import pytest
import pickle
import numpy as np
# Main C3 objects
from c3.c3objs import Quantity as Qty
from c3.optimizers.optimizer import TensorBoardLogger
from c3.parametermap import ParameterMap as Pmap
from c3.experiment import Experiment as Exp
from c3.model import Model as Mdl
from c3.g... |
the-stack_106_16004 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setuptools.setup(
name="subscene2",
version="1.0.2",
author="Rakibul Yeasin",
author_email="ryeasin03@gmail.com",
description="A Python... |
the-stack_106_16005 | import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
class STN3d(nn.Module):
'''
T-Net for 3d points
'''
def __init__(self, channel):
super(STN3d, self).__init__()
... |
the-stack_106_16010 | """empty message
Revision ID: 20210312_123136
Revises: 20210310_183119
Create Date: 2021-03-12 12:31:36.548172
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "20210312_123136"
down_revision = "20210310_183119"
branch_l... |
the-stack_106_16013 | from shapeworld.dataset import CaptionAgreementDataset
from shapeworld.generators import ReinforcedAttributesGenerator, LimitedAttributesGenerator # , ClusteredEntitiesGenerator
from shapeworld.captioners import CaptionerMixer, RegularAttributeCaptioner, RegularTypeCaptioner, AttributeTypeRelationCaptioner, Quantifier... |
the-stack_106_16016 | import pandas as pd
import numpy as np
from collections import OrderedDict
import itertools
import warnings
import jellyfish
from .pre import Prejoin as BaseJoin
# ******************************************
# helpers
# ******************************************
def set_values(dfg, key):
v = dfg[key].unique()
... |
the-stack_106_16017 | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016, 2017 Daniel Rodriguez
# Copyright (C) 2017 Ed Bartosh
#
# This program is free software: you can redistribute it and/or modify
# it under the te... |
the-stack_106_16021 | import numpy as np
from typing import List
class PathPlanner:
def __init__(self, modules_alpha: np.ndarray, modules_l: np.ndarray,
phi_dot_bounds: List, k_lmda: float, k_mu: float):
"""
Initialize the PathPlanner object. The order in the arrays
must be preserved throughout... |
the-stack_106_16024 | import pickle
import base64
from django_redis import get_redis_connection
from django.http import JsonResponse
def merge_cookie_to_redis(request,response):
cookie_carts=request.COOKIES.get('carts')
if cookie_carts=={}:
pass
elif cookie_carts is not None:
carts=pickle.loads(base64.b64decode(... |
the-stack_106_16027 | #!/usr/bin/env python
"""
Copyright 2014-2015 Taxamo, 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 app... |
the-stack_106_16028 | """
A cylinder plus two branches, with diameters according to Rall's formula
"""
from brian2 import *
defaultclock.dt = 0.01*ms
# Passive channels
gL = 1e-4*siemens/cm**2
EL = -70*mV
# Morphology
diameter = 1*um
length = 300*um
Cm = 1*uF/cm**2
Ri = 150*ohm*cm
N = 500
rm = 1 / (gL * pi * diameter) # membrane resista... |
the-stack_106_16029 | ## Assume you have run vr_kuka_setup and have default scene set up
# Require p.setInternalSimFlags(0) in kuka_setup
import pybullet as p
import math
# import numpy as np
p.connect(p.SHARED_MEMORY)
kuka = 3
kuka_gripper = 7
POSITION = 1
ORIENTATION = 2
ANALOG=3
BUTTONS = 6
THRESHOLD = .5
LOWER_LIMITS = [-.967, -2.0,... |
the-stack_106_16030 | import fnmatch
import re
import logging
from dynamo.utils.classutil import get_instance
from dynamo.dataformat import Configuration
LOG = logging.getLogger(__name__)
class SiteInfoSource(object):
"""
Interface specs for probe to the site information source.
"""
@staticmethod
def get_instance(mod... |
the-stack_106_16032 | """
``django-guardian`` template tags. To use in a template just put the following
*load* tag inside a template::
{% load guardian_tags %}
"""
from __future__ import unicode_literals
from django import template
from django.contrib.auth.models import Group, AnonymousUser
try:
# Django < 1.8
from django.tem... |
the-stack_106_16033 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
sales_dict = {'colour': ['Yellow', 'Black', 'Blue', 'Red', 'Yellow', 'Black', 'Blue',
'Red', 'Yellow', 'Black', 'Blue', 'Red', 'Yellow', 'Black', 'Blue', 'Red', 'Blue', 'Red'],
'sales': [... |
the-stack_106_16035 | # Copyright 2020 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 a... |
the-stack_106_16036 | from raytracerchallenge_python.shape import Shape
from raytracerchallenge_python.intersection import Intersection, Intersections
from raytracerchallenge_python.tuple import Vector
from raytracerchallenge_python.helpers import EPSILON
from math import sqrt
class Cylinder(Shape):
def __init__(self):
super... |
the-stack_106_16037 | import os
import aiohttp
import time
import random
from aiohttp import MultipartWriter
from aiohttp.hdrs import CONTENT_DISPOSITION, CONTENT_TYPE
from aiohttp.payload import StringPayload, BytesPayload
from collections import namedtuple
import requests
from io import BytesIO
from .cos_auth import CosAuth
CosConfig =... |
the-stack_106_16039 | #!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet accounts properly when there are cloned transactions with malleated scriptsigs."""
imp... |
the-stack_106_16040 | import torch
import numpy as np
import scipy.linalg as slin
class TraceExpm(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
# detach so we can cast to NumPy
E = slin.expm(input.detach().numpy())
f = np.trace(E)
E = torch.from_numpy(E)
ctx.save_for_backw... |
the-stack_106_16042 | # Settings for www.djangoproject.com
import json
import os
from pathlib import Path
# Utilities
PROJECT_PACKAGE = Path(__file__).resolve().parent.parent
# The full path to the repository root.
BASE_DIR = PROJECT_PACKAGE.parent
data_dir_key = 'DJANGOPROJECT_DATA_DIR'
DATA_DIR = Path(os.environ[data_dir_key]) if data_... |
the-stack_106_16043 | import tensorflow as tf
from video_prediction.ops import sigmoid_kl_with_logits
def l1_loss(pred, target):
return tf.reduce_mean(tf.abs(target - pred))
def l2_loss(pred, target):
return tf.reduce_mean(tf.square(target - pred))
def gan_loss(logits, labels, gan_loss_type):
# use 1.0 (or 1.0 - discrim_l... |
the-stack_106_16047 | from utils.utils import *
from hparams import HyperParams as hp
import torch.nn.functional as F
def train_model(model, target_model, batch, optimizer):
states = to_tensor(batch.state)
next_states = to_tensor(batch.next_state)
actions = to_tensor_long(batch.action)
rewards = to_tensor(batch.reward)
... |
the-stack_106_16049 | from old_files.network_class import Network
net = Network()
training_data, validation_data, test_data = load_mnist()
train_x_01, train_y_01 = make_mnist_subset(training_data, [0, 1])
test_x_01, test_y_01 = make_mnist_subset(test_data, [0, 1])
train_x_23, train_y_23 = make_mnist_subset(training_data, [2, 3])
test_x_... |
the-stack_106_16050 | variable_count = 1
# Variable is the main class for autodifferentiation logic for scalars
# and tensors.
class Variable:
"""
Attributes:
history (:class:`History` or None) : the Function calls that created this variable or None if constant
derivative (variable type): the derivative with respe... |
the-stack_106_16051 | #!/usr/bin/env python
# -*- coding-utf-8 -*-
# xuer ----time:
import torch
import torch.nn as nn
class focal_BCELoss(nn.Module):
def __init__(self, alpha=10, gamma=2):
super(focal_BCELoss, self).__init__()
self.alpha = alpha
self.gamma = gamma
def forward(self, input, target, eps=1e-7)... |
the-stack_106_16052 | #!/usr/bin/env python3
import logging
import csv
class GraphiteMetric:
def __init__(self, item_to_load, to_graphite_date, session):
self.logger = logging.getLogger(__name__)
self.metric_name = item_to_load['name']
self.metric_target = item_to_load['target'].replace("{","{{").replace("}","}... |
the-stack_106_16055 | #!/usr/bin/env python
# encoding: utf-8
## Very lightly modified from David Yanofsky's
## original https://gist.github.com/yanofsky/5436496
import tweepy #https://github.com/tweepy/tweepy
import csv
from utils import open_csv_w
# import authentication credentials
from secrets import TWITTER_C_KEY, TWITTER_C_SECRET, T... |
the-stack_106_16057 | # coding: utf-8
# Copyright 2020. ThingsBoard
# #
# 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
# #
# Unl... |
the-stack_106_16059 | from pathlib import Path
import os
import sys
import unittest
from ray.rllib.utils.test_utils import framework_iterator
def rollout_test(algo, env="CartPole-v0"):
for fw in framework_iterator(frameworks=("torch", "tf")):
fw_ = ", \"framework\": \"{}\"".format(fw)
tmp_dir = os.popen("mktemp -d")... |
the-stack_106_16063 | # Copyright © 2019 Province of British Columbia
#
# 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... |
the-stack_106_16064 | import pandas as pd
import ast
import json
from psutil import test
from torch.utils import data
from transformers import BertTokenizerFast as fast_tokenizer
from transformers import AutoTokenizer
import torch
import numpy as np
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
i... |
the-stack_106_16066 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
from PIL import Image
import PIL.ImageEnhance as ImageEnhance
import random
import numpy as np
class RandomCrop(object):
def __init__(self, size, *args, **kwargs):
self.size = size
def __call__(self, im_lb):
im = im_lb['im']
lb = im_lb['lb... |
the-stack_106_16067 | """
Functions inferring the syntax tree.
"""
import copy
from marso.python import tree
from medi._compatibility import force_unicode, unicode
from medi import debug
from medi import parser_utils
from medi.inference.base_value import ValueSet, NO_VALUES, ContextualizedNode, \
iterator_to_value_set, iterate_values
... |
the-stack_106_16068 | from yacs.config import CfgNode as CN
# 创建一个配置节点_C
_C = CN()
# default configuration
# Train configuration
_C.TRAIN = CN()
_C.TRAIN.SEED = 1234
_C.TRAIN.USE_CUDA = True
_C.TRAIN.MAX_EPOCH = 120
_C.TRAIN.DECAY_EPOCHS = 40
_C.TRAIN.DECAY_RATE = 0.1
_C.TRAIN.BATCH_SIZE = 16
_C.TRAIN.LR = 0.0001
_C.TRAIN.DROPOUT = 0.0
... |
the-stack_106_16069 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2011-2015 HP Development Company, L.P.
#
# This program 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 2 of the License, or
# (at... |
the-stack_106_16070 | '''
- Leetcode problem: 97
- Difficulty: Hard
- Brief problem description:
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false
- Sol... |
the-stack_106_16071 | from datetime import datetime
import os
from flask import jsonify, current_app, request, session, send_from_directory
from helpers import upload_files
class FileUploadController:
def __init__(self):
pass
def upload_avatar(self):
"""FileUpload"""
if request.method == "POST" an... |
the-stack_106_16074 | # DO NOT MODIFY THIS FILE DIRECTLY. THIS FILE MUST BE CREATED BY
# mf6/utils/createpackages.py
# FILE created on March 19, 2021 03:08:37 UTC
from .. import mfpackage
from ..data.mfdatautil import ListTemplateGenerator
class ModflowGwfwel(mfpackage.MFPackage):
"""
ModflowGwfwel defines a wel package within a ... |
the-stack_106_16075 | from stix_shifter.stix_translation.src.patterns.pattern_objects import ObservationExpression, ComparisonExpression, \
ComparisonExpressionOperators, ComparisonComparators, Pattern, \
CombinedComparisonExpression, CombinedObservationExpression, ObservationOperators
from stix_shifter.stix_translation.src.transfor... |
the-stack_106_16077 | # qubit number=2
# total number=10
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy a... |
the-stack_106_16080 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 a... |
the-stack_106_16081 | """Driver for gradient calculations."""
__authors__ = "James Bergstra, Razvan Pascanu, Arnaud Bergeron"
__copyright__ = "(c) 2011, Universite de Montreal"
__license__ = "3-clause BSD License"
__contact__ = "theano-dev <theano-dev@googlegroups.com>"
__docformat__ = "restructuredtext en"
import __builtin__
import logg... |
the-stack_106_16082 | import bw
import os
# from random import randint
table = {}
table_own = {}
ip_known = {}
IP_PREFIX = [10, 61]
IP = IP_PREFIX + [0, 1]
INTERFACE = False
OWN_MAC = False
OWN_ID = False
COUNT = 2
MAC_TO_ID_TABLE = {}
def print_mac(mac: bytes):
return str.join(':', [mac[i:i + 1].hex() for i in range(0, len(mac), ... |
the-stack_106_16083 | #savetocsv.py
import csv
import os
allfile = os.listdir()
print(allfile)
def Save(data):
with open('config_kitchen.csv','w',newline='') as file:
#fw = 'file writer'
fw = csv.writer(file)
fw.writerows(data)
print('Save Done!')
def Read():
if 'config_kitchen.csv' not in allfile:
a... |
the-stack_106_16085 | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from delivery import views
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('register/', views.Registration.as_view(), name='home'),
path('activate/<uidb... |
the-stack_106_16086 | # coding: utf-8
from django.core.urlresolvers import reverse as r
from django.template.defaultfilters import slugify
from django.db.models import Q
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.contrib import messages
from django.contrib.auth.decorators import login_re... |
the-stack_106_16087 | import numpy as np
import math
from time import time
import cvxpy as cp
import scipy.linalg as spl
import scipy.sparse.linalg as spsl
from scipy.stats import kendalltau
from scipy.sparse import csc_matrix
# Global variables
epsilon = np.finfo(np.float).eps ## machine precision
rtol = 1e-4 ## convergence t... |
the-stack_106_16089 | """
======================
General-purpose images
======================
The title of each image indicates the name of the function.
"""
import matplotlib.pyplot as plt
import matplotlib
from skimage import data
matplotlib.rcParams['font.size'] = 18
images = ('astronaut',
'binary_blobs',
'camer... |
the-stack_106_16090 | # coding=utf-8
#
# Copyright 2014-2016 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
the-stack_106_16091 | from __future__ import absolute_import
import io
import logging
import six
import zlib
try:
import uwsgi
has_uwsgi = True
except ImportError:
has_uwsgi = False
from django.conf import settings
logger = logging.getLogger(__name__)
Z_CHUNK = 1024 * 8
if has_uwsgi:
class UWsgiChunkedInput(io.RawIOBas... |
the-stack_106_16093 | # -*- coding: utf-8 -*-
import asyncio
import ccxtpro
async def loop(exchange, symbol, timeframe, complete_candles_only = False):
duration_in_seconds = exchange.parse_timeframe(timeframe)
duration_in_ms = duration_in_seconds * 1000
while True:
try:
trades = await exchange.watch_trades(... |
the-stack_106_16096 | # -*- coding: utf-8 -*-
"""
Created on Sat May 25 14:21:27 2019
@author: Tin
"""
import numpy as np
import pandas as pd
import datetime
from sys import exit
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import Binarizer
from sklearn.preprocessing import StandardScaler
from sk... |
the-stack_106_16098 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
the-stack_106_16100 | #!/usr/bin/python
#
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 et sts=4 ai:
import cStringIO as StringIO
import subprocess
import unittest
import mox
import portable_platform
def subprocess_mock(mox, *args, **kw):
mock_process = mox.CreateMock(subprocess.Popen)
mox.StubOutWithMock(subprocess, 'Popen', u... |
the-stack_106_16105 | import copy
from nose.tools import assert_equal, assert_raises, assert_in
import json
from mock import patch, MagicMock
try:
from ckan.tests.helpers import reset_db, call_action
from ckan.tests.factories import Organization, Group
except ImportError:
from ckan.new_tests.helpers import reset_db, call_acti... |
the-stack_106_16106 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 14:09:02 2018
@author: jd766
"""
def Get_flame_temperature(Ratio_tables, R_RB, R_RG, R_BG):
import numpy as np
Ratio_tables = np.array(Ratio_tables)
T_ref = Ratio_tables[0,:]
RG_ref = Ratio_tables[1,:]
RB_ref = Ratio_tables[2,:]
BG_ref... |
the-stack_106_16107 | # Copyright 2021-2022 NVIDIA 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
#
# Unless required by applicable law or agreed to ... |
the-stack_106_16108 | import sys
import os
import math
import random
from sklearn import datasets
import numpy as np
# Import helper functions
from mlfromscratch.utils.data_manipulation import normalize
from mlfromscratch.utils.data_operation import euclidean_distance
from mlfromscratch.unsupervised_learning import *
from mlfromscratch.uti... |
the-stack_106_16112 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from std_msgs.msg import Float32, UInt8
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Image, CompressedImage
from cv_bridge import CvBridge
import tensorflow as tf
import numpy as np
import enum
import rospy
import cv2
import threading
import time
# Hyper... |
the-stack_106_16114 | import pandas as pd
import numpy as np
import re
from law.utils import *
import jieba.posseg as pseg
import datetime
import mysql.connector
class case_reader:
def __init__(self, user, password, n=1000, preprocessing=False):
'''
n is total types,
preprocessing: whether needs preproc... |
the-stack_106_16115 | __all__ = ('BlockStorageFile',)
import os
import struct
import logging
import errno
from multiprocessing.pool import ThreadPool
import pyoram
from pyoram.storage.block_storage import \
(BlockStorageInterface,
BlockStorageTypeFactory)
import tqdm
import six
from six.moves import xrange
log = logging.getLogg... |
the-stack_106_16116 | import os
import platform
from .base import BaseProjectGenerator
from .cmake import DefaultArgs, CMake
from ..config import GetProjectFolder
from ..docker import RunAsContainer
from ..utilities import Execute
def SetupGmakeProjectGenerator(commands):
command = BaseProjectGenerator(commands, 'gmake',
help=... |
the-stack_106_16118 | import d2
import machine, ssd1306
d = ssd1306.SSD1306(machine.I2C(scl=machine.Pin(4), sda=machine.Pin(5)))
xscale = d2.scale_linear(0, d.width, -2.5, 1, False)
yscale = d2.scale_linear(0, d.height, -1, 1, False)
imax = 10
imax1 = imax + 1
for y in range(d.height):
y0 = yscale(y)
for x in range(d.width):
... |
the-stack_106_16119 | """
Extract signals on spheres and plot a connectome
==============================================================
This example shows how to extract signals from spherical regions.
We show how to build spheres around user-defined coordinates, as well as
centered on coordinates from Power-264 atlas [1] and Dosenbach-1... |
the-stack_106_16122 | """Test for certbot_apache._internal.entrypoint for override class resolution"""
import unittest
import mock
from certbot_apache._internal import configurator
from certbot_apache._internal import entrypoint
class EntryPointTest(unittest.TestCase):
"""Entrypoint tests"""
_multiprocess_can_split_ = True
... |
the-stack_106_16124 | # -*- coding: utf-8 -*-
"""
flask.app
~~~~~~~~~
This module implements the central WSGI application object.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import warnings
from datetime import timedelta
from functools import update_wrap... |
the-stack_106_16130 | import random
import torch
from transformers import BertTokenizer, BertForMaskedLM
import csv
import numpy as np
from transformers import *
from tqdm import tqdm
import pickle
def extract_lang_mapping(short_names, tokenizer):
# get mapping from ISO to language names (based on north_euralex)
# remove languages... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.