content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
import json_logging
import logging
# noinspection PyPackageRequirements
import sanic
import sys
app = sanic.Sanic(name="sanic-web-app")
json_logging.init_sanic(enable_json=True)
json_logging.init_request_instrument(app, exclude_url_patterns=[r'/exclude_from_request_instrumentation'])
# init th... |
#!/usr/bin/env python3
#
# General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall
# model for 1st, 2nd and 3rd generation solar cells.
# Copyright (C) 2008-2022 Roderick C. I. MacKenzie r.c.i.mackenzie at googlemail.com
#
# https://www.gpvdm.com
#
# This program is free s... |
#!/usr/bin/env python
"""
<Program Name>
serve_metadata.py
<Author>
Lukas Puehringer <lukas.puehringer@nyu.edu>
<Started>
December 10, 2018.
<Purpose
Super simple mock metadata server for rebuilder interface testing purposes.
Starts a localhost SimpleHTTPServer on the passed PORT to serve a metadata
fil... |
from doc2mysql.models import patient_LYM
from django.forms import ModelForm
from django import forms
class LYM_form(ModelForm):
class Meta:
model = patient_LYM
fields = [
# 报告抬头
'patient_ID',
'patient_name',
'patient_sex',
'patient_departm... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: VTGS Rocksat Receiver
# Generated: Tue Feb 14 20:52:14 2017
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.... |
# import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from postladim import ParticleFile
from nested_gridforce import Grid
# ---------------
# User settings
# ---------------
# Files
particle_file = "nested.nc"
# Define the grids
g = Grid(dict(grid_args... |
import logging
from apps import App, action
from scapy.sendrecv import sniff
from scapy.utils import wrpcap
import datetime
import os
import pyshark
import OpenSSL.crypto
import pickle
logger = logging.getLogger(__name__)
@action
def capture(filename=None, timeout=None, count=0, interface=None, packet_filter=None, g... |
#!/usr/bin/env python3
import click
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option(
"-c",
"--bert-config",
default="bert-large-uncased",
help="Pretrained BERT configuration",
)
@click.option("-b", "--binary", is_flag=True, ... |
#%%
# Import of pandas and numpy for work and analysis on lists and arrays
import pandas as pd
import numpy as np
#import custom present_value function
from present_value_function import present_value
#%%
# import of matplot for making graphs later on in the analysis
import matplotlib.pyplot as plt
#%%
#load rates fr... |
import logging
import msghandling as mh
import msgcreation as mc
import pickle
import socket
def create_and_bind_socket(config):
ADDR = ('', config['PORT'])
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(ADDR)
return server_socket
def send_NOT_OK_JoinRoomResp_w... |
import pandas as pd
from data.process_data.process_data import process_data
JING_DONG_PATH = 'data/jingdong/jingdong.csv'
JING_DONG_OUTPUT = 'jingdong'
JING_DONG_USER_COL = 'user_id'
JING_DONG_TIME_COL = 'day'
JING_DONG_ITEM_COL = 'sku_id'
JING_DONG_TIME_FORMAT = '%Y-%m-%d'
JING_DONG_MIN_ITEM_CNT = 3
JING_DONG_MIN_USE... |
# Copyright [2020] [Two Six Labs, LLC]
# Licensed under the Apache License, Version 2.0
from collections import namedtuple
import numpy as np
import pandas as pd
from database.local_handler import LocalCSVHandler, LocalCSVDataInventory
from utility.constants import (
DATA_LOCATION,
DATA_SOURCE_TYPE,
MAIN_... |
# -*- coding: utf-8 -*-
# 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 o... |
from utils.solution_base import SolutionBase
class Solution(SolutionBase):
def solve(self, part_num: int):
self.test_runner(part_num)
func = getattr(self, f"part{part_num}")
result = func(self.data)
return result
def test_runner(self, part_num):
test_inputs = self.get... |
import time
from pathlib import Path
from core.models import action, webui, conduct
from core import cache, helpers
class _scriptBlock(action._action):
scriptBlock = str()
def __init__(self):
self.scriptBlock = "def run(data):\n\t# Insert Code\n\treturn (True,0,data)"
def doAction(self,data):
... |
from trac.wiki.api import *
from trac.wiki.formatter import *
from trac.wiki.intertrac import *
from trac.wiki.model import *
from trac.wiki.parser import *
|
from apache_beam.io import Read
from apache_beam.io.filebasedsource import FileBasedSource
from apache_beam.io.filesystem import CompressedFile
from bulq.core.plugin import BulqInputPlugin, PluginManager
class CompressedStream:
def __init__(self, file):
self._file = file
def __iter__(self):
... |
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, re_path
from . import views
urlpatterns=[
path('', views.index, name='home'),
path('new/upload', views.upload, name='upload'),
path('profile/', views.profile, name='profile'),
path('search/', views.search_results... |
# encoding: utf-8
from __future__ import unicode_literals
import numpy as np
import pandas as pd
from jaqs.data import DataView
from jaqs.data import RemoteDataService
from jaqs.research import SignalDigger
import jaqs.util as jutil
# from config_path.py, we import the path of config files
from config_path import DA... |
#!/usr/bin/env python3
#fast.ai batch Google image downloader helper
#for the 2018 Lesson 1 that requires test images to be in test/ and train/directories
# execution example: -- note that this version cannot deal with trailing spaces with commas currently
# training-data-generator vespas "vespa gtv,vespa gts,vespa pr... |
from __future__ import absolute_import
from .fixtures import * # noqa
|
def calcAQI(cp, ih, il, bph, bpl):
a = (ih - il)
b = (bph - bpl)
c = (cp - bpl)
return int((a /b) * c + il)
def aqi_from_pm(pm):
if (pm > 350.5):
return calcAQI(pm, 500, 401, 500, 350.5)
elif (pm > 250.5):
return calcAQI(pm, 400, 301, 350.4, 250.5)
elif (pm > 150.5):
... |
import importlib
import logging
import os
import random
import time
from argparse import Namespace
from collections import defaultdict
from typing import List
import cv2
import numpy as np
import torch
import yamlenv
def setup(args):
logger = logging.getLogger('utils.setup')
torch.set_num_threads(1)
cv2... |
from typing import Callable
from starlette.requests import Request
from fastapi_admin import i18n
async def language_processor(request: Request, call_next: Callable):
locale = request.query_params.get("language")
if not locale:
locale = request.cookies.get("language")
if not locale:
... |
import os
import time
import logging
import argparse
import random
import numpy as np
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.utils.data
from common.logger_utils import initialize_logging
from common.train_log_param_saver import TrainLogParamSaver
from pytorch.utils import... |
from check_grad import check_grad
from utils import *
from logistic import *
import matplotlib.pyplot as plt
def run_logistic_regression(hyperparameters):
# TODO specify training data
train_inputs, train_targets = load_train_small()
valid_inputs, valid_targets = load_valid()
test_inputs, test_target... |
import sys
from types import ModuleType
from typing import Any
def find_imported_module(name: str) -> ModuleType:
return sys.modules[name]
def lookup_global(name: str, module: ModuleType) -> Any:
try:
return getattr(module, name)
except AttributeError:
return module.__builtins__[name]
|
#!/usr/local/sci/bin/python3 hopefully
#*****************************
#
# Take monthly merged files and output global average timeseries
#
#
#************************************************************************
'''
Author: Robert Dunn and Kate Willett
Created: March 2016
Last update: 15 April 2019
Location: /projec... |
from math import radians, cos, sin, asin, sqrt
def haversine(point1, point2, unit='km'):
""" Calculate the great-circle distance between two points on the Earth surface.
:input: two 2-tuples, containing the latitude and longitude of each point
in decimal degrees.
Keyword arguments:
unit -- a str... |
"""Make this it's own package so unit tests run properly without
having to mess with path variables, see:
__ http://stackoverflow.com/questions/1896918/running-unittest-with-typical-test-directory-structure
Note:
run ``python -m unittest discover``
"""
|
from django.contrib.syndication.feeds import Feed
import settings
from sponsors.models import Sponsor,Level
class SponsorList(Feed):
title = "UTOSC 2009 Sponsors"
link = "/speaker/list/all/"
description = "Sponsors for UTOSC 2009"
def items(self):
return Sponsor.objects.all().order_by('level')... |
# coding=utf-8
'''
v.0.0.1
lds_topo_reblocker - LayerReader_Test
Copyright 2011 Crown copyright (c)
Land Information New Zealand and the New Zealand Government.
All rights reserved
This program is released under the terms of the new BSD license. See the
LICENSE file for more information.
Tests on LayerReader class... |
#!/usr/bin/env python
# coding: utf8
import argparse
import logging
from kalliope.core import ShellGui
from kalliope.core import Utils
from kalliope.core.ConfigurationManager.BrainLoader import BrainLoader
from kalliope.core.EventManager import EventManager
from kalliope.core.MainController import MainController
from... |
import unittest
import os
from programy.utils.files.filewriter import TextFile
from programy.utils.files.filewriter import CSVFile
from programy.utils.files.filewriter import FileWriter
from programy.utils.files.filewriter import ConversationFileWriter
from programy.utils.files.filewriter import ErrorsFileWriter
from ... |
from urllib2 import unquote
from openmtc.exc import OpenMTCNetworkError
from openmtc_etsi.model import FilterCriteria
from openmtc_server.transportdomain import (RequestMethod, ErrorResponse,
Response, Request, ResponseCode)
from openmtc_etsi.scl import (
CreateRequestIn... |
import torch
import numpy as np
import utils as u
from argparse import Namespace
from torch.nn.parameter import Parameter
import torch.nn as nn
import math
class WSDM_Decoder(torch.nn.Module):
def __init__(
self,
args,
time_encoder,
out_features,
nodes_feats,
in_fea... |
import logging, time, os, json, sys, shelve, glob, csv, collections
NT_RangeValue = collections.namedtuple( "range_value", ["value","status"] )
NT_RangeSet = collections.namedtuple( "range_set", ["max","min","ma_max","ma_min"] )
NT_RangeSetX = collections.namedtuple( "range_set", ["max","min","ma_max","ma_min","max_l... |
from aiohttp import ClientSession
from random import randint, choice
from pykakasi import kakasi
from discord.ext import commands, tasks
from discord import Embed, File, PartialEmoji, Member, Spotify
from datetime import datetime
from typing import Optional
from io import BytesIO
from os import environ
from py... |
from enum import Enum
from typing import List
from typing import Optional
import numpy as np
import pandas as pd
from etna.transforms.base import PerSegmentWrapper
from etna.transforms.base import Transform
class ImputerMode(str, Enum):
"""Enum for different imputation strategy."""
zero = "zero"
mean =... |
"""
Spheres and Sticks
==================
"""
import numpy as np
from vispy import app, scene
# Create canvas and view
canvas = scene.SceneCanvas(keys='interactive', size=(600, 600), show=True)
view = canvas.central_widget.add_view()
view.camera = scene.cameras.ArcballCamera(fov=0)
view.camera.scale_factor = 500
# Pr... |
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.checkbox import CheckBox
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.togglebutton import ToggleButton
from libdw import pyrebase
projectid = "dw1d-gui"
url = "https://" + projectid + ".firebaseio.co... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# >>
# async-redis-cache, 2021
# LiveViewTech
# <<
from typing import Protocol, TypeVar
T = TypeVar('T')
__all__ = [
'PluginT',
]
class PluginT(Protocol):
async def before_first_call(self):
...
async def on_cache_hit(self, key: str):
... |
"""Download audio of Easy German videos and upload to Google Drive."""
from . import videos
from . import transcripts
def get_videos(max_downloads=1, max_results_per_page=10):
"""
Scrape video audio and upload to Google Drive.
:param int max_downloads: Maximum number of video audios to scrape and
... |
# Created by DraX on 2005.08.08 modified by Ariakas on 2005.09.19
import sys
from ru.catssoftware.gameserver.model.quest import State
from ru.catssoftware.gameserver.model.quest import QuestState
from ru.catssoftware.gameserver.model.quest.jython import QuestJython as JQuest
qn = "30520_reed_occupation_c... |
###############################################################################
# Copyright 2012-2014 The University of Texas at Austin #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #... |
class Break_(Exception):
pass
|
# Copyright 2019, A10 Networks
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# Copyright 2020 Cloudbase Solutions Srl
#
# 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 l... |
import sys
import unittest
from unittest.mock import Mock
import numpy as np
sys.modules['spams'] = Mock()
from staintools.utils.miscellaneous_functions import get_sign, normalize_matrix_rows
class TestMiscellaneousFunctions(unittest.TestCase):
def test_get_sign(self):
for arg, expect in [(42, 1), (-10,... |
import pandas as pd
file = 'Zakat_Full_2021.xlsx'
xl = pd.ExcelFile(file)
sheet_names = xl.sheet_names
i = 0
name = '';
df_collection = {}
undef = 'Unnamed';
for name in sheet_names :
df_collection[i] = xl.parse(name)
for col in df_collection[i] .columns:
if col == 'nan' :
df... |
# %% [markdown]
# This notebook is a VSCode notebook version of:
# https://www.kaggle.com/georsara1/lightgbm-all-tables-included-0-778
#
# You could find the data from:
# https://www.kaggle.com/c/home-credit-default-risk/data
## All the data files should be in the same directory with this file!
#%% Importing necessar... |
"""finally URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
import cv2
import numpy as np
import torch
import torch.nn as nn
from pytorch_bcnn.initializers import bilinear_upsample
from pytorch_bcnn.functions import crop
import matplotlib.pyplot as plt
def main():
x = cv2.imread('lenna.png')
x = cv2.resize(x, (64, 64))
x = np.transpose(x, (2,0,1))
x = np.expand... |
"""fill out fix table
Revision ID: c95c4545491e
Revises: 06ea8c057d9f
Create Date: 2021-03-10 11:52:24.711555
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c95c4545491e'
down_revision = '06ea8c057d9f'
branch_labels = None
depends_on = None
def upgrade():
... |
import json
import boto3
import re
from datetime import datetime, date, time, timezone
datenow= datetime.now()
now= datenow.strftime("%Y-%m-%d %H:%M:%S")
def lambda_handler(event, context):
# it overwrites event variable with the event coming from previous lambda
event= json.loads(event['Records'][0]['Sn... |
for x in range(10)
print(x)
|
import os
import tarfile
import shutil
from joblib import Parallel, delayed
dicomdir = os.environ.get('DICOMDIR')
subs = [x for x in os.listdir(dicomdir) if not x=='import']
def tartogethernow(sub):
subdir = os.path.join(dicomdir,sub)
protocols = os.listdir(subdir)
protocols = [x for x in protocols if not... |
#!/usr/bin/python
import os
import sys
import yaml
with open("config.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
for section in cfg:
print(section, cfg[section])
path = cfg['path']
extensions = cfg['extensions']
excludeFolders = cfg['exclude_folders']
counter_crt_vect = []
def CountFile(f):
count... |
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2015 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version... |
from tree_search import SearchDomain
from math import hypot
from tree_search import SearchTree, SearchProblem
from keeperDomain import KeeperDomain
"""
Map example:
####--
#-.#--
#--###
#*@--#
#--$-#
#--###
Legend:
@ Keeper
+ Keeper on diamond
# Wall
. Diamond free
$ Box free
* Box on diamond
In the map coordinate... |
"""Constants for the bpost integration."""
DOMAIN = "bpost"
CONF_REFRESH_TOKEN = "refresh_token"
|
from random import randint
from time import sleep
lista = list()
jogos = list()
print('ACUMULOU 1.300,000,00')
print('-=' *30)
quant = int(input('Quantos jogos quer sortear? '))
tot = 1
while tot <= quant:
cont = 0
while True:
num = randint(1, 60)
if num not in lista: # se o num nao estiver la ... |
import inspect
import sys
import unittest
from securify.__main__ import fix_pragma
from securify.analyses.analysis import AnalysisConfiguration, AnalysisContext
from securify.solidity import solidity_ast_compiler, solidity_cfg_compiler
from securify.utils.ethereum_blockchain import get_contract_from_blockchain
def c... |
import os
import glob
from setuptools import setup
package_name = 'ntrip_client'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
package_dir={'': 'src'},
data_files=[
('share/ament_index/resource_index/packages', ['resource/' + package_name]),
(os.path.join('sha... |
from project.baked_food.baked_food import BakedFood
class Cake(BakedFood):
def __init__(self, name: str, price: float):
super().__init__(name, 245.0, price)
|
import logging
logger = logging.getLogger(__name__)
from appyter.execspec.spec import AbstractExecutor
from appyter.ext.asyncio.try_n_times import async_try_n_times
from appyter.ext.asyncio.helpers import ensure_async
from appyter.ext.dict import dict_merge
def endless_watch(*args, **kwargs):
from kubernetes import... |
"""OWASP Dependency Check security warnings collector."""
from xml.etree.ElementTree import Element # nosec, Element is not available from defusedxml, but only used as type
from collector_utilities.type import Namespaces
from source_model import Entity
from .dependencies import OWASPDependencyCheckDependencies
cl... |
def initfunc():
pass
|
"""
We're given a number n.
Write a function that returns the string representation of all numbers from 1 to n based on the following rules:
If it's a multiple of 3, represent it as "fizz".
If it's a multiple of 5, represent it as "buzz".
If it's a multiple of both 3 and 5, represent it as "fizzbuzz".
If it's neither, ... |
from pymongo import MongoClient
import config
class Database():
def __init__(self):
self.client = MongoClient(config.db_host, config.db_port)
self.db = self.client['demucs']
self.jobs_collection = self.db['jobs']
|
from django.core.management.commands import startapp
APP_TEMPLATES = {
'full': 'https://github.com/assigdev/django-startapp-alt-template/archive/full.zip',
'default': 'https://github.com/assigdev/django-startapp-alt-template/archive/default.zip',
}
class Command(startapp.Command):
help = "Alternative st... |
import math
import numpy as np
__all__ = ['StatisticsCollector']
class StatisticsCollector(object):
"""
Computing :math:`\\mathrm{E}[X]` and :math:`\\operatorname{Var}[X]` online.
"""
def __init__(self, shape=()):
"""
Construct the :class:`StatisticsCollector`.
Args:
... |
import wikipedia
import wikiquotes_names
class WikiNameNormalizer(wikiquotes_names.NameNormalizer):
def __init__(self, base_csv):
super(WikiNameNormalizer, self).__init__(base_csv)
def _start_polling(self):
self._load_persons_and_locations('pantheon_wikiquotes_wikipedia.csv', 'wikipedia nam... |
import sounddevice as sd
from scipy.signal import istft
from scipy.signal import stft
import librosa
import librosa.display
import midi
import skimage.transform
import numpy as np
import os
import h5py
import time
import matplotlib.pyplot as plt
import scipy
start_time = time.time()
def save_array(arra... |
# Copyright 2015 Huawei Technologies Co.,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 agre... |
#!/usr/bin/env python
import argparse
import config
import os
import sys
"""
This is the main executable to launch dns daemon
"""
import argparse
from server import Base
def main():
parser = argparse.ArgumentParser(description='JCDNS')
parser.add_argument('-f', default='example.json', help='path of zon... |
from .saint import make_saint
from .saint_i import make_saint_i
from .saint_s import make_saint_s
from .embedding import Embedding
model_type = dict(saint = make_saint,
saint_i = make_saint_i,
saint_s = make_saint_s
)
def get_model(model_name, num_heads, embed_dim, num... |
# @date 2019-02-16
# @author Frederic Scherma, All rights reserved without prejudices.
# @license Copyright (c) 2018 Dream Overflow
# Forex Alpha strategy, sub-strategy B.
from __future__ import annotations
from typing import TYPE_CHECKING, Union
if TYPE_CHECKING:
from strategy.strategysignal import StrategySign... |
import numpy as np
class Ellipse(object):
"""
"""
def __init__(self, center, radii, phi):
"""
"""
center = np.asarray(center, dtype=np.float).flatten()
if len(center) != 2:
raise ValueError('incorrect input for center input')
else:
self.... |
from packerlabimaging.workflows.AllOptical import AllOpticalTrial
from packerlabimaging._archive.TwoPhotonImagingMain import TwoPhotonImagingTrial
from packerlabimaging._archive.ExperimentMain import Experiment
from packerlabimaging.plotting.plotting import makeSuite2pPlots, plot_flu_trace, plotMeanFovFluTrace, \
... |
# coding: utf-8
r"""Example of direct construction"""
from osvcad.nodes import Part, Assembly
from osvcad.edges import ConstraintAnchor
from osvcad.view import view_part, view_assembly, view_assembly_graph
plate_gn = Part.from_py_script(py_script_path="py_scripts/plate_with_holes.py")
print("Plate gn : %s" % plate... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#refer:https://www.bugscan.net/#!/x/22902
#http://acquydongnai.net/index.php?option=com_ebcontent&view=article&tmpl=component&id=265%27%20AND%207599=7599%20AND%20%27gefD%27=%27gefD&cid=20&print=1&Itemid=14&lang=vn
import time
def assign(service, arg):
if service =... |
"""Pattoo __init__.py file.
Do not remove
"""
|
# PRIMEIRA FORMA DE CRIAR UM GERENCIADOR DE CONTEXTO
"""
class Arquivo:
def __init__(self, arquivo, modo):
print('Abrindo o arquivo...')
self.arquivo = open(arquivo, modo)
def __enter__(self):
print('Retornando o arquivo...')
return self.arquivo
def __exit__(self, exc_type,... |
import pandas as pd
import authenticate
import data
from examples.queries import stratifications as stratification_query
from stratification import stratify
bloomberg_deal_name = 'HART 2021-B'
asset_pool_id = 1
stratification_definitions = {
"ltv": {
"step": 0.01,
"label": {
"format":... |
# 1. 字符串 str= 'reverse this string', 请使用三种方法翻转字符串。
str1 = 'reverse this string'
#方法1:
ret1 = str1[::-1]
print(ret1)
#方法2:
ret2 = ''
for i in range(len(str1)-1,-1,-1):
ret2 += str1[i]
print(ret2)
#方法3:
ret3 = ''.join(list(reversed(str1)))
print(ret3)
# 方法3里的list可以去掉,因为reversed返回的就是一个迭代器,然后拼接方法会自动迭代取值.可以尝试以下.
# 2.... |
#UTF-8
frase = 'o lobo ama o bolo'
nova_frase= frase.replace(' ','')
poli = nova_frase[::-1]
resultado = 'e um polimetro' if nova_frase == poli else 'nao é um pli'
print(f'A frase {frase} {resultado}')
|
from braces.views import LoginRequiredMixin, GroupRequiredMixin
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.views.generic import ListView... |
import statistics
import matplotlib.pyplot as plt
from matplotlib import pyplot
from database.session import Session
def survey_fatigue():
"""
Analysis to check if survey fatigue was present in the survey.
The survey key to consider can be changed in the code below.
Calculates the average survey ra... |
from typing import Any, Generic, Iterable, List, Mapping, TYPE_CHECKING, TypeVar, Union
from more_itertools import flatten
from adam.ontology import IN_REGION, OntologyNode
from adam.remappable import CanRemapObjects
from attr import attrib, attrs, evolve
from attr.validators import instance_of
from immutablecollecti... |
mapping = {
"ga:bounces": "bounces",
"ga:yearMonth": "month",
"ga:year": "year",
"ga:date": "day",
"ga:users": "users",
"ga:region": "region",
"ga:userAgeBracket": "age",
"ga:userGender": "gender",
"ga:sessions": "session",
"ga:pageviews": "page_view",
"ga:avgSessionDuration"... |
"""@package exceptions
Elo exceptions
This script contains all Elo frontend specific exceptions.
@file exceptions.py
@author Tyler Shake
@par Notifications:
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 ... |
import pygame
from paint_station_dialog import Dialog
from paint_station_config import Config
from paint_station_button import Button
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
class BrushDialog(Dialog):
def __init__(self, app, surface):
Dialog.__init__(self, app, surface)
self.__config = Config()
... |
from cheers import db
class User(db.Model):
def __init__(self, user_id, email, gift, stock):
self.user_id = user_id
self.email = email
self.gift = gift
self.stock = stock
db.mapper(User, db.Table('user', db.metadata, autoload=True))
|
#!/usr/bin/env python
"""Doing the assignment in pure python first, since it's easier."""
import matplotlib.pyplot as plt
import numpy as np
# from scipy.fftpack import fft
plt.style.use('dark_background')
np.set_printoptions(precision=2)
def basis(a, x):
return np.cos(2 * np.pi * a * x)
def condition_number(a... |
import json
import logging
import os
import psycopg2
from gmaps.commons.writer.writer import FileWriter, DbWriter
class UrlFileWriter(FileWriter):
"""Clase que implementa gmaps.commons.writer.writer.FileWriter con la lógica para registrar la url para cada código
postal comerciales en ficheros en el sistema... |
from hover.utils.snorkel_helper import labeling_function
from hover import module_config
import re
@labeling_function(targets=["rec.autos"])
def auto_keywords(row):
flag = re.search(r"(wheel|diesel|gasoline|automobile|vehicle)", row.text)
return "rec.autos" if flag else module_config.ABSTAIN_DECODED
@labeli... |
__author__ = 'sowmya'
from sls_client.records import *
from sls_client.query import *
import json
import socket
def get_ma_for_host(hostname):
ipaddresses={}
if(not hostname):
raise Exception("Null Parameter", "Hostname parameter is empty.")
ipaddr = socket.getaddrinfo(hostname, None)
ipad... |
import os
import sys
import time
import tempfile
import unittest
import threading
import multiprocessing as mp
import vivisect
import vivisect.cli as vivcli
import vivisect.const as v_const
import vivisect.tests.helpers as helpers
import vivisect.remote.server as v_r_server
import envi.memcanvas as e_mcanvas
def run... |
import argparse
import torch
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
from data_modules.dataset_factory import DatasetFactory
from data_modules.image_dataset_data_module import ImageDatasetDataModule
from metrics.cw import silverman_rule_of_thumb
def parse_program_args() -> ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.