content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
class Loja(models.Model):
"""
Model responsável por representar uma Loja Física
"""
#criar uma app para shopping e vincular uma loja a um shopping.
... |
# Copyright 2016 Cisco Systems, Inc. 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 requir... |
# Import libs
import os
return getmarkdown(mod)
# Taken from utils.sys_utils
def get_all_directories_from_path(directory_path):
"""
directory_path:
Given path that already exists.
Returns:
Returns back a set a directories with the provided path.
"""
dirs_in_paths = []
for (di... |
import re
from vee.requirement import RequirementSet
class SolveError(ValueError):
pass
def verbose(depth, step, *args):
print('{}{}'.format(' ' * depth, step), *args)
def solve(*args, **kwargs):
"""Solve abstract requirements into concrete provisions.
:param RequirementSet requires: The abs... |
stocks = {
'GOOG': 234.43,
'FB': 132.54,
'AAPL': 543.21,
'YAHOO': 23.34
}
# get the minimum value
print(min(zip(stocks.values(), stocks.keys())))
# get the maximum value
print(max(zip(stocks.values(), stocks.keys())))
# sort the dictionary prices
print(sorted(zip(stocks.values(), stocks.keys())))
# sort... |
# coding: utf-8
import pprint
import re
import six
class ListImagesRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value ... |
import pytest
pytest.importorskip('eth.utils.blake') # noqa E402
from eth.utils.blake import blake
from tests.core.helpers import (
greater_equal_python36,
)
@greater_equal_python36
def test_blake():
output = blake(b'helloworld')
assert len(output) == 32
assert output == b'\xf2@\xa8\x02\x04\x1b_\xaf... |
import os
import shutil
import six
import pytest
import numpy as np
from pyshac.config import hyperparameters as hp, data
# compatible with both Python 2 and 3
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
def deterministic_test(func):
@six.wraps(func)
def wrapper(*args, **kw... |
import os
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from course.models import Course
from .constants import PERSON_STATUSES
class Person(models.Model):
class Meta:
verbose_name = 'person'
verbose_name_plural = 'persons'
orderi... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
#
# Test our constraints parser
#
import unittest
from juju import constraints
class TestConstraints(unittest.TestCase):
def test_mem_regex(self):
m = constraints.MEM
self.assertTrue(m.match("10G"))
self.assertTrue(m.match("1G"))
self.assertFalse(m.match("1Gb"))
self.ass... |
import datetime
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Tuple
from urllib.parse import parse_qs, urlparse
import requests
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.pri... |
from leg_data import *
from hex_walker_data import *
TORSO_ARM_TABLE = {
"NEUTRAL" : Leg_Position(0, 45, 45),
"ON_HIP" : Leg_Position(0, 90, 0),
"UP" : Leg_Position(90, 0, 180),
"STRAIGHT_OUT" : Leg_Position(90,90,90),
"STRAIGHT_FOR" :Leg_Posi... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 6 20:47:43 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... |
# The MIT License (MIT) # Copyright (c) 2014-2017 University of Bristol
#
# 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... |
import cv2
class Selector:
window_name: str
dragging: bool
def __init__(self, window_name) -> None:
self.window_name = window_name
self.dragging = False
self.points = ((0, 0), (0, 0))
self.on_selecting = lambda rect: None
self.on_selected = lambda rect: None
... |
import pytest
from sqlalchemy.orm import Session
from app.orm import Server
from app.service import power_off
class MockSession(Session):
def commit(self):
pass
def test_mock():
mock = MockSession()
server = Server()
server.id = 1
server.power_on = True
assert power_off(mock, serve... |
# KMP Algorithm
import time
start_time = time.time()
def KMPurlMatch(keyword, url):
Key = len(keyword)
Url = len(url)
# create lps[] that will hold the longest prefix suffix
# values for keyword
lps = [0]*Key
j = 0 # index for keyword[]
# Preprocess the keyword (calculate lps[... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
import os
import datetime
import codecs
import re
try:
import numpy as np
import pandas as pd
except:
... |
import libtcodpy as libtcod
SCREEN_WIDTH = 16
SCREEN_HEIGHT = 16
noise2d = libtcod.noise_new(1)
m = libtcod.heightmap_new(SCREEN_WIDTH, SCREEN_HEIGHT)
for y in range(SCREEN_HEIGHT):
for x in range(SCREEN_WIDTH):
n = libtcod.noise_get(noise2d, [2.0 * x / SCREEN_WIDTH - 1.0, 2.0 * y / SCREEN_HEIGHT - 1.0])
n = (n... |
from django.db import models
from django.urls import reverse
class Book(models.Model):
title = models.CharField(max_length=50, verbose_name="Название книги")
description = models.TextField(verbose_name="Описание книги")
left = models.PositiveIntegerField(verbose_name="Книг на складе")
image = models.I... |
# PYTHON - MIT - UNICAMP
# =============================================================================
# Created By : Matheus Percário Bruder
# Created Date : February 11th, 2021
# ============================================================================
def print_grid(grid):
for l in grid:
print(l... |
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField(max_length=500)
slug = models.SlugField(max_length=200)
created = models.DateTimeField(aut... |
from trello import TrelloClient
import json
from config.config import path_credentials_directory
def get_client():
"""
Authorize in Trello.
:return: Authenticated client object.
"""
with open(path_credentials_directory / "trello_credentials.json", "r") as file:
creds = json.load(file)
... |
import unittest
from genomicinfo.entity_extraction.bow.bowdictionary import BOWdictionary
class TestBOWdictionary(unittest.TestCase):
def setUp(self) -> None:
self.extractor = BOWdictionary()
def test_extract(self):
# Bogus sentence for testing
ext = self.extractor.extract('Upon rea... |
import json
import codecs
import pandas as pd
import numpy as np
csv_path = "./fixed_tweets.csv"
save_path = "./fixed_tweets.json"
df = pd.read_csv(csv_path, header=None, encoding = "utf-8")
df.columns =["tweet"]
df_json = {"konomania-tweets" : df.to_dict(orient='records')}
# text = json.dumps(df_json, sort_keys=Tr... |
# Title: 레드 블루 스패닝 트리
# Link: https://www.acmicpc.net/problem/4792
import sys
sys.setrecursionlimit(10 ** 6)
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))
read_list_words = lambda: sys.stdin.readline().strip().split(' ')
class UnionFind:
def __init__(self, max_count):
... |
# Copyright 2022 Fuzz Introspector 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 ... |
import os
import urllib.request
import requests
from PIL import Image
from data_type_class import Data_type
from locale_class import Locale
def get_image_from_api(source: str, source_type: str, lol_version: str) -> Image:
if os.path.isfile(f'./temp/{source_type}/{source}.png'):
return Image.open(f'./temp/... |
# Copyright 2015 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 numpy as np
import random
def activate(weights, inputs):
activation = weights[-1]
for i in range(len(weights) - 1):
activation += weights[i] * inputs[i]
return activation
def transfer(activation):
return 1.0 / (1.0 + np.exp(-activation))
def forward_propagate(network,... |
"""
if not os.path.exists(self.history_file):
open(self.history_file, 'a+').close()
readline.read_history_file(self.history_file)
readline.set_history_length(self.history_length)
atexit.register(readline.write_history_file, self.history_file)
readline.parse_and_bind('set enable-keypad on')
readline.set_completer... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import torch
import torch.utils.data
from opts import opts
from models.model import create_model, load_model, save_model
from models.data_parallel import DataParallel
from logger ... |
import numpy as np
import theano
from theano.tensor import as_tensor_variable
from theano.gof import Op, Apply
from theano.gradient import DisconnectedType
from gp_kernel import kernel, symbolic_kernel
from fast_gp_block import post_mean, grad_post_mean
from fast_gp_block import post_cov_ys, grad_cov_ys, post_cov_y, gr... |
# Copyright © 2011 MLstate
#
# This file is part of Opa.
#
# 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,... |
"""
Implements an EYAML-capable version of YAML Path.
Copyright 2018, 2019 William W. Kimball, Jr. MBA MSIS
"""
import re
from subprocess import run, PIPE, CalledProcessError
from os import access, sep, X_OK
from shutil import which
from typing import Any, Generator, List, Optional
from ruamel.yaml.comments import Co... |
from setuptools import setup, find_packages
URL = "https://github.com/uzh-dqbm-cmi/data-traffic-control"
PROJECT_URLS = {
"Bug Tracker": "https://github.com/uzh-dqbm-cmi/data-traffic-control/issues",
"Documentation": "https://data-traffic-control.readthedocs.io/en/latest/",
"Source Code": "https://github.c... |
from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib import admin
from corehq.apps.case_importer.tracking.models import CaseUploadRecord
class CaseUploadRecordAdmin(admin.ModelAdmin):
list_display = ['domain', 'task_id', 'upload_id']
search_fields = ['task_id__e... |
from setuptools import setup, find_packages
with open("README.md", "r") as readme_file:
readme = readme_file.read()
requirements=["scipy>=1.3"]
setup(
name="HCRSimPY",
version="1.0.2",
author="Kevin Hannay",
author_email="khannay24@gmail.com",
description="A package to simulate and analyze hum... |
"""
The package provides a Space Imaging Simulator for Proximity Operations (SISPO)
The package creates images of a 3D object using blender. The images are render
in a flyby scenario. UCAC4 star catalogue to create the background. Afterwards
hese images are used with openMVG and openMVS to reconstruct the 3D model and... |
# Copyright 2016 VMware, Inc. 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 a... |
from .return_class import AbstractApiClass
from .nested_feature import NestedFeature
from .point_in_time_feature import PointInTimeFeature
class Schema(AbstractApiClass):
"""
A schema description for a feature
"""
def __init__(self, client, name=None, featureMapping=None, featureType=None, dataTy... |
import time
import pytest
from polog.core.utils.time_limit import time_limit
def test_integer():
"""
Проверяем, что лимит устанавливается и срабатывает с числом в качестве аргумента.
"""
quant = 0.001
function = lambda number: [time.sleep(quant) for x in range(number)]
wrapper = time_limit(... |
""" Starting point of the script is a saving of all singular values and vectors
in alex_save/
We perform the 100-optimization implemented in optim_nn_pca_greedy
"""
import math
import torch
import torchvision
import numpy as np
from lipschitz_utils import *
from max_eigenvalue import k_generic_power_method
from exp... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2021 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Community PID provider."""
from invenio_pidstore.errors import PIDAlreadyExists, ... |
class Sensor(object):
def __init__(self, name, value, unit, status, lower_non_recoverable=None, lower_critical=None,
lower_non_critical=None, upper_non_critical=None, upper_critical=None, upper_non_recoverable=None):
self.name = name
self.value = value
self.unit = unit
... |
import random
import datetime
seed = datetime.datetime.now().microsecond
random.seed(seed)
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
letters = [x for x in letters]
for i in range(10):
alphabet1 = random.choice(letters)
alphabet2 = random.choice(letters)
number1 = random.randint(0, 9)
number2 = random.ran... |
"""
Summary
-------
ASTRODF
Based on the sample average approximation, the solver makes the surrogate model within the trust region at each iteration k.
The sample sizes are determined adaptively.
Solve the subproblem and decide whether the algorithm take the candidate solution as next ieration center point or no... |
"""
O Pandas fornece muitas "funções de resumo" simples que reestruturam os dados de alguma maneira útil.
"""
import pandas as pd
reviews = pd.read_csv("./summary_maps/summary_functions_1/census.csv")
print(reviews.describe())
# print(reviews.education.describe()) # faz sentido só com dados do tipo númerico
print(re... |
# revese list without using built in function or wihout taking another list
a=[1,2,3,4,5]
i=0
j=len(a)-1
while i<j:
t=a[i]
a[i]=a[j]
a[j]=t
i+=1
j-=1
print("revese of a= ",a)
## or
a=a[len(a)-1::-1]
print(a)
##############################################################
### reverse list taking aother list usin... |
from .utils.dataIO import fileIO
from .utils import checks
from __main__ import send_cmd_help
from __main__ import settings as bot_settings
# Sys.
import discord
from discord.ext import commands
from operator import itemgetter, attrgetter
from copy import deepcopy
import random
import os
import sys
import time
import l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018-2021 Accenture Technology
#
# 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
#... |
class AromaticSystem:
def __init__(self, aromatic_system_id, atoms):
self.id = aromatic_system_id
self.atoms = set(atoms)
for atom in self.atoms:
atom.aromatic_system = self
self.electrons = set()
self.bonds = set()
self.set_bonds()
for bond in sel... |
"""
Plotting lib for regression prediction
"""
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import pdb
import pandas as pd
import seaborn as sns
sns.set_style('whitegrid')
def regression_surface_plot(Y, X1, X2, X3, ols_object, Y_lab... |
# Separando dígitos de um número
num = str(input('Digite um número de 0 a 9999: '))
n = num.zfill(4)
fri = f'Número Digitado: {num}'
print('')
print(f'{fri:^30}')
print('=#=' * 10)
print(f'Unidade: {n[3]}')
print(f'Dezena: {n[2]}')
print(f'Centena: {n[1]}')
print(f'Milhar: {n[0]}')
print('=#=' * 10)
'''num = int(input(... |
class Literal(object):
"""
A literal value that should not be escaped when used in an XPath query.
"""
def __init__(self, value):
"""
Args:
value (str): The raw value.
"""
self.value = value
|
"""
Labels are the Base class you derive your Labels from. A few simple Labels are
provided for you.
"""
from typing import Tuple
from PIL import Image
def _coord_add(tup1, tup2):
"""add two tuples of size two"""
return (tup1[0] + tup2[0], tup1[1] + tup2[1])
class Label:
"""Base class for all labels
... |
#! /usr/bin/env python3
#This code prints out the IP , port and port-state from a list
my_list = ["192.168.0.5", 5060, "UP" ]
print("The first item in the list (IP): " + my_list[0])
print ("The second item in the list (port): " + str(my_list[1]))
print ("The third item in the list (state): " + my_list[2])
new_list = ... |
#!/usr/bin/env python
#
# Copyright 2013 Andy Gimma
#
# 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... |
# -*- coding: utf-8 -*-
# 1. Standard library imports:
# 2. Known third party imports:
# 3. Odoo imports (openerp):
from openerp import api, fields, models
import openerp.addons.decimal_precision as dp
# 4. Imports from Odoo modules:
# 5. Local imports in the relative form:
# 6. Unknown third party imports:
cla... |
import math
import numpy as np
def build_rotation_matrix(ax, ay, az, inverse=False):
"""Build a Euler rotation matrix.
Rotation order is X, Y, Z (right-hand coordinate system).
Expected vector is [x, y, z].
Arguments:
ax {float} -- rotation angle around X (radians)
ay {float} -- rotat... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.1
# kernelspec:
# display_name: ita
# language: python
# name: ita
# ---
import numpy as np
import matplot... |
from apriorib.apriorib import Apriori |
#!/usr/bin/env python
# THIS EXAMPLE ISN'T COMPLETE OR WORKING
# it deadlocks (don't remember)
# there's no "self" for main in python
import inspect
import sys
import os.path
sys.path[0:0] = [ os.path.join( os.path.dirname( inspect.getabsfile( inspect.currentframe() ) ), '..', '..', '..', 'lib' ) ]
sys.path[0:0] = ... |
#!/usr/bin/env python
from __future__ import print_function
from builtins import zip
import os, sys
fin = open(sys.argv[1]).readlines()
template = open(sys.argv[2]).readlines()
def determine_format_string(numstr): # Returns something like "% 8.3f"
spl = numstr.split('.')
if len(spl) != 2:
return Exce... |
import sys
if sys.version_info >= (3, 4):
import acouchbase.py34only.iterator
sys.modules['acouchbase.iterator'] = acouchbase.py34only.iterator
if sys.version_info < (3,7):
import asyncio
acouchbase.py34only.iterator.AioBase.__aiter__=asyncio.coroutine(acouchbase.py34only.iterator.AioBase.... |
"""Renders a Threes board into an ANSI string to be printed to the console."""
from colorama import Fore, Back, Style
from threes import threes_util
# Name and colors to use for printing each possible tile.
TILE_NAMES = [" ", " -1- ", " -2- "] + [
"{:^5} ".format(3 * 2 ** i) for i in range(13)
]
BACK_COLO... |
import argparse
from src.segment import InstanceSegmenter
# construct the argument parse and parse the arguments
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--image", required=True,
help="path to input image")
parser.add_argument("-c", "--confidence", type=float, default=0.5,
... |
"""
constants.py module for ocean.tests
"""
PG_DATA_DIR = 'data'
|
import datetime
import pandas as pd
class solar_data:
# def __init__(self):
# '''
# 'data' is a dataframe
# '''
# self.data_df = data
def ingest_pvwatts(self, data):
'''
data must be a dataframe object.
This function adds a datetime column
'''
... |
a = input().split(',')
t = 0.0
for i in range(len(a)):
if int(a[i]) >=20:
t += int(a[i])
else:
t += int(a[i])*1.07
print(t)
|
# Generated by Django 2.0.3 on 2018-03-16 20:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('patientbasicinfo', '0005_auto_20180316_2003'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='b... |
import torch
from torch.nn.modules.utils import _pair
from torch.nn.functional import conv2d, conv_transpose2d
from numpy import prod, sqrt
class EqualizedConv2d(torch.nn.Module):
"""
Convolutional layer with equalized learning rate as suggested in section 4.1 of
https://research.nvidia.com/sites/default/... |
import math
import numpy as np
import torch
from utils import to_tensor, accumulate, batch_normalize
def calculate_future_rewards(rewards, gamma):
"""rewards is list of episodes where length of list is max_episode_length.
And each elements is rewards of each batches. So, shape of the rewards becomes [max_ep... |
# Copyright 2021 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Generated by Django 2.1.2 on 2018-10-14 19:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('travel', '0004_auto_20180306_1507'),
]
operations = [
migrations.CreateModel(
name='ExternalRef... |
# Generated by Django 2.2.17 on 2021-06-14 12:34
from typing import Optional
from django.db import migrations
from django.utils import timezone
AGREE = "agree"
DECLINE = "decline"
def reconsent(Consent, old_consent, term_option):
old_consent.archived_at = timezone.now()
old_consent.save()
Consent.objec... |
#!/bin/env python
# -*- coding: utf-8 -*-
##
# test_job.py: Checks correctness of azure.quantum.job module.
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
## IMPORTS ##
import unittest
import json
import uuid
import os
import time
from azure.quantum import Workspa... |
import tensorflow as tf
distr = tf.contrib.distributions
# import numpy as np
# from tqdm import tqdm
# import os
# import matplotlib.pyplot as plt
# from datetime import timedelta
#
# import time
# Embed input sequence [batch_size, seq_length, from_] -> [batch_size, seq_length, to_]
def embed_seq(input_seq, from_, ... |
import math
from pypy.interpreter.error import OperationError
from pypy.interpreter.gateway import ObjSpace, W_Root, NoneNotWrapped
class State:
def __init__(self, space):
self.w_e = space.wrap(math.e)
self.w_pi = space.wrap(math.pi)
def get(space):
return space.fromcache(State)
def math1... |
import ConfigParser
import unittest
import telegram
import telegram_commands.mc as mc
class TestMC(unittest.TestCase):
def test_mc(self):
keyConfig = ConfigParser.ConfigParser()
keyConfig.read(["keys.ini", "..\keys.ini"])
bot = telegram.Bot(keyConfig.get('Telegram', 'TELE_BOT_ID'))
... |
#!/usr/bin/env python3
import os
from os import path
import subprocess
def run_command(args, dry_run=False, verbose=False):
if dry_run or verbose:
print(" ".join(args))
if not dry_run:
subprocess.run(args, check=True)
def main():
import argparse
parser = argparse.ArgumentParser(
... |
import os
import shutil
import tinychain as tc
TC_PATH = "host/target/debug/tinychain"
PORT = 8702
def start_host(name, clusters=[], overwrite=True):
port = PORT
if clusters:
port = tc.uri(clusters[0]).port()
port = port if port else PORT
config = []
for cluster in clusters:
... |
import logging
import os
import tempfile
import time
from typing import List, Tuple
import psycopg2
import requests
from django.http.response import HttpResponseRedirect
from django.utils import timezone
from qfieldcloud.authentication.models import AuthToken
from qfieldcloud.core.geodb_utils import delete_db_and_role... |
# Generated by Django 3.0.4 on 2020-05-12 15:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('maintenancemanagement', '0009_auto_20200505_2145'),
]
operations = [
migrations.RemoveField(
model_name='task',
name='fields... |
import movietools, os, sys, visit
###############################################################################
# Class: MovieGenerator
#
# Purpose: This base class contains the machinery to create a movie and
# it provides restart capability so that if the script stops
# running, it can b... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import six
from requests import RequestException
class TeambitionException(RequestException):
def __init__(self, code=-1, message=None, client=None, *args, **kwargs):
super(TeambitionException, self).__init__(*args, **kwargs... |
# -*- coding: utf-8 -*-
'''
File name: code\cutting_rope\sol_398.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #398 :: Cutting rope
#
# For more information see:
# https://projecteuler.net/problem=398
# Problem Statement
'''
Inside a ... |
import copy
import logging
import random
from ckan_api_client.exceptions import HTTPError
from ckan_api_client.high_level import CkanHighlevelClient
from ckan_api_client.objects import CkanDataset, CkanOrganization, CkanGroup
from ckan_api_client.utils import IDMap, IDPair
# Extras field containing id of the externa... |
import GPy
import numpy as np
import os, sys
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.abspath(os.path.join(THIS_DIR, os.pardir))
GP_prob_folder = os.path.join(ROOT_DIR, 'GP_prob')
sys.path.append(GP_prob_folder)
from custom_kernel_matrix.custom_kernel_matrix import CustomMatrix
class Cu... |
#Grid expansionA*
#Mapping the path
grid1 = [[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0]]
grid = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0],
[0... |
"""
Definition of the :class:`ExportDestinationViewSet` class.
"""
from accounts.filters import ExportDestinationFilter
from accounts.models.export_destination import ExportDestination
from accounts.serializers.export_destination import ExportDestinationSerializer
from accounts.tasks import export_mri_session
from pyla... |
"""Unit test package for tusdatos_connector."""
|
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class RLsei(RPackage):
"""Solving Least Squares or Quadratic Programming Problems under
... |
import sys
fname = sys.argv[1]
lines = 0
words = 0
letters = 0
for line in open(fname):
lines += 1
letters += len(line)
pos = 'out'
for letter in line:
if letter != ' ' and pos == 'out':
words += 1
pos = 'in'
elif letter == ' ':
pos = 'out'
pri... |
from graph_ter_seg.runner.backbone_runner import BackboneRunner
from graph_ter_seg.runner.classifier_runner import ClassifierRunner
from graph_ter_seg.runner.eval_runner import EvaluationRunner
from graph_ter_seg.runner.runner import Runner
|
import arcade
from miscellaneous import Misc
from Constants import CIRCLE_RADIUS
from Point import Point
from CollisionHandler import CollisionHandler
from Vector import Vector
import math
class Obstacle:
def __init__(self, A,B, color, width):
self.pointDepart = A
self.pointFinal = B
self... |
import cv2
import os
import multiprocessing
import numpy as np
import pandas as pd
import re
file = open("..\\yinxiebing\\yinxiebing.csv", encoding='utf8')
your_data_path = '..\\yinxiebing\\img_data'
file.readline()
# lines = file.readlines()
# print (lines)
def cut_image(line):
# print(line)
# print(line.... |
#
# libjingle
# Copyright 2015 Google Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following d... |
import os
from discord.ext.commands import AutoShardedBot
emojis: dict = {
"Ql": "<:Ql:827569943955505153>",
"kl": "<:kl:827569943972544523>",
"qd": "<:qd:827569943985127436>",
"nl": "<:nl:827569944057217085>",
"Pl": "<:Pl:827569944169676901>",
"ql": "<:ql:827569944178589716>",
"Kl": "<:Kl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.