filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_11036
# -*- coding: utf-8 -*- # ============================================================================= # Copyright (c) 2020 NVIDIA. 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...
the-stack_0_11037
#!/usr/bin/env python DESC = """ ____ _ _ __ __ __ ____ _____ | __ ) ___ __ _ _ _| |_(_)/ _|_ _| \/ | _ \___ / | _ \ / _ \/ _` | | | | __| | |_| | | | |\/| | |_) ||_ \ | |_) | __/ (_| | |_| | |_| | _| |_| | | | | __/___) | |____/ \___|\__,_|\__,_|\__|_|_| \__, |_| |_|_|...
the-stack_0_11040
# Copyright 2010-2012 the SGC project developers. # See the LICENSE file at the top-level directory of this distribution # and at http://program.sambull.org/sgc/license.html. import warnings import pygame from pygame.locals import * from .._locals import * class SelectableText: _text = "" _text_offset = _te...
the-stack_0_11041
#!/usr/bin/env python3 # ============================================================================== # Copyright 2019 - Philip Paquette # # NOTICE: 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 th...
the-stack_0_11042
""" Copyright (c) IBM 2015-2017. All Rights Reserved. Project name: c4-high-availability This project is licensed under the MIT License, see LICENSE """ import sys from setuptools import setup, find_packages import versioneer needs_pytest = {"pytest", "test", "ptr", "coverage"}.intersection(sys.argv) pytest_runner ...
the-stack_0_11046
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import datetime import re from bs4 import BeautifulSoup import scrape_common as sc url = 'https://www.jura.ch/fr/Autorites/Coronavirus/Chiffres-H-JU/Evolution-des-cas-COVID-19-dans-le-Jura.html' d = sc.download(url, silent=True) d = d.replace(' ', ' ') soup = Beauti...
the-stack_0_11048
""" Source: https://pe.usps.com/text/pub28/welcome.htm """ STREET_NAME_POST_ABBREVIATIONS = { "ALLEE": "ALY", "ALLEY": "ALY", "ALLY": "ALY", "ALY": "ALY", "ANEX": "ANX", "ANNEX": "ANX", "ANNX": "ANX", "ANX": "ANX", "ARC": "ARC", "ARC ": "ARC", "ARCADE": "ARC",...
the-stack_0_11049
import nltk class Analyzer(): """Implements sentiment analysis.""" def __init__(self, positives, negatives): """Initialize Analyzer.""" # load positive and negative words # Set, list or dict?: # http://stackoverflow.com/questions/3489071/in-python-when-to-use-a-dictionary-list-...
the-stack_0_11050
import numpy as np from .trading_env import TradingEnv, Actions, Positions class ForexEnv(TradingEnv): def __init__(self, df, window_size, frame_bound, min_index_start, unit_side='left'): assert len(frame_bound) == 2 assert unit_side.lower() in ['left', 'right'] self.frame_bound = frame...
the-stack_0_11051
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
the-stack_0_11052
def selecao(a, b, c, d): if (b > c) and (d > a) and ((c+d) > (a+b)) and (c > 0) and (d > 0) and (a % 2 == 0): return print('Valores aceitos') else: return print('Valores nao aceitos') def entrada(): valores = input().split(' ') valor_a = int(valores[0]) valor_b = int(valores[1]) ...
the-stack_0_11055
import tensorflow as tf import tensorflow.keras as keras from tensorflow.keras.layers import * from tensorflow.keras import regularizers import numpy as np #tf.enable_eager_execution() #added. so as to be able to use numpy arrays easily def limit_mem(): config = tf.compat.v1.ConfigProto() config.gpu_options.al...
the-stack_0_11056
import matplotlib.pyplot as plt import numpy as np import torch from torch import nn from torch.autograd import Variable x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168], [9.779], [6.182], [7.59], [2.167], [7.042], [10.791], [5.313], [7.997], [3.1]], dtype=np.flo...
the-stack_0_11057
# SPDX-License-Identifier: Apache-2.0 # Copyright Contributors to the Rez Project """ Sends a post-release email """ from __future__ import print_function from rez.release_hook import ReleaseHook from rez.system import system from email.mime.text import MIMEText from rez.utils.logging_ import print_warning, print_er...
the-stack_0_11059
#coding:utf-8 ''' filename:relationship_of_point_circle.py chap:6 subject:8 conditions:Point(),Circle() solution:relationship between circle and point ''' from circle import Circle from point import Point import math class Relationship: def __init__(self,circle:Circle,point:Point): ...
the-stack_0_11060
#!/usr/bin/python """ (C) Copyright 2018-2022 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ import re import traceback from daos_utils_base import DaosCommandBase class DaosCommand(DaosCommandBase): # pylint: disable=too-many-ancestors,too-many-public-methods """Defines a object re...
the-stack_0_11061
# -*- coding: utf-8 -*- from app.constants import S_OK, S_ERR import random import math import base64 import time import ujson as json from wand.image import Image from StringIO import StringIO from app.constants import * from app import cfg from app import util _CONTENT_TYPE_POSTFIX_MAP = { 'image/jpeg': 'jpg',...
the-stack_0_11063
from collections import ( defaultdict, ) from operator import ( attrgetter, ) from typing import ( Any, Iterable, Optional, Union, get_args, get_origin, ) from uuid import ( UUID, ) from minos.common import ( TypeHintBuilder, is_model_type, ) from .models import ( Model...
the-stack_0_11064
from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.utils import timezone from .custom_functions import isOnlyOneTrue from users.models import OpticUser, Account import decimal from termcolor import colored # Create your models here. class Patie...
the-stack_0_11065
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import glob import os import sys import ah_bootstrap from setuptools import setup # A dirty hack to get around some early import/configurations ambiguities import builtins builtins._ASTROPY_SETUP_ = True from astropy_helpers.setup...
the-stack_0_11066
from unittest.mock import patch from django.core.management import call_command from django.db.utils import OperationalError from django.test import TestCase class CommandsTestCase(TestCase): def test_wait_for_db_ready(self): """Test waiting for db when db is available""" with patch('django.db.u...
the-stack_0_11068
from PyTsetlinMachineCUDA.tm import MultiClassConvolutionalTsetlinMachine2D import numpy as np from time import time from keras.datasets import mnist (X_train, Y_train), (X_test, Y_test) = mnist.load_data() X_train = np.where(X_train >= 75, 1, 0) X_test = np.where(X_test >= 75, 1, 0) tm = MultiClassConvolutional...
the-stack_0_11070
# Copyright 2021 The SODA Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
the-stack_0_11072
import ConfigParser import logging import os import re from galaxy import util from galaxy import web from galaxy.web.form_builder import build_select_field from galaxy.webapps.tool_shed.model import directory_hash_id from tool_shed.dependencies.repository import relation_builder from tool_shed.util import common_ut...
the-stack_0_11073
import unittest import os import sys import os.path as path import numpy as np import scipy # Path to where the bindings live sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src"))) if os.name == 'nt': # if Windows # handle default location where VS puts binary sys.path.append(o...
the-stack_0_11074
#!/usr/bin/env python3 import io import os import requests # Imports the Google Cloud client library from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types # Gazebo # prefix = "http://10.16.103.133:8080/" prefix = "http://10.16.104.100:8080/" # prefix = "http://...
the-stack_0_11075
# -*- coding: utf-8 -*- """ Created on Mon Dec 21 21:38:29 2020 @author: oxenb """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from mne_features.feature_extraction import FeatureExtractor from sklearn.pipeline import Pipeline from sklearn.discriminant_analysis import LinearDiscriminantAna...
the-stack_0_11078
''' Uses [[https://github.com/fabianonline/telegram_backup#readme][telegram_backup]] database for messages data ''' from pathlib import Path from typing import Optional, Union, TypeVar from urllib.parse import unquote # TODO mm, make it easier to rememember to use... from ..common import PathIsh, Visit, get_logger, L...
the-stack_0_11079
""" Policy rules class """ from typing import Union, List, Dict from marshmallow import Schema, fields, post_load from .conditions.attribute.base import validate_path from .conditions.schema import ConditionSchema from ..context import EvaluationContext class Rules(object): """ Policy rules """...
the-stack_0_11080
"""coBib parser test class.""" import pytest from cobib.config import config from .. import get_resource class ParserTest: """The base class for coBib's parser test classes.""" EXAMPLE_BIBTEX_FILE = get_resource("example_entry.bib") """Path to the example BibTeX file.""" EXAMPLE_YAML_FILE = get_r...
the-stack_0_11081
""" Module contains tools for collecting data from various remote sources """ import warnings import tempfile import datetime as dt import time from collections import defaultdict import numpy as np from pandas.compat import( StringIO, bytes_to_str, range, lmap, zip ) import pandas.compat as compat from pandas...
the-stack_0_11084
# -*- coding: utf-8 -*- # @createTime : 2019/10/22 20:59 # @author : Huanglg # @fileName: BOM.py # @email: luguang.huang@mabotech.com import time from mesService.lib.OracleLib.OracleDBUtil import Oracle def print_run_time(func): def wrapper(*args, **kw): local_time = time.time() func(*args, **k...
the-stack_0_11085
# coding=utf-8 from distutils.util import convert_path import os from fnmatch import fnmatchcase from setuptools import setup, find_packages from pip.req import parse_requirements import uuid import sys AUTHOR = 'Nekmo' EMAIL = 'contacto@nekmo.com' PLUGIN_NAME = 'userscommands' DESCRIPTION = '' WEBSITE = 'http://nekmo...
the-stack_0_11090
#Author: Thy H. Nguyen import turtle wn = turtle.Screen() wn.bgcolor("#E0FFFF") mom = turtle.Turtle() mom.color("#0000CD") mom.shape("circle") thy = int(input()) i=1 while i < thy: mom.right(10) mom.forward(100) mom.stamp() mom.backward(thy) mom.dot() i +=1 wn.exitonclick()
the-stack_0_11091
from __future__ import unicode_literals import re CHUNK_RANGE_RE = re.compile( r'^@@ -(?P<orig_start>\d+)(,(?P<orig_len>\d+))? ' r'\+(?P<new_start>\d+)(,(?P<new_len>\d+))? @@', re.M) def filter_interdiff_opcodes(opcodes, filediff_data, interfilediff_data): """Filters the opcodes for an interdiff to...
the-stack_0_11092
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ Pyro4客户端,此处调用远程对象 """ import Pyro4 def main(): uri = input("What is the Pyro uri of the greeting object?(help: 输入server启动时对应的uri) ").strip() name = input("What is your name? ").strip() print(f'uri:{uri}, name:{name}') server =...
the-stack_0_11093
import torch import torch.nn as nn import neat.activations as a from torch import autograd class FeedForwardNet(nn.Module): def __init__(self, genome, config): super(FeedForwardNet, self).__init__() self.genome = genome self.units = self.build_units() self.lin_modules = nn.ModuleL...
the-stack_0_11094
''' This script helps creating and managing experiments. Possible commands: - launch: launch an experiment loading its specification from a CSV file - view: list the experiments which are still running - stop: stop all the runners of the experiment ''' import pandas as pd import argparse, os, sys, ...
the-stack_0_11095
#!/usr/bin/env python3 # FreeRTOS Common IO V0.1.2 # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # 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 re...
the-stack_0_11100
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ AutoAnchor utils """ import random import numpy as np import torch import yaml from tqdm import tqdm from utils.general import LOGGER, colorstr, emojis PREFIX = colorstr('AutoAnchor: ') def check_anchor_order(m): # Check anchor order against stride order for YOL...
the-stack_0_11101
# Copyright 2021 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 writ...
the-stack_0_11102
import hashlib import json import pickle import uuid from imp import find_module from importlib import import_module from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import OperationalError from django.db.models import Manager, Model from larvik.logging import get_...
the-stack_0_11103
#!/usr/bin/env python3.6 """MISP feed worker pulling down feeds in misp_feeds.txt and adding data to the platform""" import argparse import hashlib import json import os import sys import traceback from logging import error, info from typing import Dict, Generator, Optional, Text import caep import requests import a...
the-stack_0_11104
import argparse from collections import Counter import numpy as np from mpd import load def main(): parser = argparse.ArgumentParser() parser.add_argument('jsonfile') args = parser.parse_args() playlists = load(args.jsonfile) print("N =", len(playlists)) lens = [len(p['tracks']) for p in...
the-stack_0_11105
from typing import Tuple import numpy as np import torch from .bandits import DataBasedBandit class WheelBandit(DataBasedBandit): """The wheel contextual bandit from the Riquelme et al 2018 paper. Source: https://github.com/tensorflow/models/tree/archive/research/deep_contextual_bandits Citati...
the-stack_0_11107
import math import operator as op from functools import reduce def memoize(f): """memoization decorator for a function taking one or more arguments""" class memodict(dict): def __getitem__(self, *key): return dict.__getitem__(self, key) def __missing__(self, key): ret...
the-stack_0_11108
"""Simple version of MBIE-EB Paper:An analysis of model-based Interval Estimation for Markov Decision Processes (Strehl and Littman, 2008) Link: https://doi.org/10.1016/j.jcss.2007.08.009 """ import numpy as np from rlpy.representations import Enumerable from .agent import Agent from ._vi_impl import compute_q_values ...
the-stack_0_11110
"""Module for building the autocompletion indices.""" from __future__ import print_function import os import json from six import BytesIO from docutils.core import publish_string from botocore.docs.bcdoc import textwriter import awscli.clidriver from awscli.argprocess import ParamShorthandDocGen from awsshell import ...
the-stack_0_11111
import json import redis from collections import defaultdict class RedisDB: """Backend using Redis. Parameters to open the database can be passed with the url format:: redis://[:password]@localhost:6379/0 """ def __init__(self, name): self.name = name self._dbm = redis.from_...
the-stack_0_11113
"""Play Routes rules Bazel rules for running the [Play routes file compiler](https://github.com/playframework/playframework/tree/master/framework/src/routes-compiler/src/main/scala/play/routes/compiler) on Play routes files """ gendir_base_path = "play/routes" play_imports = [ "controllers.Assets.Asset", ] # TODO:...
the-stack_0_11116
import typing as t from typing import TYPE_CHECKING from starlette.requests import Request from multipart.multipart import parse_options_header from starlette.responses import Response from .base import IOType from .base import IODescriptor from ...exceptions import InvalidArgument from ...exceptions import BentoMLEx...
the-stack_0_11117
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.internet.protocol}. """ from __future__ import division, absolute_import from zope.interface.verify import verifyObject from zope.interface import implementer from twisted.python.failure import Failure from twisted.inter...
the-stack_0_11118
import asyncio import re import requests import spotipy from aiohttp import ClientSession from nextcord import User from emoji import demojize from googleapiclient.discovery import build from spotipy.oauth2 import SpotifyClientCredentials from src.bot.__tokens__ import __tokens__ from src.music.song import Song youtu...
the-stack_0_11120
#Façaumalgoritmoquerecebaovalordosaláriomínimoeovalordosaláriodeumfuncionário, #calculeemostreaquantidadedesaláriosmínimosqueganhaessefuncionário. salarioMin=float(input("Informe o valor do salário mín:")) salarioFun=float(input("Informe o valor do salário do funcionário:")) qtdSalMin= salarioFun/salarioMin if(qtdSa...
the-stack_0_11124
# Copyright 2013 IBM Corp. # 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 app...
the-stack_0_11125
import plistlib from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, is_platform_windows def get_wifi(files_found, report_folder, seeker): data_list = [] file_found = str(files_found[0]) with open(file_found, "rb") as fp: pl = plistlib...
the-stack_0_11126
#!/usr/bin/env python # -*- coding: utf8 -*- """ The MetadataWizard(pymdwizard) software was developed by the U.S. Geological Survey Fort Collins Science Center. See: https://github.com/usgs/fort-pymdwizard for current project source code See: https://usgs.github.io/fort-pymdwizard/ for current user documentation See: ...
the-stack_0_11128
"""Requirements specific to SQLAlchemy's own unit tests. """ import sys from sqlalchemy import exc from sqlalchemy.sql import text from sqlalchemy.testing import exclusions from sqlalchemy.testing.exclusions import against from sqlalchemy.testing.exclusions import fails_if from sqlalchemy.testing.exclusions import ...
the-stack_0_11129
#!/usr/bin/env python3 from PIL import Image from struct import pack def pre(p): p = list(p) p[0] = p[0]*p[3]//255 p[1] = p[1]*p[3]//255 p[2] = p[2]*p[3]//255 return p def write(i, o, X, Y): for y in range(Y): for x in range(X): p = pre(i.getpixel((x, y))) o.wri...
the-stack_0_11131
#!/usr/bin/python3 -OO # Copyright 2007-2019 The SABnzbd-Team <team@sabnzbd.org> # # 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 your option) any late...
the-stack_0_11132
# -*- coding: utf-8 -*- """ Created on Fri Apr 22 02:51:53 2016 @author: utkarsh """ # FREQEST - Estimate fingerprint ridge frequency within image block # # Function to estimate the fingerprint ridge frequency within a small block # of a fingerprint image. This function is used by RIDGEFREQ # # Usage: # freqim = f...
the-stack_0_11133
from automata_tools.Automata import Automata from typing import Dict, List, Union, Callable import numpy as np class WFA: dfa: Automata def __init__(self, dfa: Automata, word2index: Dict[str, int], dfa_to_tensor: Callable) -> None: self.dfa = dfa self.dfaDict = self.dfa.to_di...
the-stack_0_11137
from setuptools import setup with open('README.md', 'r') as fp: long_desc = fp.read() setup( name='HTTPserver-mock', version='2', author='Tom YU Choe', author_email='yonguk.choe@gmail.com', description='a simple http-server mockup to test web crawler.', long_description=long_desc, url=...
the-stack_0_11139
from __future__ import annotations import ipaddress import json import logging import struct import sys import time import tkinter import zlib from dataclasses import astuple from pathlib import Path from tkinter import messagebox, ttk from typing import Optional, Tuple import dns import dns.resolver from idlelib.too...
the-stack_0_11140
from gremlin_python.driver import client, serializer import sys, traceback _gremlin_cleanup_graph = "g.V().drop()" _gremlin_insert_vertices = [ "g.addV('person').property('id', 'thomas').property('firstName', 'Thomas').property('age', 44)", "g.addV('person').property('id', 'mary').property('firstName', 'Mary'...
the-stack_0_11141
import pandas as pd from finvizfinance.util import webScrap, numberCovert, NUMBER_COL, util_dict BASE_URL = 'https://finviz.com/screener.ashx?v={screener}{filter}&ft=4&o={order}&r={row}' FILTER_DICT = util_dict['filter'] def set_filters(filters_dict): """Set filters. Args: filters_dict(dict): dictiona...
the-stack_0_11145
# pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103 import os from collections import Counter import pytest import numpy as np from numpy.testing import assert_allclose, assert_equal from glue.config import colormaps from glue.core.message import SubsetUpdateMessage from glue.core import HubListener, Data from gl...
the-stack_0_11147
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Autologging documentation build configuration file, created by # sphinx-quickstart on Wed Mar 27 21:07:11 2013. # # 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 # ...
the-stack_0_11148
from re import L from .TypingData import TypingData from .TypingNet import TypingNet, TypingTrain import torch as th import dgl class TypingUtility: def __init__(self): self.fn = None self.data = None self.net = None self.prob = th.nn.Softmax(dim=0) def Predict(sel...
the-stack_0_11149
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
the-stack_0_11150
import argparse import codecs import csv import datetime import errno import importlib import json import logging import os import shutil import subprocess import sys import traceback from functools import singledispatch from pathlib import Path from typing import ( Any, Iterable, List, Tuple, Union...
the-stack_0_11152
""" Tests for the bootstrap.py (formerly bootstrap_controller.py) file. """ import unittest from collections import OrderedDict import numpy as np import numpy.testing as npt import pandas as pd from scipy.sparse import csr_matrix, eye import pylogit.bootstrap as bc import pylogit.asym_logit as asym import pylogit.mi...
the-stack_0_11153
__author__ = "Nitin Kumar, Rick Sherman" __credits__ = "Jeremy Schulman" import unittest from nose.plugins.attrib import attr from jnpr.junos.jxml import NAME, INSERT, remove_namespaces @attr('unit') class Test_JXML(unittest.TestCase): def test_name(self): op = NAME('test') self.assertEqual(op['...
the-stack_0_11154
# -*- coding: utf-8 -*- import asyncio import collections import functools import json import time from typing import List, Optional from threading import Thread from vk_api import VkApi from vk_api.bot_longpoll import VkBotEventType, VkBotLongPoll from vk_api.execute import VkFunction from vk_api.upload import VkUplo...
the-stack_0_11156
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input import tensorflow as tf from tensorflow.keras import layers, regularizers def rpn(feature_map, anchors_per_location=9): shared = layers.Conv2D(512, (3, 3), padding='same', activation='relu', name='rpn_conv_shared')(feature_map) # A...
the-stack_0_11160
import unittest from bbscript.stdlib import cmd_var, cmd_doc from bbscript.errors import InvalidOperation class TestVariables(unittest.TestCase): def test_var_get(self): doc = {"docname": "testdoc"} ctx = {"$test_var": "test value", "$doc": doc} self.assertEqual(cmd_var(ctx, "test_var"), "test value") self.a...
the-stack_0_11161
# Copyright 2018 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_11162
import numpy as np from .base_actuator import Actuator from spike_swarm_sim.register import actuator_registry @actuator_registry(name='wheel_actuator') class WheelActuator(Actuator): """ Robot wheel actuator using a differential drive system. """ def __init__(self, *args, robot_radius=0.11, dt=1.,...
the-stack_0_11164
""" #Trains a ResNet on the CIFAR10 dataset. """ from __future__ import print_function import keras from keras.layers import Dense, Conv2D, BatchNormalization, Activation from keras.layers import AveragePooling2D, Input, Flatten from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, LearningRa...
the-stack_0_11165
import socket server = socket.socket() server.bind(('127.0.0.1', 5000)) server.listen(5) while True: client, (client_host, client_port) = server.accept() client.recv(4096) response_type = 'HTTP/1.1 200 OK\n' headers = 'Content-Type: text/html\n\n' with open('task_3/index.html', 'r') as f: ...
the-stack_0_11167
from operator import itemgetter from nltk.corpus import wordnet from nltk.stem import WordNetLemmatizer from nltk.stem.lancaster import LancasterStemmer from players.codemaster import Codemaster class AICodemaster(Codemaster): def __init__(self, brown_ic=None, glove_vecs=None, word_vectors=None): super...
the-stack_0_11168
# Imports for flask and sql from flask import Flask, render_template, url_for, request, redirect, flash from flask_sqlalchemy import SQLAlchemy from sqlalchemy import func # Imports for plots import plotly.express as px import pandas as pd import numpy as np import json import plotly # Other imports from datetime imp...
the-stack_0_11170
from collections.abc import Mapping, Iterable from ctypes import c_int, c_int32, c_double, c_char_p, POINTER from weakref import WeakValueDictionary import numpy as np from numpy.ctypeslib import as_array from openmc.exceptions import AllocationError, InvalidIDError from . import _dll from .core import _FortranObject...
the-stack_0_11171
from django.contrib import admin from recipes.models import Ingredient, IngredientUnitMeasure, \ IngredientFamily, IngredientPhoto, \ RecipeType, RecipeDifficulty @admin.register(IngredientUnitMeasure) class IngredientUnitMeasureAdmin(admin.ModelAdmin): list_...
the-stack_0_11174
# -*- coding: utf-8 -*- from model.group import Group import random import string import os.path import jsonpickle import getopt import sys try: opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"]) except getopt.GetoptError as err: getopt.usage() sys.exit(2) n = 5 f = "data/gro...
the-stack_0_11175
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
the-stack_0_11177
# -*- coding: utf-8 -*- # This scaffolding model makes your app work on Google App Engine too # File is released under public domain and you can use without limitations if request.global_settings.web2py_version < "2.14.1": raise HTTP(500, "Requires web2py 2.13.3 or newer") # if SSL/HTTPS is properly configured a...
the-stack_0_11181
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
the-stack_0_11182
from rest_framework.views import APIView from mysystem.models import Users from apps.oauth.models import OAuthWXUser from utils.jsonResponse import SuccessResponse,ErrorResponse from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from...
the-stack_0_11183
#!/usr/bin/env python # coding: utf-8 import json import pandas as pd from pandas.api.types import is_numeric_dtype import numpy as np from scipy.stats import ks_2samp #import matplotlib.pyplot as plt import plotly.graph_objs as go import plotly.figure_factory as ff from evidently.model.widget import BaseWidgetInfo,...
the-stack_0_11184
# -*- coding: utf-8 -*- # @Time : 20-6-4 下午4:19 # @Author : zhuying # @Company : Minivision # @File : transform.py # @Software : PyCharm from __future__ import division import math import random from PIL import Image try: import accimage except ImportError: accimage = None import numpy as np import numbers imp...
the-stack_0_11186
## Advent of Code 2019: Intcode Computer v2 ## https://adventofcode.com/2019 ## Jesse Williams | github.com/vblank182 # **Compatible with Day 5, Part 1** # Changelog: # - Added IN and OUT instructions # - Added support for parameter modes #~# Opcodes #~# ADD, MUL, IN, OUT = 1, 2, 3, 4 END = 99 #~# Parameter Modes #...
the-stack_0_11187
from collections import Counter def read_signals(): file_name = "Data/day8.txt" file = open(file_name, "r") signals = [] digits = [] for line in file: line = line.strip("\n").split(" | ") signals.append(line[0].split()) digits.append(line[1].split()) return...
the-stack_0_11188
from flask import Flask from flask_s3_viewer import FlaskS3Viewer from flask_s3_viewer.aws.ref import Region import logging logging.basicConfig( level=logging.INFO, format='%(levelname)s: %(asctime)s: %(message)s' ) app = Flask(__name__) # For test, disable template caching app.config['SEND_FILE_MAX_AGE_DEF...
the-stack_0_11189
# -*- coding: utf-8 -*- from ldap.dn import explode_dn from node.behaviors import Adopt from node.behaviors import Alias from node.behaviors import Attributes from node.behaviors import DefaultInit from node.behaviors import NodeChildValidate from node.behaviors import Nodespaces from node.behaviors import Nodify from ...
the-stack_0_11192
import pytest from diot import Diot from pyppl import Proc from pyppl.job import Job from pyppl.utils import fs from pyppl.logger import logger, LEVEL_GROUPS from pyppl_echo import expand_numbers, fileflush, echo_jobs_converter, echo_types_converter, flush, logger_init, job_poll @pytest.fixture def fd_fileflush(tmp_pa...
the-stack_0_11193
#!/usr/bin/python # ----------------------------------------------------------------------------- # # Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may o...
the-stack_0_11194
def lantern_fish(filename, days): # Data structure that will contain occurrences of fish occurrences = [0, 0, 0, 0, 0, 0, 0, 0, 0] # Retrieval of data from the input file with open(filename, 'r', encoding='utf-8') as values: for value in values: fish_list = value.split(",") ...
the-stack_0_11198
# Copyright (c) Facebook, Inc. and its affiliates. import logging import torch import tqdm from multimodelity.common.sample import Sample from multimodelity.datasets.multimodelity_dataset import multimodelityDataset from multimodelity.utils.distributed import is_master logger = logging.getLogger(__name__) class VQ...
the-stack_0_11202
import sys, os, argparse, random parser = argparse.ArgumentParser() required = parser.add_argument_group('required arguments') ## user inputs required required.add_argument('-l', '--len', help='length of random sequences', dest='length') required.add_argument('-n', '--num', help='number of random sequences', dest='n...