content stringlengths 5 1.05M |
|---|
# Generated by Django 2.0.9 on 2018-12-05 13:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notifications', '0003_notification_comment'),
]
operations = [
migrations.AlterField(
model_name='notification',
nam... |
import requests
from pyrogram import Client, filters
from pyrogram.types import Message
from config import prefix
@Client.on_message(filters.command("paste", prefix))
async def dogbin(c: Client, m: Message):
if m.reply_to_message:
if m.reply_to_message.document:
tfile = m.reply_to_message
... |
'''
#################################################################################################
AUTOR: WANDERSON ANTONIO COSTA GOMES
TRABALHO ACADEMICO: VIGILANCIA SOCIOASSISTENCIAL: MONITORAMENTO DE RISCOS E VULNERABILIDADES EM
TEMPO REAL POR MEIO DE MINERAÇÃO DE TEXTO NO TWITTER
UNIVERSIDADE: PONTIFÍCIA U... |
"""
Module to make the image stacking / production occur.
"""
import os
from glob import glob
import astropy.io.fits as pyfits
import numpy as np
import pandas as pd
from tqdm import tqdm
from . import plotting as pl
from . import registration as reg
from . import utils as u
from . import contrast as contrast
cla... |
# Copyright 2019 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 or agreed to in writing,... |
import serial # apt install python-serial
import zmq # apt install python-zmq
from Logger import Logger
import signal
import sys
from time import sleep
class SerialReader():
def __init__(self):
self.connected = False
self.enabled = True
self.baud = 115200
self.zmqOutPort =... |
import urllib
from model_mommy import mommy
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import override_settings
from tests.utils import SharedSchemaTenantsAPITestCase
from exampleproject.lectures.models import Lecture
from shared_schema_tenants.help... |
import torch
import torch.nn as nn
class ConvParameterizer(nn.Module):
""" Convolutional Parameterizer for DiSENN model
Generates parameters as relevance scores for concepts.
Follows the same architecture as the VAE Conceptizer's encoder module.
Architecture
------------
Conv: 32 channels, 4x... |
# noinspection PyBroadException
import logging
import os
import re
from string import Template
from execution.execution_service import ExecutionService
from model.model_helper import AccessProhibitedException
from utils import file_utils, audit_utils
from utils.audit_utils import get_audit_name
from utils.collection_u... |
def add_objects (a,b):
if type(a) == int and type(b) == int:
return print((a + b))
return print("Enter integer values")
add_objects (3,6)
|
from collections import namedtuple
Story = namedtuple('Story', ('id', 'title', 'link', 'hn_link', 'top_comments'))
|
from .ecdsa import is_public_pair_valid, public_pair_for_secret_exponent, public_pair_for_x, possible_public_pairs_for_signature, sign, verify
from .ellipticcurve import CurveFp, Point
from .secp256k1 import generator_secp256k1
|
from unittest import TestCase
from flask import Flask
from flask.ctx import AppContext
from flask.testing import FlaskClient
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from src.master.appfactory import AppFactory
from src.db import db
class BaseTest(TestCase):
@classmethod
def set... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.SchoolCardInfo import SchoolCardInfo
class AlipayCommerceEducateCampuscardQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayCommerceEducateC... |
import collections
from itertools import groupby
from typing import Iterable, List
from . import abc_pdf
from . import entities
from . import helper
from . import templatemanager
__all__ = [
"Empty",
"PyObjToHtmlConverter"
]
def range_subset(range1, range2):
"""Whether range1 is a subset of range2."""... |
# /***********************************************************************
# Copyright 2019 Google Inc.
#
# 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/LICE... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © by Christof Küstner
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE"
# wrote this file. As long as you retain this notice
# you can do whatever you want with this stuff. If we meet some day, and you
# t... |
name = "gfm-toc"
__version__ = '0.0.7'
from .md_toc import main |
import os
import requests
from sanic.response import json, text, html
api_key = '6u6izfSzCHTqVvphJ28lUbAtX0nXGhrd'
def loadMain():
fileName = os.path.join(os.path.dirname(__file__), 'main.html')
try:
f = open(fileName, "r")
htmlText = f.read()
f.close()
except:
return html("... |
# Copyright 2018-2020 Streamlit Inc.
#
# 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 wr... |
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
import sys
class KronaTreePlugin:
def input(self, filename):
self.kronafile = open(filename, 'r')
def run(self):
self.kingdoms = set()
self.phyla = set()
self.classes = set()
self.orders = set()
self.families = set()
self.genera = set()
self.species = se... |
# coding:utf-8
"""
Created on 2018年4月10日
@author: anning
"""
import re
import os
import sys
import h5py
from datetime import datetime
import numpy as np
from configobj import ConfigObj
from dateutil.relativedelta import relativedelta
from PB import pb_time
def dcc_find_file(ipath, ifile, c_date, rolldays):
"""... |
#!/usr/bin/env python
# coding: utf-8
import sys
import numpy as np
import pandas as pd
import tensorflow as tf
import scipy
from IPython.display import clear_output
from tensorflow.keras import activations, backend
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
import os.path
i... |
# coding: utf-8
import logging
import numpy as np
from ppyt.indicators import IndicatorBase
from ppyt.indicators.closerecenthighlow_indicators import (
CloseGtRecentHighIndicator, CloseLtRecentLowIndicator
)
logger = logging.getLogger(__name__)
class UpperBreakoutIndicator(IndicatorBase):
"""上にブレイクアウトしたかを示す指... |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... |
import h5py
import os.path
from .training_aux_wrapper import file_and_key_to_save
# load back data.
def load_model_performance(dataset, image_subset, neuron_subset,
seed, arch_name, opt_name):
model_subtype = arch_name + '+' + opt_name
# then check whether exists or not.
dir_to_... |
from Jython_tasks.task import AutoFailoverNodesFailureTask, NodeDownTimerTask
class DiskError:
FAILOVER_DISK = "failover_disk"
DISK_FULL = "disk_full"
def __init__(self, logger, task_manager, orchestrator,
server_to_fail, timeout, pause_between_failover_action,
failover_... |
from enum import Enum
class Shape(Enum):
SQUARE = 2
DIAMOND = 1
CIRCLE = 3
ALIAS_FOR_SQUARE = 2
print(Shape.SQUARE)
print(Shape.ALIAS_FOR_SQUARE)
print(Shape(2))
|
import json
import tempfile
from google.cloud import storage
import textparser
def handle_csv(file, sep=';', encoding='utf-8'):
parser = textparser.GenericParser()
for ix, line in enumerate(file):
line = line.decode(encoding).strip()
if ix == 0:
hdr = [field.lower() for field in l... |
import numpy as np
import IPython
def log_epsilon(x, epsilon=1e-10):
return np.log(np.maximum(x, epsilon))
def calculate_probability(patterns):
"""
Returns the probability from a list of patterns to be learned
:param patterns: list of patterns to be learned
:return:
"""
p = np.zeros(pa... |
from os import listdir
from numpy import average
import csv
import random
def TsvToData(filePath):
"""This method reads .tsv file and returns the data, XY split in a tuple"""
with open(filePath,'r') as file:
lines = list(csv.reader(file, delimiter = '\t'))
data = [[int(x) for x in line[0].split(',')] for line i... |
"""
Do inference on msgpack file generated in Command Center
"""
import argparse
import io
import os
import msgpack
import torch
from PIL import Image
from detectron2.config import get_cfg
from detectron2.engine import DefaultPredictor
from torch.utils.data import Dataset
from torch.utils.data.dataloade... |
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
from __fu... |
# Copyright 2013 Intel 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 require... |
# Copyright 2022 DeepMind Technologies Limited
#
# 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... |
import unittest
from jmilkfansblog.controllers import admin
from jmilkfansblog.controllers import rest_api
from jmilkfansblog import create_app
from jmilkfansblog.models import db
class TestURLs(unittest.TestCase):
"""Unit test for route functions."""
def setUp(self):
# Destroy the Flask-Admin and F... |
import threading
from PyQt5 import QtCore
from PyQt5.QtCore import QObject
from PyQt5.QtWidgets import QMainWindow, QLayout, QListWidgetItem
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets imp... |
import random
def ask(num, scores, question, answers):
"""
example, ask(2, scores, "What is your favorite color?",
[["Red", "patrick"], ["Blue", "squidward"], ["Yellow", "spongebob"]])
"""
random.shuffle(answers)
letters = ["A", "B", "C", "D", "E"]
print("{0}. {1}".format(num, question))
fo... |
# calculation for egex_sum_42.txt
import re
ofile = open('regex_sum_699035.txt')
newl = list()
sum = 0
for aline in ofile:
aline = aline.strip()
stuff = re.findall('[0-9]+', aline)
for e in stuff:
sum = sum + float(e)
print(sum)
#
newline = '<p>Please click <a href="http://www.dr-chuck.com">here<... |
import functools
import inspect
import math
import regex as re
_SQLITE_UDF_REGISTRY = set()
_SQLITE_UDAF_REGISTRY = set()
def udf(f):
"""Create a SQLite scalar UDF from `f`
Parameters
----------
f
A callable object
Returns
-------
callable
A callable object that returns... |
#!/usr/bin/env python3
from meerkat_api import app
app.run(debug=app.config['DEBUG'], host="0.0.0.0")
# Replace above with following line for production
# app.run(host='0.0.0.0')
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字符串搜索和替换
Desc :
"""
import re
from calendar import month_abbr
def change_date(m):
mon_name = month_abbr[int(m.group(1))]
return '{} {} {}'.format(m.group(2), mon_name, m.group(3))
def search_replace():
text = 'yeah, but no, but yeah, but no, bu... |
import os
import yaml
CONFKEY_STORAGE_FILE = "storage_file"
CONFKEY_STORAGE_MAX_AGE_SECS = "storage_max_age_secs" # former: "restore_last_max_diff"
class StorageException(Exception):
pass
class Storage:
def __init__(self):
self._file = None
self._data = None
def set_file(self, file)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# this is a virtual module that is entirely implemented server side
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
... |
script_location = '/fastapi/dump_dicom.sh'
from fastapi import Depends, APIRouter, HTTPException
from pydantic import BaseModel
from typing import List
import datetime
from starlette.responses import Response, FileResponse, PlainTextResponse
router = APIRouter()
from .auth import logged_in_user, User
from ..util im... |
from tensorflow.keras.layers import Activation, Reshape, Lambda, Multiply, dot, add
from tensorflow.keras.layers import Conv1D, Conv2D, Conv3D
from tensorflow.keras.layers import MaxPool1D
from tensorflow.keras import backend as K
def non_local_block(ip, out_channels, height, width, name, intermediate_dim=None, compr... |
import requests
import json
from seoulai_gym.envs.market.config import BASE_URL
class BaseAPI():
def __init__(
self,
) -> None:
"""Initialize BaseAPI
Args:
None
Returns:
None
"""
def api_post(
self,
cmd,
data,
):
... |
# Generated by Django 3.1.13 on 2021-10-28 21:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("interactive", "0018_auto_20210909_2046"),
]
operations = [
migrations.CreateModel(
name="Game",
fields=[
... |
"""
A script for executing a query and store the results.
The environment variables COSMOS_ENDPOINT and COSMOS_KEY need to be set.
"""
import json
import os
import time
from datetime import datetime
import humanfriendly
from azure.cosmos.cosmos_client import CosmosClient
#%% Common queries
# This query is used whe... |
# Generated by Django 3.0.4 on 2020-03-10 11:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("bokstaever", "0032_pagemodel_show_menu"),
]
operations = [
migrations.DeleteModel(name="Settings",),
]
|
import glob
import numpy as np
import math
from process import *
files = sorted(glob.glob("../../data/raw/trunk/60gs/3rd_eval/*.txt"))
path = files[3]
data = np.loadtxt(path, skiprows=6)
time = data[:, 0]
torque = data[:, 1]
velocity = data[:, 4]
angle = abs(data[:, 3])
angle = abs(angle - 60)
# Gravity torque vars
... |
from pypy.rlib.rarithmetic import intmask
class OPERAND(object):
_attrs_ = []
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.assembler())
class REG(OPERAND):
width = 4
def __repr__(self):
return '<%s>' % self.__class__.__name__.lower()
def assembler(self):
... |
#Arife Oran - 160401071
import socket
import time
import datetime
IP = '192.168.1.106'
Port = 142
try:
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind((IP, Port))
print("IP: ", IP, " ", Port, ".port dinleniyor")
serverSocket.listen(5)
except socket.error as messag... |
import asyncio
import logging
import platform
import ssl
import typing
from base64 import b64decode
from contextlib import suppress
import pamqp.frame
from pamqp import ProtocolHeader
from pamqp import specification as spec
from pamqp.heartbeat import Heartbeat
from yarl import URL
from . import exceptions as exc
fro... |
from lsl_register_t2 import LslRegisterT2
from lsr_register_t2 import LsrRegisterT2
from asr_register_t2 import AsrRegisterT2
from ror_register_t2 import RorRegisterT2
from sxtah_t1 import SxtahT1
from sxth_t2 import SxthT2
from uxtah_t1 import UxtahT1
from uxth_t2 import UxthT2
from sxtab16_t1 import Sxtab16T1
from sx... |
from absl import logging
import datetime
import os.path
import tornado.ioloop
import tornado.web
from icubam.db import store
class HealthHandler(tornado.web.RequestHandler):
ROUTE = '/health'
def initialize(self, start_time):
self.start_time = start_time
def get(self):
return self.write("{0:%Y/%m/%d %... |
# vim: set encoding=utf-8
from unittest import TestCase
from mock import patch
from django.conf import settings
from django.test import RequestFactory
from regulations.views import utils
class UtilsTest(TestCase):
def setUp(self):
if hasattr(settings, 'ANALYTICS'):
self.old_analytics = sett... |
from flask import Flask
from flask import request
from flask import render_template,url_for
from PIL import Image
import io
import base64
import cv2
import numpy as np
import urllib
from joblib import dump, load
from binascii import a2b_base64
import tensorflow as tf
try:
model = tf.keras.models.load_model('my_m... |
"""Test for the snakemake workflow distributed with region_set_profiler"""
import json
import subprocess
import os
import pandas as pd
import numpy as np
tmpdir = "/icgc/dkfzlsdf/analysis/hs_ontogeny/temp"
# TODO: gtfanno result has weird index
gtfanno_result: pd.DataFrame = pd.read_pickle(
"/icgc/dkfzlsdf/analy... |
"""
TCKDB backend app db base_class module
allows the creation of classes that include directives to describe the actual database table they will be mapped to
"""
from sqlalchemy.ext.declarative import declarative_base, declared_attr
class CustomBase(object):
"""
A custom base class for generating __tablenam... |
import numpy as np
arr = [[1,2,0],[0,1,1]]
arr = np.asarray(arr)
H = np.dot(arr,arr.T)
eigenval , eigenvec = np.linalg.eig(H)
print "----------A-----------"
print "eigen value is :" ,eigenval
print "eigen vector is :" ,eigenvec
print "----------B-----------"
u, s, vh = np.linalg.svd(arr, full_matrices=True)
print "s i... |
import configparser
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import logging
import sys
# 配置日志信息 输出到控制台
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, ... |
"""
Creates Singedup Home Tap
:license: MIT
"""
import json
from src.dependencies.dependency_typing import PynamoDBConsultant
def create_home_tap(consultant_uuid: str, consultant_model: PynamoDBConsultant):
'''
Creates Home tap with correct time from Consultant
-
:param consultant_u... |
# -*- coding: utf-8 -*-
"""
Part of slugdetection package
@author: Deirdree A Polak
github: dapolak
"""
import numpy as np
import pandas as pd
import math
import unittest
from slugdetection.Slug_Forecasting import Slug_Forecasting
class Test_Slug_Forecasting(unittest.TestCase):
"""
Unit tests class for S... |
from baselines.common.cmd_util import make_vec_env, make_mujoco_env
from baselines.common.vec_env.vec_frame_stack import VecFrameStack
from arguments import achieve_arguments
from a2c_agent import a2c_agent
from baselines import logger
if __name__ == '__main__':
args = achieve_arguments()
#Logger helps to set ... |
import asyncio
import os
import random
from urllib.parse import quote_plus
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from ..Config import Config
from . import drgub, deEmojify, edit_or_reply
plugin_category = "utils"
CARBONLANG = "auto"
@drgub.drg_cmd(
pattern="carbo... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
---
This code borrows heavily from the DimeNet implementation as part of
pytorch-geometric: https://github.com/rusty1s/pytorch_geometric. Licens... |
# Review class
from django import forms
from django.contrib.auth.models import User
from core.models import UserProfile
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password',)
class UserProfileForm(forms.Mod... |
#!/usr/bin/python3
__version__ = 3
__all__ = ['event_download_netease_news', 'event_record_announce_url', ]
def event_download_netease_news():
from libmysql_utils.mysql8 import mysqlHeader
from dev_global.env import SOFT_PATH
from taurus.news_downloader import neteaseNewsSpider
header = mysqlHeader('... |
from .client import AuthClient, ConfidentialAppAuthClient, NativeAppAuthClient
from .errors import AuthAPIError
from .flow_managers import (
GlobusAuthorizationCodeFlowManager,
GlobusNativeAppFlowManager,
)
from .identity_map import IdentityMap
from .response import OAuthDependentTokenResponse, OAuthTokenRespon... |
# sympy/galgebra/ncutil.py
"""
ncutil.py contains all the needed utility functions that only depend on
SymPy and that are required for the expansion and manipulation of linear
combinations of noncommutative SymPy symbols.
also contains "half_angle_reduce" which is probably not needed any more
due to the improvements ... |
# MIT License
#
# Copyright (c) 2017 Satellogic SA
#
# 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 the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from harpocrates_server.models.base_model_ import Model
from harpocrates_server.models.predicted_classification import PredictedClassification
from harpocrates_server.m... |
# Copyright 2020 ETH Zurich
#
# 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, sof... |
#!/usr/bin/env python2.7
import sys
import gzip
import hideSomePolicyLinUCB as policy # This is your policy file.
# This script loads a subset of the original yahoo data (e.g. 1 day of log data, which corresponds to 4.5 million log files)
def read_articles(path):
articles = {}
with file(path) as inf:
... |
"""
used to check the wallet information of any wallet id.
This class can be used to get a wallet balance
"""
import time
class WalletInfo:
@staticmethod
def get_wallet_balance_info(admin_inst, wallet_id):
"""
Is sent to client when requesting for balance
:param admin_inst:
... |
# coding=utf-8
# Copyright 2019 The Tensor2Tensor 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... |
#!/usr/bin/env python
import unittest
from icecube import dataclasses
from icecube import icetray
from icecube.icetray import OMKey
class TestI3FlasherInfo(unittest.TestCase):
def test_I3FlasherInfo_equality(self):
fi1 = dataclasses.I3FlasherInfo()
fi2 = dataclasses.I3FlasherInfo()
fi1... |
from matplotlib import pyplot as plt
import json
import pandas as pd
from shapely.geometry.point import Point
from shapely import affinity
from matplotlib.patches import Polygon
import random
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin_min
def shapely_ell... |
import tkinter as tk
def print_txtval():
val_en =en.get()
print(val_en)
root = tk.Tk()
root.title('get text box')
root.geometry('350x150')
lb= tk.Label(text='Label')
en=tk.Entry()
bt= tk.Button(text='button',command=print_txtval)
lb.pack()
en.pack()
bt.pack()
root.mainloop() |
def f(x):
"""
Parameters:
x: foo
""" |
from queue import Queue
from threading import Thread, Event
class Task:
"""Task to obtain function for thread pool to run"""
def __init__(self, **kargs):
self.kargs = kargs
self.event = Event()
def do(self):
pass
def task_complete(self):
self.event.set()
def wait_... |
import json
import warnings
def read_scenario(path="scenarios/rimea6.scenario"):
"""
Loads a scenario file with json
:param path: the path of the scenario file
:return: the dictionary containing the scenario's data
"""
with open(path, 'r') as f:
scenario = json.load(f)
return s... |
a,b = 0,1
for i in xrange(1,11):
print a
a,b = b,a+b
# #mod
# for i in xrange(1,11):
# print i%2
# #xrange
# for i in xrange(1,10):
# print i
# print "--------------"
# #range
# for i in range(1,10):
# print i
# print "--------------"
# #while
# i = 0
# while i<=10:
# print... |
import logging
import os
import socket
from flask import request, render_template, jsonify
from redis import Redis
from . import main_blue
redis = Redis(host="redis")
logger = logging.getLogger("app.access")
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', "xlsx", "xls", "log"}
@main_blue.route('... |
import pgzrun
# Spacewalk # by Sean McManus # www.sean.co.uk / www.nostarch.com
WIDTH = 800
HEIGHT = 600
player_x = 600
player_y = 350
def draw():
screen.blit(images.backdrop, (0, 0))
pgzrun.go() |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from eospac.base import EosUnits
from eospac import EosMaterial
from eospac.feos import FeosMaterial
import eospac.feos.interface
import numpy as np
from eospac.base import eV2K_cst
from numpy.testing import assert_allclose
def is_equal(x,y):
assert x == y
def test_low... |
x = 9
print(x * x)
|
"""
Functions related to inspecting Program objects/classes in a graph.
"""
import json
from .base import Program, SourceCodeProgram, IntermediateProgram
from .base import MachineProgram, get_program_classes
def get_targets(program):
""" Get the program names that the given Program instance/subclass
can be ... |
#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./lsass')
if args.REMOTE:
p = remote('35.238.225.156', 1004)
else:
p = process(binary.path)
# ropper --file lsass --chain "execve cmd=/bin/sh" --badbytes 0a
IMAGE_BASE_0 = 0x08048000 # da2732480d49a078e666802ee2edcd948700eacaaa48129430ea1ff6d... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-05-23 17:22
from __future__ import unicode_literals
import django.contrib.postgres.fields
import django.contrib.postgres.search
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependenci... |
"""User model"""
# local import
from .db_config import db
from api.models.Base.Base_model import BaseModel
class User(BaseModel):
"""User model"""
# table name
__tablename__ = 'users'
verified = db.Column(db.Boolean, default=False)
first_name = db.Column(db.String(80), nullable=False)
last_... |
from .utils import assert_raises
from render_liquid import LiquidRenderer, JobError
def test_renderer():
render = LiquidRenderer().render
template = r"""{{greeting | capitalize}}, {{name | append:'!'}}"""
# Does it work?
result = render(template, {'greeting': 'hello', 'name': 'world'})
assert r... |
# Google Play Store Data Filter
# Authored by Matthew Steuerer, Nikhil Sankepalli, and Seth Curry
# October 7th, 2020
# Demonstrates the use of Lists is Python with 2018 Google Play Store Data
# Data Source URL: https://www.kaggle.com/lava18/google-play-store-apps
# Initial Ideas: create a list of objects where each e... |
from __future__ import annotations
from VersionControlProvider.Issue import Issue
from VersionControlProvider.IssueState import IssueState
class IssueDefault(Issue):
def get_ref(self) -> str:
if self.number is None:
raise ValueError('Issue should have a number')
return '{prefix!s}{nu... |
from apps.email import send_mail
from django.contrib.auth.decorators import login_required
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib import messages
from django.db.models import Count
from django.urls import reverse
from django.views.decorators.c... |
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.layers import Input, BatchNormalization, Conv3D, Dense, Flatten, Reshape, Conv3DTranspose
from tensorflow.keras.models import Model
input_shape = (1, 32, 32, 32)
z_dim = 128
def get_model():
enc_in = Input(shape = i... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class DataSource(object):
'''
Defines an abstraction for all DataSources.
DataSources must have two public methods, get and Refresh. A DataSource is
... |
import math
import numpy as np
import pytest
from scipy.spatial import ConvexHull
from adaptive.learner.base_learner import uses_nth_neighbors
from adaptive.learner.learnerND import LearnerND, curvature_loss_function
def ring_of_fire(xy):
a = 0.2
d = 0.7
x, y = xy
return x + math.exp(-((x ** 2 + y *... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.