content stringlengths 5 1.05M |
|---|
# Wanderlust Wine - UK
# Tutorial from John Watson Rooney YouTube channel
import requests
from bs4 import BeautifulSoup
from requests.api import head
import pandas as pd
import re
wine_list = []
# Step 1 - Request
def request(x):
url = f'http://www.wanderlustwine.co.uk/buy-wine-online/page/{x}/'
headers = {'... |
import os.path
import tempfile
import maptools
import maptools.external
import pytest
@pytest.mark.skipif(not maptools.external.is_ccp4_available(), reason="requires CCP4")
def test_fit(ideal_map_filename, pdb_filename):
_, output_pdb_filename = tempfile.mkstemp()
_, log_filename = tempfile.mkstemp()
ma... |
#!/usr/bin/env python3
from otl866 import at89, util
import unittest
import os
class TestCase(unittest.TestCase):
def setUp(self):
"""Call before every test case."""
print("")
port = util.default_port()
self.verbose = os.getenv("VERBOSE", "N") == "Y"
self.tl = at89.AT89(po... |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
# batch running of experiments
import os
import getpass
import argparse
from utils import *
from runmm2 import Simulation
def CleanState ():
os.system('sudo killall python2 receiver sender mm-link mm-delay >/dev/null 2>&1 ')
# os.system('sudo ../ccp-kernel/ccp_kernel_unload')
# os.system('sudo ../ccp-kernel/cc... |
from file_utilities import readCSVFile
from PlotterLine import PlotterLine
solution = readCSVFile("output.csv")
a_liq_plotter = PlotterLine("Position", "Volume Fraction")
a_liq_plotter.addSet(solution["x"], solution["a_liq"], "$\\alpha_\ell$", color=4, linetype=2)
a_liq_plotter.save("volume_fraction.png")
r_liq_plot... |
"""
Benchmarks for array expressions.
"""
import numpy as np
# @jit(nopython=True)
def sum(a, b):
return a + b
# @jit(nopython=True)
def sq_diff(a, b):
return (a - b) * (a + b)
# @jit(nopython=True)
def rel_diff(a, b):
return (a - b) / (a + b)
# @jit(nopython=True)
def square(a, b):
# Note this is... |
"""
Example usages:
python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 4 -o .
python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 4-9 -o tmp
python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 1,2,4-9 -o tmp
Pages can ... |
import util
import os
def run():
util.process_usgs_source(
base_path=os.path.realpath(__file__),
url="http://pubs.usgs.gov/of/1998/of98-354/sfs_data.tar.gz",
uncompress_e00=True,
e00_path="sfs-geol.e00",
srs="+proj=lcc +lat_1=37.066667 +lat_2=38.433333 +lat_0=36.5 "
... |
class SleepSort(object):
"""
Sorting list of positive numbers using multi-threading
wherein thread will sleep for integer value and
add integer in result collection.
These multi-threads will add integers of input list
in such way that, result contains collection of sorted integers.
eg: [3, 1... |
"""
A precondition for the algorithm working is that the library 'requests'
must be installed on the device prior to using the program
"""
import requests
def auto_reconnect():
"""
Auto reconnect to password module
The ClientURL (cURL) command converted over to python for compatibility
... |
class DependencyPropertyDescriptor(PropertyDescriptor):
""" Provides an extension of System.ComponentModel.PropertyDescriptor that accounts for the additional property characteristics of a dependency property. """
def AddValueChanged(self,component,handler):
"""
AddValueChanged(self: DependencyPropertyDescrip... |
from pathlib import Path
import pytest
import caption_contest_data as ccd
filenames = list(ccd._api._get_response_fnames().keys())
DUELING_XFAIL = """These contests are dueling bandits, not cardinal bandits
(which have pairwise comparisons, not single caption ratings).
These aren't officially supported.
"""
def _... |
from pdip.cqrs.decorators import requestclass
from pdi.application.operation.CreateDataOperation.CreateDataIntegrationConnectionDatabaseRequest import \
CreateDataIntegrationConnectionDatabaseRequest
from pdi.application.operation.CreateDataOperation.CreateDataIntegrationConnectionFileRequest import \
CreateDa... |
"""Astronomical coordinate functions."""
import re,pdb
import numpy as np
from numpy import arccos,sin,cos
from math import pi
# constants
DEG_PER_HR = 360. / 24. # degrees per hour
DEG_PER_MIN = DEG_PER_HR / 60. # degrees per min
DEG_PER_S = DEG_PER_MIN / 60. # degrees per sec
DEG_PER_AMIN = 1./... |
import os
from functools import reduce
def xor(a,b):
c=bytearray()
for i,j in zip(a,b):
c.append(i^j)
return c
msg1="did you expect another rsa? sorry"
msg2=" to disappoint you. What you see is a bad use "
msg3="of the otp in encryption. It literally says one"
msg4=" and not multi time. masrt{think_out_of_the_b... |
import torch
from common.utils.clip_pad import *
import numpy as np
class BatchCollator(object):
def __init__(self, dataset, append_ind=False):
self.dataset = dataset
self.test_mode = self.dataset.test_mode
self.data_names = self.dataset.data_names
self.append_ind = append_ind
... |
from .leaderboards import *
#from .nominationAssessmentTeam import *
from .players import *
#from .publicRanking import *
#from .qualityAssuranceTeam import *
#from .rankingTeam import *
#from .websiteUser import *
|
# 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, ... |
# celcius to fahrenheit
import tkinter
class FahrenheiterGUI(): # :D
def __init__(self):
# create the main window
self.main_window = tkinter.Tk()
# set the title
self.main_window.title("Celcius to Fahrenheit")
# create three frames for this GUI
self.top_frame = tk... |
#!/usr/local/bin/python
# Physics Equation Graph
# Ben Payne <ben.is.located@gmail.com>
import sys
import os
lib_path = os.path.abspath('lib')
sys.path.append(lib_path) # this has to proceed use of physgraph
db_path = os.path.abspath('databases')
sys.path.append(lib_path) # this has to proceed use of physgraph
import ... |
import numpy as np
import torch
from colorsys import hsv_to_rgb
def get_camera_rays(c_pos, width=320, height=240, focal_length=0.035, sensor_width=0.032, noisy=False,
vertical=None, c_track_point=None):
#c_pos = np.array((0., 0., 0.))
# The camera is pointed at the origin
if c_track_p... |
from __future__ import with_statement
import re
import pytest
from flask import Flask
from blessed_extensions import csrf_token
from pg_discuss._compat import to_unicode
csrf_token_input = re.compile(
r'([0-9a-z#A-Z-\.]*)'
)
def get_csrf_token(data):
match = csrf_token_input.search(to_unicode(data))
ass... |
##############################################################################
# For copyright and license notices, see __manifest__.py file in root directory
##############################################################################
from odoo import api, fields, models, _
from odoo.exceptions import ValidationErro... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: helloworld.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.prot... |
# extract text from a img and its coordinates using the pytesseract module
import cv2
import pytesseract
# You need to add tesseract binary dependency to system variable for this to work
img =cv2.imread('img.png')
#We need to convert the img into RGB format
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
hI,wI,k=img.shape
pr... |
from cwr_admin.resources.cwr import CWRFilesResource, CWRProcessorResource, \
CWRMatchResultResource, CWRFilesRemoveResource, CWRMatchBeginResource, \
CWRMatchRejectResource, CWRMatchAcceptResource, CWRMatchFeedbackResource
|
# This code is based on https://github.com/Ryo-Ito/spatial_transformer_network
import tensorflow as tf
def mgrid(*args, **kwargs):
low = kwargs.pop("low", -1)
high = kwargs.pop("high", 1)
low = tf.to_float(low)
high = tf.to_float(high)
coords = (tf.linspace(low, high, arg) for arg in args)
gr... |
#!/usr/bin/env python
#
# Copyright (c) 2016 Nutanix Inc. All rights reserved.
#
#
# Unit tests for test reports.
import inspect
import os
import unittest
from curie.node_failure_test.node_failure_test import NodeFailureTest
from curie.node_failure_data_loss_test.node_failure_data_loss_test \
import NodeFailureDataL... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021-07-24 11:30:23
# @Author : Chenghao Mou (mouchenghao@gmail.com)
from typing import List
from datasketch import MinHash, MinHashLSH
from nltk.util import ngrams
from text_dedup.utils.group import get_group_indices
import multiprocessing as mp
import time
... |
from .binary_tree import * |
# -*- coding: utf-8 -*-
# KNN.py
import numpy as np
import matplotlib.pyplot as plt
import cv2
if __name__ == '__main__':
# 记住numpy的array有下面这种神器的用法
test = np.array([1,-2,3,-4,5])
res = test[test > 0]
# res = [1,3,5]
a = np.random.randint(0,101,(50,2),dtype=np.int64).astype(np.float32)
fl... |
"""
This is comment section
"""
def display_hello_world():
"""
This is a function to display "Hello World!"
:return: void
"""
print("Hello World!")
display_hello_world()
# Set text
texts = ["Hello", "World", "!"]
for text in texts:
print(text)
numberString = "917254"
for char in numberStri... |
import xmltodict
import defusedxml.ElementTree as ET
class Locations:
"""Provides lookup of raw location data based on UKPRN and LOCID"""
def __init__(self, root):
"""Build the locations lookup table
Locations are unique on UKPRN and LOCID
"""
self.lookup_dict = {}
f... |
from django.urls import path
from apps.contents.views import IndexView
urlpatterns = [
path('index/', IndexView.as_view()),
] |
import numpy as np
from data.external_data.maturities import convert_maturity
from data.external_data.yahoo import Yahoo
from data.local_data.parameters_generator import ParametersGenerator
from stochastic_process.markov_chain import MarkovChain, Sigma
from stochastic_process.risky_asset import RiskyAsset
class Data... |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from scipy.sparse.linalg import spsolve
def fix_source(source, mask, shape, offset):
mydict = {}
counter = 0
for i in range(mask.shape[0]):
for j in range(mask.shape[1]):
if mask[i][j]>127:
mydict[(i+offset[0], j+off... |
from typing import List, Optional, Tuple, Dict, Callable
import torch
from torch import Tensor
from tha2.poser.poser import PoseParameterGroup, Poser
from tha2.nn.batch_module.batch_input_module import BatchInputModule
from tha2.compute.cached_computation_func import TensorListCachedComputationFunc
class ... |
# test_ble_commands.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Tue May 18 22:08:51 UTC 2021
import pytest
from construct import Int32ub
from open_gopro.ble_commands import BLECommunicator, BleCommands, BleSettings, BleStatuses
from op... |
from django.conf import settings
# - {% if cookiecutter.django_media_engine == S3 %}
from storages.backends.s3boto3 import S3Boto3Storage
class PrivateMediaStorage(S3Boto3Storage):
"""Media storage which disables public access by default
When you use this as the default storage it makes sense to
turn of... |
"""
Implementation of POSFrequencyPipeline for score ten only.
"""
import json
import re
from constants import ASSETS_PATH
from core_utils.article import ArtifactType
from core_utils.visualizer import visualize
from pipeline import CorpusManager, validate_dataset
class EmptyFileError(Exception):
"""
Custom e... |
#!/usr/bin/env python
"""Helper functions to store and get the selected backend"""
from collections import namedtuple
import logging
from dosna.util import named_module
log = logging.getLogger(__name__)
_current = None
AVAILABLE = ['ram', 'hdf5', 'ceph', 'sage', 's3']
# Currently there is no need for more fancy at... |
from helpers.runner import run_main
from helpers.cli import cmdout
def test_no_cmd(cmdout):
try:
run_main([])
except SystemExit:
pass
cmdout.assert_substrs_in_line(0, ["usage:"], on_stderr=True)
|
from ZstudentDAO import studentDAO
# We put in the data we get passed up from the json
#create
latestid = studentDAO.create(('Eilish', 22))
#find by id
result = studentDAO.findByID(latestid); # needs to be made into json object
print (result)
#update
studentDAO.update(('Liam',23,latestid))
result = studentDAO.findB... |
"""
Script to solve z-factor and gas density at the same time
Using Dranchuk and Aboukassem (1975)
"""
def dranchuk(T_pr, P_pr):
# T_pr : calculated pseudoreduced temperature
# P_pr : calculated pseudoreduced pressure
from scipy.optimize import fsolve # non-linear solver
import numpy as np
a1 ... |
# Generated by Django 3.0.2 on 2020-03-06 22:30
from django.db import migrations
import streamfield.fields
class Migration(migrations.Migration):
dependencies = [
('pagine', '0014_event_carousel'),
]
operations = [
migrations.AddField(
model_name='blog',
name='ca... |
from typing import Any, Optional
from rx.disposable import Disposable
from rx.core import typing
from .subject import Subject
from .innersubscription import InnerSubscription
class AsyncSubject(Subject):
"""Represents the result of an asynchronous operation. The last value
before the close notification, or ... |
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.timezone import now
class BaseModel(models.Model):
created = models.DateTimeField(auto_now_add=True, verbose_name=_("Created, UTC"))
updated = models.DateTimeField(auto_now=True, verbose_name=_("Updated, UTC... |
# Testing various potentials.
from asap3 import *
from asap3.md.verlet import VelocityVerlet
from asap3.EMT2013Parameters import PtY_parameters
from ase.lattice.cubic import *
from ase.lattice.compounds import *
from numpy import *
from asap3.testtools import ReportTest
try:
import potResults
except ImportError:
... |
import numpy as np
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button #, RadioButtons
import scipy.signal as ss
from binary_file_options import Ui_MainWindow
def get_raw_data_from_binary_file(fname,offset_samples,duration_samples,bit_de... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ve... |
from goolabs import GoolabsAPI
import time
def name_check(api_id, text_list):
"""固有表現抽出器で名前と判断された語のリストを取得
Parameters
----------
api_id : str
text_list : list[str]
ツイッターの文章のリスト
Returns
-------
name_list : list[str]
名前と判断された語(重複あり)
"""
n_list = ["鬼太郎", "ぬらりひょん",... |
from django.contrib import admin
from .models import HeaderCTA, BlogEmbeddedCTA
# Register your models here.
admin.site.register(HeaderCTA)
admin.site.register(BlogEmbeddedCTA) |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 21:08:15 2019
@author: Olivier
"""
#####prévoir le résultat avant d'exécuter le code#######
a=3
def test0():
"""None->None
affiche a, variable non déclarée dans la fonction"""
print("valeur de a dans test0",a)
test0() #attention, si a n... |
import socket
from unittest import TestCase
from tempfile import NamedTemporaryFile
from mock import patch, Mock
from oasislmf.utils.conf import load_ini_file, replace_in_file
from oasislmf.utils.exceptions import OasisException
class LoadInIFile(TestCase):
def test_values_are_bool___values_are_correctly_conve... |
n = int(input())
ratings = [int(input()) for _ in range(n)]
candies = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i-1]:
candies[i] = candies[i-1] + 1
#print (candies)
for i in reversed(range(1, n)):
if ratings[i] < ratings[i-1]:
candies[i-1] = max(candies[i-1], candies[i]+1)... |
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
VERSION = '2.0.1'
setup(
name='usabilla-api',
version=VERSION,
description="Python client for Usabilla API",
license='MIT',
install_requires=['urllib3', 'requests'],
packages=find_pack... |
import os
from shutil import copyfile
import lxml.etree as etree
os.chdir("../")
operating_system = 'Linux'
target_level_path = '../level_variations/generated_levels/fourth generation'
origin_level_path = '../buildgame/{}/9001_Data/StreamingAssets/Levels/novelty_level_1/type1/Levels/'.format(operating_system)
game_lev... |
from random import randint
number = randint(1, 100)
print("Guess a number between 1 and 100")
#print(number)
while True:
guess = int(input("Enter guess:"))
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
break
print("Correct!") |
# DESCRIPTION
# You are a product manager and currently leading a team to develop a new product.
# Unfortunately, the latest version of your product fails the quality check.
# Since each version is developed based on the previous version, all the versions after a bad version are also bad.
# Suppose you have n versions ... |
"""
Description: This script calibrate result from LP solution.
Probablistically select ASYMPs.
Then, compute metric features from those.
"""
from utils.networkx_operations import *
from utils.pandas_operations import *
from utils.time_operations import *
from tqdm import tqdm
import pandas as pd
import numpy as np
im... |
import rubrik_cdm
rubrik = rubrik_cdm.Connect()
username = "python-sdk-read-only"
read_only_permission = rubrik.read_only_authorization(username)
|
import torch
import torch.nn as nn
import numpy as np
class AttentionGate(nn.Module):
def __init__(self, x_ch, g_ch, mid_ch, scale):
super(AttentionGate, self).__init__()
self.scale = scale
self.conv_g = nn.Conv2d(in_channels=g_ch, out_channels=mid_ch, kernel_size=1, bias=True)
sel... |
"""
Loader and Parser for the txt format.
Version: 0.01-beta
"""
from konbata.Data.Data import DataNode, DataTree
from konbata.Formats.Format import Format
def txt_toTree(file, delimiter=None, options=None):
"""
Function transforms a txt file into a DataTree.
Parameters
----------
file... |
from __future__ import print_function
from recon.core.module import BaseModule
import os
import subprocess
from libs.pentestlymodule import PentestlyModule
from libs.misc import parse_mimikatz, Colors
class Module(PentestlyModule):
meta = {
'name': 'Execute Mimikatz',
'author': 'Cory Duplantis (... |
if __name__ == "__main__":
if __package__ is None:
# add parent dir to allow relative import
from pathlib import Path
import sys
top = Path(__file__).resolve().parents[1]
sys.path.append(str(top))
# PEP 0366
__package__ = "lvscharts"
__import__(__pa... |
from .toolbar_controller import ToolbarController
|
from unittest import TestCase
import unittest
from rengine.config import TIME_BASED_CONDITIONS, ExerciseType, MuscleGroup
from rengine.exercises import pick_random_exercise
import dataframe_image as dfi
from rengine.workouts import AutoGeneratedWorkout, BaseWorkout, LowerBodyWorkout, UpperBodyWorkout, dictionary_additi... |
from sklearn.linear_model import RidgeClassifierCV, RidgeClassifier
from eye_detector.train.models.find import find_params
from eye_detector.train.models.decorator import ModelDecorator
def ridge(x, y, shape):
grid = RidgeClassifierCV(alphas=[1e-3, 1e-2, 1e-1, 1])
alpha = find_params(grid, x, y, attr="alpha_"... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import pandas as pd
import plotly.graph_objects as go
import numpy as np
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"... |
# Copyright 2013-2020 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 import *
class RStatnetCommon(RPackage):
"""Non-statistical utilities used by the software developed by t... |
# Grupo: Gabriel Macaúbas Melo, Louise Fernandes Caetano, Maria Eduarda de Almeida Vitorino e Fernando Luiz Castro Seixas
# Importando Funções
from functions import *
# Programa Principal
num = iniciar()
cartelas = criar_cartela(num)
sorteio(cartelas)
|
import os
from sklearn import datasets
import xgboost as xgb
from xgboost_ray import RayDMatrix, predict
import numpy as np
def main():
if not os.path.exists("simple.xgb"):
raise ValueError(f"Model file not found: `simple.xgb`"
f"\nFIX THIS by running `python `simple.py` first ... |
# FP involving global variables modified in a different scope
i = 0
def update_i():
global i
i = i + 1
update_i()
if i > 0:
print("i is greater than 0") # FP: This is reachable
|
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from functools import wraps
from common import Logging
from common.Logging import get_generic_logger
from common.YamlConfig import AppConfig
from lib.bottle import Bottle, request, response
from ..AppRunner import AppRunner
from ..RemoteServerApi import get_server_config, ge... |
# utils
from .rfb_utils import object_utils
from .rfb_utils import transform_utils
from .rfb_utils import texture_utils
from .rfb_utils import scene_utils
from .rfb_utils import shadergraph_utils
from .rfb_logger import rfb_log
from .rman_sg_nodes.rman_sg_lightfilter import RmanSgLightFilter
from . import rman_consta... |
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
#TODO1: Create the turtle and move it with keypress
player = Player()
screen.listen()
screen.onkey(player.go_up... |
s = list(input('Escriba el string: '))
s[0] = s[0].upper()
print(''.join(s))
|
# -*- coding: utf-8 -*-
"""Charge logging script
This script will download the get_vehicle_status every 5 minutes
and log them locally. Based on the Charge Off-Peak script.
This script is independent from visualization script in order to run it on different computers
"""
import jlrpy
import threading
import datetim... |
from time import sleep
from jumpscale import j
from .VirtualboxClient import VirtualboxClient
JSBASE = j.application.jsbase_get_class()
class VirtualboxFactory(JSBASE):
def __init__(self):
self.__jslocation__ = "j.clients.virtualbox"
JSBASE.__init__(self)
self.logger_enable()
s... |
from PIL import ImageFont
class Letter:
""" letter class- each letter is one of these objects, and is rendered in order. """
def __init__(self,char,size,font,color = (255,255,255,255),b=False,i=False,u=False):
"""
char: character.
size: size of letter.
font: PIL truetype font obj... |
#TODO: Add datadump |
# -*- coding: utf-8 -*-
from . import helpers
import os
import shutil
import json
import logging
import sys
import face_recognition
from ringFace.ringUtils import commons
def processUnencoded(imageDir):
"""
Processes any unencoded image in the new-images subdir of a person, and moves it into encoded-ima... |
from os import path
import click
from glob import glob
from pathlib import Path
from app.newAnimeEpisodes import *
@click.command()
@click.option('--source', required=True, type=str, help='Enter absolute path of directory to move from')
@click.option('--destination', required=True, type=str, help='Enter absolute path ... |
""" A test action set. """
# Enthought library imports.
from envisage.ui.action.api import Action, Group, Menu, ToolBar
from envisage.ui.workbench.api import WorkbenchActionSet
class TestActionSet(WorkbenchActionSet):
""" An action test useful for testing. """
#### 'ActionSet' interface ###################... |
"""This module provide the builder for the zlib library."""
import logging
from nvp.components.build import BuildManager
from nvp.nvp_builder import NVPBuilder
logger = logging.getLogger(__name__)
def register_builder(bman: BuildManager):
"""Register the build function"""
bman.register_builder('zlib', Bui... |
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def animale_array(xm,fname,lbls=None,cmap='gray',figsize=(7,7),fps=25,vmin=None,vmax=None):
'''
This function helps to make an animation from a (2+1+1)d array (xy+t+c)
'''
# from IPy... |
import asyncio
import json
import logging
import random
import time
import uuid
import websockets
from common import Client, ClientReport, OffsetTransform, Position, Rotation
logging.basicConfig(level=logging.INFO)
TIME_BETWEEN_UPDATES = 0.0166
LOW_POSITION = -3.0
HIGH_POSITION = 3.0
LOW_ROTATION = 0.0
HIGH_ROTATION... |
import logging
import os
from pathlib import Path
from flatpaksync.commands.command import command
from flatpaksync.configs.write import write as writeconfig
from flatpaksync.structs.app import app
from flatpaksync.structs.settings import settings
from flatpaksync.actions.app import app as appaction
from flatpaksync.... |
"""generatedata
Function that collects the transmutation data and
prepares the transmutation matrix required for depletion or decay
calculations.
The following reactions are considered:
- Radiative capture
- Capture to ground state
- Capture to metastable
- n, 2n
- n, 3n
- Fission
- n, alp... |
import pandas as pd
from sklearn.metrics import r2_score
from sklearn.svm import SVR
MAX_AGE = 71
MAX_PCLASS = 3
def process_df(df):
df = df[['pclass', 'survived', 'age', 'sex']]
df = df.dropna()
df['pclass'] = df['pclass'].map(lambda x: float(x[:-2]) / MAX_PCLASS) # drop sufix
df['age'] = df['age... |
import datetime
import calendar
from posixpath import dirname
import os
import pytz
import lockfile
import pycountry
import geoip2.errors
from flask.ext.babel import lazy_gettext
from flask import url_for
from flask.helpers import find_package
import rfk
def now():
return pytz.utc.localize(datetime.datetime.... |
from typing import List, Iterator, Dict
from pyot.conf.model import models
from pyot.core.functional import cache_indexes, lazy_property
from pyot.core.exceptions import NotFound
from pyot.utils.tft.cdragon import abs_url, join_set_data
from pyot.utils.lol.cdragon import sanitize
from .base import PyotCore, PyotStatic... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Authors: Olexa Bilaniuk
# Imports.
import sys; sys.path += [".", ".."]
import argparse as Ap
import logging as L
import numpy as np
import os, pdb, sys
import time
import tensorflow.c... |
from django.db import models
from django_handleref.models import HandleRefModel
class Org(HandleRefModel):
name = models.CharField(max_length=255, unique=True)
website = models.URLField(blank=True)
notes = models.TextField(blank=True)
class HandleRef:
tag = 'org'
delete_cascade = ["s... |
import os
import pickle
import yaml
import numpy as np
import pandas as pd
import pyprind
from stats.plot_utils import get_dn_rn_info, load_best_rl
from stats.thresholds import th
rng = np.random.RandomState(123)
ROOT_DIR = os.path.abspath(".")
RAW = False # True == num patients ; False == percentage
# Make plots d... |
from setuptools import setup, find_packages
with open("requirements.txt") as f:
install_requires = f.read().strip().split("\n")
# get version from __version__ variable in erptn/__init__.py
from erptn import __version__ as version
setup(
name="erptn",
version=version,
description="adaption of erpnext in the tunis... |
# Generated by Django 3.2.3 on 2021-08-12 05:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto_20210811_1941'),
]
operations = [
migrations.RenameField(
model_name='vehicle',
old_name='size',
... |
num = int(input('Insira um número: '))
if num % 3 == 0:
print(f'O número {num} é divisível por 3.')
else:
print(f'O número {num} não é divisível por 3.')
if num % 7 == 0:
print(f'O número {num} é divisível por 7.')
else:
print(f'O número {num} não é divisível por 7.')
|
from flask import Flask, render_template, url_for
from forms import RegistrationForm, LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = '23630345ae74e203656e76a7cab735a7'
posts = [
{
'author': 'Name',
'title': 'Blog post 1',
'content': 'First blog post',
'date_posted': 'A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.