content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from algo.dqn.train import * | python |
"""
Kalman filter implementation was based on paper "Implementation of Kalman Filter with Python Language"
Mohamed LAARAIEDH
IETR Labs, University of Rennes 1
Mohamed.laaraiedh@univ-rennes1.fr
Code was adapted to follow the notation of the course assignment
"""
from numpy.linalg import inv
import matplotlib.pyplot a... | python |
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from .config import config, root
SQL_DIR: str = "sql"
SCHEMA_FILE: str = "schema.sql"
def schema() -> None:
path: Path = (root / SQL_DIR).resolve(strict=True)
env = Environment(loader=FileSystemLoader(path))
template = env.get_te... | python |
import pygame
import os
import random
import time
from enemy.scorpion import Scorpion
from towers.archerTower import ArcherTower
from towers.archerTower import ArcherTowerShort
from enemy.Club import Club
from enemy.tmall import TMall
from towers.supportTower import DamageTower
from towers.supportTower import RangeTowe... | python |
import os
import numpy as np
import pandas as pd
df = pd.read_csv(os.getcwd() + "/city/output/list_of_countries.csv")
df.set_index("country", inplace=True)
print("Enter the name of a country : ", end=" ")
country_to_be_searched = input().title()
for i in df:
if not np.isnan(df.loc[country_to_be_searched][str(i)]... | python |
from typing import List, Dict, Any, Optional, Union
from relevanceai.operations_new.run import OperationRun
from relevanceai.operations_new.dr.models.base import DimReductionModelBase
class DimReductionBase(OperationRun):
model: DimReductionModelBase
fields: List[str]
alias: str
def __init__(
... | python |
from optparse import OptionParser
from ztf_util import make_dict_from_config, make_dict_from_optparse
from ztf_simu import Simul_lc
from ztf_hdf5 import Write_LightCurve
from ztf_util import multiproc, dump_in_yaml, checkDir
from astropy.table import Table, vstack
def simu(index, params, j=0, output_q=None):
par... | python |
import sys
import pytest
if sys.version_info >= (3, 8):
from importlib.metadata import version
else:
from importlib_metadata import version
python_3_6_plus = pytest.mark.skipif(sys.version_info < (3, 6), reason="Python 3.6+")
def test_version(flake8dir):
result = flake8dir.run_flake8(["--version"])
... | python |
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from Employees.models import Person, Employee, Project
# Create your views here.
# Display Persons
def index_persons(request):
persons = Person.objects.all()
return render(request,
'employees/index_per... | python |
# Copyright (c) 2016 EMC Corporation.
# 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 requ... | python |
from PySide2 import QtCore, QtGui, QtWidgets
import sys
class FilterEdit(QtWidgets.QLineEdit):
def __init__(self):
super(FilterEdit, self).__init__()
self.setPlaceholderText("Filter")
class SectionView(QtWidgets.QListView):
doubleClicked = QtCore.Signal(object)
def __init__(self, parent... | python |
# Iterate over string using list comprehension
list = ['Hello World', "JAVA", "C++", "MySQL"]
x = [str.lower() for str in list]
print(x) | python |
from unittest import TestCase
from gdacs.api import GDACSAPIReader, GDACSAPIError
class TestGDACSAPI(TestCase):
def setUp(self):
self.client = GDACSAPIReader()
def tearDown(self):
self.client = None
# delete all the files
def test_latest_events_no_args(self):
'''Test la... | python |
import unittest
from soap.datatype import int_type, FloatArrayType
from soap.expression import Variable
from soap.parser import parse
from soap.semantics.schedule.extract import ForLoopNestExtractor
from soap.semantics.state import flow_to_meta_state
def _extract_from_program(program):
flow = parse(program)
... | python |
import pyttsx3
import datetime
import time as t
import smtplib
import wikipedia
import webbrowser as wb
import os
import string
import wolframalpha
import pyautogui
import psutil
import pyjokes
import random
from colored import fg, attr
import speech_recognition as sr
print(f"""{fg(226)}{attr(1)}
... | python |
"""
https://leetcode.com/problems/fair-candy-swap/
https://leetcode.com/submissions/detail/186770998/
"""
class Solution:
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
diff = (sum(A) - sum(B)) / 2
setB = set(... | python |
class DiscipleClass:
def displayAllDisciples(self,language):
import json
if (language == "EN"):
try:
with open('../data/data.txt') as json_file:
data = json.load(json_file)
for i in data['disciples']:
print('... | python |
# Created by Artem Manchenkov
# artyom@manchenkoff.me
#
# Copyright © 2019
#
# Сервер для обработки сообщений от клиентов
#
from twisted.internet import reactor
from twisted.protocols.basic import LineOnlyReceiver
from twisted.internet.protocol import ServerFactory, connectionDone
class Client(LineOnlyReceiver):
... | python |
__author__ = "Nghia Doan"
__company__ = "Agiga Quanta Inc."
__copyright__ = "Copyright 2018"
__version__ = "1.0.0"
__maintainer__ = "Nghia Doan"
__email__ = "nghia71@gmail.com"
__status__ = "Production"
from ast import literal_eval
from configparser import ConfigParser, ExtendedInterpolation
class ConfigHandler(obj... | python |
import typer
from pyfiglet import Figlet
from rich.console import Console
from triggercmd_cli import __version__
from triggercmd_cli.command.command import command_app as app
# app = typer.Typer(help=__doc__)
console = Console()
app.help = __doc__
# app.add_typer(command_app, name="command")
def get_version(version... | python |
#!/usr/bin/env python
from distutils.core import setup
setup(name='widlparser',
version='0.999',
description='WebIDL Parser',
author='Peter Linss',
author_email='peter.linss@hp.com',
url='http://github.com/plinss/widlparser/',
packages = ['widlparser']
)
| python |
import asyncio
import logging
import socket
import fstrm
import dnstap_pb
from dnstap_receiver.outputs import transform
clogger = logging.getLogger("dnstap_receiver.console")
def checking_conf(cfg):
"""validate the config"""
clogger.debug("Output handler: dnstap")
valid_conf = True
if cfg["... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 13:12:12 2021
@author: z
"""
import pprint
import numpy as np
import torch
import logging
import transformers
import datasets
from dataclasses import dataclass, field
from typing import Optional
from custom_data_collator import DataCollatorForTo... | python |
"""
Find most common first names in a list of people.
This can be used after cleaning your data.
Example of cleaned data used: ./example/names.txt
Author: Christian M. Fulton
Date: 05.Aug.2021
"""
def main():
"""
Exec
"""
first_names()
#impl opt exp data
#ex = input("Would you like to expo... | python |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | python |
from django.urls import path
from . import views
app_name = "inventory"
urlpatterns = [
path("objekt/", views.ObjektListView.as_view(), name="objekt-list"),
path("objekt/add/", views.ObjektCreateView.as_view(), name="objekt-create"),
path("objekt/<int:pk>/", views.ObjektDetailView.as_view(), name="objekt-... | python |
import sys
import os
sys.path.insert(0, os.path.realpath('.'))
import mimetypes
from create_movie import generate_movie
def test_generate_movie(tmpdir):
images_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__),
'fixtures'))
output_filename = tmpdir.jo... | python |
"""
It is always Calm before a Tornado!
Calm is a Tornado extension providing tools and decorators to easily develop
RESTful APIs based on Tornado.
The core of Calm is the Calm Application. The users should initialize an
(or more) instance of `calm.Application` and all the rest is done using that
instance.
The whole... | python |
import discord
import datetime as dt
from fuzzywuzzy import fuzz
from dateutil.relativedelta import relativedelta
from data import data
DEFAULT_BIRHDAY_RANGE_IN_DAYS = 45
A_EMOJI = 127462
SKIP_EMOJI = 9197
YES_NO_SHOW = {'👍': 1, '👎': 0, '🔎': 2}
MAPS = ['Haven', 'Split', 'Ascent', 'Bind', 'Icebox']
def emoji_list(... | python |
from flask import Flask
from flask_opentracing import FlaskTracer
import lightstep.tracer
import opentracing
import urllib2
app = Flask(__name__)
# one-time tracer initialization code
ls_tracer = lightstep.tracer.init_tracer(group_name="example client", access_token="{your_lightstep_token}")
# this tracer does not tr... | python |
#!/usr/bin/env python
values = [4, 10, 3, 8, -6]
print(values)
for i in range(len(values)):
values[i] = values[i] * 2
print(values)
| python |
import random
import json
def index():
return dict(message=T('Welcome to our Crowd Sourcing Platform!'))
#@auth.requires_login()
def get_sentence():
return "bla"
#@auth.requires_login()
def tutorial():
return dict()
def getAnnotation(data):
session.data = data
ret = "<p>"
words = data['sent... | python |
from RePoE.parser.util import call_with_default_args, write_json
from RePoE.parser import Parser_Module
class quest_rewards(Parser_Module):
@staticmethod
def write(ggpk, data_path, relational_reader, translation_file_cache, ot_file_cache):
root = {}
all_classes = ["Duelist", "Marauder", "Range... | python |
from __future__ import absolute_import, division, print_function
def info(filename):
'''Generate information from EXIF headers.'''
import exifread
import datetime
import calendar
ts = 'EXIF DateTimeOriginal'
result = {}
with open(filename) as f:
tags = exifread.process_file(f, ... | python |
import spam
@spam.eggs
def eggs_and_sausage(*args):
return "spam"
| python |
###########################################################################
# Created by: Dan Xu
# Email: danxu@robots.ox.ac.uk
# Copyright (c) 2019
###########################################################################
import os
import os.path as osp
import numpy as np
import random
import collections
import tor... | python |
# Generated with SMOP 0.41-beta
try:
from smop.libsmop import *
except ImportError:
raise ImportError('File compiled with `smop3`, please install `smop3` to run it.') from None
# Get_VarthsPSI_swing.m
@function
def Get_VarthsPSI_swing(zetaj=None,ntilj=None,PSIdj=None,PSIdjm1=None,*args,**kwargs)... | python |
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from flask_httpauth import HTTPBasicAuth
import utils
app = Flask(__name__, static_folder="react-dashboard/build", static_url_path="/")
CORS(app, resources={r"/*": {"origins": "*"}})
app.config["CORS_HEADERS"] = "Content-Type"
... | python |
B_15_01_10 = {0: {'A': -0.054, 'C': 0.0, 'E': 0.52, 'D': 0.0, 'G': 0.183, 'F': -0.158, 'I': -0.377, 'H': -0.009, 'K': 0.207, 'M': -0.074, 'L': -0.365, 'N': 0.062, 'Q': 0.054, 'P': 0.164, 'S': -0.081, 'R': -0.242, 'T': 0.141, 'W': -0.11, 'V': 0.136, 'Y': 0.002}, 1: {'A': 0.094, 'C': 0.0, 'E': -0.305, 'D': 0.0, 'G': 0.20... | python |
from collections import deque
import random
import numpy as np
import tensorflow as tf
class flappydqn:
# parameters
ACTION = 2
FRAME_PER_ACTION = 1
GAMMA = 0.99 # decay rate of past observations
OBSERVE = 10000 # timesteps to observe before training
EXPLORE = 300000 # frames over which to anneal epsilon
... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2012 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... | python |
# Imports
from pysal.lib import examples
import geopandas as gpd
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from pysal.viz.splot.mapping import vba_legend, mapclassify_bin
# Load Example Data
link_to_data = examples.get_path('columbus.shp')
gdf = gpd.read_file(link_to_data)
x = gdf['HOVAL']... | python |
# coding=utf-8
from config import *
from dependency import *
from downloader import *
| python |
CLIENT_ID = None
CLIENT_SECRET = None
API_BASE_URL = 'https://api.figshare.com/v2/'
MAX_RENDER_SIZE = 1000
FIGSHARE_OAUTH_TOKEN_ENDPOINT = '{}{}'.format(API_BASE_URL, 'token')
FIGSHARE_OAUTH_AUTH_ENDPOINT = 'https://figshare.com/account/applications/authorize'
FIGSHARE_DEFINED_TYPE_NUM_MAP = {
'figure': 1,
... | python |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class TypeFileSearchResultEnum(object):
"""Implementation of the 'Type_FileSearchResult' enum.
Specifies the type of the file document such as KDirectory, kFile, etc.
Attributes:
KDIRECTORY: TODO: type description here.
KFILE: TODO: ... | python |
import json
from cardbuilder.common import Language, Fieldname
from cardbuilder.exceptions import WordLookupException
from cardbuilder.input.word import Word
from cardbuilder.lookup.data_source import WebApiDataSource
from cardbuilder.lookup.lookup_data import LookupData, outputs
from wiktionaryparser import Wiktiona... | python |
import tvm
from ..hw_abs_base import (
HardwareAbstraction,
register_abstraction,
MemoryAbstraction,
ComputeAbstraction,
ElementwiseComputeAbstraction,
ElementwiseMemoryAbstraction,
)
@register_abstraction("tenet axpy", "tenet::axpy::store_vector")
class TenetAxpyStoreVector(MemoryAbstraction)... | python |
# import os
from pathlib import Path
import pandas as pd
class QC(object):
def __init__(self, folder_path = '/Users/htelg/data/baseline/scaled/brw/2018/',
folder_path_raw='/Volumes/grad/gradobs/raw/ber/2018/',
num_files_to_be_opened = 3,
verbose = False,
... | python |
"""
Copyright 2017 NREL
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
un... | python |
"""Module for converting sysopt expression graphs into casadi functions."""
from typing import List, Union
from sysopt.symbolic import Algebraic, scalar_shape, is_op, is_matrix
import casadi as _casadi
def lambdify(graph,
arguments: List[Union[Algebraic, List[Algebraic]]],
name: str = 'f')... | python |
from django.conf import settings
from django.db.models import F
from django.utils.translation import activate
from geotrek.api.v2 import serializers as api_serializers, \
filters as api_filters, viewsets as api_viewsets
from geotrek.api.v2.functions import Transform
from geotrek.outdoor import models as outdoor_mo... | python |
import re
def count_smileys(arr):
faces = ''.join(arr)
smiley = re.findall('[:;][-~]?[D)]', faces)
return len(smiley)
def count_smileys2(arr):
smileys = [":)", ";)", ":~)", ";~)", ":-)", ";-)", ":D", ";D", ":~D", ";~D", ":-D", ";-D"]
faces = 0
if not arr:
return 0
for face in arr:
... | python |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
def vol_plot(x):
import os #TO control directories
import nibabel as nib # read and save medical images
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import plotly
import plotly.express as px
from ipywidgets import interact, interactive,... | python |
# Generated by Django 3.0.7 on 2020-07-05 01:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0014_auto_20200705_0118'),
]
operations = [
migrations.DeleteModel(
name='Family',
),
]
| python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | python |
from django import forms
from django.conf import settings
try:
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
except ImportError:
from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from ... | python |
import string
from pywebapp import http_helper
from pywebapp.errors import PyWebAppResponseHeadersAlreadySentError
class WebResponse(object):
def __init__(self, start_fn, request=None):
self._start_fn = start_fn
self.request = request
self.status_code = http_helper.status['OK']
self.headers = {'Cont... | python |
from getch import getch
import os
class TextUI:
def displayWelcome(self):
print """ ::: === === :::==== :::====
::: === === ::: === ::: ===
=== === === ======== =======
=========== === === === ===
==== ==== === === === ===
"""
def promptForPlayers(self):
num = 0
... | python |
# ../managers/operatorsSignaling/reconstructer.py
import efel
#from quantities import mV
class Reconstructer(object):
"""
**Available methods:**
+-------------------------------------------------+--------------------+
| Method name | Method type |
+------... | python |
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2016-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to dea... | python |
from . import (
secp256k1,
sha256,
utils,
merkle_part,
iavl_merkle_path,
multi_store,
tm_signature
)
| python |
# Inference code for the CVAE driver sensor model. Code is adapted from: https://github.com/sisl/EvidentialSparsification.
import os
import time
seed = 123
import numpy as np
np.random.seed(seed)
from matplotlib import pyplot as plt
import torch
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cud... | python |
#!/usr/bin/env python3
"""
Library providing convenient classes and methods for writing data to files.
"""
import sys
import json
import pickle
try:
import yaml
except ImportError:
yaml = None
class Serializer(object):
ext = ""
woptions = ""
roptions = ""
@classmethod
def marshal(cls, in... | python |
import os
import shutil
def ensure_directory(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def ensure_directory_hard(directory):
if os.path.exists(directory):
shutil.rmtree(directory)
os.mkdir(directory)
| python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import six
import hashlib
import pyscrypt
import base58
import hashlib
#from Crypto.Hash import RIPEMD
import libnacl.public
import libnacl.secret
# The public key used for verifying peer tokens which are the id... | python |
import pytest
xfail = pytest.mark.xfail(strict=True)
import numpy as np
from skroute.datasets import load_barcelona
from skroute.metaheuristics.som._utils_som import *
from skroute.metaheuristics.som import SOM
from skroute._utils._utils import _cost
from skroute.preprocessing import dfcolumn_to_dict
df_barcelona = ... | python |
import datetime
from itertools import count
import random
import string
import time
import names
from .. import models
__all__ = ['fixture_random']
ORDINARY_USERID = "42"
ADMIN_USERID = "666"
def date_to_timestamp(d) :
return int(time.mktime(d.timetuple()))
def random_text(n=100):
return ''.join(random.ch... | python |
""" Holds all statistics for some question and manages them.
One question might have multiple statistics (for example time, correctness...).
"""
from typing import Dict
from .abstract_statistics import AbstractStatistcs
from .statistics_builder import StatisticsBuilder
class StatisticsHolder:
def __init__(se... | python |
import json
import pytest
from aizynthfinder.chem import TreeMolecule, Molecule, Reaction
from aizynthfinder.analysis import TreeAnalysis, ReactionTree, RouteCollection
@pytest.fixture
def setup_complete_tree(fresh_tree, mocker, mock_stock):
tree = fresh_tree
state1 = mocker.MagicMock()
state1.mols = [... | python |
n = int(input())
X = list(map(int, input().split()))
F = list(map(int, input().split()))
S = [x for i, x in enumerate(X) for f in range(F[i])]
S.sort()
n = len(S)
assert sum(F) == n, "The number of elements must equal the total frequency."
def median(n, X):
if n % 2 == 0:
numerator = float(X[int(n /... | python |
# Generated by Django 3.2.5 on 2021-07-31 15:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('church', '0012_introduction_copywrite'),
]
operations = [
migrations.CreateModel(
name='YoutubeMass',
fields=[
... | python |
#!/usr/bin/env python
import time, sys, random
def single_loading():
print("Loading...")
for i in range(0, 100):
time.sleep(0.01)
width = (i + 1) // 4
bar = "[" + "#" * width + " " * (25 - width) + "]"
sys.stdout.write(u"\u001b[1000D" + bar)
sys.stdout.flush()
prin... | python |
from __future__ import print_function
import tweepy
import json
import pprint
FIRSTJAN2017 = 1483209000
# Using twitter account hd_irrigation01
# Using keys from app https://apps.twitter.com/app/13837356/keys
# Email for account hrishikesh.date+hd_irrigation01@gmail.com
with open('./twitterconfig.json', 'r') as file:... | python |
class Person:
# constructor
def __init__(self, real_name):
self.real_name = real_name
def report(self):
print("I'm {}".format(self.real_name))
class Agent(Person): # Agent inherits Person class
# class object attribute
planet = "Earth"
def __init__(self, real_name, eye_color... | python |
'''
Description: Maps exercise logs to exercise/feeling values using embeddings.
Author: Mandy korpusik
Date: 8/5/2020
'''
import json
import nnets
import numpy as np
from nltk.stem import PorterStemmer
from sklearn.metrics.pairwise import cosine_similarity
def get_x_y(data):
'''Loads exercise/feeling tokens an... | python |
import os
import requests
import xml.etree.ElementTree as ET
import webbrowser
# EDGAR_BASE_URL = "https://www.sec.gov"
# EDGAR_BROWSE_URL = "/cgi-bin/browse-edgar?action=getcompany"
# EDGAR_ARCHIVE_URL = "/Archives/edgar/data/"
# EDGAR_API_BASE = "https://data.sec.gov/"
class edgarFiler():
"""Accesses data from... | python |
from .utils.data_processing import DataProcessing
from .network.network_architecture import ModelArchitecture
from .core.test_worker import TestWorker
from .core.train_worker import TrainWorker
from .utils.helpers.io_helper import IOHelper
from .utils.helpers.json_helper import JsonHelper | python |
import json
from datetime import datetime
from inflection import tableize
from ..builder import QueryBuilder
from ..collection import Collection
from ..connections import ConnectionFactory
from ..grammar import MySQLGrammar
class BoolCast:
def get(self, value):
return bool(value)
class JsonCast:
d... | python |
#!/usr/bin/env python
'''
Created on Sep 2, 2020
@author: gsnyder
Parse the Synopsys Detect log to get the status.json file emitted and use status.json to monitor
the scans (codelocations) and wait for the scan processing to complete
'''
import argparse
import arrow
import json
import logging
import re
import sys
i... | python |
from time import sleep
print('==== CALCULANDO O VALOR DAS VIAGENS ====')
km = float(input('Digite em KM a distancia da viagem: '))
print('CALCULANDO O VALOR COM BASE NA DISTANCIA ....')
sleep(2)
if km <= 200:
print('O valor da viagem é de R$ {:.2f}'.format(km*0.50))
else:
print('O valor da viagem é de R$ {:.2f... | python |
from django.apps import AppConfig
class ButtonsConfig(AppConfig):
name = 'apps.buttons'
verbose_name = 'Клавиши'
| python |
import FWCore.ParameterSet.Config as cms
#
# This cfi should be included to parse the muon standalone XML geometry.
#
XMLIdealGeometryESSource = cms.ESSource("XMLIdealGeometryESSource",
geomXMLFiles = cms.vstring('Geometry/CMSCommonData/data/normal/cmsextent.xml',
'Geometry/CMSCommonData/data/cms.xml',
... | python |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
from keras import Input
from keras.layers import LSTM, Dense, Dropout, Embedding
from keras.layers.merge import add
from keras.models import Model
from keras.preprocessing.sequence import pad_sequences
from gen_train_captions import EOS_TOKEN, SOS_TOKEN
import numpy as np
... | python |
import os
import json
import sap.lambda_ as lambda_
import sap.sns as sns
from aws_cdk import core
class CdkSAPBlogSAPStack(core.Stack):
account = None
region = None
thing_name = None
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)... | python |
"""
Usage: cache_aws_security_data.py [options]
Options:
--profile PROFILE profile to use for AWS access
--loglevel LEVEL logging level
[default: INFO]
"""
import batch
from db_models import ProjectModel
import importlib.util
import importlib
import platform
import urllib3
import ... | python |
"""HTML shenanigans.
Format:
!x:word1|word2
"""
s = input('?:')
ts = []
for t in s.split(' '):
if t[0] == '!':
x, ws = t.split(':')
x = float(x[1:])
w0, w1 = ws.split('|')
# Format
ts.append('<span class="wordswap" word1="%s" word2="%s" threshold="%f"></span>' % (w0, w1, ... | python |
class Solution:
def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:
return ceil(log(buckets) / log(minutesToTest // minutesToDie + 1))
| python |
# Imports python modules
import torch
from torchvision import models
def get_arch(arch: str):
if arch == 'resnet18':
model = models.resnet18(pretrained=True)
if arch == 'alexnet':
model = models.alexnet(pretrained=True)
if arch == 'vgg13':
model = models.vgg13(pretrained=True)
... | python |
#!/usr/bin/env python3
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
"""Deploy and manage the Cinder CSI plugin for K8s on OpenStack."""
import logging
from pathlib import Path
from charms.openstack_cloud_controller_operator.v0.cloud_config import (
CloudConfigRequires,
)
from charms.o... | python |
from dataclasses import dataclass
@dataclass
class Result:
"""
Result of a trace
"""
# True if an error occurred during the execution of a function, false otherwise
error: bool
# Error type, e.g TypeError, ZeroDivisionError...
error_type: str
# True if an TimeOutError occurred during ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
http.manage
~~~~~~~~~~~
Production management script of HTTP Request & Response service
:copyright: (c) 2011 - 2013 by Alexandr Lispython (alex@obout.ru).
:license: BSD, see LICENSE for more details.
:github: http://github.com/Lispython/httphq
"""
import time
impor... | python |
"""
-- ASDL's 5 builtin types are:
-- identifier, int, string, object, constant
module Python
{
mod = Module(stmt* body, type_ignore *type_ignores)
| Interactive(stmt* body)
| Expression(expr body)
| FunctionType(expr* argtypes, expr returns)
-- not really an actual node but useful... | python |
"""
GravMag: Generate synthetic gravity data on an irregular grid
"""
import fatiando as ft
from fatiando import logger, mesher, gridder, gravmag
from fatiando.vis import mpl
log = logger.get()
log.info(logger.header())
log.info(__doc__)
prisms = [mesher.Prism(-2000, 2000, -2000, 2000, 0, 2000, {'density':1000})]
xp,... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
main
----------------------------------
An entry point to using the ingestion package
"""
import sys
import getopt
import os
from ingestion.conversion_factory import ConversionFactory
CSV_CONVERSION = 'CSVConversion'
PROJECT_ROOT = os.path.abspath(os.path.dirname(_... | python |
import numpy as np
import matplotlib.pyplot as py
class svm():
def __init__(self):
self.w=[]
self.b=[]
starting_w=1
starting_b=10
self.w=[starting_w,starting_w,starting_b] #some implementations have rolled bias together to simplify calculations.
self.C = 1.0
def fit (self,data,labels... | python |
from scipy.special import gammaln
from numpy import log, exp, sqrt
import numpy as np
import scipy.stats
class GrowthRateConversion(object):
def __init__(self):
self.lam, self.k = self.get_params(5.0, 1.9)
def get_params(self, mu, sigma):
# we know that mu = lambda * Gamma(1+1/k)
# and... | python |
import collections.abc
import weakref
import teek
from teek._structures import ConfigDict
from teek._tcl_calls import make_thread_safe
from teek._widgets.base import ChildMixin, Widget
class TabConfigDict(ConfigDict):
def __init__(self, tab):
self._tab = tab
super().__init__()
self._type... | python |
# coding=utf-8
# ----------------
# author: weiyu
# create_time : 5/2/2021
# description :
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# 如果根节点和p,q的差相乘是正数,说明这两个差值要么都是正数要么都是负数,也就是说
# 他们肯定都位于根节点的同一侧,就继续往下找
while (root.val - p.... | python |
import sys
sys.path.append('')
from src.parser.queryParser import Parser
from src.engine.label import Label
from src.engine.property import Property
from src.engine.property_type import PropertyType
from src.engine.graph_engine import GraphEngine
from src.parser.relationCreator import RelationCreator
from src.config im... | python |
#!/usr/bin/env python
#
# Author: Prem Karat (pkarat@mvista.com)
# License: MIT
# (C) Copyright MontaVista Software, LLC 2016-2019. All rights reserved.
from apis.utils import check_kernel_configs
from apis.utils import run_cmd
import re
import sys
import glob
def pytest_configure(config):
"""Provide additional... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.