content stringlengths 5 1.05M |
|---|
import numpy as np
import sympy as sp
from sympy.plotting import plot
def f(x):
return np.exp(1 - x) / np.cos(x**2)
a = 1
b = 2
n = 5
xs = np.sort(np.random.uniform(low=a, high=b, size=5))
ys = f(xs)
c = xs[0] + (b - a) / 10
print(xs, ys)
def getNewtonPolynomial(xs, ys):
sum = 0
x = sp.Symbol('x')
... |
"""
Description for boto3 service.
"""
from typing import Literal
from mypy_boto3_builder.constants import MODULE_NAME, PYPI_NAME
from mypy_boto3_builder.utils.strings import get_anchor_link, is_reserved
__all__ = (
"ServiceName",
"ServiceNameCatalog",
)
class ServiceName:
"""
Description for boto3 ... |
#
# Stephen Vondenstein, Matthew Buckley
# 10/08/2018
#
from tqdm import tqdm
import tensorflow as tf
from src.agents.baseagent import BaseAgent
from src.utils.utility import AverageMeter
class Trainer(BaseAgent):
def __init__(self, config):
super(Trainer, self).__init__(config)
# Step and epoch ... |
import os
from pathlib import Path
import numpy as np
from numpy.testing import assert_
ROOT = Path(np.__file__).parents[0]
FILES = [
ROOT / "py.typed",
ROOT / "__init__.pyi",
ROOT / "char.pyi",
ROOT / "ctypeslib.pyi",
ROOT / "emath.pyi",
ROOT / "rec.pyi",
ROOT / "version.pyi",
ROOT / ... |
"""
sudo pip uninstall dronekit
sudo pip uninstall pymavlink
cd dronekit-python
git pull
sudo python setup.py build
sudo python setup.py install
¬¬¬¬¬¬¬¬¬ $$$$ -> UNDER development <-$$$$ ¬¬¬¬¬¬¬¬
"""
import speech_recognition as sr
from time import ctime
import time
import os
from gtts import gTTS
import time
from dr... |
from glasskit import ctx
from telegram.bot import Bot
from telegram.error import TimedOut, TelegramError
from telegram.parsemode import ParseMode
from ask.models import User, Chat
from .abstract_bot import AbstractBot
class TelegramBot(AbstractBot):
NETWORK_NAME = "telegram"
NETWORK_BASE_URL = "https://api.... |
import os
import json
import shutil
from acscore.counter import Counter
from celery import shared_task
from django.conf import settings
from dulwich import porcelain
from . import models
@shared_task
def calc_metrics(code_style_id):
code_style = models.CodeStyle.objects.get(id=code_style_id)
try:
pa... |
from reminders.airtable_client import AirtableClient
from reminders.reminders_sheet import RemindersSheet
from reminders.task import Task
from reminders.ses_mailer import send_email
from jinja2 import Template
import os
import settings
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INF... |
"""
DeepLabCut2.0 Toolbox (deeplabcut.org)
© A. & M. Mathis Labs
https://github.com/AlexEMG/DeepLabCut
Please see AUTHORS for contributors.
https://github.com/AlexEMG/DeepLabCut/blob/master/AUTHORS
Licensed under GNU Lesser General Public License v3.0
"""
import numpy as np
import math
from skimage import io
from sk... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
from torch.utils.data import ConcatDataset, DataLoader
from torch.utils.data.dataloader import default_collate
from .registry import DATALOADERS
from .base import BaseDataloader
@DATALOADERS.register_module
class BatchRandomDataloader(BaseDataloader):
def __init__(self, dataset, batch_size, each_usage, shuffle=F... |
# -*- coding: utf-8 -*-
import socket
# Address and Port
HOST = 'localhost'
PORT = 8000
ADDR = (HOST, PORT)
# BufferSize
BUFSIZ = 1024
# build socket
udpCliSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
data = raw_input('> ')
udpCliSock.sendto(data, ADDR)
data =... |
# -*- coding: utf-8 -*-
from akad.ttypes import ApplicationType
import re, json, requests, urllib
class LineServer(object):
LINE_HOST_DOMAIN = 'https://gd2.line.naver.jp'
LINE_OBS_DOMAIN = 'https://obs-sg.line-apps.com'
LINE_TIMELINE_API = 'https://gd2.line.naver.jp/mh/api'... |
while True:
n=int(input())
if(n==2002):
print("Acesso Permitido")
break
else:
print("Senha Invalida") |
# This file is in the public domain.
import sys
from xml.dom.minidom import *
from generated.PersonDocument import *
from generated.PersonListDocument import *
def main():
#unmarshal personIn from stdin
personIn = PersonDocument.fromxml(sys.stdin)
#create a list containing personIn and some other person
... |
from docx import *
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import *
from docx.shared import Pt
# 修改word文档样式
doc = Document()
p1 = doc.add_paragraph("水平居中对齐")
# 设置段落水平居中对齐
p1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
p2 = doc.add_paragraph("左对齐")
# 设置段落左对齐
p2.paragraph_format.... |
import unittest
import configuration
class TestService(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
def test_get_stage_name(self):
self.assertEqual(configuration.get_stage_name([configuration.get_branch_name()]), '')
if __name__ =... |
import requests
from bs4 import BeautifulSoup
#定义天气城市代码
cityCodeDict={
"北京":101010100,"上海":101020100,"天津":101030100,"重庆":101040100,"哈尔滨":101050101,
"长春":101060101,"沈阳":101070101,"呼和浩特":101080101,"石家庄":101090101,"太原":101100101,
"西安":101110101,"济南":101120101,"乌鲁木齐":101130101,"拉萨":101140101,"西宁":... |
"""
Helper script to create gif.
"""
import imageio
from os import listdir
from os.path import isfile, join
mypath = './outputdir/'
fileNames = [f for f in listdir(mypath) if isfile(join(mypath, f))]
print("only files", fileNames)
print("files", type(fileNames))
files = sorted(fileNames)
print("only files", fileNames)... |
"""
used for any type on en/decryption
for fridrich (ex. End to End encryption,
password hashing, private config files
for the Client, ...)
(Server & Client)
Author: Nilusink
"""
import contextlib
import random
import math
import json
import os
# cryptography imports
from cryptography.hazmat.primitives.kdf.pbkdf2 imp... |
"""Perform classical functional region delimitation."""
import logging
from typing import Any, List, Tuple, Optional, TypeVar
import numpy as np
import pandas as pd
class EvaluatorInterface:
"""Objects that evaluate fitness of regions."""
def feed(self, interactions: pd.Series, unit_props: pd.DataFrame) ->... |
import warnings
warnings.filterwarnings("ignore")
import flair
from flair.models import TextClassifier
from flair.data import Sentence
classifier = TextClassifier.load('en-sentiment')
def sentimentAnalysis(inputQuery):
sentence = Sentence(inputQuery)
classifier.predict(sentence)
label = sentence.labels[0]
labscore... |
from peewee import BlobField, IntegerField, TextField
from playhouse.postgres_ext import BinaryJSONField
from slim import json_ex_dumps
from model._post import LongIdPostModel, POST_TYPES
class Mention(LongIdPostModel):
who = BlobField(index=True) # 被@的用户
loc_post_type = IntegerField() # 地点,类型
loc_post... |
# 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,... |
#!/usr/bin/env python
# (c) Copyright [2016] Hewlett Packard Enterprise Development LP 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 Unless required by applicable
# law or agreed to in writ... |
from __future__ import print_function
import sys
from bs4 import BeautifulSoup
from config import config
from vertitem import VertItem
class DocumentTopicBase(object):
def __init__(self, path):
with open(path, 'r') as file:
try:
soup = BeautifulSoup(file, "xml")
... |
import webbrowser, sys, pyperclip
# webbrowser.open('https://www.python.org') open website
# sys.argv['myProgram.py','6703','Bellare','Gardens','Drive']
if len(sys.argv) > 1:
address = ' '.join(sys.argv[1:])
else:
address = pyperclip.paste()
webbrowser.open(f"https://www.google.com/maps/place/{address}/"... |
from helper_functions import *
import torch
import torch.nn as nn
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import normalize
import numpy as np
from sklearn.utils import shuffle
# We train a classical neural network to zero training error 1... |
# connect to registration table
# search entries with status "job_created"
# check the job input files are indeed there
# launch job, get jobid and update status "job_launched"
import os
import subprocess
import autoqm.utils
from autoqm.connector import saturated_ringcore_table
config = autoqm.utils.read_config()... |
import pygame
import sys
import random
BLACK = (0, 0, 0)
WHITE = (200, 200, 200)
WINDOW_HEIGHT = 600
WINDOW_WIDTH = 600
RED = (255,0,0)
def main():
global SCREEN, CLOCK
pygame.init()
SCREEN = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
CLOCK = pygame.time.Clock()
SCREEN.fill(BLACK)
... |
# -*- coding: utf-8 -*-
from django.db import models, migrations
from django.core.management import call_command
app_name = 'api'
fixture = model_name = 'PartOfSpeech'
def load_fixture(apps, schema_editor):
call_command('loaddata', fixture, app_label=app_name)
def unload_fixture(apps, schema_editor):
"Dele... |
# -*- coding: utf-8 -*-
"""
All spiders should yield data shaped according to the Open Civic Data
specification (http://docs.opencivicdata.org/en/latest/data/event.html).
"""
import re
import urllib3
from datetime import datetime
from legistar.events import LegistarEventsScraper
from documenters_aggregator.spider imp... |
"""
Django settings for devops_backend project.
Generated by 'django-admin startproject' using Django 2.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
impor... |
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import check_password
class UserModelEmailBackend(ModelBackend):
"""
Authentication backend for login with email address.
"""
def authenticate(self, request, username=... |
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from time import sleep
# caminho para a raiz do projeto
ROOT_FOLDER = Path(__file__).parent.parent.parent
# Caminho p... |
# Copyright 2019 NetApp, 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 ... |
"""
trace_utils.py: Routines for finding xwavecal orders across a CCD.
Authors
G. Mirek Brandt (gmbrandt@ucsb.edu)
Tim Brandt (tbrandt@physics.ucsb.edu)
Curtis McCully (cmccully@lcogt.net)
"""
import numpy as np
from scipy import ndimage, optimize, signal
from astropy.table import Table, Column
from xwa... |
import pytest
import math
import base64
import copy
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.exceptions import ValidationError
from src.apps.runs.models import Run
from src.apps.trainings.mod... |
# coding: utf-8
"""
Helper for formatting exception messages. Exports the following items:
- pretty_message()
"""
from __future__ import unicode_literals, division, absolute_import, print_function
import re
import textwrap
__all__ = [
'pretty_message',
]
def pretty_message(string, *params):
"""
Tak... |
from setuptools import setup, find_packages
setup(
name='django-useful',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.2',
packages=find_packages(),
license='ISC',
url='http://github.com/yprez/django-useful',
description='Reusable Django snippets',
long_descripti... |
#!/usr/bin/env python
"""FEEL data download"""
# pylint: disable=abstract-class-instantiated
import cgi
import datetime
import os
import pandas as pd
from pyiem.util import get_dbconn, ssw
def run(sts, ets):
""" Get data! """
dbconn = get_dbconn('other', user='nobody')
sql = """SELECT * from feel_data_da... |
from flask import render_template, request
from wtforms import Form, StringField, validators
from python.admin.login.login_check import *
from python.database.flask_database import *
add_category_admin = Blueprint('add_category_admin', __name__)
# admin add new category validator form
class CategoryForm(Form):
... |
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class ItemType:
"""
:ivar id:
:ivar lang:
"""
id: Optional[str] = field(
default=None,
metadata=dict(
type="Attribute",
required=True
)
)
lang: Optional[str] = fi... |
import numpy as np
from matplotlib import pyplot as plt
import cv2
import random
filename = 'images/safak.jfif'
img_original = cv2.imread(filename)
height, width, channels = img_original.shape
img_process = img_original.copy()
# img_edited = cv2.cvtColor(img_original, cv2.COLOR_BGR2GRAY)
blur = cv2.G... |
import argparse
BLOCK_SIZE = 500
MSA_PROG_PATH = '/groups/hachgrp/projects/calib/scripts/calib_spoa/simulating/seqan_msa'
PBS_MSA_CMD = '{} {} {};'
def parse_args():
parser = argparse.ArgumentParser(
description="Runs MSA on server cluster")
parser.add_argument("-f",
"--forwar... |
from monty.json import MSONable
class DispatcherPayload(MSONable):
"""
class for storing all the arguments required by the reaction
filter dispatcher. We do this instead of passing arguments
directly because it makes it easier to pass arguments through the
MPI barrier.
"""
def __init__(
... |
from idex.exceptions import IdexWalletAddressNotFoundException, IdexPrivateKeyNotFoundException
def require_address(f):
def check_address(self, *args, **kwargs):
if not self._wallet_address:
raise IdexWalletAddressNotFoundException()
return f(self, *args, **kwargs)
return check_add... |
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# 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, c... |
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used i... |
# Copyright (c) 2021 PaddlePaddle 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 app... |
n1 = float(input('Insira o salário do funcionário para ser calculado o aumento. R$:'))
n = n1 + (n1 * 15 / 100)
print('O salário do funcionário passará de R${} para R${} com um reajuste salarial de 15%.'.format(n1, n))
|
#!/usr/bin/env python3
import xarray as xr
import numpy as np
import operator
from typing import Dict, List, Tuple, Union
from os.path import basename
from djs.job_scheduler.filehandler import identify_domain_file
def _check_parameter_validity(parameter_file: Union[str, xr.core.dataset.Dataset]):
'''
... |
# (c) mohdsabahat&Navipavi
import logging
logging.basicConfig(level = logging.DEBUG,
format="%(asctime)s - %(name)s - %(message)s - %(levelname)s")
logger = logging.getLogger(__name__)
import os
if os.path.exists('testconfig.py'):
from testconfig import Config
else:
from config import ... |
from contextlib import contextmanager
from typing import Generator
from sqlalchemy import create_engine, event
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from time_manager.settings import DB_CONFIG
from time_manager.utils.db import Database, get... |
from processor import RedirectProcessor, PayloadMarshallingProcessor, \
ExecuteRequestProcessor, AuthenticationProcessor
from request import Request
class Dsl(object):
"""
Configuration object for requests at a given URI.
"""
HTTP_VERBS = ['delete', 'get', 'head', 'options', 'patch', 'post', 'put... |
from django.conf.urls import url
from . import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^api/checker/create/$', views.LinkCreate.as_view()),
url(r'^api/checker/delete/(?P<pk>[0-9]+)/$', views.LinkDelete.as_view()),
url(r'^api/checker/(?P<pk>[0-9]+)/$', vi... |
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request
from flask_login import current_user, login_user, logout_user, login_required
from werkzeug.urls import url_parse
from . import auth
from .forms import LoginForm, RegistrationForm, EditProfileForm, \
ChangePasswordF... |
from .basics import *
from .operator import *
|
from band import settings, start_server
def main():
start_server(**settings)
if __name__ == '__main__':
main()
|
# Copyright 2009-2012 Yelp
# Copyright 2015-2016 Yelp
#
# 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 a... |
from fuzzywuzzy import process
with open('r.txt', 'r') as f:
cities = f.read().split("\n")
def get_matches(query, choices, limit=3):
results = process.extract(query, choices, limit=limit)
return results
a = get_matches((input(" ")), cities)
print(a)
|
from gevent import monkey
import json
from flask import Flask, request, Response, render_template, abort, url_for, redirect
import gevent
import requests
import mysql
import os
import subprocess
import time
from werkzeug.utils import secure_filename
from pdf_convert import *
UPLOAD_FOLDER = 'webapp/pdf'
ALLOWED_EXTENS... |
from django.contrib.auth.decorators import login_required
import json
from django.core.mail import EmailMultiAlternatives, send_mail
from django.utils.html import strip_tags
from django.template.loader import render_to_string
from random import randint
import re
from django.shortcuts import render, redirect
from django... |
from django.db import models
from django.utils import timezone
class CowsayDisplay(models.Model):
userInputText = models.CharField(max_length = 100)
cowsayDisplay = models.CharField
publishDate = models.DateTimeField(default = timezone.now)
def __str__(self):
return self.userInputText |
#
# 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 ... |
def import_maccor_data(file_path , file_name):
df = pd.read_csv(file_path+file_name,sep='\t', header = 2) # Read data from .txt is the line the data starts on
df = clean_maccor_df(df)
return df |
#!/usr/bin/env python3
import re
class IOutput(object):
"""Interface for things that write InDesign Tagged Text."""
def define_style(self, style):
"""Add a style definition."""
raise NotImplementedError()
def define_text_variable(self, name, value):
"""Add a text variable."""
... |
import streamlit as st
import streamlit_book as stb
st.markdown("# Python")
st.markdown("""
This is a **python file** that gets rendered using streamlit_book,
providing examples for the python functions to create certain types of activities.
""")
st.markdown("---")
st.markdown("A true-or-false question using python ... |
import pathlib
import pytoml as toml
import os
BASE_DIR = pathlib.Path(__file__).parent.parent
PACKAGE_NAME = 'app'
def load_config(path):
print(os.getcwd())
with open(path) as f:
conf = toml.load(f)
return conf
|
import os
import sys
ips = ["usny2-cn.sslwonders.com", "uswdc2-cn.sslwonders.com", "usla2-cn.sslwonders.com", "usut2-cn.sslwonders.com", "ussf2-cn.sslwonders.com", "us2-cn.sslwonders.com", "ukman2-cn.sslwonders.com", "ukl2-cn.sslwonders.com", "ukm2-cn.sslwonders.com", "cato2-cn.sslwonders.com",
"nl2-cn.sslwonder... |
from pycograph.project import PythonProject
from pycograph.schemas.basic_syntax_elements import CallSyntaxElement
from pycograph.schemas.parse_result import CallsRelationship, PackageWithContext
from ..helper import create_module_with_content
def test_import_and_call():
content = """
def do_stuff(nr):
return... |
def add(a, b):
return a + b
if __name__ == '__main__':
print(add(2, 3))
print(add(1, 5)) |
# Best to use conda to easily install geopandas
import geopandas as gpd
#Shape files can be found here:
#https://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/bound-limit-2011-eng.cfm
#Convert NAD83 to WGS84 aka epsg:3347 to epsg:4326
nad83 = gpd.read_file(r"data\lfed000b16a_e.shp",encoding='ansi')
wgs... |
from django import forms
from jobboard.models import Job
class FormControl(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for form_field in self.visible_fields():
form_field.field.widget.attrs['class'] = 'form-control'
class CreateNewJobForm(... |
import datetime as dt
from Stephanie.Modules.base_module import BaseModule
class SystemModule(BaseModule):
def __init__(self, *args):
super(SystemModule, self).__init__(*args)
self.name = self.get_configuration(section="USER", key="name")
self.gender = self.get_configuration(section="USER"... |
# pylint:skip-file
import sys, random, time, math
sys.path.insert(0, "../../python")
import mxnet as mx
import numpy as np
from collections import namedtuple
from nce import *
from operator import itemgetter
from optparse import OptionParser
LSTMState = namedtuple("LSTMState", ["c", "h"])
LSTMParam = namedtuple("LSTMP... |
#!/usr/bin/env python2
"""The main module that orchestrates everything"""
import json
import functools
import time
import sys
import os
from multiprocessing import Pool
from pyzabbix import ZabbixMetric, ZabbixSender
from pyzabbix.api import ZabbixAPIException
from pyzabbix_socketwrapper import PyZabbixPSKSocketWrapp... |
import pytest
try:
from _pytest.cacheprovider import Cache
except ImportError:
from pytest_cache import Cache
if hasattr(pytest, 'hookimpl'):
tryfirst = pytest.hookimpl(tryfirst=True)
else:
tryfirst = pytest.mark.tryfirst
|
# Generated by Django 2.1.3 on 2018-11-25 10:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import argparse
import csv
import datetime
import gzip
import logging
import os
import shutil
import sys
import dateutil.parser
import pytz
from influxdb import InfluxDBClient
UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
def convert_to_seconds(s):
"""
Convert string like 500s, 120m, 24h, 5d... |
import os
import csv
import copy
import MySQLdb
import warnings
import tempfile
from django.db import connection
from calaccess_raw.models import RcptCd, S497Cd
from calaccess_raw import get_download_directory
from calaccess_campaign_browser.management.commands import CalAccessCommand
from calaccess_campaign_browser.mo... |
user_input = 0.0
output_destination= '/home/ubuntu/Webpage/app_collaborative_sci_workflow/workflow_outputs/test_workflow/Module_1' |
#usr/bin/env python3
import socket
import sys
import pickle
import select
import os
#To print all clients connected
def print_conn(sock_addr_port):
os.system('clear')
for clients in sock_addr_port:
print('Client: ' + str(clients[1]) + '| Port: '+str(clients[2]))
#To remove from list when some cl... |
#!/usr/bin/env python3
# Copyright 2016 The Meson development team
# 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 appli... |
# Generated by Django 2.1.7 on 2019-03-19 14:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('travelling', '0042_auto_20190319_1541'),
]
operations = [
migrations.AlterField(
model_name='trip',
name='lead_inact... |
"""
Separate object to store config values.
I avoided usage of the 'dataclasses' module to ensure of Python 3.6 compatibility
"""
from .const import BFD_PORT
__all__ = ['BFDConfig']
class BFDConfig:
"""
Attrubutes:
`listen_addr` IP address to listen on (default 0.0.0.0)
`listen_port` Lis... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from gaiatest import GaiaTestCase
from gaiatest.mocks.mock_contact import MockContact
from marionette.errors import NoS... |
from machine import Pin, PWM
import math
import time
led_pin = Pin( 2 )
led = PWM( led_pin )
led.freq(1000)
while True :
for i in range(20):
duty = int( i / 20 * 1023 )
print( duty )
led.duty( duty )
time.sleep_ms(100)
|
from enum import IntEnum
from marshmallow import fields, Schema
from . import db
from .helpers.IntEnumField import IntEnumField
class IngredientUnit(IntEnum):
GRAM = 1,
KILOGRAM = 2,
MILLILITRE = 3,
LITRE = 4,
TEASPOON = 5,
TABLESPOON = 6,
CUP = 7,
NONE = 8
class Ingredient(db.Model... |
import subprocess
import os
samples = ['c9ALS_M01', 'c9ALS_M02', 'c9ALS_M34', 'c9ALS_M57', 'c9ALS_M06', 'c9ALS_M62', 'c9ALS_M63', 'c9ALS_M07', 'sALS_M11', 'sALS_M12', 'sALS_M13', 'sALS_M14', 'sALS_M70', 'sALS_M71', 'sALS_M72', 'sALS_M73', 'sALS_M74', 'sALS_M75', 'Ctl_M24', 'Ctl_M86', 'Ctl_M90', 'Ctl_M91', 'Ctl_M93', '... |
#!/usr/bin/env python3
import sys
import os
import importlib
packages = []
location = ''
packagePrefix = ''
if (__file__ is not None) and (len(__file__) > 0):
# import inspect
# print(inspect.getframeinfo(inspect.currentframe()).filename)
location = os.path.dirname(os.path.abspath(__file__))
locat... |
import os
import numpy as np #used for numerical analysis
from flask import Flask,request,render_template
# Flask-It is our framework which we are going to use to run/serve our application.
#request-for accessing file which was uploaded by the user on our application.
#render_template- used for rendering the html ... |
##
# \file correct_intensities.py
# \brief Script to perform intensity correction across images given a
# reference image
#
# \author Michael Ebner (michael.ebner.14@ucl.ac.uk)
# \date October 2017
#
# Import libraries
import numpy as np
import os
# Import modules
import niftymic.base.data_... |
from lesson02n2.fruits_v02n2 import fruits_v02n2
if __name__ == "__main__":
program = [
("Apple", "My name is Apple!"), # プログラムは縦に並べると見やすいです
("Apple", "Refreshing!"),
("Banana", "My name is Banana!"),
("Banana", "Very sweet!"),
("Cherry", "My name is Cherry!"),
("C... |
XPATH_ITEMS = {
"hemato": "//div[contains(@class,'item-estoque')]",
"hemope": "//ul[contains(@class,'list-estoque')]/li",
"ihebe": "//div[contains(@class, 'bolsa-sangue')]",
"hemoba": "//div[contains(@id, 'box-estoque')]/div",
}
XPATH_TIPO_SANGUE = {
"hemato": ".//div[contains(@class, tipo-sangue)]... |
import numpy as np
import torch
import torch.nn.functional as F
from matplotlib.font_manager import findfont, FontProperties
from PIL import Image, ImageFont, ImageDraw
from torchvision.utils import make_grid
from datasets.definitions import MOD_SS_CLICKS, MOD_RGB, MOD_SS_DENSE, MOD_VALIDITY, MOD_SS_SCRIBBLES
class ... |
import re
import unicodedata
from typing import Dict, List, Union
import numpy as np
import pandas as pd
# pd.set_option('mode.chained_assignment', "raise")
def normalize_names(name):
return ''.join([
c for c in unicodedata.normalize('NFD', name)
if unicodedata.category(c) != 'Mn'
... |
from generative_cfg import *
backend = SVGBackend()
turtle = Turtle(backend)
grammar = Grammar()
grammar.add_non_terminal('S', [
lambda turtle: turtle.forward(1),
lambda turtle: turtle.turn_right(89.5),
lambda turtle: turtle.scale(0.99),
'S'
])
grammar.expand('S', turtle, 300)
backend.write('rect_sp... |
#!/usr/bin/env python
import sys
from os.path import dirname, realpath
path = dirname(dirname(dirname(dirname(realpath(__file__)))))
sys.path.insert(0, path)
import libproton # isort:skip
class Scorer:
def __init__(self, teams_data, arena_data):
self._teams_data = teams_data
def calculate_scores(... |
import django
django.setup()
import csv, sys, os
from wijn.models import *
data_dir = sys.argv[1]
Vraag.objects.all().delete()
for row in csv.DictReader(open(os.path.join(data_dir, "vragendld.csv"))):
for f in row:
row[f] = None if row[f] == "" else row[f].decode("utf-8")
rubriek = row["rubriek"]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.