text stringlengths 2 999k |
|---|
import numpy as np
from gisutils import shp2df, get_values_at_points
|
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
"""Baby Names exercise
Define the extract_names() function below and c... |
# Copyright 2021 The Forte Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
import os
import random
import monopyly
TOURNAMENT = True # enable this just before I submit to disable the debug code
NBR_OWNABLE = 28
def ExceptionSafe(defaultReturnValue) :
def ExceptionSafeDecorator(undecoratedFunc) :
def DecoratedFunc(*args, **kwargs) :
try :
return undec... |
import socket
import pickle
server_addr = "127.0.0.1"
server_port = 1493
sockt = socket.socket();
conn_result = sockt.connect_ex((server_addr, server_port))
if conn_result == 0:
print("Server Port is opening.")
else:
print("ServerPort is not open.")
msg = "A message from development client."
msg = pickle.dump... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_commoner_old_twilek_male_01.iff"
result.attribute_temp... |
import subprocess
import sys
from django.db.backends.base.creation import BaseDatabaseCreation
from .client import DatabaseClient
class DatabaseCreation(BaseDatabaseCreation):
def sql_table_creation_suffix(self):
suffix = []
test_settings = self.connection.settings_dict['TEST']
if test_... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, \
unicode_literals
import sys
import warnings
from unittest import TestCase
from jubakit.nearest_neighbor import Schema, Dataset, NearestNeighbor, Config
from . import requireEmbedded
from .stub import StubLoader
def filt... |
# -*- coding: utf-8 -*-
"""Top-level package for pytree."""
__author__ = """Breck Yunits"""
__email__ = 'breck7@gmail.com'
__version__ = '0.1.0'
from .pytree import Pytree
from .pytree import Pytree as PyTree
|
def load_data():
file_name = '../data/data.tsv'
data_df = pd.read_csv(file_name, sep='\t', header=[0,1,2], index_col=0)
data_df.columns = data_df.columns.droplevel(0)
data_df = (data_df / stats.trim_mean(data_df, 0.02)).apply(np.log2)
return data_df
def load_info():
file_name = '../data/info.tsv'
return ... |
#!/usr/bin/env python2
# -*- encoding=utf-8 -*-
# description:
# author:jack
# create_time: 2018/1/3
"""
desc:pass
"""
import os
import fcntl
import hashlib
# import OpenSSL
import urllib2
# from Crypto.PublicKey import RSA
# from Crypto.Signature import PKCS1_v1_5
# from Crypto.Hash import SHA
from base64 import... |
CURRENT_SERVER_NAME= 'mac1'
APPLICATION_ID = '3274ab1f-ec04-459e-9321-3ae8814b630c'
REST_API_KEY = ''
MASTER_KEY = '84bmz9qwoq0YcRWn2SiVUk09UqIa1xOB'
PARSE_SERVER_URI = "https://parse.buddy.com"
LOG_PATH = ''
SINGLE_TEST_MODE = False # whether only for testing single movie per task
|
from import_export import resources
from .models import simple, repContact, sfcontact, duplifyTime, dedupTime, uploadTime
from import_export.fields import Field
class DuplifyTimeResource(resources.ModelResource):
class Meta:
model = duplifyTime
class DedupTimeResource(resources.ModelResource):
... |
# -*- coding: utf-8 -*-
"""The reports module."""
from . import views
|
from pytest_bdd import scenario, given, when, then
from pages.login_page import LoginPage
from pages.account_creation_page import AccountCreationPage
@scenario("register_scenario.feature", "Register on site")
def test_register():
pass
@given("open authentication page")
def launch_browser(browser):
LoginPage... |
import random
from itertools import product
CS = 10 # cell size
W = 600 # width
H = 600 # height
COLS = W // CS
ROWS = H // CS
DENSITY = 0.35
dirs = list(product((-1, 0, 1), repeat=2))
dirs.remove((0, 0))
points = []
new_points = []
run = False
def xy2flat(x, y):
x = (x + COLS) % COLS
y = (y + ROWS) % RO... |
#!/usr/bin/env python
import multiprocessing
import sys
import spotipy
from spotipy import util
from spotipy.client import SpotifyException
import pickle
import os
import time
from spotify_tokens import * # stick your CLIENT_ID and CLIENT_SECRET here
# PLAYLIST_PATH = 'playlists.pickle'
TRACKS_PATH = 'tracks.pickle'
... |
"""
We use this in development to build jquery.preview.js
"""
import os
import glob
import shutil
from time import sleep
from docutils.core import publish_string
from optparse import OptionParser
DIR_PATH = os.path.abspath(os.path.dirname(__file__))
SRC_PATH = os.path.join(DIR_PATH, 'src/')
def build():
p = ope... |
#!/usr/bin/env python3
import sys
import os
import matplotlib.pyplot as plt
import numpy as np
import helper
import glob
from skimage import io, transform
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, datasets, models
import torchvision.utils
from collections import ... |
# Copyright (c) 2020, MD2K Center of Excellence
# - Nasir Ali <nasir.ali08@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above cop... |
import sys, ctypes, warnings, itertools
_version_list = ["10.2.1.89", "10.2.0.243", "10.1.168", 10.0, 9.2, 9.1, 9.0, 8.0]
if sys.platform == "linux":
_libnppc_libname_list = [
"libnppc.so.%s" % v for v in _version_list
]
_libnppi_libname_list = [
"libnppi%s.so.%s" % ("g" if isinstance(v, str) or v >= 9.0 else... |
import numpy as np
import pandas as pd
from nltk.stem import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
import re
from HTMLParser import HTMLParser
from sklearn.cross_validation import StratifiedShuffleSplit
from bs4 import BeautifulSoup
from collections import Counter
import difflib
from nltk import... |
from warriorpy import towers
from warriorpy import warriorpyAbilities
from warriorpy import warriorpyCli
from warriorpy import warriorpyCore
from warriorpy import warriorpyGeography
from warriorpy import warriorpyUnits
__all__ = ["towers", "warriorpyAbilities", "warriorpyCli", "warriorpyCore", "warriorpyGeography", "... |
# coding=utf-8
# Copyright 2018-2020 EVA
#
# 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 ... |
# Copyright 2011 Nicholas Bray
#
# 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... |
# content of conftest.py
import pytest
try:
import safe_exploration.ssm_gpy
safe_exploration.ssm_gpy.__name__
_has_ssm_gpy_ = True
except:
_has_ssm_gpy_ = False
try:
import safe_exploration.ssm_pytorch
safe_exploration.ssm_pytorch.__name__
_has_ssm_pytorch = True
except:
_has_ssm_pytor... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import PurePath
from typing import Sequence
from pants.engine.engine_aware import EngineAwareP... |
"""Initial Migration
Revision ID: d5353fa1f0bd
Revises: 0b6bfbce4494
Create Date: 2019-09-23 23:35:44.517817
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd5353fa1f0bd'
down_revision = '0b6bfbce4494'
branch_labels = None
depends_on = None
def upgrade():
... |
from discord.ext import commands
from time import sleep
class Cleaner(commands.Cog):
""" Clean Messages """
def __init__(self, bot):
self.bot = bot
@commands.command(name="limpar", help="Limpa mensagens enviadas no chat. Argumentos: Quantia de mensagens a serem deletadas (limite = 300)", alias... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_connectivity_connectivity_service_ref import TapiConnectivityConnectivityServiceRef # noq... |
import collections
import copy
import dataclasses
import inspect
import re
import sys
import unittest
from typing import *
import pytest # type: ignore
from crosshair.core import get_constructor_params
from crosshair.core import proxy_class_as_masquerade
from crosshair.core import run_checkables
from crosshair.core_... |
# coding: utf-8
"""
Nodeum API
The Nodeum API makes it easy to tap into the digital data mesh that runs across your organisation. Make requests to our API endpoints and we’ll give you everything you need to interconnect your business workflows with your storage. All production API requests are made to: http... |
from django.contrib import admin
from hmsifba.models import *
class Empresas(admin.ModelAdmin):
list_display = ('id', 'nomeEmpresa', 'proprietario', 'endereco', 'telefone', 'categoria', 'email')
list_display_links = ('id', 'nomeEmpresa', 'proprietario', 'endereco', 'telefone', 'categoria', 'email')
class Clie... |
#!/usr/bin/env python
import mirheo as mir
ranks = (1, 1, 1)
domain = (8, 8, 8)
u = mir.Mirheo(ranks, domain, debug_level=3, log_filename='log', no_splash=True)
pv = mir.ParticleVectors.ParticleVector('pv', mass = 1)
ic = mir.InitialConditions.Uniform(number_density=2)
u.registerParticleVector(pv, ic)
u.registerP... |
import mdtraj as md
import numpy as np
import tensorflow as tf
import tftraj.rmsd
import tftraj.rmsd_op
def test_works(sess, traj):
rmsd = tftraj.rmsd_op.load()
inds = [5, 19, 234, 235]
target = np.array(traj.xyz[inds])
target = tf.Variable(target)
prmsd, _ = rmsd.pairwise_msd(traj.xyz, target)
... |
# 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 may ... |
# Generated by Django 3.1.2 on 2020-10-19 08:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0002_userdet... |
import functools
from typing import List, Any
import numpy as np
import scipy.sparse as sp
import pytest
from sklearn.metrics import euclidean_distances
from sklearn.random_projection import johnson_lindenstrauss_min_dim
from sklearn.random_projection import _gaussian_random_matrix
from sklearn.random_projection im... |
# 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... |
""" Ex-022- Crie um programa que leia o nome completo de uma pessoa
e mostre:
> O nome com todas as letras maiúsculas e minúsculas.
> Quantas letras ao todo (sem considerar espaços).
Quantas letras tem o primeiro nome."""
# Usamos .strip() para descartar espaços vazios antes e depois da string
nom... |
from data import features
from player import message_output
import random
import time
class Character:
def __init__(self, params):
self.name = params['name']
self.lives = params['lives']
self.energy = params['energy']
self.energy_max = params['energy_max']
self.energy_name ... |
import discord
from discord.ext import commands
from dataIO import dataIO
from collections import namedtuple, defaultdict
from datetime import datetime
from random import randint
from copy import deepcopy
import Checker
import os
import time
import logging
default_settings = {"PAYDAY_TIME" : 300, "PAYDAY_CREDITS" : 12... |
from generator.model import get_model
from ast import literal_eval
import numpy as np
class Generator:
def __init__(self, file: str = 'trained_data/cyber_weights'):
with open('trained_data/char_indices') as f:
char_indices = f.read()
self._char_indices = literal_eval(char_indices)
... |
import pvlib
import numpy as np
import pandas as pd
import cnosolar as cno
from tqdm.auto import tqdm
from functools import reduce
def run(system_configuration, data, irrad_instrument, availability, energy_units):
'''
Wrapper that executes the production stages of the PV system,
including system losses.
... |
from django.utils.timezone import now
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from .sync_to_async import get_room_or_error, get_user_or_error, save_message
class ChatConsumer(AsyncJsonWebsocketConsumer):
"""
handles websocket connections and messages
"""
async def connect(se... |
import logging
import os
import io
import sys
import inspect
import traceback
from datetime import datetime
import azure.functions as func
CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
PARENTDIR = os.path.dirname(CURRENTDIR)
sys.path.insert(0, PARENTDIR)
from SharedCode.mail... |
# Convolutional Neural Network
# Importing the libraries
import tensorflow as tf
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
# Data Preprocessing
# Preprocessing the Training set
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,... |
"""
This file offers the methods to automatically retrieve the graph Candidatus Mycoplasma haemobos.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein-... |
import komand
from .schema import GetALogInput, GetALogOutput, Input, Output, Component
from komand_rapid7_insightidr.util.endpoints import Logs
from komand_rapid7_insightidr.util.resource_helper import ResourceHelper
from komand.exceptions import PluginException
# Custom imports below
import json
class GetALog(koma... |
import cv2
import mediapipe as mp
mp_hands = mp.solutions.hands
hands = mp_hands.Hands()
mp_draw = mp.solutions.drawing_utils
cap = cv2.VideoCapture(0)
finger_tips = [8, 12, 16, 20]
thumb_tip = 4
while True:
ret,img = cap.read()
img = cv2.flip(img, 1)
h,w,c = img.shape
results = hands.process(img)
... |
import time
print "Hello, World!",
while 1:
time.sleep(120000)
|
# -*- coding: utf-8 -*-
from decimal import Decimal
from django.contrib.auth.models import User
from django.db import models
from shop.cart.modifiers_pool import cart_modifiers_pool
from shop.models.productmodel import Product
class Cart(models.Model):
'''
This should be a rather simple list of items. Ideally ... |
valor_hora = float(input('Digite o valor da hora: '))
horas_trab_mes = int(input('Digite as horas trabalhadas por mes: '))
salario_bruto = valor_hora*horas_trab_mes
IR = 0.11*salario_bruto
INSS = 0.08*salario_bruto
sindicato = 0.05*salario_bruto
descontos = IR + INSS + sindicato
salario_liquido = salario_bruto - desco... |
''' 3.9. Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário. Calcule o total em segundos. '''
print('Cálculo de Tempo em Segundos')
n1=int(input('Quantos Dias: '))
n2=int(input('Quantas Horas: '))
n3=int(input('Quantos minutos: '))
#1 minuto == 60 segundos; 1 horas == 3600 segundo... |
#! /usr/bin/env python
#
# Copyright (C) 2018 Mikko Kotila
DESCRIPTION = "Talos Hyperparameter Tuning for Keras"
LONG_DESCRIPTION = """\
Talos radically changes the ordinary Keras workflow by
fully automating hyperparameter tuning and model evaluation.
Talos exposes Keras functionality entirely and there is no... |
#This is the controls for parameters for the criteria we are filtering properties on
#Download inputs Enabled
DOWNLOAD_ENABLED = False
#Parsing Enabled
PARSER_ENABLED = True
#Jason Excel Automation Enabled
JASON_ENABLED = True
#When handling err msgs, should those be printed to the screen?
PRINT_ERR_MSG_TO_SCREEN =... |
#print('Hello.')
from Map_handler import Map_handler
from Guess_and_Check_Path_Finder import Guess_and_Check_Path_Finder
city_count = 6
time_limit_in_seconds = 3
map_handler_object = Map_handler(city_count)
map_handler_object.load_map()
guess_and_check_path_finder = Guess_and_Check_Path_Finder(city_count)
guess_and_... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# Power by viekie. 2017-05-27 09:23:04
import numpy as np
class Filter(object):
def __init__(self, width, height, depth):
'''
构造初始化
'''
self.width = width
self.height = height
self.depth = depth
self.weights = np.r... |
#!/usr/bin/python3
from . import Generator
class PhpGenerator(Generator):
# one day this will generate awesome random code
min_content_size = 2
def __init__(self):
pass
def insert(self, content, num):
if len(content) <= self.min_content_size:
content.clear()
... |
import json
import logging
import ibmsecurity.utilities.tools
from ibmsecurity.utilities import tools
from io import open
logger = logging.getLogger(__name__)
uri = "/extensions"
requires_modules = None
requires_version = "9.0.5.0"
try:
basestring
except NameError:
basestring = (str, bytes)
def get_all(isa... |
from __future__ import unicode_literals
__version__ = '2021.02.10'
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.20.7
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unitte... |
# Copyright (c) 2010-2012 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 law or agree... |
from django.conf import settings
from . import defaults
__title__ = 'eximagination.conf'
__author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>'
__copyright__ = '2013-2017 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('get_setting',)
def get_setting(setting, override=None):
"""Get setting.
... |
def kadane(a,n):
ans=max(a)
s=0
for e in a:
s+=e
if s<0:
s=0
ans = max(ans,s)
return ans
n=int(input('Enter the size of array'+'\n'))
a=[int(i) for i in input().split()]
print(kadane(a,n))
|
import asyncio
from collections.abc import AsyncGenerator, AsyncIterator, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from typing import Optional, Protocol, Union, cast
import aiodocker
import pytest
from aiohttp import ClientError, ClientResponseError
from aiohttp.hdrs... |
__author__ = 'dudevil'
import pickle
import functools
import operator
import numpy as np
import pandas as pd
import theano
import theano.tensor as T
from importlib import import_module
from theano.tensor.nnet import conv
from sklearn.metrics import confusion_matrix
import lasagne
def load_config(file):
... |
import collections
import sqlite3
import typing
from hydrus.core import HydrusConstants as HC
from hydrus.core import HydrusData
from hydrus.core import HydrusDB
from hydrus.client import ClientConstants as CC
from hydrus.client import ClientSearch
from hydrus.client.db import ClientDBMaster
from hydrus.client.db imp... |
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('users', '0004_remove_userprofile_start_workflow'),
]
operations = [
migrations.RenameField(
model_name='invitation',
old_name='uuid',
new_nam... |
from run import app
if __name__ == "__main__":
app.run()
|
"""
DJANGO MATERIAL WIDGETS READTHEDOCS SETTINGS
config/settings/readthedocs.py
"""
# pylint: disable=wildcard-import, unused-wildcard-import
from config.settings.base import *
### SECURITY WARNING: DO NOT USE READTHEDOCS SETTINGS IN PRODUCTION
DEBUG = True
SECRET_KEY = "THIS IS A SECRET KEY"
###
INSTALLED_APPS += ... |
import os
from unittest import mock
from tornado.testing import AsyncTestCase, ExpectLog, gen_test
from remoteappmanager.docker.container import Container
from remoteappmanager.docker.docker_labels import SIMPHONY_NS_RUNINFO
from remoteappmanager.docker.container_manager import ContainerManager, \
OperationInProg... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import mxnet as mx
import argparse
import segmentation_models as sm
import keras
import os
from narya.narya.models.keras_models import KeypointDetectorModel
from narya.datasets.keypoints_dataset import KeyPoin... |
import os
import sys
import re
import json
import unittest
from codecs import getdecoder
sys.path.insert(0, os.path.abspath("."))
REGEXP_DIR = os.path.join("test", "lang", "regexp")
class FirstLinesTestCase(unittest.TestCase):
"""Tests for codetype's utility functions.
"""
def test_identify(self):
... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
i... |
from django.test import SimpleTestCase
from django.urls import reverse, resolve
from store.views import store, cart, checkout, updateItem, processOrder
# TestUrls checks that the URL returns a specific view
class TestUrls(SimpleTestCase):
def test_store_url_resolves(self):
url = reverse('store')
... |
from __future__ import annotations
from typing import Any, Type, Optional
import torch
import numpy as np
from transformers import AutoConfig
import daluke.ner.data as datasets
from daluke.model import get_ent_embed_size
from daluke.ner.data import NERDataset
from daluke.model import ent_dims_from_state_dict
from dal... |
from unique_name import foo
print(foo)
|
import os
os.system("python3 webserver.py &")
import asyncio
import uvloop
import sys
import discord
import ps2
import pyps4
from fortnitepy.ext import commands
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
try:
from typing import Any, Union, Optional
import asyncio
import datetime
import j... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy2 Experiment Builder (v1.85.1),
on September 08, 2017, at 18:43
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal... |
from __future__ import division, print_function, absolute_import
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.contrib import layers
from sklearn import cluster
from munkres import Munkres
import scipy.io as sio
from scipy.sparse.linalg import svds
from sklearn.preprocessi... |
# Copyright 2013 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 law or agreed to in... |
from django.urls import reverse
from django.test import TestCase
from prometheus_client.parser import text_string_to_metric_families
from zentral.contrib.inventory.models import MachineSnapshotCommit
class PrometheusViewsTestCase(TestCase):
def test_prometheus_metrics_403(self):
response = self.client.get... |
from Jumpscale import j
from .JSBase import JSBase
"""
classes who use JSXObject for data storage but provide nice interface to enduser
"""
from .JSAttr import Attr
class JSConfigBCDBBase(JSBase, Attr):
def _init_pre(self, **kwargs):
self._model_ = None
self._bcdb_ = None
self._schema_ =... |
from __future__ import unicode_literals, absolute_import
from abc import ABCMeta, abstractmethod
from collections import defaultdict, namedtuple
import copy
import re
import sys
import os
from diff_cover.command_runner import execute, run_command_for_code
Violation = namedtuple('Violation', 'line, message')
cla... |
"""
Django settings for locallibrary project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pa... |
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# import struct
import scipy.io as sio
import logging
logger = logging.getLogger('root.' + __name__)
logger.addHandler(logging.NullHandler())
MNIST_TRAIN_LABELS = 'data/train-labels-idx1-ubyte/data'
MNIST_TRAIN_IMAGES = 'data/train-images-idx3-... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Pedro Navarro Perez
# Copyright 2013 Cloudbase Solutions Srl
# 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 th... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt5.QtCore import QModelIndex
from PyQt5.QtWidgets import QListWidget
class EditInList(QListWidget):
def __init__(self):
super(EditInList, self).__init__()
self.edited_item = None
def item_clicked(self, modelindex: QModelIndex):
tr... |
# -*- coding: utf-8 -*-
class Node:
# vértice v
to = 0
# costo, peso
cost = 0
# siguiente
nxt = None
class Graph:
# aristas
edges = []
# grado externo
grade = []
# num nodos
numNodes = 0
# num aristas
numEdges = 0
# dirigida o no?
directed = False
def s... |
import queue
import json
import os
import datetime
from threading import Thread
from flask import Response, request
from flask_restplus import Namespace, Resource
from flask.json import jsonify
from hti.server.state.events import subscribe_for_events, log_event
from hti.server.state.globals import (
get_catalog,... |
import pytest
from wemake_python_styleguide.violations.complexity import (
OverusedStringViolation,
)
from wemake_python_styleguide.visitors.ast.complexity.overuses import (
StringOveruseVisitor,
)
string_actions = """
first = {0}
second({0})
third[{0}]
'new' + {0}
"""
string_function_type_annotations1 = """... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime, timedelta
import unittest
from flask_babel import gettext as __
from mock import Mock, patch, PropertyMock
from se... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Particl Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_particl import ParticlTestFramework
from test_framework.util import *
class AnonTes... |
from __future__ import absolute_import, division, print_function
import numpy as np
import torch
from torch.autograd import Variable
from pyro.distributions.util import copy_docs_from
from pyro.distributions.distribution import Distribution
from torch.autograd import Function
def potri_compat(var):
return Varia... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class MybankCreditSceneprodFinanceConsultResponse(AlipayResponse):
def __init__(self):
super(MybankCreditSceneprodFinanceConsultResponse, self).__init__()
sel... |
from .firestation import draw_firestation
from .hospital import draw_hospital
from .policestation import draw_policestation
def draw_safety():
draw_firestation()
draw_hospital()
draw_policestation()
return |
import string
sonnets = open("sonnets.txt").readlines()
word_set = set([elt.strip() for elt in open("sowpods.txt")])
sonnet_words = set()
def strip_punctuation(word):
# Remove surrounding punctuation. If there's an apostrophe in the
# middle of the word, skip it.
word.replace("-", " ")
apostrophe_inde... |
"""
builtin_comp.py - Completion builtins
"""
from _devbuild.gen.runtime_asdl import value_e
from core import completion
from core import error
from core import ui
from core import vm
#from core.pyerror import log
from frontend import flag_spec
from frontend import args
from frontend import consts
from frontend import... |
class Solution:
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
ans = []
times = len(queries)
A_len = len(A)
for i in range(times):
temp = 0
val = queries[i][0]
index = queries[i][1]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.