content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from django.apps import AppConfig
class TrantoolConfig(AppConfig):
name = 'transtool'
# todo check settings and show errors if there are any mistakes
| python |
from layout import fonts
import pygame
from utils import gen_text_object
class Button:
def __init__(self, display, x, y, w, h,
color_active, color_inactive, border_w, border_color, pressed_down_color, text_color_norm,
text_color_pressed, text='', action=None, jump_inc=0):
... | python |
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了88.07% 的用户
内存消耗:13.4 MB, 在所有 Python3 提交中击败了42.98% 的用户
解题思路:
双指针
p指针用于记录位置,q指针寻找小于x的节点。
q指针找到<x的节点后,交换链表
"""
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
p, q = ListNode(0, next = head), head ... | python |
import logging
from typing import Any, Dict
import requests
LOG = logging.getLogger(__name__)
class Client:
CROSSWALK_ENDPOINT = '/crosswalks'
STATISTICS_ENDPOTIN = '/statistics'
TOKEN_ENDPOINT = '/login/access-token'
def __init__(self, base_url: str, username: str, passwd: str) -> None:
se... | python |
from tacred_enrichment.internal.ucca_enhancer import UccaEnhancer
from tacred_enrichment.internal.ucca_types import UccaParsedPassage
from tacred_enrichment.internal.dep_graph import Step, DepGraph
from tacred_enrichment.internal.ucca_types import is_terminal
class UccaEncoding(UccaEnhancer):
def enhance(self, t... | python |
from flask import jsonify
class InvalidSearchException(ValueError): pass
class InvalidRequestException(Exception):
def __init__(self, error_message, code=None):
self.error_message = error_message
self.code = code or 400
def response(self):
return jsonify({'error': self.error_message... | python |
from argparse import ArgumentParser
import pysam
def merge(input_path, output_path, custom_id='custom_id', line_length=80):
with open(output_path, 'w+') as out_f:
out_f.write(f'>{custom_id}\n')
data = ''
with pysam.FastxFile(input_path) as in_f:
for record in in_f:
... | python |
n=input()
if(len(n)<4):
print("NO")
else:
count=0
for i in range(0,len(n)):
if(n[i]=='4' or n[i]=='7'):
count=count+1
dig=0
flag=0
if(count==0):
print("NO")
else:
while count>0:
dig=count%10
if(dig!=4 and dig!=7):
fl... | python |
# Generated by Django 2.2.3 on 2019-07-12 14:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('TeamXapp', '0047_auto_20190712_1504'),
]
operations = [
migrations.AlterField(
model_name='allm... | python |
import os
import numpy
import math
import cv2
from skimage import io
from skimage import color
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from random import randint
class ClusterDataset(Dataset):
"""Camera localization dataset."""
def __cluster__(self, root_dir, num_exp... | python |
import pytest
from pretalx.common.forms.utils import get_help_text
@pytest.mark.parametrize('text,min_length,max_length,warning', (
('t', 1, 3, 't Please write between 1 and 3 characters.'),
('', 1, 3, 'Please write between 1 and 3 characters.'),
('t', 0, 3, 't Please write no more than 3 characters.'),
... | python |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
Provides a set of I/O routines.
.. include common links, assuming primary doc root is up one directory
.. include:: ../links.rst
"""
import os
import sys
import warnings
import gzip
import shutil
from packaging import version
... | python |
# stateio.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
"""
Supporting functions for accessing files from stateior via data commons.
https://github.com/USEPA/stateior
"""
import os
import pandas as pd
from esupy.processed_data_mgmt import download_from_remote, Paths,\
load_preprocessed_output
from flowsa.met... | python |
from sys import argv
import json
finalOutput = {"result": ""}
outputFile = argv[3]
if_spark = argv[4]
reviewFile = argv[1]
businessFile = argv[2]
nCates = int(argv[5])
def no_spark():
def LOAD_FILE(filePath):
output = []
with open(filePath) as file:
for line in file:
... | python |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import dj_database_url
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable f... | python |
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from PIL import Image
import scipy.misc
import pandas as pd
import numpy as np
import random
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from glob import glob
from torch.util... | python |
"""
Define some reference aggregates based on *exact* site names
"""
import logging
import pandas as pd
from solarforecastarbiter import datamodel
from solarforecastarbiter.io import api
logger = logging.getLogger('reference_aggregates')
REF_AGGREGATES = [
{
'name': 'NOAA SURFRAD Average GHI',
... | python |
import sys
import unittest
import dask.array as da
import dask.distributed as dd
import numpy as np
import xarray as xr
# Import from directory structure if coverage test, or from installed
# packages otherwise
if "--cov" in str(sys.argv):
from src.geocat.comp import heat_index
else:
from geocat.comp import h... | python |
# INPUT
N = int(input())
A = [int(input()) for _ in range(N)]
# PROCESSES
"""
Critical observation:
To reach a value $V$, we must have come from a value SMALLER than $V$ AND that is before it.
Assuming that ALL values before $V$ have an optimal solution, we can find the optimal solution for $V$.
Define the DP ta... | python |
""" Simple mutually-recursive coroutines with asyncio. Using asyncio.ensure_future
instead of yield from allows the coroutine to exit and merely schedules the next
call with the event loop, allowing infinite mutual recursion. """
import asyncio
@asyncio.coroutine
def a(n):
print("A: {}".format(n))
asyncio.asy... | python |
from __future__ import unicode_literals
from collections import OrderedDict
from django import forms
from django.forms.widgets import Textarea
from django.utils.translation import ugettext_lazy as _
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
mark_safe_lazy = lazy(mark_safe... | python |
"""
Just another Python API for Travis CI (API).
A module which provides the tests of our requester module.
Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Project link:
https://github.com/funilrys/PyTravisCI
Project documentation:
https://pytravisci.readthedocs.io/en/latest/
License
::... | python |
#!/usr/bin/env python
from __future__ import print_function, division, absolute_import
import sys
from channelfinder import ChannelFinderClient, Channel, Property, Tag
import aphla as ap
#GET http://channelfinder.nsls2.bnl.gov:8080/ChannelFinder/resources/resources/channels?~name=SR*
cfsurl = 'http://web01.nsls2.bn... | python |
from django.db import models
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class PinCard(models.Model):
token = models.CharField(max_length=32, db_index=True, editable=False)
display_n... | python |
#!/usr/bin/env python
"""The setup script."""
from setuptools import (
find_packages,
setup,
)
from authz import __version__
with open('README.md') as readme_file:
readme = readme_file.read()
requirements = ["casbin==1.9.3"]
test_requirements = ['pytest>=3', ]
setup(
author="Ezequiel Grondona",
... | python |
real = float(input('Quanto você tem na Carteira? R$'))
dolar = real / 5.11
euro = real / 5.76
print('Com R${:.2f} você pode comprar U$${:.2f} e €{:.2f} '.format(real, dolar, euro))
| python |
def fib(n):
if (n==0):
return 0
elif (n==1):
return 1
else:
x = fib(n-1) + fib(n-2)
return x
print(fib(6))
| python |
#!/usr/bin/python
from hashlib import sha1
from subprocess import check_output
import hmac
import json
import os
import sys
# Due to |hmac.compare_digest| is new in python 2.7.7, in order to be
# compatible with other 2.7.x version, we use a similar implementation of
# |compare_digest| to the Python implementation.... | python |
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'ix4hnvelil^q36!(bg#)_+q=vkf4yk)@bh64&0qc2z*zy5^kdz'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'user',
'job',
'ckeditor',
'django_filters',
'widget_tweaks',
'django.contrib.admin',
... | python |
import io
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import time
class Analyzer:
'''Controls plotting of different object properties'''
def __init__(self):
self.plot_number = 1
self.xdata = []
self.reactors = []
self.reactor_numbe... | python |
from ..gl import AGLObject, GLHelper
from ...debugging import Debug, LogLevel
from ...constants import _NP_UBYTE
from ...autoslot import Slots
from OpenGL import GL
import numpy as np
import time
class TextureData(Slots):
__slots__ = ("__weakref__", )
def __init__(self, width: int, height: int):
self.width: int ... | python |
# This is a work in progress - see Demos/win32gui_menu.py
# win32gui_struct.py - helpers for working with various win32gui structures.
# As win32gui is "light-weight", it does not define objects for all possible
# win32 structures - in general, "buffer" objects are passed around - it is
# the callers responsibility to... | python |
import numpy as np
from numba import njit
@njit
def linspace(x1,x2,n):
'''
Jit compiled version of numpy.linspace().
'''
x = np.zeros(n)
x[0] = x1
x[-1] = x2
for i in range(1,n-1):
x[i] = x[0] + i*(x2-x1)/(n-1)
return x
@njit
def trapezoid(x,y):
'''
Jit compiled versio... | python |
from setuptools import setup, find_packages
setup(
name='k8sfoams',
version='1.0.2',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='https://github.com/mmpyro/k8s-pod-foamtree',
description='K8s pod foamtree visualizer',
author="Michal Marszale... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2019 Andreas Bunkahle
# Copyright (c) 2019 Bohdan Horbeshko
#
# 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 th... | python |
import threading
import datetime
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
import pandas as pd
import numpy as np
import time
from functools import reduce
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Ou... | python |
largura = float(input('Qual a largura da parede? '))
altura = float(input('Qual a altura da parede? '))
area = largura*altura
qtd_tinta = area/2
print(qtd_tinta) | python |
import os
from unittest.mock import call
import numpy as np
import pytest
import sparse
from histolab.slide import Slide
from histolab.tiler import RandomTiler, Tiler
from histolab.types import CoordinatePair
from ..unitutil import (
ANY,
PILImageMock,
SparseArrayMock,
function_mock,
initializer_... | python |
import numpy as np
import pandas as pd
import talib as ta
from cryptotrader.utils import safe_div
def price_relative(obs, period=1):
prices = obs.xs('open', level=1, axis=1).astype(np.float64)
price_relative = prices.apply(ta.ROCR, timeperiod=period, raw=True).fillna(1.0)
return price_relative
def momen... | python |
"""
@author : Krypton Byte
"""
import requests
def igdownload(url):
req=requests.get(url, params={"__a":1})
if ('graphql' in req.text):
media=req.json()["graphql"]["shortcode_media"]
if media.get("is_video"):
return {"status": True,"result":[{"type":"video", "url":media["video_url"]}... | python |
import requests
from bs4 import BeautifulSoup
#https://en.wikipedia.org/wiki/List_of_companies_operating_trains_in_the_United_Kingdom
def main():
urlList = ['https://twitter.com/ScotRail','https://twitter.com/LDNOverground','https://twitter.com/AvantiWestCoast','https://twitter.com/c2c_Rail','https://twitte... | python |
# coding: utf-8
nms = ['void',
'Front bumper skin',
'Rear bumper skin',
'Front bumper grille',
'network',
'Hood',
'Front fog lamp',
'Headlamp',
'Front windshield',
'Roof panel',
'Front fender',
'Rear fender',
'Front door shell outer plate',
'Rear door shell outer plate',
'Door glass front',
'Door glass rear',
'Rearvi... | python |
import httpretty
from tests import FulcrumTestCase
class MembershipTest(FulcrumTestCase):
@httpretty.activate
def test_search(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/memberships',
body='{"memberships": [{"id": 1},{"id": 2}], "total_count": 2, "current_page": 1, "tot... | python |
import pytest
from picorss.src.domain import entities
@pytest.fixture()
def rss_page() -> entities.RssPage:
return entities.RssPage(url="https://example.com")
def test_rss_page_has_url(rss_page: entities.RssPage) -> None:
assert rss_page.url
| python |
def process(self):
self.edit("LATIN")
self.replace("CAPITAL LETTER D WITH SMALL LETTER Z", "Dz")
self.replace("CAPITAL LETTER DZ", "DZ")
self.edit("AFRICAN", "african")
self.edit("WITH LONG RIGHT LEG", "long", "right", "leg")
self.edit('LETTER YR', "yr")
self.edit("CAPITAL LETTER O WITH... | python |
#!/usr/bin/env python3
# Write a program that computes typical stats
# Count, Min, Max, Mean, Std. Dev, Median
# No, you cannot import the stats library!
import sys
import math
units = []
#Create your list of integers/floating-point numnbers making sure to covert from strings
for i in sys.argv[1:]:
units.append(f... | python |
"""
Copyright (c) 2014, Samsung Electronics Co.,Ltd.
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, this
list of conditions ... | python |
import os
from config.config import get_config
import shutil
def main():
config = get_config()
if not os.path.exists(config.dataset):
print(f"[!] No dataset in {config.dataset}")
return
for image_transfer in os.listdir(config.dataset):
print(image_transfer)
if not '2' in ... | python |
'''
Created on 2020-02-13
@author: wf
'''
from flask import Flask
from flask import render_template
from flask import request
from dgs.diagrams import Generators,Generator,Example
import os
from flask.helpers import send_from_directory
import argparse
import sys
from pydevd_file_utils import setup_client_server_paths
... | python |
import boto3
import codecs
import xmltodict
import re
class Example:
'''Represents a single source line and all corresponding target lines
we would like a Turker to evaluate.
'''
def __init__(self, source_line, key):
self.source_line = source_line # The single source line
self.target_lines = [] # Lis... | python |
def inputMatrix(m,n, vektori = False):
if vektori:
border = "border-right: 2px solid black; border-left: 2px solid black; border-top: none; border-bottom: none;"
else:
border = "border: none;"
tmp = ""
tmp+= """
<div class="container">
<div style="border-left: ... | python |
from django.contrib import admin
from .models import Trailer
# Register your models here.
admin.site.register(Trailer) | python |
from sklearn.datasets import load_breast_cancer
dataset=load_breast_cancer()
x=dataset.data
y=dataset.target
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
from logistic_regression import LogisticRegression
clf=LogisticRegression(lr=0.01,n_iters=10... | python |
# En este ejercicio se nos solicitó:
# 1.- El retorno total y anualizado de tres stocks: SPY, VWO y QQQ entre 2015 y 2021 (ambos inclusive)
# 2.- Graficar el retorno acumulado de los stocks indicados durante ese mismo período
# Para ambos ejercicios se nos indicó que utilizáramos la free API key de Alpha Vantage
impor... | python |
# Aula 13 (Estrutura de Repetição for)
from time import sleep
for c in range(10, -1, -1):
print(c)
sleep(1)
print('BOOM!')
| python |
# Collaborators: https://www.decodeschool.com/Python-Programming/Branching-Statements/Divisible-by-3-or-not-in-python#:~:text=Program%20Explanation,3%20using%20print()%20method.
#
for x in range (2, 51):
if x % 3==0:
print ("{} is divisible by 3".format(x))
else:
print ("{} is not divisible b... | python |
import argparse
import os
from watermark_add_dct import do_singleRun_dct
from watermark_add_dwt import do_singleRun_dwt
from image_utils import encoding
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="main")
# general options
parser.add_argument(
"--inFolder",
type... | python |
"""Filters that are used in jobfunnel's filter() method or as intermediate
filters to reduce un-necessesary scraping
Paul McInnis 2020
"""
import logging
from collections import namedtuple
from copy import deepcopy
from datetime import datetime
from typing import Dict, List, Optional, Tuple
import nltk
import numpy as... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .ctdet import CtdetTrainer
from .exdet import ExdetTrainer
train_factory = {
'exdet': ExdetTrainer,
'ctdet': CtdetTrainer,
}
| python |
p1 = int(input('digite o primeiro termo:'))
r = int(input('digite a razõ da P.A'))
d= p1 + (10-1) * r
for c in range(p1-1,d,r):
print(c) | python |
import factory
import time
import random
from spaceone.core import utils
class MetricFactory(factory.DictFactory):
key = factory.LazyAttribute(lambda o: utils.generate_id('metric'))
name = factory.LazyAttribute(lambda o: utils.random_string())
unit = {
'x': 'Datetime',
'y': 'Count'
... | python |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... | python |
import lasagne
from lasagne.regularization import regularize_network_params, l2, l1
import time
import theano
import numpy as np
from theano.tensor import *
import theano.tensor as T
import gc
import sys
sys.setrecursionlimit(50000)
#then import my own modules
import seqHelper
import lasagneModelsFingerprints
#get m... | python |
"""Profile model."""
# Django
from django.db import models
# Utilities
from feelit.utils.models import FeelitModel
class Profile(FeelitModel):
""" Profile model.
Profile holds user's public data like bio, posts and stats.
"""
user = models.OneToOneField('users.User', on_delete=models.CASCADE)
... | python |
import re
ncr_replacements = {
0x00: 0xFFFD,
0x0D: 0x000D,
0x80: 0x20AC,
0x81: 0x0081,
0x81: 0x0081,
0x82: 0x201A,
0x83: 0x0192,
0x84: 0x201E,
0x85: 0x2026,
0x86: 0x2020,
0x87: 0x2021,
0x88: 0x02C6,
0x89: 0x2030,
0x8A: 0x0160,
0x8B: 0x2039,
0x8C: 0x0152,... | python |
"""The Twinkly API client."""
import logging
from typing import Any
from aiohttp import ClientResponseError, ClientSession
from .const import (
EP_BRIGHTNESS,
EP_COLOR,
EP_DEVICE_INFO,
EP_LOGIN,
EP_MODE,
EP_TIMEOUT,
EP_VERIFY,
)
_LOGGER = logging.getLogger(__name__)
class TwinklyClient:... | python |
"""add private column to group
Revision ID: 9612aba86eb2
Revises: 789ac8c2844f
Create Date: 2021-06-06 10:31:28.453405
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "9612aba86eb2"
down_revision = "789ac8c2844f"
branch_labels = None
depends_on = None
def upg... | python |
from stormberry.config import Config
import signal
import sys
import stormberry.logging
from stormberry.station import WeatherStation
from stormberry.plugin import ISensorPlugin, IRepositoryPlugin, IDisplayPlugin, PluginDataManager
from stormberry.plugin.manager import get_plugin_manager
class SignalHandling(object):... | python |
from use_cases.encryption.makeEncryptString import *
from use_cases.encryption.makeDecryptString import *
from use_cases.encryption.makeCreateKeyPair import *
| python |
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... | python |
import abc
class Policy(object, metaclass=abc.ABCMeta):
"""
General policy interface.
"""
@abc.abstractmethod
def get_action(self, observation):
"""
:param observation:
:return: action, debug_dictionary
"""
pass
def reset(self):
pass
class Ex... | python |
import os
os.chdir("Python/Logging")
# log_settings changes sys.excepthook to log_settings.log_exceptions, so
# importing log_settings is sufficient to capture uncaught exceptions to the
# log file, meanwhile they are also (still) printed to stdout
import log_settings
# adds 'Starting new program!' with timestamp to... | python |
class IBSException(Exception):
pass
#TODO: This doesn't make sense for negative numbers, should they even be allowed?
class NumericValue():
""" To store a number which can be read to/from LE or BE """
def __init__(self, value):
self.value = value
@classmethod
def FromLEBytes(cls, databytes... | python |
from pyrocko import automap
import math
import shutil
from pyrocko import model, gmtpy
from pyrocko.moment_tensor import magnitude_to_moment as mag2mom
from pyrocko.moment_tensor import to6
from pyrocko.guts import Object, Float, String, List
class ArrayMap(automap.Map):
stations = List.T(model.Station.T(), optio... | python |
import sys
import json
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
class Fetcher:
'''
The crawler class used for retrieving information from sodexo's menu page
Note:
Blitman Commons is not yet included in sodexo's page. The class should throw an ... | python |
import math
def round_up(n, multiple):
"""
can be used to ensure that you have next multiple if you need an int, but have a float
n = number to check
multiple = number you'd like to round up to
EX:
num_ranks = 64
num_ios = 26252
this is not an even number if you divide
returns t... | python |
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=["mushr_rhc_ros"], package_dir={"": "src"}
)
setup(install_requires=["numpy"... | python |
# Copyright 2018 Google, Inc.,
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | python |
from nltk.stem.porter import PorterStemmer
from nltk.tokenize import word_tokenize
import random
from tqdm import tqdm
from summariser.ngram_vector.base import Sentence
from summariser.ngram_vector.state_type import *
from utils.data_helpers import *
# from summariser.utils.data_helpers import *
class Vectoriser:
... | python |
# coding: utf-8
# In[7]:
import numpy as np
#toy example of fixImages_stackocclusions
#a = np.arange(16).reshape(4, 2, 2)
#b = a + 2
#print("a")
#print(a)
#print(2*'\n')
#print("b")
#print(b)
#print(2*'\n')
#print("stack_axis = 0")
#print(np.stack((a,b), axis=0))
#print(2*'\n')
#print("stack_axis = 1")
#print(np.s... | python |
# Copyright 2020 Antonio Macaluso
#
# 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 writ... | python |
# Generated by Django 3.0.3 on 2020-09-10 12:25
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sequence', '0026_sequence_coordinates_ele'),
]
operations = [
migrations.AddField(
mo... | python |
# -*- coding: utf-8 -*-
"""Query web services."""
import gzip
import logging
from ._bouth23 import bstream, s
from ._exceptions import ISBNLibHTTPError, ISBNLibURLError
from ..config import options
# pylint: disable=import-error
# pylint: disable=wrong-import-order
# pylint: disable=no-name-in-module
try: # pragma:... | python |
# Copyright 2014, Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
# rights in this software.
"""Functionality for managing scene graphs.
Note that the scenegraph is an internal implementation detail for developers
adding new functionalit... | python |
__all__ = ["analysis", "data", "geometry", "io", "util"] | python |
# coding: utf-8
#
from tornado.web import RequestHandler
from tornado.escape import json_decode
class BaseRequestHandler(RequestHandler):
pass
class IndexHandler(BaseRequestHandler):
def get(self):
self.write("Hello ATX-Storage")
| python |
import os
from Crypto.Protocol.KDF import scrypt
KEY_LENGTH = 32
N = 2**16 ##meant for ram
R = 10
P = 10
import binascii
import bcrypt
from loguru import logger
def generate_bcrypt(password):
if isinstance(password, str):
password = password.encode()
hashed =bcrypt.hashpw(password, bcrypt.gensalt())... | python |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
app_name = 'url_shorter'
urlpatterns = [
url(r'user_url_list/', views.UserURLListView.as_view(), name="user_url_list"),
url(r'user_url_create/', views.UserURLCreateView.as_view(), name="use... | python |
#!/usr/bin/python3
#coding=utf-8
"""
A flask based server for calculating.
@author: vincent cheung
@file: server.py
"""
from flask import Flask,render_template,request,redirect,url_for
from flask import send_file, Response
import os
import sys
sys.path.append('../')
from calculate import *
app = Flask(__name__)
@ap... | python |
if ((True and True) or (not True and True)) and \
(True or True):
pass | python |
value = '382d817119a18844865d880255a8221d90601ad164e8a8e1dd8a48f45846152255f839e09ab176154244faa95513d16e5e314078a97fdb8bb6da8d5615225695225674a4001a9177fb112277c45e17f85753c504d7187ed3cd43b107803827e09502559bf164292affe8aaa8e88ac898f9447119a188448692070056a2628864e6d7105edc5866b9b9b6ebcad6dc3982952a7674a62015025695225... | python |
from taichi.misc.util import *
from taichi.two_d import *
from taichi import get_asset_path
if __name__ == '__main__':
scale = 8
res = (80 * scale, 40 * scale)
async = True
if async:
simulator = MPMSimulator(
res=res,
simulation_time=30,
frame_dt=1e-1,
base_delta_t=1e-6,
... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys
con = lite.connect('Database.db')
with con:
cur = con.cursor()
#Create data for the user table
cur.execute("CREATE TABLE users(UserId INT, UserName TEXT, Password TEXT)")
cur.execute("INSERT INTO users VALUES(1,'Adm... | python |
import itertools
import logging
import os.path
import sys
import time
import click
import pychromecast
from pychromecast.error import PyChromecastError
import pylast
import toml
logger = logging.getLogger(__name__)
# Default set of apps to scrobble from.
APP_WHITELIST = ['Spotify', 'Google Play Music', 'SoundCloud'... | python |
from this_is_a_package import a_module
a_module.say_hello("ITC") | python |
# coding: utf-8
"""
CMS Audit Logs
Use this endpoint to query audit logs of CMS changes that occurred on your HubSpot account. # noqa: E501
The version of the OpenAPI document: v3
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from hubspot.cms.a... | python |
import numpy as np
import time
# Number of random numbers to be generated
nran = 1024
# Generate a random number from the normal distribution
result = [np.random.bytes(nran*nran) for x in range(nran)]
print(len(result), "======>>> random numbers")
# Wait for tsleep seconds
tsleep = 40
print("I am sleeping for {... | python |
# Example of using StagingAreaCallback for GPU prefetch on a simple convnet
# model on CIFAR10 dataset.
#
# https://gist.github.com/bzamecnik/b9dbd50cdc195d54513cd2f9dfb7e21b
import math
from keras.layers import Dense, Input, Conv2D, MaxPooling2D, Dropout, Flatten
from keras.models import Model
from keras.utils impor... | python |
from requests import get
READ_SUCCESS_CODE = 200
class ConfigurationGateway(object):
def __init__(self, url, executables_path, repositories_path, results_key):
self.url = url
self.executables_path = executables_path
self.repositories_path = repositories_path
self.results_key = r... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.