filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_1520 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
the-stack_0_1523 | from __future__ import annotations
import functools
import operator
from abc import abstractmethod
from typing import (
Callable,
Dict,
NamedTuple,
Protocol,
Tuple,
TypeVar,
Union,
overload,
runtime_checkable,
)
from torch import Tensor
from torch import device as Device
from torch... |
the-stack_0_1524 | import argparse
def parse_args():
parser = argparse.ArgumentParser(
description="Get parameters for the ABM Simulation"
)
# Name and seed
parser.add_argument("--name", help="experiment name", required=True)
parser.add_argument("--seed", help="seed for reproducibility", type=int, default=4... |
the-stack_0_1527 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 18 2017
@author: Alvaro Radigales
A simple Python implementation of the Lanchester Linear Law. Force
strength for each time pulse of the simulation is stored in a NumPy
array, and later plotted using MatPlotLib.
"""
import numpy
import matplotli... |
the-stack_0_1528 | """Loguru utils"""
# List of files in `fairseq_cli` that use logging. Any files other than these
# attempting to use logging will have their logger with the same file name
# (i.e., `__name__`).
name_list = ["eval_lm", "generate", "hydra_train", "interactive", "preprocess",
"train", "validate"]
def logur... |
the-stack_0_1529 | import pytest
import fsspec
pytest.importorskip("distributed")
@pytest.fixture()
def cli(tmpdir):
import dask.distributed
client = dask.distributed.Client(n_workers=1)
def setup():
m = fsspec.filesystem("memory")
with m.open('afile', 'wb') as f:
f.write(b'data')
client.r... |
the-stack_0_1530 | # Copyright (c) 2015-2016, 2018-2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2015-2016 Ceridwen <ceridwenv@gmail.com>
# Copyright (c) 2015 Florian Bruhin <me@the-compiler.org>
# Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>
# Copyright (c) 2018 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c... |
the-stack_0_1534 | import pytest
from mock import Mock, patch
from service import get_maps
@patch('service.map_service_common.get_all_maps')
def test_get_maps(get_all_maps_mock):
get_all_maps_mock.return_value = {}
response = get_maps.lambda_handler({}, None)
valid_response = {'statusCode': 200, 'body': '{"Maps": {}}', ... |
the-stack_0_1535 | import os
import json
import random
META = "../../important_data/"
N = 10000
def load_metadata(filename):
print("Start reading " + filename)
with open(os.path.join(META, filename)) as f:
data = json.load(f)
return data
def remove_version_ending(arxiv_id):
return arxiv_id.rsplit("v", 1)[0]
... |
the-stack_0_1537 | # Copyright 2021 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
the-stack_0_1538 | """Classes for providing extra information about an :class:`ihm.Entity`"""
# Handle different naming of urllib in Python 2/3
try:
import urllib.request as urllib2
except ImportError:
import urllib2
import sys
class Reference(object):
"""Base class for extra information about an :class:`ihm.Entity`.
... |
the-stack_0_1539 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import logging
import socket
import time
import traceback
from telemetry import decorators
from telemetry.internal.backends.chrome_inspector imp... |
the-stack_0_1540 | import graphene
from graphql_jwt.exceptions import PermissionDenied
from ...core.permissions import WebhookPermissions
from ...webhook import models, payloads
from ...webhook.event_types import WebhookEventType
from ..utils import sort_queryset
from .sorters import WebhookSortField
from .types import Webhook, WebhookE... |
the-stack_0_1541 | import factory
USERS = 1000
GROUPS = 5
EVENTS = 5
NOTIFICATIONS = 5000
OCCURENCES = 2000
AUDITLOGS = 1000
if __name__ == '__main__': # noqa: C901
import os
import random
from django.core.wsgi import get_wsgi_application
os.environ['DJANGO_SETTINGS_MODULE'] = 'bitcaster.config.settings'
applicati... |
the-stack_0_1543 | #!/usr/bin/env python
# Copyright (C) 2013 The Android Open Source Project
#
# 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 b... |
the-stack_0_1546 | import re
from parso.python import tree
from jedi._compatibility import zip_longest
from jedi import debug
from jedi.evaluate import analysis
from jedi.evaluate.lazy_context import LazyKnownContext, LazyKnownContexts, \
LazyTreeContext, get_merged_lazy_context
from jedi.evaluate.filters import ParamName
... |
the-stack_0_1547 | import json
class PEXEL:
def __init__(self, annotations_file):
print("Loading captions from pexels dataset ...")
self.annotations_file = annotations_file
self.dataset = dict()
self.anns = dict()
if not annotations_file == None:
self.dataset = json.load(open(annot... |
the-stack_0_1552 | import os
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import app, server
style = {'maxWidth': '960px', 'margin': 'auto'}
app.layout = html.Div([
dcc.Tabs(id='tabs', value='tab-intro', children=[
dcc.Tab(label='Intro', value='... |
the-stack_0_1554 | #!/usr/bin/env python
#
# Copyright 2007 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
the-stack_0_1561 | _base_ = [
'../../_base_/models/faster_rcnn_r50_dc5.py',
'../../_base_/datasets/imagenet_vid_fgfa_style.py',
'../../_base_/default_runtime.py'
]
model = dict(
type='SELSA',
detector=dict(
roi_head=dict(
type='SelsaRoIHead',
bbox_roi_extractor=dict(
typ... |
the-stack_0_1562 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
import os
from madminer.analysis import DataAnalyzer
from madminer.utils.various import math_commands, weighted_quantile, sanitize_array, mdot
from madminer.utils.various import less_logging
from madmi... |
the-stack_0_1566 | import math
import itertools
def menu():
while True:
try:
print(menuStr)
print(stars)
choose = int(input("For Encrypter = 1\nFor Decrypter = 2\nFor Exit = 0\nChoose : "))
print(stars)
break
except:
print("Girdi de bir problem v... |
the-stack_0_1569 | import unittest
import pandas as pd
import numpy as np
from copy import deepcopy
from darts.dataprocessing.transformers import BoxCox, Mapper
from darts.utils.timeseries_generation import sine_timeseries, linear_timeseries
from darts import TimeSeries
class BoxCoxTestCase(unittest.TestCase):
sine_series = sine_... |
the-stack_0_1570 | #!/usr/bin/python3
from brownie import *
from scripts.deployment.deploy_protocol import deployProtocol
from scripts.deployment.deploy_loanToken import deployLoanTokens
from scripts.deployment.deploy_tokens import deployTokens, readTokens
from scripts.deployment.deploy_multisig import deployMultisig
import shared
impo... |
the-stack_0_1571 | # Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
the-stack_0_1573 | #!/usr/bin/env python3
import json
import os
import platform
import struct
import sys
import subprocess
def main():
message = get_message()
url = message.get("url")
args = ["mpv", "--", url] # need to remove terminal because it need to capture the output of yt-dlp
kwargs = {}
# https://develope... |
the-stack_0_1574 | """ @ saving utils
"""
import math
import torch
from torchvision import utils
import matplotlib.pyplot as plt
from PIL import Image
from torchvision import transforms
def numpy_grid(x, pad=0, nrow=None, uint8=True):
""" thin wrap to make_grid to return frames ready to save to file
args
pad (int [... |
the-stack_0_1576 | """
Functions for applying functions that act on arrays to xarray's labeled data.
"""
from __future__ import annotations
import functools
import itertools
import operator
import warnings
from collections import Counter
from typing import (
TYPE_CHECKING,
AbstractSet,
Any,
Callable,
Hashable,
It... |
the-stack_0_1577 | import datetime
import json
import logging
import os
import re
import shutil
import cherrypy
import core
from core import plugins, snatcher
from core.library import Metadata, Manage
from core.downloaders import PutIO
logging = logging.getLogger(__name__)
class Postprocessing(object):
def __init__(self):
... |
the-stack_0_1583 | """
Support for WeMo device discovery.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/wemo/
"""
import logging
from homeassistant.components.discovery import SERVICE_WEMO
from homeassistant.helpers import discovery
from homeassistant.const import EVENT... |
the-stack_0_1584 | #!/usr/bin/env python
import asyncio
import websockets
import time
import threading
connections=set()
def mandar():
global connections
vPrint=True
while True:
if len(connections)>0:
print(connections)
mensaje=input("Esto es un mensaje : ")
if mensa... |
the-stack_0_1585 | import random
def int2bin_str(d):
return bin(d)[2:]
def txt2int(s):
result = ''
for c in s:
result += '{:03d}'.format(ord(c))
if result.startswith('0'):
result = '999' + result
return int(result)
def int2txt(d):
s = str(d)
if len(s) % 3 != 0:
print('bad int')
... |
the-stack_0_1586 | """
Building and world design commands
"""
import re
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Q, Min, Max
from evennia import InterruptCommand
from evennia.scripts.models import ScriptDB
from evennia.objects.models import ObjectDB
from evennia.locks.lockh... |
the-stack_0_1589 | class _Creep:
body = []
memory = {'class' : 'AbstractBaseCreep'} # Override this in subclasses
name = None
def __init__(self, spawner):
self.spawner = spawner
def spawn(self):
resp = self.spawner.canCreateCreep(self.body, self.name)
if resp == OK:
print("Spawning new " + self.type)
print("Body: " + se... |
the-stack_0_1590 | # https://gist.github.com/seanchen1991/a151368df32b8e7ae6e7fde715e44b78
# reduce takes a data structure and either finds a key piece of data or
# be able to restructure the data structure
# 1. Reduce usually takes a linear data structure (99% we use reduce on an array)
# 2. Reduce "aggregates" all of the data in the... |
the-stack_0_1591 | """Plot a Lyapunov contour"""
from typing import cast, List, Tuple, Optional, TYPE_CHECKING
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import pandas as pd
import seaborn as sns
import torch
import tqdm
from neural_clbf.experiments import Experiment
from neural_clbf.systems import ObservableS... |
the-stack_0_1592 | # Copyright 2021 the authors.
# This file is part of Hy, which is free software licensed under the Expat
# license. See the LICENSE.
from __future__ import unicode_literals
from contextlib import contextmanager
from math import isnan, isinf
from hy import _initialize_env_var
from hy.errors import HyWrapperError
from f... |
the-stack_0_1593 | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPoster(PythonPackage):
"""Streaming HTTP uploads and multipart/form-data encoding."""
... |
the-stack_0_1594 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2019. 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.... |
the-stack_0_1596 | # -*- coding: utf-8 -*-
# question 3
def count_letters(word,find):
"""
Example function with types documented in the docstring.
Ce code doit retourner le nombre d'occurences d'un caractère passé en paramètre dans un mot donné également
Parameters
----------
param1 : str
Le 1er paramètre est une chaine de ca... |
the-stack_0_1597 | """Arnoldi algorithm.
Computes V and H such that :math:`AV_n = V_{n+1}\\underline{H}_n`. If the Krylov
subspace becomes A-invariant then V and H are truncated such that :math:`AV_n = V_n
H_n`.
:param A: a linear operator that works with the @-operator
:param v: the initial vector.
:param ortho: (optional) orthogonali... |
the-stack_0_1600 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2018 the authors.
# This file is part of Hy, which is free software licensed under the Expat
# license. See the LICENSE.
import os
import re
import shlex
import subprocess
import pytest
from hy._compat import builtins
from hy.importer import get_bytecode_pa... |
the-stack_0_1601 | # MIT License
# Copyright (c) 2022 Zenitsu Prjkt™
# 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,... |
the-stack_0_1602 | # Marcelo Campos de Medeiros
# ADS UNIFIP
# Estrutura de Repetição
# 25/03/2020
'''
27 -Faça um programa que calcule o número médio de alunos por turma.
Para isto, peça a quantidade de turmas e a quantidade de alunos
para cada turma. As turmas não podem ter mais de 40 alunos.
'''
print('=' * 40)
print('{:=^40}'.forma... |
the-stack_0_1603 | """Shared class to maintain Plex server instances."""
import logging
import ssl
import time
from urllib.parse import urlparse
from plexapi.exceptions import NotFound, Unauthorized
import plexapi.myplex
import plexapi.playqueue
import plexapi.server
from requests import Session
import requests.exceptions
from homeassi... |
the-stack_0_1604 | from __future__ import print_function
import datetime
import time
import httplib2
import os
import sys
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from oauth2client import file
from logbook import Logger, FileHandler, StreamHandler
log = Logger('... |
the-stack_0_1606 | """Base class for task type models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import dateutil.parser
from saltant.constants import HTTP_200_OK, HTTP_201_CREATED
from .resource import Model, ModelManager
class BaseTaskType(Model):
"... |
the-stack_0_1607 | # -*- coding: utf-8 -*-
'''
这是一个计算origins到targets的自驾行车OD矩阵的exmaple,同时这里会将解析出来的数据存在本地
'''
import pandas as pd
import json
import os
from BaiduMapAPI.api import SearchPlace, MapDirection
AK = os.environ["BaiduAK"]
SK = os.environ["BaiduSK"]
origins_data = pd.read_csv("data/exmaple_citydata_coords.csv", encoding="u... |
the-stack_0_1608 | """
Bidirectional search is a graph search algorithm that finds a shortest path from an initial vertex to a goal
vertex in a directed graph. It runs two simultaneous searches: one forward from the initial state
, and one backward from the goal, stopping when the two meet in the middle. [Wikipedia]
"""
import que... |
the-stack_0_1609 | import os
import sys
import stripe
import datetime
from flask import *
#import cloudinary as Cloud
#import cloudinary.uploader
from Backend.models import *
from Backend import db, bcrypt
from Backend.config import Config
from flask_cors import cross_origin
from Backend.ext import token_required
from Backe... |
the-stack_0_1612 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
the-stack_0_1614 | #!/usr/bin/env python
#
# Copyright 2010 Per Olofsson
#
# 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 ... |
the-stack_0_1615 | # SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
from typing import Any
from manifests.component_manifest import ComponentManifest, Components, Component
"""
A BuildManifest i... |
the-stack_0_1617 | # Practical 1
# Load in the California house pricing data and unpack the features and labels
# Import a linear regression model from sklearn
# Fit the model
# Create a fake house's features and predict it's price
# Compute the score of the model on the training data
#%%
from sklearn import linear_model
from sklearn im... |
the-stack_0_1619 | from audiomate import annotations
from audiomate.utils import textfile
WILDCARD_COMBINATION = ('**',)
class UnmappedLabelsException(Exception):
def __init__(self, message):
super(UnmappedLabelsException, self).__init__(message)
self.message = message
def relabel(label_list, projections):
"... |
the-stack_0_1620 | # -*- coding: utf-8 -*-
#
# Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
#
# 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
#
# Un... |
the-stack_0_1622 | import numpy as np
def make_batches(size, batch_size):
nb_batch = int(np.ceil(size/float(batch_size)))
return [(i*batch_size, min(size, (i+1)*batch_size)) for i in range(0, nb_batch)] # zgwang: starting point of each batch
def pad_2d_vals_no_size(in_vals, dtype=np.int32):
size1 = len(in_vals)
size2 = n... |
the-stack_0_1623 | #
#
# bignum.py
#
# This file is copied from python-filbitlib.
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bignum routines"""
from __future__ import absolute_import, division, print_function, unicode_literals
impo... |
the-stack_0_1624 | ## Copyright 2015-2019 Ilgar Lunin, Pedro Cabrera
## 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... |
the-stack_0_1628 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.website.utils import cleanup_page_name
from frappe.website.render import clear_cache
from frappe.modules impor... |
the-stack_0_1632 | # from profilehooks import profile
from django.http import HttpResponse
from .loader import get_template, select_template
class ContentNotRenderedError(Exception):
pass
class SimpleTemplateResponse(HttpResponse):
rendering_attrs = ['template_name', 'context_data', '_post_render_callbacks']
def __init... |
the-stack_0_1633 | # Copyright 2017 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_0_1634 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Documentation build configuration file, created by
# sphinx-quickstart on Sat Jan 21 19:11:14 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenera... |
the-stack_0_1636 | """Regresssion tests for urllib"""
import urllib
import httplib
import unittest
from test import test_support
import os
import mimetools
import StringIO
def hexescape(char):
"""Escape char as RFC 2396 specifies"""
hex_repr = hex(ord(char))[2:].upper()
if len(hex_repr) == 1:
hex_repr = "0%s" % hex_... |
the-stack_0_1637 | # Copyright 2019 MilaGraph. 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... |
the-stack_0_1639 | """
defines:
* nids_close = find_closest_nodes(nodes_xyz, nids, xyz_compare, neq_max, tol)
* ieq = find_closest_nodes_index(nodes_xyz, xyz_compare, neq_max, tol)
"""
from itertools import count
from typing import List, Optional
import numpy as np
from pyNastran.bdf.mesh_utils.bdf_equivalence import (
_get... |
the-stack_0_1640 | #!/usr/bin/env python3
from testUtils import Utils
import testUtils
from Cluster import Cluster
from WalletMgr import WalletMgr
from Node import Node
from TestHelper import TestHelper
import decimal
import math
import re
import time
###############################################################
# nodeos_voting_test... |
the-stack_0_1641 | import sys
import dateutil.parser
from mongoengine import DoesNotExist
import copy
from issueshark.backends.basebackend import BaseBackend
from issueshark.backends.helpers.bugzillaagent import BugzillaAgent
from validate_email import validate_email
import logging
from pycoshark.mongomodels import Issue, People, Even... |
the-stack_0_1644 | # commentaire
# resolution approchée d'une equation du troisième degre
# version 2
import math
# Fonction calcul de delta
def calculerDelta(a, b, c):
return b**2-4*a*c
# Fonction Résolution Equation Second Degre
def resoudreEquationSecondDegre(a, b, c):
delta = calculerDelta(a, b, c)
if delta > 0:
... |
the-stack_0_1646 | import torch
import os
import configs
import datasets
import models
class BaseTest(object):
def __init__(self, model):
self.model = model
def run(self):
for model_cfg in models.allcfgs():
if hasattr(model_cfg, 'name') and model_cfg.name == self.model.__name__:
mod... |
the-stack_0_1647 | """
LF-Font
Copyright (c) 2020-present NAVER Corp.
MIT license
"""
from functools import partial
import torch.nn as nn
import torch
from base.modules import ConvBlock, ResBlock, GCBlock, CBAM
class ComponentConditionBlock(nn.Module):
def __init__(self, in_shape, n_comps):
super().__init__()
self.i... |
the-stack_0_1648 | import logging
import math
import re
import warnings
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from matplotlib import pyplot as plt, gridspec, cm, colors
import csv
from utils.utils import unscale, unnormalize, get_key_def
from utils.geoutils import... |
the-stack_0_1650 | """
SubtreeSegmenter.py
A discourse unit segmentation module based on a moving window capturing parts of
a dependency syntax parse.
"""
import io, sys, os, copy
# Allow package level imports in module
script_dir = os.path.dirname(os.path.realpath(__file__))
lib = os.path.abspath(script_dir + os.sep + "..")
models = ... |
the-stack_0_1651 | #!/usr/bin/env python
from mapHrEstimator import *
#
# Global function
#
class Tracker:
def __init__(self, start, alpha=.01, beta=0, deltaFreqState = np.float(0), time=-1000,
maxChange = .5, boundHi=205, boundLo=40, maxDeltaT=3000):
self.freqState = np.float(start)
self.deltaFr... |
the-stack_0_1654 | from __future__ import annotations
import inspect
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
from .command import Command
from .converters import _CONVERTERS
if TYPE_CHECKING:
from .context import Context
__all__ = ("StringParser",)
class StringParser:
"""
A class repres... |
the-stack_0_1659 | import os
import pickle
from pathlib import Path
import pytest
import autofit as af
from autoconf.conf import output_path_for_test
from autofit.non_linear.paths.null import NullPaths
def test_null_paths():
search = af.DynestyStatic()
assert isinstance(
search.paths,
NullPaths
)
class ... |
the-stack_0_1660 | import game
import pygame
from config import Config
class Main:
def __init__(self):
self.game_clock = pygame.time.Clock()
self.game = game.Game()
def mainloop(self):
while Config.BOOLEAN['game_loop']:
self.game.change_screen()
self.game_clock.tick(Config.CONSTA... |
the-stack_0_1662 | from __future__ import unicode_literals
import re
import os
import spotipy.util as util
import youtube_dl
from spotify_dl.scaffold import *
def authenticate():
"""Authenticates you to Spotify
"""
scope = 'user-library-read'
username = ''
return util.prompt_for_user_token(username, scope)
def f... |
the-stack_0_1663 | from slideshow import SlideShow
def test_init_title(mocker):
"""Test init function sets title value"""
stub = mocker.stub()
mocker.patch("tkinter.Tk")
slideshow = SlideShow("ZlNLpWJUv52wgu2Y", stub)
slideshow.root.title.assert_called_once_with("ZlNLpWJUv52wgu2Y")
def test_init_callback(mocker):
... |
the-stack_0_1664 | import os
import re
import shutil
import yaml
from io import BytesIO
import bzt
from bzt import ToolError, TaurusConfigError
from bzt.engine import EXEC
from bzt.modules._apiritif import ApiritifNoseExecutor
from bzt.modules.functional import LoadSamplesReader, FuncSamplesReader
from bzt.modules.provisioning import L... |
the-stack_0_1665 | #!/usr/bin/env python3
# Copyright 2016 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""Tries to evaluate global constructors, appl... |
the-stack_0_1666 | import os
from ..brew_exts import (
build_env_statements,
DEFAULT_HOMEBREW_ROOT,
recipe_cellar_path,
)
from ..resolvers import Dependency, NullDependency
class UsesHomebrewMixin:
def _init_homebrew(self, **kwds):
cellar_root = kwds.get('cellar', None)
if cellar_root is None:
... |
the-stack_0_1667 | """
Unit test each component in CADRE using some saved data from John's CMF implementation.
"""
import unittest
from parameterized import parameterized
import numpy as np
from openmdao.api import Problem
from CADRE.attitude import Attitude_Angular, Attitude_AngularRates, \
Attitude_Attitude, Attitude_Roll, Att... |
the-stack_0_1674 | from random import choice, sample
cartas = {
chr(0x1f0a1): 11,
chr(0x1f0a2): 2,
chr(0x1f0a3): 3,
chr(0x1f0a4): 4,
chr(0x1f0a5): 5,
chr(0x1f0a6): 6,
chr(0x1f0a7): 7,
chr(0x1f0a8): 8,
chr(0x1f0a9): 9,
chr(0x1f0aa): 10,
chr(0x1f0ab): 10,
chr(0x1f0ad): 10,
chr(0x1f0ae): ... |
the-stack_0_1675 | import csv
import os
#import pandas as pd
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
#import scipy.stats as stats
def main():
test_dir = "length_500"
data = get_data(test_dir)
plot_aggregate_over_time(data, "schaffer", test... |
the-stack_0_1677 | # Copyright 2015 Jason Meridth
#
# 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 t... |
the-stack_0_1679 | """
To run the code for each problem, simply run the 'runP#.py' file.
So for this problem, run runP3.py
The P#classes.py files are very similar across problems,
but each includes a scaling which is (roughly) optimized for that specific problem.
The runP#.py file will automatically import the necessary classes from th... |
the-stack_0_1680 | from turtle import Turtle, Screen
import time
screen = Screen()
screen.bgcolor('black')
screen.title('My Snake Game')
screen.tracer(0)
starting_positions = [(0, 0), (-20, 0), (-48, 0)]
pace = 20
segments = []
for position in starting_positions:
new_segment = Turtle("square")
new_segment.color("... |
the-stack_0_1681 | from __future__ import print_function
import pathlib
from builtins import object
from builtins import str
from typing import Dict
from empire.server.common import helpers
from empire.server.common.module_models import PydanticModule
from empire.server.database.models import Credential
from empire.server.utils import ... |
the-stack_0_1682 | import numpy as np
import openmdao.api as om
from mphys.multipoint import Multipoint
from mphys.scenario_aerostructural import ScenarioAeroStructural
from vlm_solver.mphys_vlm import VlmBuilder
from tacs.mphys import TacsBuilder
from mphys.solver_builders.mphys_meld import MeldBuilder
from struct_dv_components import... |
the-stack_0_1683 | # You wish to buy video games from the famous online video game store Mist.
# Usually, all games are sold at the same price, p dollars. However, they are planning to have the seasonal
# Halloween Sale next month in which you can buy games at a cheaper price. Specifically, the first game you
# buy during the sale will ... |
the-stack_0_1684 | import numpy as np
import random
import itertools
import scipy.misc
from PIL import Image
import matplotlib.pyplot as plt
class gameOb():
def __init__(self,coordinates,size,intensity,channel,reward,name):
self.x = coordinates[0]
self.y = coordinates[1]
self.size = size
self.intensi... |
the-stack_0_1686 | # -*- coding: utf-8 -*-
"""
JSON encoder/decoder adapted for use with Google App Engine NDB.
Usage:
import ndb_json
# Serialize an ndb.Query into an array of JSON objects.
query = models.MyModel.query()
query_json = ndb_json.dumps(query)
# Convert into a list of Python dictionaries.
query_dicts = ndb_js... |
the-stack_0_1689 | import base64
import copy
import os
from datetime import datetime, timedelta
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import deferred
from sqlalchemy_json import MutableJson
from anubis.utils.data import rand
db = SQLAlchemy()
THEIA_DEFAULT_OPTIONS = {
"autosave": True,
"persistent_storag... |
the-stack_0_1691 | """Classes and algorithms related to 1D tensor networks.
"""
import re
import operator
import functools
from math import log2
from numbers import Integral
import scipy.sparse.linalg as spla
from autoray import do, dag, reshape, conj, get_dtype_name, transpose
from ..utils import (
check_opt, print_multi_line, en... |
the-stack_0_1693 | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... |
the-stack_0_1695 | #!/usr/bin/env python
from sklearn import svm
import numpy as np
from sklearn.externals import joblib
from sklearn import linear_model
import classifier.msg as msg
import os
SINGLE = 0
MULTIPLE = 1
def ini(path=None):
'''initialization
Args:
Returns:
'''
global clf
clf = linear_model.L... |
the-stack_0_1698 | import FWCore.ParameterSet.Config as cms
process = cms.Process("write2DB")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.load("CondCore.CondDB.CondDB_cfi")
#################################
# Produce a SQLITE FILE
process.CondDB.connect = "SQLITEFILE"
#################################
process.PoolDBO... |
the-stack_0_1700 | # Copyright 2014 Diamond Light Source 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 agreed t... |
the-stack_0_1701 | import requests
import re
from bs4 import BeautifulSoup
import traceback
import json
def get_html_text(url):
try:
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
}
r = requests.get(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.