content stringlengths 5 1.05M |
|---|
import torch
"""Compute df/dtheta"""
def compute_df_dtheta(pi_, values_, return_, actor_network, value_network, gamma, c=0.5):
theta1 = torch.autograd.grad(pi_, actor_network.parameters())
theta1 = [item.view(-1) for item in theta1]
theta1 = torch.cat(theta1)
theta2 = torch.autograd.grad(values_, ... |
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2018 AT&T Intellectual Property
#
# 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
#
# ... |
"""add datetime to forum models
Revision ID: f3927c7ad77e
Revises: e32bf2e2b443
Create Date: 2016-11-24 01:44:05.894107
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f3927c7ad77e'
down_revision = 'e32bf2e2b443'
branch_labels = None
depends_on = None
def upg... |
"""
- finds the omega dN/dS for a sliding window
Look at the README.md in the home directory for information
"""
### imports ==================================================================
from Bio import SeqIO # to read fasta in and out
from pprint import pprint as pprint # testing
import sy... |
# run simulations
#
#
#
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
import seaborn as sns
from data.generate_synth_data import gen_synth_causal_dat, intervention_sem
from models import RECI, ANM, EntropyLR, CAReFl
def res_save_name(config, algo):
if 'carefl' not in algo.lower():
... |
import numpy as np
np.random.seed(0)
from sklearn.base import TransformerMixin
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from scipy.sparse import lil_matrix, csc_matrix, hstack
from sklearn.linear_model import SGDClassifier, LogisticRegression
import pickle
class DomainVectorizer_tf... |
from django import template
register = template.Library()
@register.filter
def unread(thread, user):
return bool(thread.userthread_set.filter(user=user, unread=True))
|
from auto_derby.single_mode.item.effect_summary import EffectSummary
from ... import _test
from ...constants import Mood, TrainingType
from .. import race, training
from ..commands import RaceCommand, TrainingCommand
from ..context import Context
from ..training import Training
from . import game_data
from . import tes... |
#!/usr/bin/env python
##############################################################
# _ __ ____ ___ _ __ __ __ ____ #
# | | | ( (` | |_ | |_) | | | ( (` / /\ / /`_ | |_ #
# \_\_/ _)_) |_|__ |_| \ \_\_/ _)_) /_/--\ \_\_/ |_|__ #
# Userusage Python by Will Dr... |
"""
Coupling Network / Graph
===============================================================================
Builds a coupling network from a coupling matrix.
>>> from techminer2 import *
>>> directory = "/workspaces/techminer2/data/"
>>> file_name = "/workspaces/techminer2/sphinx/images/coupling__network_graph.png"
... |
#!/usr/bin/python
import unittest
from verses import accordURL
class TestAccordURL(unittest.TestCase):
def test_accordURL(self):
self.assertEqual(accordURL(u'KJVS', u'Matt 1:1'),
'accord://read/KJVS?Matt_1:1')
def test_accordURLEscape(self):
self.assertEqual(accordURL(u'Torah\u00b0', u'... |
import os
from conans import ConanFile, CMake, tools
class LibwebsocketsConan(ConanFile):
name = "libwebsockets"
version = "3.2.2"
description = "Canonical libwebsockets.org websocket library"
url = "https://github.com/bincrafters/conan-libwebsockets"
homepage = "https://github.com/warmcat/libwebs... |
# 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 applicab... |
# Copyright (c) 2021 Luis Liñán Villafranca. All rights reserved.
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
This module is the B{Template Macro} module. It preprocesses a web
template in which variables and blocks are contained. This package
plays an important role as an explicit boundary between web template
designing and script implementation.
@note: A block can be defi... |
"""
This is the PyTurbSim debug package. It contains debugging tools
specifically valuable to PyTurbSim.
"""
import time
class timer(object):
"""
A timer class for tracking 'real' time (rather than CPU time).
"""
def __init__(self, label='NONE'):
self.tnew = 0.
self.total = 0.
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from app import app, db, admin
from .models import *
from .formats import *
from .convert import reindex_data, refresh_data
from flask_admin.contrib.sqla import ModelView, filters
from flask_admin.form import FileUploadField
from flask_admin import (
BaseView, expose... |
import sys
import os
import glob
import subprocess
import time
from xml.sax.saxutils import escape
def read_entities_from_file(filename):
entities = []
with open(filename, "r") as f:
entity = None
for line in f:
line_stripped = line.rstrip()
if line_stripped == "":
if not entity is Non... |
import json
import glob
import requests
class RiskLevel:
def __init__(self, config, logger):
self._logger = logger
self._config = config
def process_risk_level(self, data):
"""
change users group according to the user's risk level
:param data: json file
:return... |
from enum import Enum
class EnumNicLinkType(Enum):
vlan = "vlan"
vxlan = "vxlan"
default = "default"
bridge = "bridge"
|
from serif.theory.serif_offset_theory import SerifOffsetTheory
from serif.xmlio import _ChildTextElement, _SimpleAttribute
class Region(SerifOffsetTheory):
contents = _ChildTextElement('Contents')
tag = _SimpleAttribute() # is_required=True)
is_speaker = _SimpleAttribute(bool, default=False)
is_recei... |
"""
tuhulgadple.py
Hulkade defineerimine ja operatsioonid nende peal
"""
#
# Deklareerimine
#
# Tühja hulga deklareerimine
hulk = set()
print(hulk)
# hulk, milles on mõned elemendid(osad neist topelt)
ostukorv = { "Õunad", "Kartulid", "Makaronid", "Õunad", "Sidrunid", "Kartulid" }
print(ostukorv)
# kasutame set() ... |
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.views.algolia_api_key_view import AlgoliaApiKeyView
from impact.views.api_registration_view import APIRegistrationView
from impact.views.general_view_set import GeneralViewSet
from impact.views.index_view import IndexView
from impact.views.jwt_cookie_n... |
"""Module: Log"""
import sys
# log colors
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[1;36m"
PURPLE = "\033[95m"
ENDC = "\033[39m"
# -----------------------------------------------------------------------------
def error(msg, fatal=True):
"""
Print error message and exit with error ... |
__author__ = 'rohitsinha'
|
""" Base functions for computes central tendencies """
from collections import Counter
from typing import List
Vector = List[float]
def de_mean(xs: List[float]) -> List[float]:
""" Translate xs by subtracting its mean (so the result has mean 0) """
x_bar = mean(xs)
return [x - x_bar for x in xs]
def da... |
# Copyright (c) 2021 CNES
#
# All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
Histogram 2D
------------
"""
from typing import Optional, Union
import copy
import dask.array as da
import numpy as np
from . import core
class Histogram2D:
"... |
from scheme import *
from tests.util import *
class TestMap(FieldTestCase):
def test_construction(self):
with self.assertRaises(TypeError):
Map(True)
with self.assertRaises(TypeError):
Map(Text(), True)
with self.assertRaises(TypeError):
Map(Text(), requi... |
#!/usr/bin/env python3
from rich import box
from rich.table import Table
from rich.prompt import Prompt
import pwncat
from pwncat.util import console
from pwncat.manager import Listener, ListenerError, ListenerState
from pwncat.commands import Complete, Parameter, CommandDefinition
class Command(CommandDefinition):
... |
import numpy as np
data = [15, 16, 18, 19, 22, 24, 29, 30, 34]
print("mean:", np.mean(data))
print("median:", np.median(data))
print("50th percentile (median):", np.percentile(data, 50))
print("25th percentile:", np.percentile(data, 25))
print("75th percentile:", np.percentile(data, 75))
print("standard deviation:",... |
import torch
import torch.nn as nn
from torch.autograd import Variable
class deeplog(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, vocab_size, embedding_dim):
super(deeplog, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.embe... |
"""Test Nautobot Utilities."""
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from django.utils.text import slugify
from nautobot.dcim.models import DeviceRole, DeviceType, Manufacturer, Site
from nautobot.dcim.models.devices import Device
from nautobot.extras.models.statuse... |
import unittest
import numpy as np
from staticmap import StaticMap
from coord2vec.config import IMG_WIDTH, IMG_HEIGHT, tile_server_dns_noport, tile_server_ports
from coord2vec.image_extraction.tile_image import render_single_tile, generate_static_maps, render_multi_channel
from coord2vec.image_extraction.tile_utils im... |
import os
import sys
import json
import argparse
import pandas as pd
import numpy as np
from tabulate import tabulate
from collections import defaultdict
import seaborn as sns
import matplotlib.pyplot as plt
from IPython import embed
test_metrics = [
'testing.balanced_accuracy',
'testing.auroc_weighted',... |
import numpy as np
import multiprocessing
import skimage
from ACSN_core import ACSN_core
from Quality_Map import Quality_Map
from metric import metric
from im2tiles import im2tiles
from tiles2im import tiles2im
from numba import prange, njit
import vapoursynth as vs
from vapoursynth import core
import mvsfun... |
######################################
# Import and initialize the librarys #
######################################
import time
from code.api.core import os, log, PgEss
from code.api.objects import Screen, Frame
from code.api.actions import Runclass, Switchscreen, Info
from code.api.data.Text import Text, TextFormat, ... |
n=int(input('Enter number whose table you want : \n'))
while 1: #while 1: means an infinite loop because it's always true
#for x in range (1,999999,1): #also works as infinite loop
for i in range (1,11):
print(n,'×',i,'=',n*i)
a=int(input('Enter a number for next table (enter 0 to stop) : \n'))
if a==0:
break;
... |
import os
import sys
import json
class Movie:
id=0
name=" "
year=0
seats=0
#time=[0,0] #Tof the movie, represented in array, hour[0]= hour and hour[1]= minutes ex: h[0]=14 hour[1]=32 (14:32)
def __init__(self, id, name, year):
self.id=id
self.name=name
self.year=year
... |
import logging
import os
import sys
class LsassyFormatter(logging.Formatter):
"""
Custom formatting. Inspired by impacket "Logger" class
"""
def __init__(self):
logging.Formatter.__init__(self, '%(bullet)s %(threadName)s %(message)s', None)
if os.name == 'nt':
... |
import unittest
import matplotlib.pyplot as plot
import numpy as np
import sys
sys.path.append('.') # T_T
from lib.rtnorm import rtnorm
class RtnormTest(unittest.TestCase):
longMessage = True
def test_histogram(self):
"""
This should plot a histogram looking like a gaussian
... I... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from copy import deepcopy
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.utils.six import string_types
try:
from django.urls import resolve, Resolver404
except M... |
# -*- coding: utf-8 -*-
"""
pyGIMLi - An open-source library for modelling and inversion in geophysics
"""
# py 2.7 compatiblity
from __future__ import division, print_function
import locale
import sys
def checkAndFixLocaleDecimal_point(verbose=False):
"""
"""
if locale.localeconv()['decimal_point'] == ... |
import re
from typing import Tuple
import requests
class Session(requests.Session):
def __init__(self, stuid: str, password: str, origin: str, service: str, exam: str) -> None:
self.stuid = stuid
self.password = password
self.origin = origin
self.service = service
self.exa... |
"""
Views to provide downloadable pdf files from a Django project.
"""
from django.conf import settings
from django.http import HttpResponse
from django.template import loader, Context
from cStringIO import StringIO
from rst2pdf import createpdf
DEFAULT_RST2PDF_ARGUMENTS = {
'breaklevel': 0,
'breakside': 'any'... |
def test_iris_netcdftime_compatibility_1():
import iris, netcdftime
t1 = netcdftime.datetime(1997, 2, 2, 1, 0, 0, 0, -1, 1)
t2 = iris.time.PartialDateTime(year=1997)
assert (t1 == t2)
def test_iris_netcdftime_compatibility_2():
import cf_units
from iris.time import PartialDateTime as PDT
... |
"""Data model for Serverless Ordering Platform.
The model contains ORM classes for managing the Firestore documents which make
up the database backend for the Serverless Ordering Platform. Each data model
object has a constructor which takes either a DocumentReference or a
DocumentSnapshot. If a DocumentReference is p... |
# 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 ap... |
#!/usr/bin/env python
import argparse
import pathlib
import pp
import alignment.sequenceloader
import alignment.alignmenthelper
import alignment.substmatrices
SUBST_MATRIX = alignment.substmatrices.simplematrix
DEFAULT_GAP_SCORE = -1
def alignmany(target, cands, length,
match=None, mismatch=None, ma... |
import os
from fastapi import FastAPI, HTTPException
from starlette.middleware.cors import CORSMiddleware
from routers import auth, groups
app = FastAPI(root_path="/api", version="0.2.0")
origins = [os.getenv("URL", "*")]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright (C) 2005-2007 Carabos Coop. V. All rights reserved
# Copyright (C) 2008-2013 Vicent Mas. All rights reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public ... |
import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product_dict(
[{'dtype': numpy.float16,
'double_backward_options': {'at... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: buildman.proto
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
... |
"""A module for asynchronously interacting with KEF wireless speakers."""
from aiokef.aiokef import AsyncKefSpeaker, SyncKefSpeaker
from ._version import __version__
__all__ = ["AsyncKefSpeaker", "SyncKefSpeaker", "__version__"]
|
"""Routines for opening the NGAqua Dataset"""
import xarray as xr
import os
from os.path import join
from uwnet import thermo
class NGAqua:
def __init__(self, basedir):
self.basedir = basedir
@property
def data_2d(self):
path = join(self.basedir, "coarse", "2d", "all.nc")
ds = xr.... |
# Copyright 2018 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 applicable ... |
import requests
headers={'content-type':'application/json'}
r=requests.get("http://119.29.0.61:8000/ls",auth=("admin","TvvRvHkyr9b6ls1I"),headers=headers)
print r.text |
# Copyright 2020 Toyota Research Institute. All rights reserved.
import argparse
import numpy as np
import os
import torch
from glob import glob
from cv2 import imwrite
from packnet_sfm.models.model_wrapper import ModelWrapper
from packnet_sfm.datasets.augmentations import resize_image, to_tensor
from packnet_sfm.u... |
import os
import unittest
from bmaclient import utils
from bmaclient.models import DataModel
class UtilTest(unittest.TestCase):
def test_encode_string(self):
self.assertEqual(utils.encode_string('test string'), b'test string')
def test_object_from_list(self):
entry = [{'key1': 'value1'}, {'k... |
from game import Game
from board import Board
import numpy as np
from typing import Tuple
from human_player import HumanPlayer
from clever_player import CleverPlayer
from play import play_game
class NoughtsAndCrosses(Game):
def clean_board(self) -> Board:
return Board(np.zeros((3, 3), dtype=int),... |
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from pages.base_page import BasePage
class AuthLocators:
"""Локаторы для авторизации."""
LOCATOR_EMAIL_FIELD = (By.XPATH, '//input[@type="email"]')
LOCATOR_NEXT_BUTTON = (By.ID, 'identifierNext')
LOCATOR_PASSW... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import hashlib
import json
import os
import socket
import sys
import time
from struct import pack, unpack
from threading import Event, Lock, Thread
# Default port - it can be changed by specifying a different one in the script argument.
CHAT_PORT = 59999
PY3 = False
if sys.ve... |
from django.db import models
from .fitimage import fit
from django.conf import settings
# Create your models here.
class Artwork(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
photo = models.ImageField(upload_to='originals')
_... |
from time import sleep
def linha():
print('-=' * 30)
def contador(inicio, fim, passo):
linha()
if passo == 0:
passo = 1
if passo < 0:
print(f'Contagem de {inicio} até {fim} de {passo * -1} em {passo * -1}')
for c in range(inicio, fim, passo):
print(c, end=' ')
... |
import asyncio
from hopeit.app.events import collector_step
from hopeit.app.logger import app_extra_logger
from hopeit.app.context import EventContext
from hopeit.server.collector import Collector
from . import MockData, MockResult
__steps__ = [collector_step(payload=MockData).gather('step1', 'step2', 'step3'), 'resu... |
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
import argcomplete
from .args import make_parser
from .filelib import FileLib
from .logging import setup_logger
from .menu import WorkbenchMenu
from .workbench import Workbench
import json
import yaml
import os
def cli():
# Get the base parser for the CLI
pa... |
from .description import Description
def name_check(description):
d = Description(description)
d.normalize()
return d.output()
|
import operator
from pkg_resources import parse_version
operator_mapping = {"<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge,
">": operator.gt}
def compare_versions_str(version_str_obj1, comparison_operator_str, version_str_obj2, default=False):
i... |
from systems.plugins.index import BaseProvider
class Provider(BaseProvider('field_processor', 'combined_text')):
def exec(self, dataset, field_data, append = None, separator = ","):
if append:
for field in append.split(','):
field_data = field_data.str.cat(
... |
import doctest
import copy
from decitala.hm import schultz
from decitala.hm import contour
def test_doctests():
assert doctest.testmod(schultz, raise_on_error=True)
####################################################################################################
# Tools
def test_no_schultz_repetition():
c = [[1... |
from MenuDisplayer import MenuDisplayer
from ChoiceSelector import ChoiceSelector
from StudentRecorder import StudentRecorder
from LessonRecorder import LessonRecorder
from StudentFileOperation import StudentFileOperation
from LessonFileOperation import LessonFileOperation
from Lesson import Lesson
class OBSSytem:
... |
class ERM:
def __init__(self, model, criterion, args):
self._model = model
self._criterion = criterion
self._fname = f'erm-lr-{args.lr}-trial-{args.trial_index}'
def __call__(self, imgs, labels):
return self.step(imgs, labels)
def __str__(self):
return 'ERM'
... |
#!/usr/bin/env python
# encoding:utf8
import requests
import time
import sys
def getPayload(indexOfResult, indexOfChar, mid):
startStr = "1' and ("
endStr = ") and '1"
payload = "select ascii(substr((select table_name from information_schema.tables where table_schema=database() limit " + indexOfResult +", 1), " + ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
import tensorflow as tf
from skimage.transform import resize
def scatter(data, label, dir, file_name, mus=None, mark_size=2):
if label.ndim == 2:
label = np.argmax(label, axis=1)
df = pd.... |
import sys
from nwe import gurafikkuu
gurafikkuu.main()
|
import abc
class Base(abc.ABC):
command_name = None
def __init__(self, client, message, payload=None):
self.client = client
self.message = message
self.payload = payload
if not self.command_name:
raise ValueError('Should have a command name!')
@abc.abstractme... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... |
import numpy as np
def deflect_SIE(lens, x, y): # SIE lens model
x0 = 0.0
y0 = 0.0
pi = 3.14
tr = pi * (th / 180.0) + pi / 2.0
sx = x − x0
sy = y − y0
cs = cos(tr)
sn = sin(tr)
sx_r = sx * cs + sy * sn
sy_r = −sx * sn + sy * cs
psi = sqrt(lens.fl**2.0 * (lens.rc**2.0 + ... |
from __future__ import unicode_literals
from django.apps import AppConfig
class RegistrationConfig(AppConfig):
name = 'registration'
def ready(self):
# registering signals with the User model string label
from . import signals
|
from __future__ import absolute_import
import h5py
import numpy
from ..common import ut, TestCase
@ut.skipUnless(h5py.version.hdf5_version_tuple >= (1, 8, 11), 'Direct Chunk Writing requires HDF5 >= 1.8.11')
class TestWriteDirectChunk(TestCase):
def test_write_direct_chunk(self):
filename = self.mktemp... |
from office365.runtime.client_object import ClientObject
from office365.runtime.client_query import DeleteEntityQuery
class FileVersion(ClientObject):
"""Represents a version of a File object."""
@property
def url(self):
"""Gets a value that specifies the relative URL of the file version based on... |
import re
from typing import Match
from random import shuffle
from collections import Counter
def same(word_1: str, word_2: str) -> bool:
"""
a simple helper function for checking if words match
:param word_1: a word
:param word_2: a word
:return: boolean, do words consist of exactly same letters?... |
HELP_DESC = ("!help\t\t\t-\tDisplay this help message\n")
async def register_to(plugin):
def format_help(text):
html_text = "<pre><code>" + text + "</code></pre>\n"
return html_text
async def help_callback(room, event):
available = plugin.mroom.bot.available_plugins
pluginname... |
# Generated by Django 3.1.3 on 2020-11-20 17:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('student', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='data',
old_name='File',
new_name... |
import oauth2 as oauth
import cgi
# Django
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import log... |
#!/usr/bin/env python
# coding: utf-8
import requests as rq
def getInfo(user):
url = f"https://api.github.com/users/{user}"
userInfo = rq.get(url).json()
ghInfo = {}
shortInfo = {}
if not 'message' in userInfo:
ghInfo['Name'] = userInfo['name']
ghInfo['Login'] = userInfo['login']... |
"""Utility functions that aren't core functionality."""
from __future__ import print_function, division, unicode_literals, \
absolute_import
def raises(exception_types, function, args=None, kwargs=None):
"""Return whether or not the given function raises the error.
Parameters
==========
exceptio... |
def sum(n):
if n == 0:
return 0
else:
return n % 10 + sum(n//10)
n = int(input())
print(sum(n))
|
from ...helpers import assert_raises
from mock import patch
import socket
from tagalog.shipper.statsd import StatsdShipper
from tagalog.shipper.shipper_error import ShipperError
class DumbStatsdShipper(StatsdShipper):
def _statsd_msg(self, msg):
return "dumb|msg"
class TestStatsdShipper(object):
@pa... |
# Add utils here |
#!/usr/local/CyberCP/bin/python
import os.path
import sys
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
import django
django.setup()
from websiteFunctions.models import Websites
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
from xm... |
"""
Save the TwoRavens workspace to a session
"""
import json
from collections import OrderedDict
from tworaven_apps.workspaces.models import (\
DataSourceType, SavedWorkspace)
from tworaven_apps.configurations.models import AppConfiguration
from tworaven_apps.workspaces.models import \
(UI_KEY_APP_DOMAIN, UI_... |
try:
from SacraMathEngine import *
except:
raise ImportError("Cannot import SacraMathEngine.")
class Lightsource:
def __init__(self, vec):
self.vec = vec
def LightingAngle(self, Triangle):
"""Compute the angle of which the triangle plane is facing."""
pass
|
#encoding=utf8
import re, os, sys
sys.path.append("../../../../")
from pythonx.funclib import *
copydir(r"E:\kSource\LearnOpenGLz\LearnOpenGL-og\resources\textures\\",
r".\\")
copydir(r"E:\kSource\LearnOpenGLz\LearnOpenGL-og\resources\objects\nanosuit",
r".\\nanosuit_reflection/")
|
# Copyright 2013 Locaweb.
# 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 appli... |
celsius_temperature=input("celsius_temperature: ")
fahrenheit_temperature=(int(celsius_temperature)*9/5)+32
print(fahrenheit_temperature) |
# from .classes import *
from .autogenerated import *
|
from flask import Flask, render_template, url_for, request
import requests
app = Flask(__name__)
@app.route('/')
def home():
return render_template("index.html")
@app.route('/search')
def search():
return render_template("search.html")
@app.route('/city', methods =['POST'] )
def search_city():
API_KEY... |
from natoki.core.models import Interface
class Websocket(Interface):
pass |
from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib import auth
from django.contrib.auth.models import User
# Create your views here.
def signup(request):
if request.method == "POST":
if request.POST['user-password'] == request.POST['user-password-check']:
user = ... |
"""グレゴリオ曆の日時をユリウス通日に變換する."""
from imperial_calendar.GregorianDateTime import GregorianDateTime
from imperial_calendar.JulianDay import JulianDay
import math
def grdt_to_juld(grdt: GregorianDateTime) -> JulianDay:
"""グレゴリオ曆の日時をユリウス通日に變換する."""
intercept_day = 1721088
intercept_second = 0.5 * 24.0 * 60.0 * 6... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.