content
stringlengths
0
894k
type
stringclasses
2 values
import getpass import smtplib from email.mime.text import MIMEText from email.utils import formataddr import urllib.request, urllib.parse, urllib.error import ssl import json import time import re import os import sys # Email setting for notification def Email(sender, password, recipient, emailsub, emailmsg, smtpsever...
python
import unittest from buscasrc.core.analyzer import Analyzer class TestAnalyzer(unittest.TestCase): def setUp(self): self.analyzer = Analyzer() def test_prepare_text(self): text = "Conan, the barbarian is a great HQ. Conan, #MustRead!" self.assertListEqual(self.analyzer.prepare_text(...
python
import yaml from functools import lru_cache from flask import current_app as app from atst.utils import getattr_path class LocalizationInvalidKeyError(Exception): def __init__(self, key, variables): self.key = key self.variables = variables def __str__(self): return "Requested {key} a...
python
from .validate import Validate __all__ = ["Valdate"]
python
"""Application tests."""
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import inselect REQUIREMENTS = [ # TODO How to specify OpenCV? 'cv2>=3.1.0', 'numpy>=1.11.1,<1.12', 'Pillow>=3.4.2,<3.5', 'python-dateutil>=2.6.0,<2.7', 'pytz>=2016.7', 'PyYAML>=3.12,<3.2', 'schematics>=1.1.1,<1.2', 'scikit-lea...
python
# get camera list import logging from datetime import datetime from typing import Any from typing import List import requests from protect_archiver.dataclasses import Camera def get_camera_list(session: Any, connected: bool = True) -> List[Camera]: cameras_uri = f"{session.authority}{session.base_...
python
# -*- coding: utf-8 -*- """ Created on Thu Apr 26 15:15:55 2018 @author: Madhur Kashyap 2016EEZ8350 """ import os import sys import logging import numpy as np from functools import partial from keras.optimizers import Adadelta from sklearn.metrics import confusion_matrix prog = os.path.basename(__file...
python
from connect4 import Connect4Board from connect4 import GameState from connect4 import Player def test_win_condition(): # check vertical for row in range(6-3): for col in range(7): game = Connect4Board() for i in range(row, row+4): game.board[i][col] = Player.PLAYER_1 if not game.chec...
python
import urllib import os import threading import time import errno from functools import partial import weakref import base64 import json import socket from socketserver import ThreadingMixIn from http.server import SimpleHTTPRequestHandler, HTTPServer from urllib.parse import unquote from urllib.parse import urlparse ...
python
from twisted.trial import unittest from twisted.internet import defer from nodeset.core import config from nodeset.common.twistedapi import NodeSetAppOptions class ConfigurationTest(unittest.TestCase): def setUp(self): cfg = NodeSetAppOptions() cfg.parseOptions(['-n', '--listen', 'localhost:4...
python
acceptable_addrs = ["192.168.0.16"]
python
# Generated by Django 2.1.5 on 2019-01-27 00:11 from django.db import migrations, models import django.db.models.deletion import simplemde.fields import uuid class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Event",...
python
from .operator_bot import main main()
python
from episerver.vanir.configuration import Configuration from azure.common.client_factory import get_client_from_json_dict from azure.mgmt.resource import ResourceManagementClient class AddEnvironmentCommand: def __init__(self): config = Configuration() self.resource_client = get_client_from_json_di...
python
from tensorize import * class InceptionResnetV1(Model): def inference(self, inputs, output): stem(inputs, outputs) for x in xrange(4): inceptionA() reductionA() for x in xrange(7): inceptionB() reductionB() for x in xrange(3): ...
python
# -*- coding: utf-8 -*- import trello.checklist as checklist class Checklist(checklist.Checklist): pass
python
import os import unittest from skidl import * class UnitTestsElectronicDesignAutomationSkidlExamples(unittest.TestCase): def test_introduction(self): print("test_introduction") # Create input & output voltages and ground reference. vin, vout, gnd = Net('VI'), Net('VO'), Net('GND') ...
python
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import contextlib import importlib import itertools import numbers import operator from collections import OrderedDict, namedtuple from functools import reduce import numpy as np import opt_einsum from multipledispatch import dispatch...
python
import unittest import torch.cuda as cuda from inferno.utils.model_utils import MultiscaleModelTester class TestUnetMultiscale(unittest.TestCase): def test_unet_multiscale_2d(self): from neurofire.models import UNet2DMultiscale input_shape = (1, 1, 512, 512) output_shape = ((1, 1, 512, 512...
python
from .linear_growth_class import CosmoLinearGrowth from .linear_growth_functions import a2z from .linear_growth_functions import z2a from .linear_growth_functions import get_Hz from .linear_growth_functions import get_Dz from .linear_growth_functions import get_r from .linear_growth_functions import get_omega_m_z fro...
python
#!/usr/bin/python #-*- coding: utf-8 -*- # >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>. # Licensed under the Apache License, Version 2.0 (the "License") # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # --- File Name: loss_uneven.py # --- Creation Date: 19-04-2021 # --- Last Modified: Sat 2...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from pathlib import Path from wildfires.utils import handle_array_job_args try: # This will only work after the path modification carried out in the job script. from specific import ( CACHE_DIR, SimpleCache, get_model, da...
python
import aiohttp import asyncio import json import time from pydigitalstrom.client import DSClient from pydigitalstrom.log import DSLog class DSWebsocketEventListener: def __init__(self, client: DSClient, event_name: str): self._client = client self._event_name = event_name self._callbacks ...
python
from django.core.exceptions import ObjectDoesNotExist from django.db import models class OrderField(models.PositiveIntegerField): def __init__(self, for_fields=None, *args, **kwargs): self.for_fields = for_fields super().__init__(*args, **kwargs) def pre_save(self, model_instance, add): ...
python
# Copyright 2020 Lynn Root """Functional tests for interrogate/coverage.py.""" import os import sys import pytest from interrogate import config from interrogate import coverage HERE = os.path.abspath(os.path.join(os.path.abspath(__file__), os.path.pardir)) SAMPLE_DIR = os.path.join(HERE, "sample") FIXTURES = os.p...
python
# Inspired by: # https://codereview.stackexchange.com/questions/42359/condorcet-voting-method-in-oop-python # and https://github.com/bradbeattie/python-vote-core/tree/master/pyvotecore import sys import os import itertools def main(): file = sys.argv[1] if not os.path.isfile(file): print("File path ...
python
import os, time def cmd(cmdd): os.system(cmdd) while(True): time.sleep(2) cmd("cls") cmd("python app.py")
python
import getpass import sys from constants import cx_status import paramiko # setup logging paramiko.util.log_to_file("/tmp/paramiko.log") # Paramiko client configuration UseGSSAPI = ( paramiko.GSS_AUTH_AVAILABLE) DoGSSAPIKeyExchange = ( paramiko.GSS_AUTH_AVAILABLE) class SilentPolicy(paramiko.MissingHostKeyPolicy)...
python
# Utilities for reading score-files import numpy as np from utils.data_loading import readlines_and_split_spaces def load_scorefile_and_split_to_arrays(scorefile_path): """ Load a scorefile where each line has multiple columns separated by whitespace, and split each column to its own array """ ...
python
import numpy as np from numpngw import write_apng # Example 5 # # Create an 8-bit RGB animated PNG file. height = 20 width = 200 t = np.linspace(0, 10*np.pi, width) seq = [] for phase in np.linspace(0, 2*np.pi, 25, endpoint=False): y = 150*0.5*(1 + np.sin(t - phase)) a = np.zeros((height, width, 3), dtype=np...
python
from django.apps import AppConfig class TmplConfig(AppConfig): name = 'tmpl'
python
from rpython.flowspace.model import Variable, Constant, Block, Link from rpython.flowspace.model import SpaceOperation, FunctionGraph, copygraph from rpython.flowspace.model import checkgraph from rpython.flowspace.model import c_last_exception from rpython.translator.backendopt.support import log from rpython.translat...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # # # # model-bi-gramms.py # @author Zhibin.LU # @created Fri Feb 23 2018 17:14:32 GMT-0500 (EST) # @last-modified Wed Mar 14 2018 19:11:45 GMT-0400 (EDT) # @website: https://louis-udm.github.io # # # # import gzip import time from collections import Counter import re...
python
"ZKit-Framework Github : https://github.com/000Zer000/ZKit-Framework" # Copyright (c) 2020, Zer0 . All rights reserved. # This Work Is Licensed Under Apache Software License 2.0 More # Can Be Found In The LICENSE File. __author__ = "Zer0" __version__ = "1.4.5" __license__ = "Apache Software License 2.0" __status__ = "P...
python
# Implement Bubble Sort import time # we have a data set starting with the very basic happy path to complex data = { "data1" : [5,4,1,3,2], # happy path easy to vizualize "data2" : [5,4,1999,3,2,8,7,6,10,100], #larger range of values "data3" : [5,4,1,3,2,2], # repeated values "data4" : ...
python
import numpy as np import time from numba import njit, prange def exact_solver_wrapper(A_org, Q, p, L, delta_l, delta_g, constr='1'): """ Exact attacks for A^1, A^2 or A^{1+2} param: A_org: original adjacency matrix Q: matrix, Q_i = Q[i] p: ve...
python
from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager from django.conf import settings # Create your models here. class UserProfileManager(BaseUserManager): """Manager for U...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from unittest import TestCase import os from auxlib.packaging import get_version # from auxlib.packaging import (_get_version_from_pkg_info, _is_git_dirty, _get_most_recent_git_tag, # _get_git_hash,...
python
from rest_framework import serializers from daily_tracker.models import Attandance class AttandanceSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api:attandance-detail') class Meta: model = Attandance fields = ('id', 'enter_at', 'out_a...
python
import numpy as num from decimal import * import scipy as sci from numpy.polynomial import polynomial as pol def euler(f,a,b,n ,y_0): h=Decimal((b-a))/Decimal(n) vals = [] vals.append(y_0) print ("Indice\t | t | Aproximado(u) ") print("0\t | 0 |\t"+str(y_0)) for i in range (0, n-1): ...
python
from __future__ import absolute_import import inspect from textwrap import dedent from types import FunctionType from ..core.properties import Bool, Dict, Either, Int, Seq, String, AnyRef from ..model import Model from ..util.dependencies import import_required from ..util.compiler import nodejs_compile, CompilationE...
python
import random import sys def room(map, times, max, min): # map width = len(map) height = len(map[0]) # Storage generated rooms rooms = [] for i in range(times): sp = (random.randint(0, int((width-1)/2))*2+1, random.randint(0, int((height-1)/2))*2+1) length = rando...
python
# -*- coding: utf-8 -*- """Main module.""" import warnings from collections import Counter from math import sqrt import mlprimitives import numpy as np from mlblocks import MLPipeline from scipy.stats import entropy from sklearn import metrics from sklearn.model_selection import KFold from sklearn.neighbors import Ne...
python
import torch import torch.nn as nn import torch.optim as optim import torch_geometric.transforms as transforms from torch_geometric.data import Data, Batch from tensorboardX import SummaryWriter import matplotlib.pyplot as plt import matplotlib.animation as animation import mpl_toolkits.mplot3d.axes3d as p3 import nump...
python
""" :Copyright: 2014-2022 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional import pytest from byceps.services.board.dbmodels.posting import Posting as DbPosting from byceps.services.board.dbmodels.topic import Topic as DbTopic from byceps.services.board.tran...
python
""" Here is a batch of evaluation functions. The interface should be redesigned carefully in the future. """ import pandas as pd from typing import Tuple from qlib import get_module_logger from qlib.utils.paral import complex_parallel, DelayedDict from joblib import Parallel, delayed def calc_long_short_prec( pr...
python
from setuptools import setup, find_packages from os.path import join, dirname import sys if sys.version_info[0] != 3 or sys.version_info[1] < 6: print("This script requires Python >= 3.6") exit(1) setup( name="vkmix", version="1.5", author="alekssamos", author_email="aleks-samos@yandex.ru", url="...
python
"""A basic JSON encoder to handle numpy and bytes types >>> bool_array = np.array([True]) >>> bool_value = bool_array[0] >>> obj = {'an_array': np.array(['a']), 'an_int64': np.int64(1), 'some_bytes': b'a', 'a_bool': bool_value} >>> assert dumps(obj) """ import base64 import json from functools import partial import ...
python
# -*- coding: utf-8 -*- import codecs import io import logging import os import re import shutil import sys try: from StringIO import StringIO except ImportError: from io import StringIO import tempfile if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest from py3kwarn2to...
python
from django.contrib import admin from .models import Nurse, NursePatient class NurseAdmin(admin.ModelAdmin): model = Nurse list_display = ['user', ] class NursePatientAdmin(admin.ModelAdmin): model = NursePatient list_display = ['nurse', 'patient', ] admin.site.register(Nurse, NurseAdmin) admin.s...
python
class Reactor(object) : def addReadCallback( self, sockfd, callback ) : raise NotImplementedError def removeReadCallback( self, sockfd ) : raise NotImplementedError def addWriteCallback( self, sockfd, callback ) : raise NotImplementedError def removeWriteCallback( self, ...
python
from dronekit import * from pymavlink import mavutil import argparse import serial from random import uniform class Pixhawk: def __init__(self): self.status = ( "down" ) # this status is used to check if a service is functioning normaly or not self.vehicle = None def star...
python
import brownie def test_withdraw_all(splitter, alice, bob): initial_alice_balance = alice.balance() initial_contract_balance = splitter.balance() initial_alice_contract_balance = splitter.balances(alice)["balance"] initial_bob_balance = bob.balance() initial_bob_contract_balance = splitter.balance...
python
#econogee, 1/28/2016 #Stock Data Retrieval Script #If executed via the command line, will produce 500 data files with stock price information #between the dates specified in the main method. Can also be imported to use the RetrieveStock method. import os import sys import numpy as np import urllib2 def RetrieveStoc...
python
import os import sys def pre_process(baseDir, x1, x2, x3): """ An utility function to pre-process the .comm input files by reading it and replacing the design variables(Length, Breadth and Thickness) values with the values provided by BOA PARAMS: baseDir - The path of the directory which hold...
python
#! /usr/bin/env python3.8 from larning.setup import ( get_version, get_github_url, PACKAGE_NAME, PACKAGES, setup, LONG_DESCRIPTION, require_interpreter_version, ) # ˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇ require_i...
python
import torch.nn as nn import torch import math class AffinityLayer(nn.Module): """ Affinity Layer to compute the affinity matrix from feature space. M = X * A * Y^T Parameter: scale of weight d Input: feature X, Y Output: affinity matrix M """ def __init__(self, dim): super(Af...
python
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def softmax(x): x_exp = np.exp(x) return x_exp /np.sum(x_exp) def relu(x): return np.maximum(x, np.zeros_like(x))
python
""" Author: Trenton Bricken @trentbrick All functions in this script are used to generate and approximate the circle intersection in binary and continuous space and also convert between cosine similarity and hamming distance. """ import numpy as np import matplotlib.pyplot as plt from scipy.stats import binom, norm...
python
import json import sys from concurrent.futures import ThreadPoolExecutor, Future from urllib3.connectionpool import HTTPSConnectionPool, HTTPResponse from urllib3.exceptions import NewConnectionError, MaxRetryError, HTTPError from typing import Dict, List, Any from string import Template class NetMod: _instance =...
python
import argparse import logging import sys from pathlib import Path import requests from flask import Flask from packaging import version from .views.assets import blueprint as assets_blueprint from .views.index import blueprint as index_blueprint PROCESS_NAME = "Spel2.exe" # Setup static files to work with onefile e...
python
import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Dense import numpy as np import os # We set seeds for reproduciability tf.random.set_seed(1) np.random.seed(1) url = 'https://archive.ics.uci.edu/ml/machine...
python
# Aula 20 - 05-12-2019 # Analise de dados superficial # Dica: Para este formulário será necessário usar um metodo para string novo. # Vocês já conhecem o .strip() que remove os caracteres especiais \n do final # da string. o .splint('') que quebra a string em uma lista conforme o caracteres # que tem dentro das aspa...
python
# pylint: disable=invalid-name """Utility function to get information from graph.""" from __future__ import absolute_import as _abs import tvm from . import graph_attr def infer_shape(graph, **shape): """Infer the shape given the shape of inputs. Parameters ---------- graph : Graph The graph ...
python
BLACK = '\033[30m' RED = '\033[31m' GREEN = '\033[32m' YELLOW = '\033[33m' BLUE = '\033[34m' MAGENTA = '\033[35m' CYAN = '\033[36m' GRAY = '\033[90m' WHITE = '\033[37m' UNDERLINE = '\033[4m' END = '\033[0m'
python
# -*- coding: utf-8 -*- """ .. module:: Backend.utils :platform: Unix, Windows .. moduleauthor:: Aki Mäkinen <aki.makinen@outlook.com> """ __author__ = 'Aki Mäkinen' s_codes = { "OK": 200, "BAD": 400, "UNAUTH": 401, "FORBIDDEN": 403, "NOTFOUND": 404, "METHODNOTALLOWED": 405, "TEAPOT":...
python
import logging from common.DataSyncer import DataSyncer from common.logger import initialize_logger from models.User import User logger = logging.getLogger(__name__) initialize_logger(logger) class UserPartialSyncer: """ Sync only latest users info from API to db """ def __init__(self): sel...
python
import sys import ui if __name__ == "__main__": app = ui.QtWidgets.QApplication(sys.argv) MainWindow = ui.QtWidgets.QMainWindow() ui = ui.Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
python
import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv("student_scores.csv") # verisetinin boyutları dataShape = dataset.shape print(dataShape) print(dataset.head(7)) # datasetin başını gösterir. default değer 5'tir. print(dataset.tail(7)) # datasetin sonunu gösteri...
python
import os, sys variables_size = 3 dataset_name = "Epilepsy" class_dictionary = {} class_count = 1 dirname = os.path.abspath(os.path.dirname(sys.argv[0])) train_test_str = ["_TRAIN","_TEST"] for i in range(0,2): arff_data_flag = 0 series_count = 1 file_location = dirname + "/" + dataset_name + train_test_...
python
from .AlgerianMobilePhoneNumber import AlgerianMobilePhoneNumber
python
from automl_infrastructure.experiment.observations import SimpleObservation import numpy as np class Std(SimpleObservation): """ Implementation of standard deviation scores aggregation. """ def __init__(self, metric): super().__init__(metric) def agg_func(self, values): return np....
python
import torch import torchvision.transforms as T from pytorch_grad_cam import GradCAMPlusPlus from pytorch_lightning import LightningModule from pawpularity.augmentations import mixup from . import efficientnet, levit_transformer, swin_transformers, vision_transformers, learnable_resizer class Model(LightningModule): ...
python
# Generated by Django 3.1.5 on 2021-04-29 10:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('webpage', '0014_auto_20210428_0912'), ] operations = [ migrations.AddField( model_name='notification', name='read', ...
python
from __future__ import print_function # Time: O(n) # Space: O(1) # # Given a roman numeral, convert it to an integer. # # Input is guaranteed to be within the xrange from 1 to 3999. # class Solution: # @return an integer def romanToInt(self, s): numeral_map = {"I": 1, "V": 5, "X": 10, "L": 50, "C":100...
python
from mat_mult.mcm import memoized_mcm def test_memo(test_cases): for test in test_cases: dims = test['dims'] best_cost = memoized_mcm(dims=dims)[0] assert best_cost == test['cost']
python
########################################################################### # # 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 # # https://www.apache.org/...
python
import torch from change_detection_pytorch.encoders import get_encoder if __name__ == '__main__': sample = torch.randn(1, 3, 256, 256) model = get_encoder('mit-b0', img_size=256) res = model(sample) for x in res: print(x.size())
python
# -*- Mode: Python -*- # # This file calls PARC_FAME_Toolkit and determine possible fault modes # that exists in CyPhy Driveline Model. import sys, os, traceback, json, shutil from collections import OrderedDict import fetch script_dir = os.path.dirname(os.path.realpath(__file__)) output_dir = os.path.abspath(os.pat...
python
import logging from openpyxl import load_workbook, Workbook from openpyxl.utils.exceptions import InvalidFileException class XLSXWorkbook: def __init__(self, filename: str): self.filename = filename @property def filename(self): return self.__filename @filename.setter def filenam...
python
from __future__ import annotations from unittest import TestCase from tests.classes.simple_book import SimpleBook from tests.classes.simple_deadline import SimpleDeadline class TestUpdate(TestCase): def test_update_without_arguments_wont_change_anything(self): book = SimpleBook(name='Thao Bvê', published...
python
#CYBER NAME BLACK-KILLER #GITHUB: https://github.com/ShuBhamg0sain #WHATAPP NO +919557777030 import os CorrectUsername = "g0sain" CorrectPassword = "sim" loop = 'true' while (loop == 'true'): username = raw_input("\033[1;96m[#] \x1b[0;36m Enter Username\x1b[1;92m➤ ") if (username == CorrectUsername): pass...
python
# coding=utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import logging import re from scout_apm.compat import iteritems logger = logging.getLogger(__name__) key_regex = re.compile(r"^[a-zA-Z0-9]{20}$") class Register(object): __slots__ = ("app", "key", "hostname") ...
python
"""Compute dispersion correction using Greenwell & Beran's MP2D executable.""" import pprint import re import sys from decimal import Decimal from typing import Any, Dict, Optional, Tuple import numpy as np import qcelemental as qcel from qcelemental.models import AtomicResult, Provenance from qcelemental.util import...
python
__all__ = ["partitionN"] from partition import *
python
# yellowbrick.utils.helpers # Helper functions and generic utilities for use in Yellowbrick code. # # Author: Benjamin Bengfort <bbengfort@districtdatalabs.com> # Created: Fri May 19 10:39:30 2017 -0700 # # Copyright (C) 2017 District Data Labs # For license information, see LICENSE.txt # # ID: helpers.py [79cd8cf] ...
python
import os import random class Playlist: # maintains individual playlist def __init__(self, path): self.path = path self.clips = [] n = os.path.basename(self.path).split(".")[:-1] self.name = ".".join(n) self.desc = "" def load(self): # each line has the form...
python
# -*- coding: utf-8 -*- # Copyright (C) SME Virtual Network contributors. All rights reserved. # See LICENSE in the project root for license information.
python
# -*- coding: utf-8 -*- """ Created on Fri Nov 6 14:07:32 2020 """ from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap data = Dataset(r"C:\Users\Jiacheng Li\Desktop\Study\University of Birmingham Relevant\Final Year Project\NetCDF_Handling\NetCDF_da...
python
from __future__ import absolute_import from requests.exceptions import HTTPError from six.moves.urllib.parse import quote from sentry.http import build_session from sentry_plugins.exceptions import ApiError class GitLabClient(object): def __init__(self, url, token): self.url = url self.token = t...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-06 04:34 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): replaces = [(b'coding', '0001_initial'), (b'coding', '...
python
import json from nebulo.sql.reflection.function import reflect_functions from sqlalchemy.dialects.postgresql import base as pg_base CREATE_FUNCTION = """ create table account( id int primary key, name text ); insert into account (id, name) values (1, 'oli'); create function get_account(id int) returns accou...
python
# code modified from https://stackoverflow.com/questions/38401099/how-to-count-one-specific-word-in-python/38401167 import re filename = input('Enter file:') # you can input any .txt file here. you need to type the path to the file. # you can try the file in this folder: text_diamond.txt handle = open(filename, 'r')...
python
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='store-home-page'), path('login/', views.login, name='login-page'), path('signup/', views.signup, name='signup-page'), ]
python
N = int(input()) X = list(map(int,input().split())) menor = X[0] pos = 0 for k in range(1,N): if X[k] < menor: menor = X[k] pos = k print("Menor valor: %d" % (menor)) print("Posicao: %d" % (pos))
python
""" Utilities Tests --------------- """ from poli_sci_kit import utils def test_normalize(): assert sum(utils.normalize([1, 2, 3, 4, 5])) == 1.0 def test_gen_list_of_lists(): test_list = [0, 1, 2, 3, 4, 5, 6, 7, 8] assert utils.gen_list_of_lists( original_list=test_list, new_structure=[3, 3, 3]...
python
from tark import constants class DBSettings(object): def __init__(self, db_type=constants.DEFAULT_DB_TYPE, db_name=constants.DEFAULT_DB_NAME, db_user=constants.DEFAULT_DB_USER, db_password=constants.DEFAULT_DB_PASSWORD, db_node...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # (C) 2011 Alan Franzoni. APL 2.0 licensed. from unittest import TestCase from abc import abstractmethod from pydenji.ducktypes.function_copy import copy_raw_func_only, fully_copy_func @abstractmethod def example_func(a, b, c=1): return 1 class AbstractTestFunction...
python
# Standard utils file # Developed by Anodev Development (OPHoperHPO) (https://github.com/OPHoperHPO) import time import network def wifi_connect(SSID, PASSWORD): """Connects to wifi.""" sta_if = network.WLAN(network.STA_IF) if not sta_if.isconnected(): print('Connecting to network...') sta...
python