content
stringlengths
5
1.05M
import glob import gzip import os from collections import defaultdict __author__ = "jkkim" def parse_fasta(fa_handler): ''' takes a file handler. so if you want to use this function then put the with statement before this function :param fa_handler: :return: ''' name, seq = None, [] for l...
from .execute import simple_execute __all__ = [ 'simple_execute', ]
from django.core.urlresolvers import reverse from django.http import HttpResponseForbidden from django.views.generic.edit import CreateView from django.views.generic.list import ListView from core.mixins import LoginRequiredMixin from .forms import ProductForm from .models import Product class ProductListView(LoginR...
import unittest from os import path from src.utils.config import Configuration # from src.utils.reader import ReaderLogFile class TestConfigMethods(unittest.TestCase): def setUp(self) -> None: self.configurator = Configuration("./src/config.ini") return super().setUp() def test_printAllGroup...
from flask import Flask, render_template from newsapi import NewsApiClient app = Flask(__name__) @app.route('/') def index(): newsapi = NewsApiClient(api_key = 'c43cae8199d1435fa1e4cc0737cd4a88') topheadlines = newsapi.get_top_headlines(sources = "al-jazeera-english") articles = topheadlines['articles']...
# Generated by Django 2.2.13 on 2020-09-21 01:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library', '0021_auto_20200917_0103'), ] operations = [ migrations.AlterField( model_name='bookversion', name='langu...
# Copyright The OpenTelemetry Authors # # 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 ...
""" 数据记录插件 记录排行版插件,历史插件,状态插件所需的数据 如果遇到老版本数据,则自动升级 """ from datetime import datetime, timedelta from coolqbot import PluginData, bot VERSION = '1' DATA = PluginData('recorder') def get_history_pkl_name(dt: datetime): time_str = dt.strftime('%Y-%m') return time_str def update(data: list, group_id: int): ...
""" MutantX-S Implementation for EMBER Function Imports This work is our rendition of MutantX-S, a static malware classification system. @Authors: Noah MacAskill and Zachary Wilkins """ import random from json import loads, dump from sys import argv from collections import OrderedDict, Counter import logging as lg im...
# -*- coding: utf-8 -*- ### # (C) Copyright [2020] Hewlett Packard Enterprise Development LP # # 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 #...
# -*- coding: utf-8 -*- # ******************************************************* # Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved. # SPDX-License-Identifier: MIT # ******************************************************* # * # * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT # * WARRANTIES OR C...
from lewis.devices import Device from lewis.adapters.epics import EpicsInterface, PV from lewis.adapters.stream import StreamInterface, Var from lewis.core.utils import check_limits class VerySimpleDevice(Device): upper_limit = 100 lower_limit = 0 simple = 42 ropi = 3.141 param = 10 _second...
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2021, OMRON SINIC X # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must...
#!/usr/bin/env python # -*- coding: utf-8 -*- __license__= """ GoLismero 2.0 - The web knife - Copyright (C) 2011-2014 Golismero project site: https://github.com/golismero Golismero project mail: [email protected] This program is free software; you can redistribute it and/or modify it under the terms of ...
#!/usr/bin/python3 # WDT: Watchdog Timer # A python 3 interface to use the linux watchdog timer # # (c) Marco Tedaldi <[email protected]> 2014 # License: MIT, http://opensource.org/licenses/MIT import time # for the delay inside main import sys # needed for exit import os # needed for file handling # Watchdog tim...
#! encoding=utf8 # ====================================================================================================================================== # Serialization is used for performance tuning on Apache Spark. All data that is sent over the network or written to the disk or persisted # in the memory should be ...
import csv from itertools import product import os import random import time import numpy as np import mxnet as mx import tensorflow as tf import torch as pt from common import render_exception def set_seed(seed): # cover our bases: different frameworks and libraries # need to have their seeds set np.ra...
import cv2 import pafy from genericDetector import GenericDetector model_path='models/object_detection_mobile_object_localizer_v1_1_default_1.tflite' threshold = 0.25 out = cv2.VideoWriter('outpy2.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 30, (720,720)) # Initialize video # cap = cv2.VideoCapture("video.avi") v...
import streamlit as st import datetime as dt with st.sidebar: n_holes = int(st.number_input("No. of hole played", min_value=1)) format_hole = lambda x: f"Hole {x}" hole = st.selectbox("Select hole to edit:", range(1, n_holes+1), format_func=format_hole) possible_end_lies = ["Fairway", "Green", "In The Hol...
class Option: def __init__(self, description:str = "...", type:int = 3): self.description = description self.type = type def to_dict(self): return { "type": type, "description":self.description, "required": self.required }
#!/usr/bin/python3 # Basic shellcode crypter for C# payloads # By Cas van Cooten import re import platform import argparse import subprocess from random import randint if platform.system() != "Linux": exit("[x] ERROR: Only Linux is supported for this utility script.") class bcolors: OKBLUE = '\033[94m' ...
def Odd_and_Even_Sum(number_as_string): odd_sum = 0 even_sum = 0 for element in number_as_string: if int(element) % 2 == 0: even_sum += int(element) else: odd_sum += int(element) return (f"Odd sum = {odd_sum}, Even sum = {even_sum}") number = input() r...
class TriangleType: def type(self, a, b, c): s = sorted([a, b, c]) if s[2] >= s[0] + s[1]: return "IMPOSSIBLE" c = cmp(s[0] ** 2 + s[1] ** 2, s[2] ** 2) if c == 0: return "RIGHT" elif c > 0: return "ACUTE" return "OBTUSE"
from tqdm import tqdm from os.path import join, exists import json import collections import tensorflow as tf import random random.seed(0) class ZaloDatasetProcessor(object): """ Base class to process & store input data for the Zalo AI Challenge dataset""" label_list = ['False', 'True'] def __init__(self...
# -*- coding: utf-8 -*- """ Milstein's method on linear SDE dX = λ*X dt + μ*X dW, X(0) = X0 timesteps for Brownian and Integrator are dt and Dt (see em.py) """ import numpy as np from numpy.random import randn import matplotlib.pyplot as plt np.random.seed(100) # problem parameters λ = 2; μ = 1; X0 = 1 T = 1; N = ...
from rest_framework import routers from .api import ( AttemptLogViewSet, ContentSessionLogViewSet, ContentSummaryLogViewSet, ExamAttemptLogViewSet, ExamLogViewSet, MasteryLogViewSet, TotalContentProgressViewSet, UserSessionLogViewSet ) from .csv import ContentSessionLogCSVExportViewSet, ContentSummaryLogCSVExp...
from unittest.case import TestCase from unittest.mock import patch import pytest import requests_mock from .. import Rumetr, exceptions @requests_mock.Mocker() @patch.object(Rumetr, 'check_complex', return_value=True) class TestHouseChecking(TestCase): TEST_URL = 'http://api.host.com/developers/dvlpr/complexes/...
def convert_to_binary(prm1): _bits_needed = 1 _start = 1 _user_value = int(prm1) _original_in = str(_user_value) _binary_value = "" """ Loop through the numbers from 1 increasing by a power of 2 until we get a number that is equal to or exceeds the users input. Increase bit ...
def navier_stokes_x(i, j, u, u_tp, v, dx, dy, dt, Re): uu_f = ((1.0/2.0) * (u[i+1, j] + u[i, j]))**2.0 uu_b = ((1.0/2.0) * (u[i-1, j] + u[i, j]))**2.0 Duu_x = (uu_f - uu_b)/dx u_sum_f = u[i, j] + u[i, j+1] u_sum_b = u[i, j] + u[i, j-1] v_sum_f = v[i, j] + v[i+1, j] v_sum_b = v[i, j-1] + ...
import torch import torchvision import torchvision.transforms as transforms def get_transforms(dataset): transform_train = None transform_test = None if dataset == 'cifar10': transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHoriz...
import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html def build_slider(tab, multiple=False): children = [ dbc.Card([ dbc.Row(id='app-controller', children=[ dbc.Col(children=[ dbc.Row([ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `python_greek_names` package.""" from __future__ import unicode_literals from python_text_utils.generic import Generic from python_greek_names.utils import ( normalize_name, VocativeMapper, GenitiveMapper ) def test_normalize(): assert norma...
import os import pandas as pd import xml.etree.ElementTree as ET from tqdm import tqdm image_source = '/kaggle/input/siim-covid19-resized-to-1024px-jpg' os.makedirs('lung_crop', exist_ok=True) if __name__ == '__main__': df = pd.read_csv('../../dataset/siim-covid19-detection/train_kfold.csv') for fold in ran...
import prometheus.tftpd ''' import prometheus.tftpd prometheus.tftpd.tftpd() to run: set PYTHONPATH=p:\lanot\src\core\python ''' prometheus.tftpd.tftp_client('greenhouse01.iot.oh.wsh.no', 'main.py', 'greenhouse01.py') # prometheus.tftpd.tftp_client('greenhouse01.iot.oh.wsh.no', 'cacert.pem') # prometheus.tftpd.tftp...
from django.db import models from django.utils.translation import ugettext_lazy as _ from internationalflavor.iban.validators import BICCleaner, IBANCleaner from .forms import IBANFormField from .data import IBAN_MAX_LENGTH from internationalflavor.iban.forms import BICFormField from .validators import IBANValidator, ...
import libtmux def ensure_server() -> libtmux.Server: ''' Either create new or return existing server ''' return libtmux.Server() def spawn_session(name: str, kubeconfig_location: str, server: libtmux.Server): if server.has_session(name): return else: session = server.new_ses...
from unittest import TestCase from db_credentials import DBCredentials class TestDBCredentials( TestCase ): def setUp( self ): self.creds = DBCredentials.DBCredentials() self.creds.loadFile( '/Users/damonsauve/git/db-credentials/db_credentials/test/test.creds' ) self.test_creds = { ...
#!/usr/bin/env python ################################################################## # Copyright (c) 2012, Sergej Srepfler <[email protected]> # February 2012 - March 2012 # Version 0.2.6, Last change on Mar 20, 2012 # This software is distributed under the terms of BSD license. ##################...
#!/usr/bin/python3 # Converts nsi_presets.json to a sqlite db # Not currently used, but maybe in the future when NSI is unbearably large # # Output can be piped to sqlite3 to create the database import json file = open("nsi_presets.json") data = json.load(file) print("create table brands(id INTEGER, identifier TEXT...
#!/usr/bin/python from mod_pywebsocket import msgutil import time import urllib def web_socket_do_extra_handshake(request): msgutil._write(request, 'x') time.sleep(2) def web_socket_transfer_data(request): msgutil._write(request, urllib.unquote(request.ws_location.split('?', 1)[1]).decode("string-escape")) time...
import mgear.core.pyqt as gqt from mgear.vendor.Qt import QtCore, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(344, 635) self.verticalLayout_3 = QtWidgets.QVBoxLayout(Form) self.verticalLayout_3.setObjectName("verticalLayout_3") ...
import os, pytest from pathlib import Path from ..fast import FAST @pytest.mark.parametrize("inputs, outputs", []) def test_FAST(test_data, inputs, outputs): in_file = Path(test_data) / "test.nii.gz" if inputs is None: inputs = {} for key, val in inputs.items(): try: inputs[key...
import rospy import tf2_ros as tf import queue from threading import Thread class TestResult: def __init__(self, name, msg): self.success = False self.msg = msg self.name = name self.timed_out = False def set_result(self, value): self.success = value def print(self...
import unittest from . import test_column from . import test_map_mooring from . import test_loading from . import test_substructure from . import test_floating def suite(): suite = unittest.TestSuite( (test_column.suite(), test_map_mooring.suite(), ...
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) operacao = 0 print('Escolha uma opção:\n1. Somar\n2. Multiplicar\n3. Maior.\n4. Novos números.\n5. Sair do programa') while operacao != 5: operacao = int(input()) if operacao == 1: print('{} + {} = {}'.format(n1, n2, n1 + n2)) ...
import config import urllib.parse import datetime import traceback import time # import tqdm import zlib import settings import datetime import sqlalchemy.exc from sqlalchemy import or_ from sqlalchemy import and_ from sqlalchemy import func from sqlalchemy import text import common.database as dbm import RawArchive...
''' Matrix Chain Multiplication Send Feedback Given a chain of matrices A1, A2, A3,.....An, you have to figure out the most efficient way to multiply these matrices. In other words, determine where to place parentheses to minimize the number of multiplications. You will be given an array p[] of size n + 1. Dimension of...
# coding: utf-8 import ee import datetime import ee.mapclient region = [[-25.0, -37.0], [60.0, -41.0], [58.0, 39.0], [-31.0, 38.0], [-25.0, -37.0]] VisPar_AGBPy = {"opacity": 0.85, "bands": "b1", "min": 0, "max": 12000, "palette": "f4ffd9,c8ef7e,87b332,566e1b", "region": regi...
# -*- coding:utf-8 -*- # !/usr/bin/env python3 """ """ def test_print_num(): from minghu6.algs.pprint import print_num result = print_num(10000000000, split_len=3, split_char='_', need_print=False) assert result == '10_000_000_000' if __name__ == '__main__': test_print_num()
# -*- coding: utf-8 -*- """Untitled13.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1bREcXDsoDGSvarUHDBVYKuh8AFtpRFD1 """ import numpy as np import matplotlib.pyplot as plt ket_basis_0=np.array([[1],[0]]) print(ket_basis_0) ket_basis_1=np.arr...
import boto3 def main(): ec2 = boto3.client('ec2', region_name='eu-west-1') print(ec2.describe_instances()) print("coucou !") if __name__==__main__: main()
from __future__ import print_function from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import numpy as np import os ###################################### ######### Necessary Flags ############ ###################################### tf.app.flags.DEFINE_string( 'train_root', os.pa...
from datetime import timedelta from django.test import TestCase from django.utils import timezone from app.models import Game, PlayerRole from app.tests.helpers.tag_tester import TagTester from app.tests.helpers.user_tester import UserTester class TagTest(TestCase): def setUp(self): user_tester = UserTe...
# -*- coding: utf-8 -*- u"""SDDS utilities. :copyright: Copyright (c) 2018 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from pykern import pkio from pykern import pksubprocess from pykern.pkdebug impo...
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from lib.batch_annotator import BatchAnnotator def main(csv_filename): batch_annotator = BatchAnnotator(linker="umls") output_filename = csv_filename.replace(".csv", ".json") batch_annotator.load_csv(csv_filename) b...
# -*- coding: utf-8 -*- from google.appengine.api import urlfetch from google.appengine.api import urlfetch_errors from bs4 import BeautifulSoup import models URL = "http://www.metoffice.gov.uk/climate/uk/summaries/datasets#Yearorder" recording_fields = ['Year', 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', ...
import json with open('sample.json', 'r') as file: result = json.load(file) print(result)
SERVER_MOVE = "102 MOVE" SERVER_TURN_LEFT = "103 TURN LEFT" SERVER_TURN_RIGHT = "104 TURN RIGHT" SERVER_PICK_UP = "105 GET MESSAGE" SERVER_LOGOUT = "106 LOGOUT" SERVER_OK = "200 OK" SERVER_LOGIN_FAILED = "300 LOGIN FAILED" SERVER_SYNTAX_ERROR = "301 SYNTAX ERROR" SERVER_LOGIC_ERROR = "302 LOGIC ERROR" SERVER_KEY = 546...
from kivy.clock import Clock from kivy.properties import BooleanProperty, ObjectProperty from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label class IndexedItem: def __init__(self, index=None, item=None): self.index = index self.item = item class ListView(BoxLayout): sele...
import flask import flask_oauthres from . import config app = flask.Flask(__name__) app.config.from_mapping( SECRET_KEY=config.SECRET_KEY, TESTING=config.TESTING, DEBUG=config.DEBUG ) oauth = flask_oauthres.OAuth2Resource(app=app, resource_id=config.OAUTH2_RESOURCE_ID,...
from typings import * class Event(object): def __init__(self, start_date: int, end_time: int, event_type: str, room: str, color="cyan", **args): self.start_date = start_date self.end_time = end_time self.event_type = event_type self.room = room self.color = color #...
""" Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the firs...
""" Definitions of classes that define the imported model """ import numpy as np from pyvista import UnstructuredGrid from .step import Step from .faces import RigidSurface, DeformableSurface, Face from .elements import N_INT_PNTS class Model: """Class for the model. This contains all the information of the ...
class DefaultProcedure: def __init__(self): return 0 def simulate(self): return 0 def setup(self): return 0 def initialize(self): return 0
import logging import re from looker_sdk import models from looker_deployer.utils import deploy_logging from looker_deployer.utils.get_client import get_client from looker_deployer.utils.match_by_key import match_by_key logger = deploy_logging.get_logger(__name__) def get_filtered_groups(source_sdk, pattern=None): ...
# (c) Copyright 2017-2018 SUSE 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 writ...
from typing import TYPE_CHECKING, List, Optional from .formatter import Formatter if TYPE_CHECKING: from sharptable.tables import Table class CompositeFormatter(Formatter): """ Class allowing for multiple formatters to be applied. """ def __init__(self, formatters: Optional[List[Formatter]] = N...
"""Pluggable utilities for Hydrus.""" from contextlib import contextmanager from flask import appcontext_pushed from flask import g from hydrus.hydraspec import doc_writer_sample from hydrus.data.db_models import engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.session import Session from hydrus.hydr...
# Pyhton code to run the ABC-SMC algorithm to parametrise the multi-stage model with cell generations # making use of F5 T cells data. # Reference: "Approximate Bayesian Computation scheme for parameter inference and model selection # in dynamical systems" by Toni T. et al. (2008). # Import the required modules. impor...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import struct import z3 def s264(s): return struct.unpack('<Q', s)[0] def to8(i): return i & 0xff def to16(i): return i & 0xffff def to32(i): return i & 0xffffffff ################################################################################ ...
from django.contrib import admin # Register your models here. from apps.models import App import hashlib @admin.register(App) class ApisAppAdmin(admin.ModelAdmin): fields = ['name', 'application', 'category', 'url', 'publish_date', 'desc'] # exclude = ['appid'] def save_model(self, request, obj, form, c...
from org.gluu.oxauth.service import AuthenticationService from org.gluu.oxauth.service import UserService from org.gluu.oxauth.auth import Authenticator from org.gluu.oxauth.security import Identity from org.gluu.model.custom.script.type.auth import PersonAuthenticationType from org.gluu.service.cdi.util import CdiUt...
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Country, State from api.serializers import StateSerializer def states_url(country): """Return state...
import json import os import pprint history = {} home = os.path.expanduser('~') history_directory = home + "/.bash_history" history_file = open(history_directory, 'r') for command in history_file: #sanitize command and split into arguments command = command.strip("\n") args = command.split(" ") args = [arg for a...
import FWCore.ParameterSet.Config as cms # File: RecHits.cfi # Author: B. Scurlock # Date: 03.04.2008 # # Fill validation histograms for ECAL and HCAL RecHits. ECALAnalyzer = cms.EDAnalyzer( "ECALRecHitAnalyzer", EBRecHitsLabel = cms.InputTag("ecalRecHit","EcalRecHitsEB"), EERecHitsLabel = cms.InputTag("ec...
""" """ import pytest class TestCommon(object): storage = {} @pytest.fixture() def number(self, pytestconfig): return int(pytestconfig.getoption('n')) @pytest.fixture() def text(self, pytestconfig): return pytestconfig.getoption('t') @pytest.fixture() def number_double...
import logging from zope.interface import implements from twisted.internet import defer from lbrynet.cryptstream.CryptBlob import CryptBlobInfo from lbrynet.interfaces import IMetadataHandler log = logging.getLogger(__name__) class EncryptedFileMetadataHandler(object): implements(IMetadataHandler) def __in...
import io from PIL import Image, ImageTk def get_img_data(site, maxsize=(500, 500), first=False): """ Generate image data using PIL """ image = Image.open(site) image.thumbnail(maxsize) if first: # tkinter is inactive the first time bio = io.BytesIO() image.save(bio, format="...
# Add new commands in this file # Also modify `__init__.py` to expose the methods in the package from .utils import get import json from .config import Config from random import sample async def getUserInfo(handles): """ Refer: https://codeforces.com/apiHelp/methods#user.info Fetches the user info of the...
from django.template import (Node, Variable, TemplateSyntaxError, Library) try: from django.template.base import render_value_in_context except ImportError: from django.template.base import _render_value_in_context as render_value_in_context from phrase.compat import TOKEN_TEXT, TOKEN_VAR, is_string_type from d...
from __future__ import annotations class BroodError(Exception): pass class UnknownFormat(BroodError): pass
import pytest from porcupine import get_main_window code = """\ with open(path) as f: while True: try: line = f.readline().decode('utf-8') except OSError: break print(repr(line)) print("foo") """ except_folded = """\ with open(path) as f: while True: ...
from typing import Dict, Set from functools import reduce from gym_splendor_code.envs.mechanics.enums import GemColor class GemsCollection(): '''This class is used to desribed a collection of gemes. It can be treated both as a wallet of games or as a price of a single card.''' def __init__(self, ...
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from adminsortable2.admin import SortableInlineAdminMixin from real_estate.admin import ( AdminInlineImages, MultiuploadInlinesContainerMixin, ) from .models import ( ResaleApartment, ResaleApartmentImage, Re...
import time import threading import zmq import traceback THREAD_DELAY_SEC = 0.05 SHOTS_BUFFER_SIZE = 100 ''' class DataEventCallBack(PyTango.utils.EventCallBack): def __init__(self, parent_obj): self.parent = parent_obj return def push_event(self, event_data): try: if not event_data.e...
# #!/usr/bin/env python # # """ # @package ion.agents.platform.test.test_platform_agent_with_rsn # @file ion/agents/platform/test/test_platform_agent_with_rsn.py # @author Carlos Rueda # @brief Test cases for platform agent interacting with RSN # """ # # __author__ = 'Carlos Rueda' # __license__ = 'Apache 2.0' # ...
from . import db from werkzeug.security import generate_password_hash,check_password_hash from flask_login import UserMixin from . import login_manager from datetime import datetime @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMixin,db.Model): __tablen...
from django.http.response import HttpResponseRedirect from django.contrib.auth.decorators import login_required from datetime import datetime from django.contrib import messages from django.shortcuts import get_object_or_404, redirect, render from django.views import generic from .models import Post from .forms import ...
import discord from discord.ext import commands import random import re class Fun: def __init__(self, client): self.client = client # Say message then delete author message @commands.command(pass_context=True, no_pm=True) async def say(self, ctx, *, words): await self.client.delete_m...
#!/usr/bin/env python import rospy from mavros_msgs.msg import State from mavros_msgs.srv import CommandBool, SetMode from geometry_msgs.msg import Pose, PoseStamped, Point, Quaternion import math import numpy from geometry_msgs.msg import Twist from std_msgs.msg import Header from threading import Thread x=1 print x ...
from abc import ABC, abstractmethod import logging from logging import Logger from pathlib import Path import socket from typing import Any, Generator, Mapping, Sequence, Union from pyproj import CRS from shapely.geometry import LinearRing, MultiPolygon, Polygon from shapely.geometry.base import BaseGeometry, GEOMETRY...
import django import pytest from anylink.models import AnyLink from markymark.templatetags.markymark import markdown_filter from markymark.widgets import MarkdownTextarea @pytest.mark.skipif(django.VERSION[0] >= 2, reason='Requires Django<2') @pytest.mark.django_db class TestFilerFileExtension: def setup(self):...
""" @author: David Lei @since: 21/08/2016 @modified: """
#!/usr/bin/python # -*- coding:utf-8 -*- # Download data into Excel # Date for Version 2: 2020.04.08 import MySQLdb import xlrd,xlwt import time from datetime import datetime import os def getData(): file_new = xlwt.Workbook(encoding = 'utf-8') sheet_1 = file_new.add_sheet('main') # prepare some setti...
from django.urls import include, path from .views import login, logoutFlutter, daftar, json_fb, fb_json, feedback_json, ListFeedback, DetailFeedback urlpatterns = [ path('', login, name='loginflutter'), path('logout', logoutFlutter, name='logoutflutter'), path('daftar', daftar, name='daftarflutter'), #...
#!/usr/bin/env python import time from threading import Thread import pybullet as p from .core.op3 import OP3 from .walking.wfunc import WFunc class Walker(OP3): """ Class for making Darwin walk """ def __init__(self, x_vel=1, y_vel=0, ang_vel=0, interval=0.0054, *args, **kwargs): OP3.__ini...
""" Legacy mid-level functions. """ from __future__ import absolute_import, division, print_function import os from ._password_hasher import ( DEFAULT_HASH_LENGTH, DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_RANDOM_SALT_LENGTH, DEFAULT_TIME_COST, ) from .low_level import Type, hash_secret, ...
"""Viajar é bom demais! Uma agência de viagens está propondo uma estratégia para alavancar as vendas após os impactos da pandemia do coronavírus. A empresa ofertará descontos progressivos na compra de pacotes, dependendo do número de viajantes que estão no mesmo grupo e moram na mesma residência. Para ajudar a tornar e...
def print_hello_world(): print('Hello World!') def my_print(msg): print(msg) # my_print('Hello Cyber!') def add(a, b): return a + b a = 5 b = 3 print(f'the sum of {a} + {b} is {add(a,b)}') c = 7 if add(a,b) > c: print(f'{add(a,b)} is greater than {c}') elif add(a,b) > 10: print(f'{add(a,b)}...
class Solution(object): def spiralOrder(self, matrix): if not matrix: return [] t, b, l, r, d = 0, len(matrix) - 1, 0, len(matrix[0]) - 1, 0 res = [] while t <= b and l <= r: if d == 0: res.extend(matrix[t][l : r + 1]) t += 1 ...