content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-10-10 20:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ip_manager', '0001_initial'), ] operations = [ migrations.AlterField( ...
#!/usr/bin/env python # license removed for brevity import rospy import actionlib from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal def movebase_client(): client = actionlib.SimpleActionClient('move_base',MoveBaseAction) client.wait_for_server() # Sequence goal_seq=[1.8878 , 0.031 , -0.001...
"""Run trakem alignment in parallel with MPI.""" import os import argparse import numpy as np import cv2 import re import glob from PIL import Image from tqdm import tqdm import logging import pkg_resources def parse_args(args=None): parser = argparse.ArgumentParser() parser.add_argument('input', default=Non...
import os from unittest import TestCase from unittest.mock import patch, Mock from lessweb_org.service.cookbook import CookbookService class TestCookbookService(TestCase): @patch('lessweb_org.utils.markdown_tool') def test_fetch_wiki_and_get_html(self, markdown_tool_patch): serv = CookbookService() ...
from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views urlpatterns = [ url(r'^$', views.home, name="home"), url(r'^review/(?P<pk>\d+)/$', views.review, name="review"), ]
#!/usr/bin/env python # # Script for getting Google Page Rank of page # Google Toolbar 3.0.x/4.0.x Pagerank Checksum Algorithm # # original from http://pagerank.gamesaga.net/ # this version was adapted from http://www.djangosnippets.org/snippets/221/ # by Corey Goldberg - 2010 # # important update (http://www.ser...
from datetime import timedelta from .interchange import WaypointType class ActivityStatisticCalculator: ImplicitPauseTime = timedelta(minutes=1, seconds=5) def CalculateDistance(act, startWpt=None, endWpt=None): import math dist = 0 altHold = None # seperate from the lastLoc variable,...
import requests import json from utils.validate_input import validate_required_field_existence from torre.constants import API_URL, URL, SEARCH_URL GENOME_USERNAME_FIELD = 'genome_username' LOCATION_FIELD = 'location' ROLE_FIELD = 'role' SALARY_RANGE_FIELD = 'salaryRange' MIN_SALARY_RANGE_FIELD = 'min' MAX_SALARY_RANG...
import os import random import numpy as np import tqdm from absl import app, flags from ml_collections import config_flags from tensorboardX import SummaryWriter import sys sys.path.append("../") from jax_rl.agents import AWACLearner, SACLearner,SACEMLPLearner from jax_rl.datasets import ReplayBuffer from jax_rl.eval...
#from https://www.hackerrank.com/challenges/countingsort4 def countingsort(ar): results=[[] for i in range(100)] for place,value in ar: results[place].append(value) retString= sun(results,[]) print ''.join(retString) # for x in range(arrayLength): # theValue=ar[x] # if (x<firstHalf): # theValue[1]="-" ...
import numpy as np import time import os import glob import cv2 import math from math import * from PIL import Image, ImageDraw from scipy.misc import imsave import matplotlib.pyplot as plt plt.ion() from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential, Model from keras.layers i...
import logging import requests from cacheops.simple import cache, CacheMiss from django.conf import settings from packaging import version from nautobot.core.celery import nautobot_task # Get an instance of a logger logger = logging.getLogger("nautobot.releases") @nautobot_task def get_releases(pre_releases=False)...
from test_sib import generate_references if __name__ == '__main__': generate_references()
import logging import os from igraph import Graph from parvusdb import GraphDatabase _path = os.path.dirname(__file__) class HeadTokenVisitor: __logger = logging.getLogger(__name__) def __init__(self, sentence_number): self._rules = """ MATCH {'is_head_token': True}(a) SET (assoc a ...
import json from pytest import mark import demistomock as demisto from CrowdStrikeFalconStreamingV2 import (get_sample_events, merge_integration_context) def test_get_sample_events_with_results(mocker): """ Given: - Samples events stored in the integration cont...
print('') print('') print('===== DESAFIO 4 =====') print('') n1 = input('Digite algo: ') print('Seu tipo é:',type(n1)) print('E alfanumérico:', n1.isalnum()) print('Ele e um número:', n1.isnumeric()) print('Ele e alfabético:', n1.isalpha()) print('Ele está em letras maiúsculas:', n1.isupper()) print('Ele está em letra...
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D # create cluster builder def cluster(center, radius=10, n=50): c = np.asarray(center) xx, yy, zz = np.random.uniform(c - radius, c + radius, size=(n, 3)).T return xx, yy, zz # crea...
#!/usr/bin/env python # coding: utf-8 # In[ ]: import pickle import datetime import time import sys from collections import Counter from operator import methodcaller # In[ ]: import pandas as pd import numpy as np import xlsxwriter # In[ ]: from repeat_analyzer.vectorizer import FeauterVectorizer, SequenceVe...
def convert_spreadsheet_to_unix(val): return 86400 * (val - 25569)
""" Functionality to synchronise properties """ import ast from os import path from cdd import emit from cdd.ast_utils import RewriteAtQuery, annotate_ancestry, find_in_ast, it2literal from cdd.pure_utils import strip_split from cdd.source_transformer import ast_parse, to_code def sync_properties( input_eval, ...
# -- -------------------------------------- # -- READ SALARIES IN DATABASE # -- --------------------------------------
import pytest from mock import Mock import json from pyptv3 import RoutesResponse, RouteResponse, StatusResponse, ONLINE, TRAIN, TRAM, BUS, VLINE_TRAIN, NIGHT_BUS class TestRoutesResponse: @pytest.fixture(scope="module") def response(self): return json.loads(""" { "routes": [ ...
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import argparse import os import pathlib from .onnx_model_utils import get_optimization_level, optimize_model def optimize_model_helper(): parser = argparse.ArgumentParser(f'{os.path.basename(__f...
# -*- coding: utf-8 -*- # Some basic scenarios with real-space encoding. __author__ = 'Luis Da Costa' __all__ = [ 'MUXProblem', 'ExploitTrackingScenarioObserver', ] import pathlib import math import queue import logging import time from typing import Tuple, Optional from util.general import get_free_file_n...
# Copyright (c) 2021 Emanuele Bellocchia # # 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, publish,...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def whiteside(path): """House Insulation: Whiteside's Data Mr Derek Wh...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Account class AccountDetail(UserAdmin): list_display = ( 'username','email', 'sector','first_name','middle_name','last_name',) search_fields = ('email','username',) readonly_fields = (...
# https://www.hackerrank.com/challenges/backreferences-to-failed-groups/problem Regex_Pattern = r"^\d\d(-?)\d\d\1\d\d\1\d\d$" # Do not delete 'r'. import re print(str(bool(re.search(Regex_Pattern, input()))).lower())
__auther__ = 'Xinyu Wang' import os import pathos import numpy as np import pandas as pd import multiprocessing import math from ._correlation_matrix_collector import correlation_matrix_collector def addiction_reader(path_file='/shared/healthinfolab/hcpdata/aal_corr_matrices/number_addiction/',Dp=True,Ab=True): ...
# -*- coding: utf8 -*- # # DB migration 002 by 2018-06-06 # # Table `name` uses md5 hash as BINARY(16) now # __author__ = 'sergey' __NUMBER__ = 20180606002 def run(manager): """ :param manager: Database manager :type manager: dedupsqlfs.db.sqlite.manager.DbManager|dedupsqlfs.db.mysql.manager.DbManager ...
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) setup( name = 'twarkov', version = '0.0.2', description = 'Markov generator built for generating Tweets from timelines', license = 'MIT', author = 'Amanda Pickering', author...
import matplotlib.pyplot as plt def remove_legend_title(ax, name_dict=None, fontsize=16): handles, labels = ax.get_legend_handles_labels() if name_dict is not None: labels = [name_dict[x] for x in labels] ax.legend(handles=handles, labels=labels, fontsize=fontsize) def adjust_legend_fontsize(ax, f...
#!python3 ### Exceptions ### class Error(Exception): pass class SignalTypeError(TypeError): pass class SignalValueError(ValueError): pass class FileIOValueError(ValueError): pass class CostValueError(ValueError): pass class UITypeError(TypeError): pass class UIValueEr...
import os def get_encryptions(): filelst = [item[:-3] for item in os.listdir(os.path.join(os.path.dirname(__file__))) if not item.endswith(".pyc")] return sorted(filelst)[1:]
from sqlalchemy.exc import IntegrityError from pf_py_common.pf_exception import PFException class PFFlaskDBException: EXCEPTION_TYPE = "FLASK_DB" def parse_integrity_error(self, exception: IntegrityError): try: if exception.orig and exception.orig.args and len(exception.orig.args) >= 1: ...
# Create a Python script that analyzes the PyBank records to calculate each of the following: # The total number of months included in the dataset # The net total amount of "Profit/Losses" over the entire period # The average of the changes in "Profit/Losses" over the entire period # The greatest increase in profits (d...
import json from math import inf # import rtree as rtree from pymunk import Vec2d from k_road.entity.entity_type import EntityType class CarlaMapBuilder: def __init__( self, parent: 'KRoadProcess', filename: str, ): """ Creates a roadway with lanes, c...
# tools from nexus.tools.check_zeros import check_zeros, remove_zeros from nexus.tools.combine_nexuses import combine_nexuses from nexus.tools.shufflenexus import shufflenexus from nexus.tools.sites import iter_constant_sites from nexus.tools.sites import iter_unique_sites from nexus.tools.sites import count_site_value...
from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import OriginValidator from django.conf import settings import notifications.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter(...
from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.core.validators import RegexValidator class User(AbstractUser): """Default user for talana_pru...
# TODO: docstrings # XXX: can this move into tests/? def is_file(path): return path.is_file() and not path.is_symlink() def is_link(path): return path.is_file() and path.is_symlink() def mkdir(path): try: path.mkdir(parents=True) except FileExistsError: pass def touch(path): ...
# Source Generated with Decompyle++ # File: decompyle (Python 2.7) import string restrictions = [ 'uudcjkllpuqngqwbujnbhobowpx_kdkp_', 'f_negcqevyxmauuhthijbwhpjbvalnhnm', 'dsafqqwxaqtstghrfbxzp_x_xo_kzqxck', 'mdmqs_tfxbwisprcjutkrsogarmijtcls', 'kvpsbdddqcyuzrgdomvnmlaymnlbegnur', 'oykgmfa_cmr...
"""Tests to assure the FormProcessMapper Service""" from formsflow_api.services import FormProcessMapperService from tests.utilities.base_test import get_form_service_payload form_service = FormProcessMapperService() def test_form_get_all_mappers(session): rv = form_service.get_all_mappers(page_number=0, limit=0...
__author__ = 'davidfreestone' # TODO(David): This might be easy to put into Cython import numpy as np from scipy.special import gamma def rrand(r, rho, N, size=1): if np.abs(rho)>=1: return np.ones(size) y = rcdf(r, rho, N) u = np.random.rand(size) idx = np.searchsorted(y, u) return r[id...
import FWCore.ParameterSet.Config as cms from PhysicsTools.NanoAOD.nano_eras_cff import * from PhysicsTools.NanoAOD.common_cff import * from PhysicsTools.NanoAOD.jets_cff import fatJetTable as _fatJetTable from PhysicsTools.NanoAOD.jets_cff import subJetTable as _subJetTable jetMCTable = cms.EDProducer("SimpleCandida...
import os #Path for the INPUT file to get the network topology information from the user my_path = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(my_path, "Net_topology.txt") #Get the data from the user to create the topology document by writing the file with open(path, "w") as f: number_of_...
import logging import deeprank.config class useLevelsFilter(logging.Filter): def __init__(self, levels): if not isinstance(levels, (tuple, list)): levels = (levels, ) self.levelnos = [getattr(logging, i) for i in levels] def filter(self, record): if record.levelno in self...
#SPDX-License-Identifier: MIT from augur.application import Application from augur.augurplugin import AugurPlugin from augur import logger class MetricsStatusPlugin(AugurPlugin): """ This plugin serves as an example as to how to load plugins into Augur """ def __init__(self, augur): self.__metr...
# # This file is part of softboxen software. # # Copyright (c) 2020, Ilya Etingof <etingof@gmail.com> # License: https://github.com/etingof/softboxen/LICENSE.rst # import json import sys import unittest from unittest import mock from softboxen.client.resources.box import box from softboxen.client.resources.box import...
import json import logging from dateutil.parser import parse from datetime import datetime from ugeapi.get_hostip import get_hostip def process_host(host_data: object, time: int) -> list: """ Process host data according to the schema """ all_data = {} data_points = [] jobs_detail = {} c...
# Copyright (C) 2021-2022 Modin authors # # SPDX-License-Identifier: Apache-2.0 """Core base actor specific functionality.""" from .common import filter_arguments class ActorMethod: """ A class that is base for any actor method class specific for the backend. This wraps an instance of the child class, ...
import numpy as np import pytest from conftest import prostate_data from autorad.visualization.plot_volumes import BaseVolumes image_path = prostate_data["img"] mask_path = prostate_data["seg"] @pytest.mark.parametrize("constant_bbox", [True, False]) def test_from_nifti(constant_bbox): volumes = BaseVolumes.fro...
# Copyright 2016 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...
import unittest import tkp.db.consistency as db_consistency import tkp.db from tkp.testutil.mock import Mock class MockResult(object): def __init__(self, result): self.result = result def fetchone(self): return self.result class TestDBConsistencyCheck(unittest.TestCase): def test_is_consi...
from abc import ABC, abstractmethod class Config(ABC): production = False @property @abstractmethod def attestation_verifier_class(self): ... @property @abstractmethod def assertion_verifier_class(self): ...
import sys from doubly_linked_list import DoublyLinkedList class Queue: def __init__(self): self.size = 0 # Why is our DLL a good choice to store our elements? self.storage = DoublyLinkedList() def enqueue(self, value): # add the value to the DLL self.storage.add_to_ta...
from functools import reduce import numpy as np import torch from .kernels import GaussianKernel class KernelRegressionEnvironment: def __init__(self, num_basis_elems, d, kernel, noise=0.1, device="cpu"): self.num_basis_elems = num_basis_elems self.d = d # We don't want to training the e...
from __future__ import unicode_literals import os import click DOT = "\u2603" DASH = "\u26C4\u26C4\u26C4" MORSE = { 'a': (DOT, DASH), 'b': (DASH, DOT, DOT, DOT), 'c': (DASH, DOT, DASH, DOT), 'd': (DASH, DOT, DOT), 'e': (DOT,), 'f': (DOT, DOT, DASH, DOT), 'g': (DASH, DASH, DOT), 'h'...
import streamlit as st from pydantic import BaseModel from typing import Union import streamlit_pydantic as sp class PostalAddress(BaseModel): street: str city: str house: int class EmailAddress(BaseModel): email: str send_news: bool class ContactMethod(BaseModel): contact: Union[PostalA...
from django.contrib import admin from readme.models import Readme # Register your models here. admin.site.register(Readme)
from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from .app_urls import( register_url, reset_password_url, login_url, new_passord_url, activate_url ) from .test_data import valid_user, invalid_token, expired_token class RequestNewPasswordTestCase(Te...
# -*- coding: utf-8 -*- """ @author: Vitor Baldoino Think Python, 2ed. Chapter 3. """ def right_justify(s): num_char = len(s) missing_chars = 70 - num_char print(' ' * missing_chars + s)
# Copyright 2020 Makani Technologies 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...
from enum import Enum from dapr.proto import common_v1 from typing import Dict, Optional, Union class Consistency(Enum): """Represents the consistency mode for a Dapr State Api Call""" unspecified = common_v1.StateOptions.StateConsistency.CONSISTENCY_UNSPECIFIED # type: ignore eventual = common_v1.StateO...
from actstream.models import Action from mayan.apps.common.tests.base import GenericViewTestCase from ..events import event_role_created, event_role_edited from ..permissions import permission_role_create, permission_role_edit from .mixins import RoleTestMixin, RoleViewTestMixin class RoleEventsTestCase(RoleTestMi...
#!/usr/bin/python # -*- coding: utf-8 -*- import base64 import sys from os.path import join, dirname, realpath from flask import Flask, request, jsonify import cifar_cnn.details as details from nas_cnn.prediction import get_class from prediction import get_next sys.path.append('.') app = Flask(__name__) UPLOADS_PATH =...
import csv import hashlib import json from pathlib import Path from PIL import Image import torchbearer as tb from model import SKETCHES, RECEIVER_IMAGES from torchbearer import Callback class GameLogger(Callback): def __init__(self, args, transform=None, sketch_transform=None): self.transform = transfo...
import os import logging import warnings import argparse import numpy as np from tqdm import tqdm import torch from torch.utils.data import DataLoader from datasets.generic import Batch from datasets.flyingthings3d_hplflownet import FT3D from datasets.kitti_hplflownet import Kitti from model.RAFTSceneFlow import RSF ...
from ..client import Client class ProductTargeting(Client): def create_targets(self, params): self.uri_path = "/v2/sp/targets" self.method = "post" self.data = params return self.execute() def update_targets(self, params): self.uri_path = "/v2/sp/targets" self...
import pandas as pd import numpy as np import seaborn as sn import matplotlib.pyplot as plt import time dataset = pd.read_csv('new_appdata10.csv') ## Data Preprocessing response = dataset["enrolled"] dataset = dataset.drop(columns = 'enrolled') from sklearn.model_selection import train_test_split X_tr...
from gaia.EnvironmentLauncher import EnvironmentLauncher class EnvironmentManager: def __init__(self, gaia): self.gaia = gaia self.ensure_eb_app_in_all_regions() self.environment_launchers = [] self.cb = None def ensure_eb_app_in_all_regions(self): for region in self....
def setup(): size(500, 500) smooth() background(0) strokeWeight(1) i = 0 k = 1 flug = 1 def draw(): global i global k global flug stroke(i, 20) if(flug == 1): line(mouseX, mouseY, 500, random(0, 500)) else: line(mouseX, mouseY, 0, random(0, 500)) ...
# -*- coding: utf-8 -*- ''' QSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems This module is developed by: Joy Zhang <joycheung1994@gmail.com> This module is under the University of Illinois/NCSA Open Source License. Please refer to https://github.com/QSD-Group/QSDsan/blob/main/...
class BaseScheme(object): """ Base class for versioning schemes """ def __init__(self, comparable, printable=None): """ Arguments: comparable -- some object which can be compared to other objects of the same type printable -- a printable representation of the...
from typing import Tuple import cv2 import os import numpy as np import math FileNameHighContrast = "HighContrastImage_Operation_" FileNameLowContrast = "LowContrastImage_Operation_" OperationName = ["TH_127","Mean","Median"] def Save_Image(filename,img): directory = path = r'IMAGEPATH' os.chdir(...
n1 = int(input('Digite um valor:\n')) n2 = int(input('Digite outro valor:\n')) soma = n1+n2 print(f'A soma de {n1} e {n2} vale {soma}')
import abc from abc import abstractmethod class Dataset(abc.ABC): @abstractmethod def fetch_entries(self): """ Returns fetched entries as Iterable[dict]. Each entry is a dict with the following keys: - "content": raw content of the entry (e.g., HTML) - "...
import matplotlib.pyplot as plt import numpy as np import math x = np.random.randint(10, 50, 24) y = np.random.randint(12, 60, 24) fig, ax = plt.subplots() ax.scatter(x, y) ax.set_title('Random points') plt.show() grid_size = 1 h = 10 x_min = min(x) x_max = max(x) y_min = min(y) y_max = max(y) x_grid = np.arange ...
import re from pathlib import Path import pytest from pydantic import ValidationError import copier from copier.config.factory import make_config from copier.config.objects import DEFAULT_EXCLUDE, ConfigData, EnvOps from copier.config.user_data import ( InvalidConfigFileError, MultipleConfigFilesError, lo...
from .csv import CSV # noqa: F401 from .kafka import Kafka # noqa: F401
""" The ReportableQty class """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain right...
# python3 # Copyright 2021 InstaDeep Ltd. 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 applic...
for i in range(int(input())): n = int(input()) d = {} a = [int(j) for j in input().split()] for j in a: if(j in d): d[j]+=1 else: d[j]=1 if(max([j for j in list(d.values())]) <= int(n/2)): print('Yes') else: print('No')
import sys import typing import numba as nb import numpy as np MOD = 998_244_353 S = typing.TypeVar('S') @nb.njit def fw_build( op: typing.Callable[[S, S], S], a: np.ndarray, ) -> np.ndarray: n = len(a) fw = np.empty((n + 1, ) + a.shape[1:], np.int64) fw[1:] = a.copy() for i in range...
from mlep import __version__ def test_version(): assert __version__ == '0.1.1.dev3'
# jogue par ou impar com o computador, #o jogo será interrompido quando o jogador perder; #mostrandoo a quantidade de vitorias consecutivas from random import randint from time import sleep dedosmao = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] vitórias = 0 print("~^~"*16) print(" P A R OU I M P A R!") print("~^~"*16...
import os import flopy import numpy as np def test_usg_disu_load(): pthusgtest = os.path.join('..', 'examples', 'data', 'mfusg_test', '01A_nestedgrid_nognc') fname = os.path.join(pthusgtest, 'flow.disu') assert os.path.isfile(fname), 'disu file not found {}'.format(fname) ...
# Faça um algoritmo que leia um preço de um produto, # e mostre seu novo preço, com 5% de desconto. p = float(input('Preço do produto(R$): ')) d = float(input('Desconto (%): ')) pcd = p-(p*(d/100)) print('O valor com {}% de desconto é R${:.2f}'.format(d, pcd))
from operator import itemgetter from nodeconductor.logging import elasticsearch_client from nodeconductor.logging.log import event_logger class ElasticsearchDummyClient(elasticsearch_client.ElasticsearchClient): # We do not need connection with real elasticsearch def __init__(self): pass def _g...
from .node import Tnode_Op, Onode_Op, Anode_Op from .base import * from aognet.aog.aog_1d import * eps = 2e-5 def aog_unit(data, cfg, aog, in_channels, out_channels, stride=(1, 1), bn_mom=0.9, workspace=512, name=''): def calculate_slices(dim, channels): slices = [0] * dim for i in range(channels...
#author Kollen Gruizenga #recursive function to take string S and int N, return #string S repeated N times def repeatNTimes(S, N): if N == 0: return '' else: return S + repeatNTimes(S, N-1)
import django from django.contrib import admin from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView if django.VERSION >= (2, 0): from django.urls import path urlpatterns = [ path("admin/", admin.site.urls), path( "graphql", csrf_exempt(...
from math import sqrt, log import numpy as np from .IndexAlgorithm import IndexAlgorithm class UCBTuned(IndexAlgorithm): """ Ref: Finite-time analysis of the multiarmed bandit problem Peter Auer, Nicolò Cesa-Bianchi and Paul Fischer. """ def start_game(self): self.t = 1 self....
__doc__ = """ QCP rotation calculation This is an RMSD and optimal rotation calculator, written in pure Python. The goal of this is to allow the code to be run in a JIT compiler such as PyPy, Jython that cannot interface with extern C modules, such as numpy. The algorithm was originally developed by Douglas Theobal...
# -*- coding: utf-8 -*- """ zang.domain.carrier_lookup ~~~~~~~~~~~~~~~~~~~ `Carrier` model """ from zang.domain.base_resource import BaseResource class CarrierLookup(BaseResource): _strs = [ 'sid', 'account_sid', 'phone_number', 'network', 'country_code', 'mnc', ...
import torch.nn as nn import torch.nn.functional as F class CustomL1Loss(nn.Module): def __init__(self, reduction='mean'): super().__init__() if reduction == 'sum': self.sum_outputs = True elif reduction == 'sum': self.sum_outputs = False else: ...
# # This file is part of `gitflow`. # Copyright (c) 2010-2011 Vincent Driessen # Copyright (c) 2012-2013 Hartmut Goebel # Distributed under a BSD-like license. For full terms see the file LICENSE.txt # from unittest2 import TestCase, skip from gitflow.core import GitFlow from tests.helpers.factory import create_git_r...
import time import datetime from stocks.models import Stock from django.shortcuts import get_object_or_404 def process_user_agent(data): request = data['request'] remote_addr = request.META.get('HTTP_USER_AGENT') if remote_addr == None: return "" else: return remote_addr def process_se...
#def hook_fsb(pt): # pt.verbose = True # fsb_addr = 0x0000000000000C00 # hook_addr = pt.inject(asm=r''' # mov rsi, rdi # push 0x0a0d7325 # mov rdi, rsp # add rsp, 8 # ret # ''') def hook_add(pt): pt.verbose = True ASLR = 0x0000555555554000 hello, size = pt.inject(raw='hello world...
import pandas as pd # The database hockey_players = pd.read_csv('data/canucks.csv') hockey_players