content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the reproman package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #... |
# -*- coding: utf-8 -*-
import re
from collections import defaultdict
dfnClassToType = {
"abstract-opdef" : "abstract-op",
"propdef" : "property",
"valdef" : "value",
"at-ruledef" : "at-rule",
"descdef" : "descriptor",
"typedef" : "type... |
from __future__ import division
from time import sleep
from select import epoll, EPOLLIN, EPOLLOUT, EPOLLPRI, EPOLLERR, EPOLLHUP, \
EPOLLET, EPOLLONESHOT, EPOLLMSG
from base import ProactorBase, perform_recv, perform_accept, perform_send, \
perform_... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# HowTo
# https://docs.python.org/3.8/howto/sockets.html#socket-howto
import ssl
import socket
import struct
import psutil
import select
class Tcp(object):
def __init__(self):
self.socket_fd = None
def is_connected(self):
return self.socket_fd != No... |
import re
import time
import helpers.list_validation_methods as lvm
from config import business_insider_article_archive_link as archive_link
from helpers.enums import *
from helpers.reddit import post_to_reddit
def find_article_to_parse(create_post=True):
"""Finds a list article in Business Insider's latest arti... |
"""
Utilities for working with vim module.
Documentation for the vim module is here
http://vimdoc.sourceforge.net/htmldoc/if_pyth.html#python-vim
"""
from vimzk.context import vim
def buffer_is_empty(idx=-1):
"""
Return whether indicated buffer is empty. Use current buffer for idx of -1.
"""
buf = ... |
#
# Lockstep Software Development Kit for Python
#
# (c) 2021-2022 Lockstep, Inc.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# @author Ted Spence <tspence@lockstep.io>
# @copyright 2021-2022 Lockstep, Inc.
# @version 2021.39
#... |
import unittest
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QDropEvent
from PyQt5.QtTest import QTest
import tests.utils_testing
from tests.utils_testing import get_path_for_data_file
from urh.controller.DecoderWidgetController import DecoderWidgetController
from urh.controller.MainController import MainContr... |
import random
import pandas as pd
import tqdm
import numpy as np
data = pd.read_csv(
'../data/2009_skill_builder_data_corrected/skill_builder_data_corrected.csv',
usecols=['order_id', 'user_id', 'sequence_id', 'skill_id', 'correct']).fillna(0) # 给缺省的skill_id填为0
# print(data.isnull().sum()) # 缺省信息
raw_questi... |
import scrapy
import csv
#
# http://www.languagedaily.com/learn-german/vocabulary/common-german-words
#
# source activate scanki
# scrapy crawl Top1000GermWords
#
class Top1000GerWords(scrapy.Spider):
name = "Top1000GermWords"
start_urls = [
'http://www.languagedaily.com/learn-german/vocabulary/c... |
from pathlib import Path
from urllib.parse import urlparse
import site
from pynvim import Nvim
from paramiko import SFTPClient
from defx.action import ActionAttr
from defx.kind.file import Kind as Base
from defx.base.kind import action
from defx.clipboard import ClipboardAction
from defx.context import Context
from d... |
# -*- coding: utf-8 -*-
# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules
# Copyright (C) 2020-2021, Yoel Cortes-Pena <yoelcortes@gmail.com>
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt
# for license details... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-10-20 17:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0153_auto_20180911_1325'),
]
operations = [
migrations.AddField(
... |
import base64
import quopri
from .base import Param
__all__ = ["Base64Param", "QuotedPrintableParam"]
class EncodingParam(Param):
def __init__(self, value, decoder, encoder):
super().__init__("ENCODING", value)
self._decoder = decoder
self._encoder = encoder
def decode(self, text)... |
import re
import time
import isodate
import requests
from cloudbot import hook
from cloudbot.util import timeformat
from cloudbot.util.formatting import pluralize
youtube_re = re.compile(r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)([-_a-zA-Z0-9]+)', re.I)
base_url = 'https://www.googleapis.com/youtube... |
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.station import MonitoringStation
from floodsystem import flood, plot, stationdata
import datetime
def run():
"""Plots the water level over the past 10 days for the ... |
from .dataset import *
from .lightcurve import *
|
import sys
import os
class suppress(object):
def __init__(self,stdout = None, stderr = None):
self.devnull = open(os.devnull,'w')
self._stdout = stdout or self.devnull or sys.stdout
self._stderr = stderr or self.devnull or sys.stderr
def __enter__(self):
self.old_stdout, self.old_stderr = sys.stdout, sys.st... |
import subprocess
import os
cam_found = False
subprocess.Popen('sudo modprobe -r uvcvideo', shell=True)
while True:
if os.path.exists("/dev/video0"):
print "camera found"
break
else:
subprocess.Popen('sudo modprobe uvcvideo', shell=True)
time.sleep(2)
print "Try again"
|
import sys
import matplotlib.pyplot as plt
def read_line(line):
line = line.strip()
parts = line.split(',')
return float(parts[0]), float(parts[1]), int(parts[2])
def main(argv):
x_1 = []
y_1 = []
x_0 = []
y_0 = []
with open(argv[1], 'r') as in_file:
for line in in_file:
... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.1)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\xab\xed\
\xff\
\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x01\x00\x78\x00\
... |
#!/usr/bin/env python
import os
import shutil
import unittest
from kronos_executor import generate_read_files
from kronos_executor.global_config import global_config
from .testutils import scratch_tmpdir
class ReadFileGenerationTests(unittest.TestCase):
def test_human_readable_bytes(self):
"""
... |
# -*- coding: utf-8 -*-
from ..config import __hassympy__, __haspylatex__
if __hassympy__ and __haspylatex__:
import sympy as sy
from sympy import symbols, Function, diff, Matrix, MatMul, \
integrate, Symbol, sin, cos, pi, simplify
import pylatex as pltx
from pylatex import Section, Subsection... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from endpoints.utils.decorators import room_required
from django.conf import settings
from sources import source
class SearchView(APIView):
@room_required
def get(self, request, room, form... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://tech-blog.cloud-config.jp/2019-04-27-new-hire-training-windows-nfcpy/
import nfc
import binascii
clf = nfc.ContactlessFrontend('usb')
print('touch card:')
try:
tag = clf.connect(rdwr={'on-connect': lambda tag: False})
finally:
clf.close()
idm = binascii... |
from flask import Flask, send_file, send_from_directory, request
from werkzeug.utils import secure_filename
import subprocess
import random
import string
import tempfile
import tarfile
class CompileError(ValueError):
pass
def get_random_filename(length=15):
result = ''.join((random.choice(string.ascii_low... |
from django.contrib import admin
from django.urls import path, include
from .views import Quiz_View
app_name = 'Addon'
urlpatterns = [
path('quiz_hello', Quiz_View.loadHello, name='quiz_hello'),
path('quiz', Quiz_View.loadQuiz, name='quiz'),
path('quiz_next', Quiz_View.loadNextQuiz, name='quiz'),
... |
# -*- encoding: utf-8 -*-
# Copyright (c) 2021 Stephen Bunn <stephen@bunn.io>
# ISC License <https://choosealicense.com/licenses/isc>
"""Contains module-wide helpers."""
from .config import instance as config
from .log import DEFAULT_LOG_DIRPATH, configure_logger
from .log import instance as log
def setup_logging()... |
# -*- coding: utf-8 -*-
from django import http
from django.conf import settings
from django.core.exceptions import PermissionDenied
from redsocks.redisstore import SELF, RedisStore
from redsocks.exceptions import WebSocketError, HandshakeError, UpgradeRequiredError
from redsocks import log
DEFAULT_CHANNELS = [
's... |
import os
import numpy as np
import glob
class nms_iou(object):
def __init__(self, miji_thr=0.3, h_thr=0.3, nms_thr=0.05,num_thr=0):
self.miji_thr=miji_thr
self.h_thr=h_thr
self.nms_thr=nms_thr
# 输出第几个阈值的结果
self.num_thr=num_thr
def get_iou(self,bb, bbgt):
... |
#!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import datetime
import functools
import logging
from data.resource import ResourceData
class DayOhlcData(ResourceData):
def __init__(self, stock_id, latest_time=None, level: logging = logging.INFO,
logger_dir="resource_data", logger_name=datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")):
... |
import pandas as pd
import numpy as np
from numpy.random import randint
import os
import netCDF4
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
from tensorflow.keras.optimizers import Adam
import logging
logger = logging.getLogger(__nam... |
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1468532389.722097
_enable_loop = True
_template_filename = '/home/sumukh/Documents/thesis/Cyberweb... |
# -*- coding: utf-8 -*-
# Header ...
import numpy as np
import struct, os, math
from tensorflow.keras.utils import to_categorical as one_hot
def load_mnist(path, kind='train', num_classes=10):
labels_path = os.path.join(path,'%s-labels.idx1-ubyte'% kind)
images_path = os.path.join(path,'%s-images.idx3-u... |
"""Test Soup Sieve API."""
from __future__ import unicode_literals
import unittest
import bs4
import soupsieve as sv
from soupsieve import util
import copy
import random
import pytest
import pickle
class TestSoupSieve(unittest.TestCase):
"""Test Soup Sieve."""
def test_comments(self):
"""Test comment... |
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import (conjugate, im, re, sign)
from sympy.functions.elementary.exponential import (exp, log as ln)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigono... |
from werkzeug.exceptions import HTTPException
from werkzeug.serving import run_simple
from .router import Router
from .request import Request
from .response import Response
from injector import inject
class HttpKernel:
@inject
def __init__(self, router: Router):
self.router = router
def dispatch_... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 15:23:31 2015
@author: Ben
"""
import clearplot.plot_functions as pf
import numpy as np
xa = np.arange(0.1, 4, 0.5)
ya = 1.5 * np.exp(-xa) - 1.5
#Symmetric vertical error bars
xa_err = None
ya_err = 0.1 + 0.2*np.sqrt(xa)
xb = np.arange(0.01, 3.5, 0.5)
yb = 1.5 * np.si... |
from itertools import chain
import glob
import logging
import os
from functools import partial
from typing import List
import h5py
import numpy as np
from scipy import io as scio
from spdivik import types as ty
def _has_quilt() -> bool:
try:
import quilt
return True
except ImportError:
... |
import uuid
from appkernel import Role
from appkernel.model import resource
from checkout.orders.order_service import AuthorisationRequest
class PaymentService(object):
@resource(http_method='POST', require=[Role('user')])
def authorize(self, authorisation: AuthorisationRequest):
assert authorisatio... |
from .pytest_ethereum import ( # noqa: F401
deployer,
linker,
)
|
"""Thermal Grid Camera"""
import logging
import asyncio
import aiohttp
import async_timeout
import requests
import io
import math
import time
import numpy as np
import voluptuous as vol
from colour import Color
from PIL import Image, ImageDraw
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
from urllib.par... |
from __future__ import division
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import json
import time
import glob
import cv2
import math
from numpy import array
from sklearn.cluster import KMeans
from io import StringIO
from PIL import Im... |
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, BigInteger, Integer, Date, ForeignKey, Sequence, Table
from DatabaseModel import relationsFunctions as relations
from DatabaseModel.sqlalchemyCore import SQLBase as Base, GetUnitedSequence
def CreateModels(Base):
class PersonModel(Base)... |
# BSD 2-Clause License
#
# Copyright (c) 2021, Hewlett Packard Enterprise
# All rights reserved.
#
# 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 noti... |
import os
from django.conf import settings
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from backend_utils.logs import log_params
from logging import getLogger
log = getLogger(__name__)
class LogView(APIView):
"""
... |
import time
def prefixes(word):
"A list of the initial sequences of a word, not including the complete word."
return [word[:i] for i in range(len(word))]
def readwordlist(filename):
file = open(filename)
text = file.read().upper()
wordset = set(word for word in text.splitlines())
prefixset = s... |
from setuptools import setup
long_version = """
Flask extension that provides a common framework out of the box for
builing RESTful microservices. It integrates a common structure for
flask projects, json validation and unit testing.
"""
setup(
name='Flask-Philo-Core',
version='0.4.0',
description='Flas... |
description = 'Email and SMS notifiers'
group = 'lowlevel'
devices = dict(
# email = device('nicos.devices.notifiers.Mailer',
# description = 'Notifications via email',
# sender = 'sans1@frm2.tum.de',
# copies = [
# ('andreas.wilhelm@frm2.tum.de', 'important'),
# ('... |
from django.contrib.auth import login, logout, authenticate
from .models import ResumeCategory,Document,Profile,ProfileTransaction,HomeSlider, Region, Link, MetaData, Notification, SocialLink, OurTeam, OurService, GalleryPhoto, Testimonial, Blog, Parameter, FAQ, MainPic
from .enums import ParametersEnum, PicEnum, Profi... |
#!/usr/bin/python3 -i
# -*- coding: utf-8 -*-
import requests
import json
import subprocess
import time
from config import (JANUS_SCHEMA, JANUS_HOST, JANUS_PORT)
__version__ = '0.1.0'
janus_url = JANUS_SCHEMA + '://' + JANUS_HOST + ':' + str(JANUS_PORT) + '/janus'
mountpoint_id = "Ababagalamaga"
insttemplate = {
... |
"""Enrichment Component tests"""
from unittest import TestCase
import nose
from nose.tools import assert_equal, assert_not_equal, assert_raises, raises, \
assert_almost_equal, assert_true, assert_false, with_setup
import os
import warnings
import tables as tb
import numpy as np
import bright.enrichment_paramet... |
from __future__ import print_function, division
import gc
import time
from collections import Counter
from collections import namedtuple
from copy import copy, deepcopy
from datetime import timedelta
from sys import stdout
from warnings import warn
import matplotlib.pyplot as plt
import networkx as nx
import numpy as... |
#!/usr/bin/env python
"""
Compare two files for equality.
Usage::
python -m riboviz.tools.compare_files [-h]
-1 FILE1 -2 FILE2 [-n]
-h, --help show this help message and exit
-1 FILE1, --file1 FILE1
File1
-2 FILE2, --file2 FILE2
F... |
#1. Create a dictionary to hold the values
#dic = { '1':I,'4':IV,'5':V,'9':IX,'10':X,'40':XL,'50':L,'90':XC,'100':C,'400':CD,'500':D,'900':CM,'1000':M}
def int2rom(num):
numbs = [1,4,5,9,10,40,50,90,100,400,500,900,1000]
roms = ['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M']
i = len(numbs)-1
keep... |
#!/usr/bin/env python3
from decimal import Decimal
from robinhood.RobinhoodCachedClient import RobinhoodCachedClient, FORCE_LIVE
from robinhood.util import get_last_id_from_url
client = RobinhoodCachedClient()
client.login()
def display_popular_stocks():
popular_stocks = client.get_popular_stocks()['data']
pr... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can r... |
import time
import argparse
import json
import os
import glob
import sys
parser = argparse.ArgumentParser(description="Apache data cleaning + join")
parser.add_argument(
"--path",
type=str,
dest="data_path",
default="../../test/resources/2000.01.01.txt",
help="path or pattern to log data",
)
parser... |
# Copyright (c) 2019 China Telecom Corporation
# 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
#
# Un... |
N = int(input())
A = [int(input()) for _ in range(N)]
dic = {}
ans = 0
for a in A:
if dic.get(a, 0) > 0:
ans += 1
else:
dic[a] = 1
print(ans)
|
"""This module defines the asynchronous tasks needed for deposits, run via Celery."""
import logging
from celery.task.schedules import crontab
from celery.decorators import periodic_task
from django.conf import settings
from django.utils.timezone import now
from stellar_sdk.exceptions import BaseHorizonError
from ste... |
import logging
logging.basicConfig(level=logging.DEBUG)
# TODO: this needs to be done in a different way, this is just a quick hack
USE_TEST_DB = False
DB_TYPE = 'sqlite'
DB_FILE_NAME = 'locmess.sqlite'
PBKDF2_ITERATIONS = 1000 # number of pbkdf2 iterations
KEY_PATH = 'keys/server.key' # path of server's symmetri... |
import datetime
import os
from dateutil import rrule
from osgeo import gdal
import numpy as np
np.set_printoptions(linewidth=700, precision=2)
startTime = datetime.datetime.now()
print startTime
def cells(array):
window = array[480:510, 940:970]
return window
# Set start datetime object
start, end = datet... |
from django.core.exceptions import ValidationError
from wagtail.admin.forms import WagtailAdminPageForm
from bc.area_finder.utils import validate_postcode
class LookupPageForm(WagtailAdminPageForm):
def clean(self):
super().clean()
formset = self.formsets["responses"]
seen_values = set(... |
from ..base import ShopifyResource
from shopify import mixins
from .draft_order_invoice import DraftOrderInvoice
class DraftOrder(ShopifyResource, mixins.Metafields):
def send_invoice(self, draft_order_invoice = DraftOrderInvoice()):
resource = self.post("send_invoice", draft_order_invoice.encode())
... |
import aspose.pydrawing as drawing
import aspose.slides as slides
#ExStart:MultipleParagraphs
# The path to the documents directory.
dataDir = "./examples/data/"
outDir = "./examples/out/"
# Instantiate a Presentation class that represents a PPTX file
with slides.Presentation() as pres:
# Accessing first slide
... |
"""
Coordinames of TCP [0.9397630240339654, -0.3843922313849588, 0.4602265733339505]
ERROR = 0.001281180361159151
Approached
Input is insertion was successfull (y/n)
y
""" |
# mpcutilities/tests/test_ele220.py
"""
--------------------------------------------------------------
Nov 2018
Payne
Test the ele220 classes & functions written by Sonia Keys
These are for parsing & manipulating orbit data in MPC-220 format
Most / all of these tests were written by Sonia Keys
- Payne has... |
#!/usr/bin/env python
# D. Jones - 2/13/14
"""This code is from the IDL Astronomy Users Library"""
import numpy as np
def cntrd(img, x, y,
fwhm, verbose = True,
debug = False,
extendbox = False,
keepcenter = False):
"""Compute the centroid of a star using a derivative se... |
#Crie um script python que leia o dia, o mês e o ano de nacimento de uma pessoa
#e mostre uma mensagem com a data formatada.
dia=input('Digite o Dia do seu nascimento! ')
mes=input('Digite o Mês do seu nascimento! ')
ano=input('Digite o Ano do seu nascimento! ')
print('Você nasceu no dia', dia, 'de', mes, 'de', ano,'.... |
# Version 1.2
import requests
import json
from flask import Flask
from flask import request
from flask import Response
import sys
import random
import configparser
#/////////////// Parameters /////////////////
config = configparser.ConfigParser()
with open('default.json', 'r') as f:
config = json.load(f)
# CSE Pa... |
from rest_framework import serializers
from otree.models.subsession import BaseSubsession
from otree.models.group import BaseGroup
from otree.models.player import BasePlayer
from otree.models import Session, Participant
# we filter out these 'technical' fields.
block_fields = ['_gbat_arrived', '_gbat_grouped', '_index... |
from voximplant.apiclient import VoximplantAPI, VoximplantException
if __name__ == "__main__":
voxapi = VoximplantAPI("credentials.json")
# Deny all.
RULE_ID = 1
RULE_NAME = "denyall"
RULE_PATTERN_EXCLUDE = ".*"
try:
res = voxapi.set_rule_info(RULE_ID,
rule_name=R... |
# -*- coding: utf-8 -*-
"""Top-level package for Questioner."""
__author__ = """Lars Yencken"""
__email__ = 'lars@yencken.org'
__version__ = '0.1.0'
from .cli import Cli
|
# -*- coding: utf-8 -*-
import io
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='bamp',
version='0.2.3',
install_requires=['Click', 'd... |
"""test validate_bes_xml"""
import argparse
import os.path
import sys
# check for --test_pip arg
parser = argparse.ArgumentParser()
parser.add_argument(
"--test_pip", help="to test package installed with pip", action="store_true"
)
args = parser.parse_args()
if not args.test_pip:
# add module folder to impor... |
"""WebSocket Executor
=====================
"""
from trio_websocket import connect_websocket_url, WebSocketConnection, \
open_websocket_url
from trio import Nursery
from pymoa_remote.socket.client import SocketExecutor
__all__ = ('WebSocketExecutor', )
class WebSocketExecutor(SocketExecutor):
"""Executor t... |
import tensorflow as tf
from feeder import VarFeeder
import os
import argparse
import pandas as pd
import numpy
import logging
import yaml
import datetime
import math
import numpy as np
from typing import Tuple
import pickle
from predictor_dl_model.pipeline.util import get_dow
from typing import Tuple, Di... |
# General utility library
from re import match
import inspect
import sys
import ctypes
import logging
logger = logging.getLogger(__name__)
def comma_sep_list(input_lst):
"""Set up string or list to URL list parameter format"""
if not isinstance(input_lst, basestring):
# Convert list to proper format ... |
#
# @lc app=leetcode id=9 lang=python3
#
# [9] Palindrome Number
#
# https://leetcode.com/problems/palindrome-number/description/
#
# algorithms
# Easy (45.60%)
# Likes: 1728
# Dislikes: 1422
# Total Accepted: 728.9K
# Total Submissions: 1.6M
# Testcase Example: '121'
#
# Determine whether an integer is a palind... |
""" Module responsible with data augmentation """
import numpy as np
def augment_with_advantages(synergy, counter, radiant_heroes, dire_heroes):
""" Computes a numpy array containing the features that have to be appended to a game
Args:
synergy: synergy matrix
counter: counter matrix
r... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_bouncy', '0002_auto_20150927_1413'),
]
operations = [
migrations.CreateModel(
name='Delivery',
... |
# Copyright 2019-2021 Hewlett Packard Enterprise Development LP
#
# 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, ... |
from django.shortcuts import render, get_object_or_404
from .models import Album, Genre, Review
from .forms import AlbumForm, GenreForm, ReviewForm
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
return render(request, 'musicapp/index.html')
def getGenres(re... |
import os
from fastapi import FastAPI
from src.left.routes import create_routes
from src.right.in_memory.games_repository import InMemoryGamesRepository
basedir = os.path.abspath(os.path.dirname(__file__))
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
dependencies = { 'game... |
from argparse import ArgumentParser, FileType
from numpy import loadtxt, savetxt
from sys import stdin, stdout
import util
def get_args():
parser = ArgumentParser(prog="reddener")
parser.add_argument("-i", "--input", type=FileType("r"),
default=stdin.buffer,
help="Input table.")
parser.ad... |
FORMATS = ["CSM",
"LWS",
"B3D",
"COB",
"PLY",
"IFC",
"OFF",
"SMD",
"IRRMESH",
"3D",
"DAE",
"MDL",
"HMP",
"TER",
"WRL",
"XML",... |
from typing import List, Dict
from config import Config
def get_recipients(sheets, config: Config) -> List[Dict[str, str]]:
# Get the recipients sheet
sheet_id = config['recipients']['sheet_id']
range = f"{config['recipients']['tab']}!{config['recipients']['range']}"
recipients = sheets.values().get... |
import pytest
import os, shutil
from collections import OrderedDict
import pypospack.utils
from pypospack.task.lammps import LammpsNptSimulation
from pypospack.workflows import LammpsThermalExpansion
# Stillinger and Weber, Phy. Rev. B. v. 31, p.5262 (1985)
Si__stillingerweber = OrderedDict()
Si__stillingerweber['pot... |
import io
import requests
import sys
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.forms import AuthenticationForm
from django.contr... |
# -----------------------------------------------------------------------------
# define polarimetry parameters
# -----------------------------------------------------------------------------
def load_polar_parameters() :
#initialize parameters dictionary
p = {}
# Whether or not in APERO
p['... |
# Copyright 2018 Canonical Ltd.
#
# 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 writin... |
import ast
import logging
import signal
import time
from typing import Union, List
from kombu.utils.uuid import uuid
from kombu import Connection, Exchange
from amqp import AccessRefused
from leek.api.conf import settings
from leek.api.db.store import STATES_TERMINAL
from leek.api.errors import responses
from leek.ap... |
numbs = [int(x) for x in input().split()]
numbs = sorted(numbs)
A, B, C = numbs
lets = [char for char in input()]
for char in lets:
print(eval(char), end = ' ') |
import torch.nn as nn
import torch.nn.functional as F
from CNN.config_CNN import Config
class CNN(nn.Module):
def __init__(self, input_size, output_size):
super(CNN, self).__init__()
self.input_size = input_size
self.conv1 = nn.Conv2d(1, Config.conv1_num_filter, Config.conv1_size)
... |
import sys
import traceback
import pdb
from typing import Callable
__all__= ['run_and_debug']
def run_and_debug(func: Callable[[], None], enable_debugging: bool)-> None:
try:
func()
except:
if enable_debugging:
_, value, tb = sys.exc_info()
traceback.prin... |
#!/bin/python
#Copyright (c) 2013, Regents of the University of California
#All rights reserved.
#
#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... |
# Natural Language Toolkit Discretized attribute
# Capable of mapping continuous values to discrete ones
#
# Author: Sumukh Ghodke <sumukh dot ghodke at gmail dot com>
#
# URL: <http://nltk.sf.net>
# This software is distributed under GPL, for license information see LICENSE.TXT
from nltk_contrib.classifier import a... |
import atexit
import sys
# import threading
from flask import Flask, request, session, Response, jsonify
from flask_bcrypt import Bcrypt
from flask_restful import Resource, Api, reqparse
from flask_jwt_extended import (JWTManager, jwt_required, jwt_optional, create_access_token, get_jwt_identity, get_jwt_claims)
from f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.