text stringlengths 2 999k |
|---|
# @author Carey Nation
# @title Chapter 2, Exercise 2
# @description Calculate profit
PROFIT_MARGIN = 0.23
total_sales_s = input("Please enter your total sales: ")
try:
total_sales = float(total_sales_s)
profit = total_sales * PROFIT_MARGIN
print("Your profit is: %2.2f" % profit)
except:
print(tota... |
#!/usr/bin/env python
import os, re, sys, os.path, zipfile, contextlib
from classes import CreateQualityParams
# get the genome file
input_file = 'input.info'
fixMisencoded = 0;
# get the parameters in the class CreateQualityParams
params = CreateQualityParams()
# function to check if the fixMisencoded for the geno... |
import json
names = ['ali', 'mehrdad', 'naeim', 'masoud', 'omid']
file_name = 'names.json'
with open(file_name, 'w') as f:
json.dump(names, f)
with open (file_name) as f:
my_read = json.load(f)
print(my_read) |
# Shell Game, by Al Sweigart al@inventwithpython.com
# A random gambling game.
import random, time, sys
print('''SHELL GAME
By Al Sweigart al@inventwithpython.com
Try to find the diamond!
Press Enter to continue...''')
input()
CUPS = ['diamond', 'pocket lint', 'nothing']
while True:
print()
print('Shufflin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import find_packages
from setuptools import setup
setup(
name='ftl',
version='0.0.7',
packages=find_packages(),
install_requires=[
'h2',
'hpack',
'multidict>=3.1.3',
],
author='Adam Rothman',
author_e... |
import torch
from torch.autograd import Variable
from torch import nn, optim
import torch.nn.functional as F
from transformers import BertForSequenceClassification, BertModel
class BertClassification(nn.Module):
def __init__(self, model="bert-base-uncased"):
super().__init__()
self.bert = BertFor... |
#!/usr/bin/env python3
from pl_curve import calculate_cumulative_relative_abundance
from pl_curve import remove_cumulative_abundance_over_one
from pl_curve import calculate_cumulative_prop_trf
import pandas
import numpy as np
def test_calculate_cumulative_prop_trf():
data1 = np.array([['', 'Step I'],
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Refnet Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Linux network utilities.
Roughly based on http://voorloopnul.com/blog/a-python-netstat-in-less-than-100... |
# 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 the... |
from __future__ import print_function
import os.path
import apertium
import typing
import random
import re
import json
PATTERN = re.compile(r'[#\@\*;]+')
path = '/home/jacob/Coding projects/Trumpifyve/campaignCorpus/Trump_Campaign_Corpus/trump_campaign_corpus.json'
min_langs = 5
batch_size=128
write_path = '/home/jac... |
from ..check import Check
_REQUIRED_FIELDS = set(['description'])
_OPTIONAL_FIELDS = set([
'author', 'es5id', 'es6id', 'esid', 'features', 'flags', 'includes',
'info', 'negative', 'timeout'
])
_VALID_FIELDS = _REQUIRED_FIELDS | _OPTIONAL_FIELDS
class CheckFeatures(Check):
'''Ensure tests specify only `fea... |
# -- api request for BTC and ETH cryptocurrencies --
import requests
import csv
API_KEY = 'A6I5R4BAUKN0Z9CU'
function = 'DIGITAL_CURRENCY_DAILY'
symbol = input("Please write the ticker symbol of the cryptocurrency: ")
market = 'USD'
def get_crypto_raw(API_KEY, function, symbol, market):
url = f'https://www.alp... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# If extensions (or modules to document with autodoc) are in another directory,
# add ... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Copyright (c) 2017-2020 The Sheet Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test transaction signing using the signrawtransact... |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='family',
parent_name='bar.marker.colorbar.titlefont',
**kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=pl... |
#!/usr/bin/python
# Created by Korey McKinley, Senior Security Consulant at LMG Security
# https://lmgsecurity.com
# July 12, 2019
# This tool will query the Microsoft Office 365 web server to determine
# if an email account is valid or not. It does not need a password and
# should not show up in the logs of a clien... |
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, merg... |
from __future__ import division
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import cv2
from util import *
from darknet import Darknet
from preprocess import prep_image, inp_to_image
import pandas as pd
import random
import pickle as pkl
import argparse
def ... |
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import uuid
import requests_mock
import warnings
from canvasapi import Canvas
from canvasapi.file import File
from canvasapi.folder import Folder
from tests import settings
from tests.util import register_uris, cleanup_... |
"""added tags
Revision ID: 31728148ab63
Revises: add5f60f0f67
Create Date: 2020-01-20 15:11:56.273986+00:00
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '31728148ab63'
down_revision = 'add5f60f0f67'
branch_labels = None
depends_on = None
def upgrade():
... |
"""
In information theory, the Hamming distance between two strings
of equal length is the number of positions at which the corresponding symbols
are different. Calculate the Hamming distace for the following test cases.
Calculate the hamming distance of the two strings
Args:
str1(string),str2(string): ... |
from io import BytesIO
from ledger.settings_base import TIME_ZONE
from django.utils import timezone
import requests
from requests.auth import HTTPBasicAuth
import json
import pytz
from django.conf import settings
from django.db import connection, transaction
from mooringlicensing.components.approvals.models import St... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2018-2020 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
import os
from .meta_voc import register_meta_voc, load_filtered_voc_instances
from .meta_coco import register_meta_coco
from .builtin_meta import _get_builtin_metadata
from detectron2.data import DatasetCatalog, MetadataCatalog
# -------- COCO -------- #
def register_all_coco(root="datasets"):
METASPLITS = [
... |
#Librerias para webservice_request(nit)
from zeep import Client
import os
import codecs
#Funciones para lectura de XML e
#inserción del mismo en BD
import logging
import pyodbc
import pandas as pd
import numpy as np
#xml
from collections import OrderedDict
import xml.etree.ElementTree as ET
import collections
from ... |
from big_ol_pile_of_manim_imports import *
from old_projects.crypto import sha256_tex_mob, bit_string_to_mobject, BitcoinLogo
def get_google_logo():
result = SVGMobject(
file_name = "google_logo",
height = 0.75
)
blue, red, yellow, green = [
"#4885ed", "#db3236", "#f4c20d", "#3cba5... |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
import numpy as np
import onnxruntime as ort
import torch
from mmcls.models.classifiers import BaseClassifier
class ONNXRuntimeClassifier(BaseClassifier):
"""Wrapper for classifier's inference with ONNXRuntime."""
def __init__(self, onnx_file,... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
import asyncio
from fastapi import APIRouter, File, Query, UploadFile
from fastapi.responses import ORJSONResponse
from loguru import logger
from textblob import TextBlob
router = APIRouter()
title = "Delay in Seconds"
@router.post(
"/spellcheck",
tags=["textblob"],
response_desc... |
import os
import csv
import sys
import time
import subprocess
LOG_FILE = "validation.log"
ONLY_ANALYSIS = False
'''
Instances and seeds used for the article 'Binary Classification On Hypergraphs'
'''
INSTANCES = [
('adult', None), # 1509029032), # 0.8217306
#('audiology', 1506863181), # 0.9886078
#('breas... |
from dataclasses import dataclass
from silicoin.types.blockchain_format.sized_bytes import bytes32
from silicoin.util.ints import uint32
from silicoin.util.streamable import Streamable, streamable
@dataclass(frozen=True)
@streamable
class PoolTarget(Streamable):
puzzle_hash: bytes32
max_height: uint32 # A m... |
from routes.routes_user import (
current_user,
login_required,
)
from utils import (
template,
http_response,
redirect,
)
from models.todo import Todo
from models.user import User
def index(request):
"""
todo 首页 的路由函数
"""
# 找到当前登录的用户, 如果没登录, 就 redirect 到 /login
uid = current_us... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import time
import subprocess
# Import parameters from the setup file.
sys.path.append('.')
from setup import (
setup_dict, get_project_files, print_success_message,
print_failure_message, _lint, _test, _test_all,
CODE_DIR... |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017 Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to... |
import os
import sys
import logging
from multiprocessing import Process
SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
PACKAGE_PATH = os.path.abspath(os.path.join(SCRIPT_PATH, ".."))
sys.path.append(PACKAGE_PATH)
from settings import *
level = logging.INFO
if 'LOGGING_DEBUG' in locals():
if LOGGING_DEB... |
from rest_framework import permissions
class IsTeacher(permissions.BasePermission):
message = "Only teacher is allowed to perform this action."
def has_permission(self, request, view):
return request.user.is_teacher
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('hiwi_portal', '0018_auto_20160103_2026'),
]
operations = [
migrations.RemoveField(
model_name='worklog',
... |
# Copyright 2013-2019 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)
#: major, minor, patch version for Spack, in a tuple
spack_version_info = (0, 13, 2)
#: String containing Spack version ... |
from .metriccronjob import CronProcessor
from .mismatchcron import AlertCronProcessor |
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import FileExtensionValidator
# Create your models here.
class Profile(models.Model):
username = models.CharField(max_length = 255,blank=True)
user = models.OneToOneField(User,on_delete=models.CASCADE)
bio ... |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
import logging
from pajbot import utils
from pajbot.apiwrappers.base import BaseAPI
from pajbot.apiwrappers.twitch.base import BaseTwitchAPI
from pajbot.apiwrappers.twitch.helix import TwitchGame, TwitchVideo
from p... |
from datetime import date
import pytest
from db.models.profile_state import ProfileState
from db.models.student import Student
@pytest.fixture
def student_valid_args(create_user, create_branch, create_job_type):
return {
'user': create_user,
'mobile': '0279929444',
'street': 'Teststrasse... |
from hashlib import md5
from unittest import mock
import pytest
from django.conf import settings
from imagekit.cachefiles import ImageCacheFile, LazyImageCacheFile
from imagekit.cachefiles.backends import Simple
from .imagegenerators import TestSpec
from .utils import (DummyAsyncCacheFileBackend, assert_file_is_fals... |
# -*- coding: utf-8 -*-
#
# 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
#... |
#!/usr/bin/env python
"""
Script for setting up and using [all]reduce with a binary-tree engine interconnect.
usage: `python bintree_script.py`
This spanning tree strategy ensures that a single node node mailbox will never
receive more that 2 messages at once. This is very important to scale to large
clusters (e.g.... |
"""Linear Search."""
def linear_search(myList, item):
"""Linear search through a list to find an item."""
"""
Args:
myList: List to search through.
item: Item to find.
Return: Return True if item is found and False otherwise.
"""
position = 0
found = False
while positi... |
import re
def security(data):
# <input type="hidden" name="login_security" value="158911e7321cdb70d91e4c91dcebba9a-609d143b876affd0e1e949f98257682d">
return re.findall('<input.+hidden.+login_security.+value="(.+)"', data)[0]
|
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..dti import DTLUTGen
def test_DTLUTGen_inputs():
input_map = dict(
acg=dict(argstr='-acg', ),
args=dict(argstr='%s', ),
bingham=dict(argstr='-bingham', ),
environ=dict(
n... |
import os
from django.conf.urls.defaults import patterns, include, url
from local_settings import SETTINGS
docroot = os.path.dirname(os.path.abspath(__file__)) + '/dashboard/static'
urlpatterns = patterns('',
# API
url(r'^api/connections/?$', 'copilot_dashboard.dashboard.views.connections', name='connections'),
... |
from selenium import webdriver
#from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ActionChains
#chromeOptions = Options()
#chromeOptions.add_experimental_option("pref",{"download.default_directory":"c:\Downloadedfiles"})
driver = webdriver.Chrome() # give executabe_path = "dr... |
from symbol.builder import FasterRcnn as Detector
from symbol.builder import MXNetResNet50V2 as Backbone
from symbol.builder import Neck
from symbol.builder import RpnHead
from symbol.builder import RoiAlign as RoiExtractor
from symbol.builder import BboxC5Head as BboxHead
from mxnext.complicate import normalizer_facto... |
import os
import subprocess
import sys
from typing import Dict, List, Union
from app.pipelines import Pipeline
class SentenceSimilarityPipeline(Pipeline):
def __init__(
self,
model_id: str,
):
# At the time, only public models from spaCy are allowed in the inference API.
full_... |
# Copyright (C) 2015-2021 by Vd.
# This file is part of Rocketgram, the modern Telegram bot framework.
# Rocketgram is released under the MIT License (see LICENSE).
from dataclasses import dataclass
from typing import Optional
from .request import Request
from .utils import BoolResultMixin
@dataclass(frozen=True)
... |
from django.contrib import admin
class ProjektyGminneAdminSite(admin.AdminSite):
site_header = "Projekty Gminne - Warszawa"
index_template = "admin/base/index.html"
login_template = "admin/base/login.html"
admin_site = ProjektyGminneAdminSite(name="projekty-gminne-admin-site")
|
from bisect import bisect_right
from logging import getLogger
from typing import Any, Dict, List, Optional
from dgl import unbatch
from torch.nn import LogSoftmax, Module, NLLLoss
from formatml.models.model import Model
from formatml.modules.graph_encoders.graph_encoder import GraphEncoder
from formatml.modules.misc.... |
# coding: utf-8
import copy
import logging
import os
import sys
import time
import numpy as np
import pytest
import ray
import ray.cluster_utils
import ray._private.gcs_utils as gcs_utils
from ray._private.test_utils import (
SignalActor, kill_actor_and_wait_for_failure, put_object,
wait_for_condition, new_s... |
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2018 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
#
# Authors: Salim Fadhley <salimfadhley@gmail.com>
# Matteo Dell'Amico <matteodellamico@gmail.com>
"... |
# coding: utf-8
#
# Copyright 2021 The Oppia 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 requi... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
from abc import ABC, abstractmethod
# Abstract class for ROOM listener
# class is just an interface of functions to handle the Room events received
# from DataFeed see Real Time Events in REST API documentation for more
# details. The developer will handle actual event logic in your implementation
# of this abstract c... |
#!/usr/bin/env python
"""
This file will preprocess the SuperGLUE Winograd Schema Challenge data, aligning the span indices
to the tokenizaer of choice, and saving as a JSON file.
An example of the span index transformation is below:
[Mr., Porter, is, nice] with span indices [0, 2] -> [Mr, ., Por, ter, is, nice ]
wit... |
#Exercicio 1
def ex1(vet):
for i in range(3):
if vet[i] >= 0:
vet[i] = 1
else:
vet[i] = 0
return vet
vet = [0]*3
for i in range(3):
vet[i] = int(input('Digite um valor: '))
print(vet)
ex1(vet)
print(vet)
-------------------------------------------... |
#!/usr/bin/env python3
from hash_table import HashTable
from hash_table_with_collision import HashTable as HashTableCollision
def main():
print("Simple Hash Table")
t = HashTable()
t['test 1'] = 120
t['test 2'] = 130
print(t['test 2'])
del(t['test 1'])
print(t.arr)
print("*" * 50)
... |
# Auto-generated by pydicom-data-sr
# -*- coding: utf-8 -*-
from typing import Dict, List, Tuple
concepts_DCM: Dict[str, Dict[str, Tuple[str, List[int]]]] = {
"AAPM204APDimension": {
"113935": ("AAPM 204 AP Dimension", [10023]),
},
"AAPM204EffectiveDiameterEstimatedFromPatientAge": {
"113... |
"""
Django settings for williambucks_28640 project.
Generated by 'django-admin startproject' using Django 2.2.2.
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/
"""
i... |
# Copyright 2016 The TensorFlow 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 applica... |
from oscar.apps.checkout.app import CheckoutApplication
from oscar.core.loading import get_class
class Przelewy24CheckoutApplication(CheckoutApplication):
payment_details_view = get_class(
'apps.checkout.views', 'Przelewy24PaymentDetailsView')
application = Przelewy24CheckoutApplication()
|
import pandas as pd
import numpy as np
import os
import albumentations as A
import torch
from torch.utils.data import Dataset
import random
# import cv2
from skimage.io import imread
SEED = 42
TRAIN_RATIO = 0.9
class PadChest(Dataset):
"""
PadChest dataset
Hospital San Juan de Alicante - University of Alic... |
"""Smoke tests ranging across the CIDC REST API.
This file doesn't contain tests for methods that don't directly correspond
to data resources, like endpoints that handle upload-related functionality.
"""
from cidc_api.models.templates.trial_metadata import ClinicalTrial
from collections import OrderedDict
from cidc_ap... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
from typing import List, Tuple
import logging
import sys
import argparse
... |
#!/usr/bin/env python3
# Copyright (c) 2017-2019 The ReBitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test that the wallet can send and receive using all combinations of address types.
There are 5 nodes... |
""" This module refers to unpackaged directories needed by this package. """
import os
# The location of the AppScale git repository.
APPSCALE_HOME = os.path.join('/root', 'appscale')
# The location of the Python AppServer.
APPSCALE_PYTHON_APPSERVER = os.path.join(APPSCALE_HOME, 'AppServer')
# The location of the da... |
import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import graphviz
import matplotlib
import matplotlib.cm as cm
# define which genes are targets of drugs
rectangles = ['ACVR2A', 'AURKC', 'BRSK1', 'CDK17', 'EGFR', 'FGFR1', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Lorena Mesa'
SITENAME = 'What To Do Today USA Election 2020'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Chicago'
DEFAULT_LANG = 'en'
# Theme Settings
THEME = 'pelican-mg'
ALT_NAME = 'WHAT TO DO TODAY USA ELECTI... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [ ]
setup_requirements = [ ]
test_re... |
#!/usr/bin/env python
"""Download ERA5 variables."""
import argparse
import textwrap
import sys
from datetime import datetime
import era5cli.inputref as ref
import era5cli.info as einfo
import era5cli.fetch as efetch
def _level_parse(level):
"""Parse levels as integers, or the string 'surface'"""
if level ... |
def palindromeCheck(str):
return str[::-1] == str
print(palindromeCheck('mom')) #True
print(palindromeCheck('dope')) #False
|
"""
Created by Marcel Santos - Intel Intelligent Systems Lab - 2021
This script implements several utility routines for manipulating tensorflow records.
"""
import tensorflow as tf
def image_feature(value):
"""Returns a bytes_list from a string / byte."""
return tf.train.Feature(
bytes_list=tf.train.B... |
import logging
from pyfiles.db import player, character, attributes
from pyfiles.db.character import CHARACTER_DATA_JSON_NAME
from pyfiles.db.attributes import ATTRIBUTES_JSON_NAME, ATTRIBUTE_SCORES_JSON_NAME
from pyfiles import userInput, playerController
from pyfiles.model import overworld
from pony.orm.core import... |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class Link(Component):
"""A Link component.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional)
- href (string; optional)
- refresh (boolean; optional)
- c... |
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
message = ' '.join(sys.argv[1:]) or "Hello World!"
channel.basic_publish(exchange='',
routing_key='task... |
"""
This module converts requested URLs to callback view functions.
RegexURLResolver is the main class here. Its resolve() method takes a URL (as
a string) and returns a tuple in this format:
(view_function, function_args, function_kwargs)
"""
from __future__ import unicode_literals
import functools
import re
im... |
from __future__ import division, print_function
from types import FunctionType
from mpmath.libmp.libmpf import prec_to_dps
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.compatibility import (
Callable, NotIterable, as_int, default_sort_key, is_sequence, range,
reduce, stri... |
from __future__ import print_function
import unittest
import os
import datetime
from support.pyro import async as async_util
from support.configuration import tams_config
test_dir = os.path.dirname(os.path.abspath(__file__))
class TestConfiguration(unittest.TestCase):
def test_on(self):
class Handler... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from ._enums import *
from .domain import *
from .domain_topic import *
from .event_subscription import *
f... |
"""Tests for the evaluate_teams module."""
import cStringIO
import csv
import json
import logging
import zipfile
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
class TestEvaluateTeams(TestCase):
"""Te... |
import sys
import json
'''
Derive the sentiment of new terms from the twitter data
a script that computes the sentiment for the terms that do not appear in the file AFINN-111.txt.
Schamnad, 16 Nov 2016
'''
# build the dicionary of sentiment of each word form the AFINN-111 file
def build_sent_dict(sent_file):
... |
#!/usr/bin/env python
# encoding: utf-8
# Copyright (C) Alibaba Cloud Computing
# All rights reserved.
__all__ = ['CreateLogStoreResponse', 'DeleteLogStoreResponse', 'GetLogStoreResponse',
'UpdateLogStoreResponse', 'ListLogStoreResponse']
from .util import Util
from .logresponse import LogResponse
class... |
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
from MainWindow import Ui_MainWindow
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
... |
"""Auto-generated file, do not edit by hand. VC metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_VC = PhoneMetadata(id='VC', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='9\\d{2}', possible_length=(3,)),
em... |
class ScoreCard:
def __init__(self, score_text: str):
score_texts = score_text.split('|')
self.normal_turns = [score_texts[i] for i in range(10)]
if len(score_texts) == 12:
self.additional_turns = [score_texts[11]]
self.all_turns = self.normal_turns + self.additional_tur... |
import time
import RPi.GPIO as GPIO
from moisture import *
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
def servoinit():
GPIO.setup(24, GPIO.OUT)
def servodown():
pwm=GPIO.PWM(24,100)
pwm.start(8.5)
pwm.ChangeDutyCycle(8.5)
time.sleep(0.8)
def servoup():
pw... |
"""Track and analyze grocery spending at an item level.
This app allows a user to input a grocery item.
"""
# app.py
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import plotly.express as ... |
"""
Copyright Snap Inc. 2021. This sample code is made available by Snap Inc. for informational purposes only.
No license, whether implied or otherwise, is granted in or to such code (including any rights to copy, modify,
publish, distribute and/or commercialize such code), unless you have entered into a separate agree... |
from django.http import Http404
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.views import APIView
from time_entries.models import TimeEntry
from t... |
from tulip import *
import tulipplugins
class SetSizeComponent(tlp.SizeAlgorithm):
def __init__(self, context):
tlp.SizeAlgorithm.__init__(self, context)
self.addSizePropertyParameter("Size property","The size property to modify",
"viewSize", True, True, False)
self.addStringCollectio... |
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file accom... |
from django.apps import apps
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.state import StateApps
from django.test import TestCase
# Use this TestCase class in order to test migrations
# migrate_from – the name of the migration where the test st... |
import logging
import os
import shutil
from tempfile import mkdtemp
import pytest
try:
from unittest import mock
except ImportError:
import mock
try:
import pathlib
except ImportError:
import pathlib2 as pathlib
from jsonextended.utils import MockPath
from atomic_hpc.config_yaml import format_config_y... |
# Generated with SMOP 0.41-beta
try:
from smop.libsmop import *
except ImportError:
raise ImportError('File compiled with `smop3`, please install `smop3` to run it.') from None
# BSM_Greeks.m
@function
def BSM_Greeks(G=None,S_0=None,sigma=None,r=None,q=None,T=None,K=None,call=None,*args,**kwargs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.