content stringlengths 5 1.05M |
|---|
import time
from os import environ
from datetime import datetime
from models import Application, Request, Test, TestGroup
BASE_DEV_URL = environ["TRANSIT_DEV_BACKEND_URL"]
BASE_PROD_URL = environ["TRANSIT_BACKEND_URL"]
GTFS_EXPIRATION_BUFFER = 7 # number of days before GTFS feed expiration date
# We want to verify... |
# -*- coding: utf-8 -*-
# main converter file, converts datasheet to Lektor format
import glob
import os
import json
import re
import htmlparser
import referenceparser
import symbolreplace
def convert(datasheet, url_context):
data = {}
# metadata, the template and model
data['_model'] = 'glossary'
... |
from .image import Image, ImageWindow
from .image_bmp import ImageBmp
|
from django import forms
from .models import Transportadora, FormaPagamento
class FinalizarPedido(forms.Form):
"""
Formulário para receber qual opção de transportadora e forma de pagamento o usuário deseja
Attribute transportadora: Recebe a opção de transportadora que o usuário escolher
Attribute for... |
# Copyright 2020 Makani Technologies 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... |
import sqlalchemy as sa
from .db_session import SqlAlchemyBase
class Forum(SqlAlchemyBase):
__tablename__ = 'forums'
__table_args__ = {'extend_existing': True}
id = sa.Column(sa.Integer,
primary_key=True, autoincrement=True)
name = sa.Column(sa.String, nullable=True)
title = sa.... |
'''
Harvester for the ASU Digital Repository for the SHARE project
Example API call: https://zenodo.org/oai2d?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class ZenodoHarvester(OAIHarvester):
short_name = 'zenodo'
long_name = 'Zenodo... |
import scipy.interpolate as interpolate
import matplotlib
import matplotlib.image as image
from matplotlib import rc, rcParams
import numpy as np
def get_ax_size(fig, ax):
'''
Returns the size of a given axis in pixels
Args:
fig (matplotlib figure)
ax (matplotlib axes)
'''
b... |
# -*- coding: utf-8 -*-
"""Experiments: code to run experiments as an alternative to orchestration.
This file is configured for runs of the main method with command line arguments, or for
single debugging runs. Results are written in a standard format
todo: Tidy up this file!
"""
import os
import sklearn.preprocessi... |
__all__ = ["Log", "Progbar", "RandomSeeds", "ModelParamStore", "DefaultDict", "Visualize"]
|
# coding: utf-8
import requests
from bs4 import BeautifulSoup
url = "http://www.pythonscraping.com/pages/page3.html"
res = requests.get(url)
bs = BeautifulSoup(res.text,'html.parser')
for child in bs.find("table", {"id":"giftList"}).children:
print(child)
|
inp = list(map(int, input().split()))
before = inp.copy()
inp.sort()
for i in inp:
print(i)
print()
for j in before:
print(j)
|
# encoding: utf-8
"""Custom element classes related to end-notes"""
from __future__ import absolute_import, division, print_function, unicode_literals
from docx.oxml.xmlchemy import BaseOxmlElement
class CT_Endnotes(BaseOxmlElement):
"""`w:endnotes` element""" |
import sys
import matplotlib.pyplot as plt
import numpy as np
def readData(dataFile):
data=[]
with open(dataFile) as f:
for line in f:
items = line.split(' ')
assert len(items) == 4
tup = (int(items[0]), int(items[1]), int(items[2]), float(items[3]))
data... |
import os
from abc import ABC
from thonny import get_runner
from thonny.common import normpath_with_actual_case
from thonny.plugins.cpython_frontend.cp_front import LocalCPythonProxy
from thonny.plugins.pip_gui import BackendPipDialog
class CPythonPipDialog(BackendPipDialog, ABC):
def _is_read_only(self):
... |
from typing import List
import collections
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k == len(nums):
return nums
count = collections.Counter(nums)
return heapq.nlargest(k, count.keys(), key = count.get)
if __n... |
# function to call the main analysis/synthesis functions in software/models/sineModel.py
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import get_window
import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../models/'))
import utilFunctions as UF
import sineM... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from scrapy import Item, Field
class Subject(Item):
douban_id = Field()
type = Field()
class Meta(Item):
douban_id = Field()
type = Field()
cover = Field()
name = Field()
slug = Field()
year = Field()
directors = Field()
actors =... |
#CLASE EDIFICIOS
class Edificio:
#Atributos del Objeto
def __init__(self, type, count, huella, dptos, ancho, largo, adpto, prior, areacons, niveles):
self.type = type
self.count = count
self.huella = huella
self.dptos = dptos
self.ancho = ancho
... |
import os
import glob
import numpy as np
import torch
import pydicom
from pydicom.pixel_data_handlers.util import apply_modality_lut
import nibabel as nib
def read_ct_scan(ct_dir, hu_range=None):
dicom_paths = glob.glob(f"{ct_dir}/*.dcm")
dicom_files = sorted(
[pydicom.read_file(path) for path in di... |
"""Assigment#1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1zDOQ7DiZycLsPiQp9KkLTJIKcqIqOAjl
"""
# Commented out IPython magic to ensure Python compatibility.
import datetime, warnings, scipy
import pandas as pd
import numpy as np
import sea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __BEGIN_LICENSE__
# Copyright (c) 2009-2013, United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The NGT platform is licensed under the Apache License, Version 2.0 (the
# "Lic... |
#!/usr/bin/env python
#############################################################################
### pubchem_assaysim.py - assay similarity based on activity profiles
### from PubChem CSV assay file[s]
#############################################################################
import os,sys,re,getopt,gzip,zipfile,... |
## Gerenciando Pagamentos
print('{:=^40}'.format(' Loja do Wollacy '))
valor=float(input('Qual valor da compra? '))
print('''FORMAS DE PAGAMENTO
[1] à vista dinheiro
[2] débito
[3] até 3x cartão
[4] mais de 3x no cartão
''')
opcao=int(input('Escolha a opção de pagamento: '))
if opcao==1:
valorFinal=valor-(valor*10/... |
import numpy as np
import math
def extract_patches(kpts, img, PS=32, mag_factor = 10.0, input_format = 'cv2'):
"""
Extracts patches given the keypoints in the one of the following formats:
- cv2: list of cv2 keypoints
- cv2+A: tuple of (list of cv2 keypoints, Nx2x2 np array)
- ellipse: Nx5 np ar... |
#!/usr/bin/env python
# Copyright 2015-2016 Scott Bezek and the splitflap contributors
#
# 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/LICENS... |
from typing import Union, Optional
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from statannot import add_stat_annotation
plt.style.use("default")
plt.rcParams.update(plt.rcParamsDefault)
def plot_scores_boxplot(scores_test: Union[dict, pd.DataFrame],
... |
import queue
import logging
import argparse
import kubernetes.client
from utils.kubernetes.config import configure
from utils.signal import install_shutdown_signal_handlers
from utils.kubernetes.watch import KubeWatcher, WatchEventType
from utils.threading import SupervisedThread, SupervisedThreadGroup
from .config ... |
from setuptools import setup
setup(
name='equibel',
version='0.9.5', # v0.9.5
description='A toolkit for equivalence-based belief change',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'... |
""""
this package contains the main and support classes for the layout widgets
""" |
"""
This file contains the implementation of the DeepDream algorithm.
If you have problems understanding any parts of the code,
go ahead and experiment with functions in the playground.py file.
"""
import os
import argparse
import shutil
import time
import numpy as np
import torch
import cv2 as cv
imp... |
from .SearchTree import SearchTree, ActionNode, ChanceNode, expand_action, Node, MCTS_Info, HeuristicVector
from .Samplers import MockPolicy, Policy
from .searchers.search_util import ContinueCondition
from .searchers.deterministic import deterministic_tree_search_rollout, get_node_value, mcts_ucb_rollout
from .searche... |
#!/usr/bin/env python
# The outputManager synchronizes the output display for all the various threads
#####################
import threading
class outputStruct():
def __init__( self ):
self.id = 0
self.updateObjSem = None
self.title = ""
self.numOfInc = 0
class outputManager( threading.Thread ):
def __in... |
from errbot import BotPlugin, botcmd
class Example(BotPlugin):
"""
This is a very basic plugin to try out your new installation and get you started.
Feel free to tweak me to experiment with Errbot.
You can find me in your init directory in the subdirectory plugins.
"""
@botcmd # flags a comm... |
#!/usr/bin/env python3
import os,sys
import traceback
from pymongo import MongoClient
from bson.objectid import ObjectId
from data_backup import Data_backup
from solr import SOLR
from solr import SOLR_CORE_NAME
'''
_id => str(_id)
增加scene:db_name topic:collection
如果有super_intention字段且为空,则替换为null
如果有questions或equal_qu... |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2022 David E. Lambert
#
# 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 ... |
import inspect
import logging
import sys
from datetime import timedelta
from .. import heating, sensing
from ..utils import broadcast, time_utils, translation
_ = translation.translator_fx()
_logger = logging.getLogger('NonHeatingJobs')
def function_names_for_non_heating_jobs():
"""Returns the function names ... |
#!/usr/bin/env python3
"""Monte Carlo blackbox collocation-based FEM system id."""
import argparse
import importlib
import os
import pathlib
import numpy as np
import scipy.io
import sympy
import sym2num.model
import fem
import symfem
# Reload modules for testing
for m in (fem, symfem):
importlib.reload(m)
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'text_editor.ui'
#
# Created: Sun Nov 15 17:09:47 2009
# by: PyQt4 UI code generator 4.6.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_DockWidget(object):
def setupUi(self, Dock... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import shipment
admin.site.register(shipment)
|
#!/bin/python
import sys, os
sys.path.append("/network/lustre/iss01/home/daniel.margulies/data/lsd/")
from load_fs import load_fs
import numpy as np
import nibabel as nib
from mapalign import embed
from numba import jit
from scipy.sparse.linalg import eigsh
from scipy import sparse
@jit(parallel=True)
def run_perc(da... |
#!/usr/bin/python3
from setuptools import setup, find_packages
setup(
name="RedPaper",
version="1.0",
install_requires=['docutils>=0.3', 'praw>=6.2.0'],
# metadata to display on PyPI
author="Teddy Okello",
author_email="[email protected]",
description="A program to download and change d... |
# poropy/coretools/vendor.py
class Vendor(object):
""" Fresh fuel vendor. *NOT IMPLEMENTED*
"""
def __init__(self):
""" Constructor.
"""
|
import re
with open("input", "r") as f:
lines = f.readlines()
lines = [line.strip() for line in lines if line.strip()]
class TargetArea:
def __init__(self, desc_str):
target_area_regexp = re.compile("target area: x=([0-9]+)\\.\\.([0-9]+), y=(-[0-9]+)\\.\\.(-[0-9]+)")
bounds = target_area_reg... |
#################################################################################
# Author: Jacob Barnwell Taran Wells
# Username: barnwellj wellst
#
# Assignment: TO3
# Purpose:
#################################################################################
# Acknowledgements:
#
#
###################################... |
# Generated with RandomSeedGeneration
#
from enum import Enum
from enum import auto
class RandomSeedGeneration(Enum):
""""""
INTRINSIC = auto()
RANLUX = auto()
RNSNLW = auto()
def label(self):
if self == RandomSeedGeneration.INTRINSIC:
return "Intrinsic"
if self == Ran... |
#création des matrices
#IMPORTS
import json
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
from scipy.cluster.hierarchy import dendrogram, linkage
from matplotlib import pyplot as plt
import glob
import codecs
import sys
... |
Experiment(description='Relational ABCD',
data_dir='../srkl-data/stocks/',
max_depth=5,
random_order=False,
k=1,
debug=False,
local_computation=True,
n_rand=9,
sd=2,
jitter_sd=0.1,
max_jobs=400,
verbose=False,
make_predictions=True,
skip_complete=True,
results_dir='../srkl-results/stocks/',
iters=250,
b... |
import ROOT
import os, types
from math import *
from PhysicsTools.HeppyCore.utils.deltar import *
class JetReCalibrator:
def __init__(self,globalTag,jetFlavour,doResidualJECs,jecPath,upToLevel=3,
calculateSeparateCorrections=False,
calculateType1METCorrection=False, type1METParams... |
import cvxpy as cp
import numpy as np
import torch
def cvxLP(X, Y, xn):
# solve min gamma
# s.t. |x_i theta - y_i | <= gamma
# <=> -gamma <= x_i theta - y_i <= gamma
# <=> x_i theta - gamma <= y_i
# -x_i theta - gamma <= -y_i
X = X.numpy()
Y = Y.numpy()
n = X.shape[0]
dim = X.sh... |
"""
Globus Auth OpenID Connect backend, docs at:
https://docs.globus.org/api/auth
"""
import logging
from social_core.backends.globus import (
GlobusOpenIdConnect as GlobusOpenIdConnectBase
)
from social_core.exceptions import AuthForbidden
from globus_portal_framework.gclients import (
get_service_url, GRO... |
# SweepGen2x.py
#
# A DEMO Audio Sweep Generator from 4KHz down to 100Hz and back up again
# using standard Text Mode Python. Another kids level piece of simple, FREE,
# Test Gear project code...
# This working idea is copyright, (C)2010, B.Walker, G0LCU.
# Written in such a way that anyone can understand how it works.... |
import socket
import telnetlib
import time
from typing import Optional
from termcolor import colored
from cool.util import b2s
from .tube import Tube
class Remote(Tube):
"""Class for connecting to a remote server.
:param host: host name of the server
:param port: port number of the server
:param t... |
__author__ = 'faner'
def check_callable(target):
if not (target and callable(target)):
raise TypeError('target is not callable!')
class PromiseRunner(object):
def __init__(self, promiseObj, run):
self._promiseObj = promiseObj
from threading import Thread
def _run_wrap():
... |
import argparse
import pickle
import os
import sys
from pdb import set_trace as bp
import numpy as np
import torch
#import gym
import my_pybullet_envs
import pybullet as p
import time
from a2c_ppo_acktr.envs import VecPyTorch, make_vec_envs
from a2c_ppo_acktr.utils import get_render_func, get_vec_normalize
import inspe... |
import json
import logging
import math
import numbers
import os
import platform
import resource
import sys
from collections import MutableMapping
from contextlib import contextmanager
from IPython.core.display import display, HTML
from pyhocon import ConfigFactory
from pyhocon import ConfigMissingException
from pyhoco... |
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
data = {
'train': pd.read_pickle('../features/train_with_minmax_p2.pkl'),
'test': pd.read_pickle('../features/test_with_minmax_p2.pkl')... |
# Copyright (c) 2017 Jared Crapo, K0TFU
import datetime
import persistent
import persistent.mapping
from netcontrol.checkin import Checkin
class Session(persistent.Persistent):
"""Model class for a single session of a directed ham radio net
Data elements for a specific instance of a directed net
... |
#-*- coding: gbk -*-
import requests
from threading import Thread, activeCount
import Queue
queue = Queue.Queue()
dir_file="php.txt"
def scan_target_url_exists(target_url):
headers={
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0... |
#!/usr/bin/env python
import logging
import sys
import unittest
import scipy as sp
import numpy as np
import mango.mpi as mpi
import mango.image
import mango.io
logger, rootLogger = mpi.getLoggers(__name__)
class NeighbourhoodFilterTest(unittest.TestCase):
def setUp(self):
self.mode = "mirror"
se... |
from django.conf.urls import url
from misago.search.views import landing, search
urlpatterns = [
url(r'^search/$', landing, name='search'),
url(r'^search/(?P<search_provider>[-a-zA-Z0-9]+)/$', search, name='search'),
]
|
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home,name='home'),
path('badge/', include('badge.urls')),
]+ static(settings.... |
from functools import partial
from operator import is_not
import numpy as np
import pandas as pd
def nutrient_color(value):
return 'text-success' if value <= 0.15 else 'text-danger'
def make_list(x):
return list(filter(partial(is_not, np.nan), list(x)))
def rank_suffix(i):
i = i + 1
if i >= 11 an... |
from batou.component import Component, Attribute
from batou.lib.file import File
from batou.utils import Address
from batou_ext.keypair import KeyPair
import socket
import os
def resolve_v6(address):
return socket.getaddrinfo(
address.connect.host,
address.connect.port,
socket.AF_INET6)[0]... |
from ctypes import byref
from ctypes import c_uint
from pyglet import gl
from .vertex import Vertices
class VertexArrayObject:
"""
A vertex array object (VAO) is a kind of context object for a bunch of
vertex buffers and related settings.
"""
def __init__(self, vertices_class=Vertices):
... |
from typing import List, Optional as Opt
from assemblyline import odm
from assemblyline.common import forge
from assemblyline.common.constants import DEFAULT_SERVICE_ACCEPTS, DEFAULT_SERVICE_REJECTS
Classification = forge.get_classification()
@odm.model(index=False, store=False)
class EnvironmentVariable(odm.Model)... |
#! /usr/bin/env python
#
##plotting exercise
##created by Nate
##06/24/2019
import numpy as np
import matplotlib.pyplot as plt
def vrot(x, m):
return x / pow(1+x**m, 1/m)
x =np.linspace(0,10,1000)
ve = 1-np.exp(-x)
v7 = vrot(x,0.75)
v1 = vrot(x,1)
v2 = vrot(x,2)
v4 = vrot(x,4)
v100 = vrot(x,100)
#plt.plot(x, v... |
from discord.ext import commands
from discord.message import Message
class DiscordLimb:
""" Effectively contains documentation for the useful pycord functions. """
@commands.Cog.listener()
async def on_ready(self)-> None:
""" Called when the client is done preparing the data received from Discord... |
import sys
import numpy as np
I = np.array(sys.stdin.read().split(), dtype=np.int64)
n = I[0]
t = I[1 : 1 + n]
m = I[1 + n]
p, x = I[2 + n :].reshape(m, 2).T
def main():
default = np.sum(t)
res = default + (x - t[p - 1])
return res
if __name__ == "__main__":
ans = main()
pri... |
"""alie cli tests."""
from os import environ
from click.testing import CliRunner
from alie import cli
def test_main(tmpdir):
"""Sample test for main command."""
runner = CliRunner()
environ['ALIE_JSON_PATH'] = tmpdir.join('json').strpath
environ['ALIE_ALIASES_PATH'] = tmpdir.join('aliases').strpath
... |
import argparse
import os
import random
import time
import logging
import pdb
from tqdm import tqdm
import numpy as np
import scipy.io as sio
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.optim.lr_scheduler as ... |
"""
Unittest for familytree.person module.
"""
from familytree.person import Person
class TestPerson:
def test_init_minimal(self):
p = Person(1, "Name")
assert p.id_ == 1
assert p.name == "Name"
assert p.gender == None
assert p.father_id == None
assert p.mother_i... |
try:
import unzip_requirements
except ImportError:
pass
import json
import os
import tarfile
import boto3
import tensorflow as tf
import numpy as np
import census_data
import logging
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
FILE_DIR = '/tmp/'
BUCKET = os.environ['BUCKET']
def _easy_inpu... |
# Copyright 2004-2019 Tom Rothamel <[email protected]>
#
# 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, m... |
import numpy
import cupy
from cupy.cuda import cublas
from cupy.cuda import device
from cupy.linalg import util
def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False,
overwrite_b=False, check_finite=False):
"""Solve the equation a x = b for x, assuming a is a triangular matrix... |
from vininfo import Vin
def test_opel():
vin = Vin('W0LPC6DB3CC123456')
assert '%s' % vin
assert vin.wmi == 'W0L'
assert vin.manufacturer == 'Opel/Vauxhall'
assert vin.vds == 'PC6DB3'
assert vin.vis == 'CC123456'
assert vin.years == [2012, 1982]
assert vin.region_code == 'W'
asse... |
import numpy
import cv2
def contour_coordinates(contour):
'''
Returns coordinates of a contour
'''
if cv2.contourArea(contour) > 10:
M = cv2.moments(contour)
return (int(M['m10']/M['m00']))
def drawSquare(image):
'''
Draws a square around the found digits
'''
b = [0,0,0]
height, width = image.shape[0]... |
# Generated by Django 2.2 on 2020-04-21 14:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0056_auto_20200420_1340'),
]
operations = [
migrations.AddField(
model_name='projectpricing',
name='custom_... |
'''
Created on Jul 30, 2012
@author: Gary
'''
import abc
from pubsub import pub
from housemonitor.lib.base import Base
from datetime import datetime
from housemonitor.lib.common import Common
from housemonitor.lib.getdatetime import GetDateTime
from housemonitor.lib.constants import Constants
import copy
class abcSt... |
# Copyright (c) 2019 Princeton University
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import markdown
import base64
def main(params):
try:
text = params["markdown"]
except:
return {'Error' : 'Possibly lacking mar... |
import json
import pickle
import matplotlib.pyplot as plt
from sklearn.metrics import plot_confusion_matrix, classification_report
from sklearn.svm import SVC
from sklearn.model_selection import RandomizedSearchCV, RepeatedStratifiedKFold
# Funtion to fine-tune hyperparameters to find th... |
"""
View
Abstract class responsible for drawing the state of the lights
either for the simulator or for the hardware.
Calls the update method before each call.
Maintains a delta time, which is how long it took in between each update.
"""
from abc import ABC, abstractmethod
class View(ABC):
def __init__(self, c... |
import os
from updateSteamInfo import create_info_file
def destination_list():
return [
"Artifacts.xml",
"Battles.xml",
"Enemies.xml",
"Heroes.xml",
"HeroesExtra.xml",
"Pacts.xml",
"Spells.xml",
"Structures.xml",
"Tilefields.xml",
"Z... |
"""Generate metric in CSV & XML"""
import csv
import xml.etree.ElementTree as xml
from sys import stdout
from xml.dom import minidom # Used for pretty printing
from metric import metric
print('CSV')
headers = ['time', 'name', 'value']
writer = csv.DictWriter(stdout, fieldnames=headers)
writer.writeheader()
row = {k:... |
#!/usr/bin/env python
import socket
import subprocess
import json
import base64
import sys
import os
import shutil
class Backdoor:
def __init__(self, ip, port):
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection.connect((ip, port))
def run(self):
while True:
received_dat... |
import random
dice6 = random.randint(1,6)
dice20 = random.randint(1,20)
coin = random.randint(1,2)
rps = random.randint(1,3)
def heads_tails() :
if (coin == 1) :
return "You got heads."
else :
return "You got tails."
ht_var = heads_tails()
def rock_paper_scissors() :
if (rps == 1) :
... |
class Node:
def __init__(self,val=None,nxt=None,prev=None):
self.val = val
self.nxt = nxt
self.prev = prev
class LL:
def __init__(self):
self.head = Node()
self.tail = Node()
self.head.nxt = self.tail
self.tail.prev = self.head
def find(s... |
from decimal import ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, Decimal
from math import ceil, floor, log2
from typing import Union
import torch
from ppq.core import RoundingPolicy
def ppq_numerical_round(value: float,
policy: RoundingPolicy=RoundingPolicy.ROUND_HALF_EVEN) -> int:
"""
reference... |
# coding=utf-8
from math import sqrt
def read_file(filename):
lines = [line for line in file(filename)]
# 第一行是列标题
colnames = lines[0].strip().split('\t')[1:]
rownames = []
data = []
for line in lines[1:]:
p = line.strip().split('\t')
# 每行的第一列是行名
rownames.append(p[0])
... |
import json
from typing import Dict, List, Tuple, Any
import pytest
Request = Tuple[str, List[Dict[str, Any]]]
@pytest.fixture(scope="module")
def inputs() -> List[str]:
# Some random examples where sentence 1-2 and 3-4 are most similar to each other.
return [
"The inhibition of AICAR suppresses the... |
# coding: utf-8
from sympy import count_ops as sympy_count_ops
from sympy import Tuple
from sympy.core.expr import Expr
from sympy.utilities.iterables import iterable
from pyccel.ast import (For, Assign, While,NewLine,
FunctionDef, Import, Print,
Comment, AnnotatedComm... |
import logging
log = logging.getLogger(__name__)
import threading
import numpy as np
from neurogen import block_definitions as blocks
from neurogen.calibration import (PointCalibration, InterpCalibration,
CalibrationError, CalibrationTHDError,
Calib... |
import configparser
import logging
import os
from pathlib import Path
from . import consts
logger = logging.getLogger()
def read_config(path):
config = configparser.ConfigParser()
config.read(path)
return config
def parse_config(args):
default_config_path = os.path.expanduser('~/.eden')
if not... |
"""
The aim of this file is to give a standalone example of how an environment runs.
"""
import os
import numpy as np
from tgym.core import DataGenerator
from tgym.envs.trading_tick import TickTrading
from tgym.gens.deterministic import WavySignal, RandomGenerator
from tgym.gens.csvstream import CSVStreamer
gen_type ... |
from sqlalchemy import Column, Integer, String
from .database import Base
class Blog(Base):
__tablename__ = "blogs"
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
body = Column(String)
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=Tru... |
"""
Custom Controllers for DRKCM
License: MIT
"""
from gluon import current
from gluon.html import *
from gluon.storage import Storage
from core import FS, CustomController
THEME = "DRK"
# =============================================================================
class index(CustomController):
""" C... |
#!/usr/bin/env python
##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and/or modify
# it under th... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 19:11:35 2020
@author: garci
"""
'''
A PROBABILITY DENSITY FUNCTION (PDF) FITTING PROGRAM
pdsfit_more.py - fit multiple datasets to probability distributions and tabulate all statistical data thereof to Excel
Andrew Garcia, 2020
'''
from scipy import stats
import... |
def get_person():
name="leonardo"
age=35
country="uk"
return name,age,country
name,age,country = get_person()
print(name)
print(age)
print(country) |
from aiogram.types import ContentTypes, Message
from dialog.avatar_picture_dialog import AvatarDialog
from dialog.main_menu import MainMenuDialog
from lib.depcont import DepContainer
async def sticker_handler(message: Message):
s = message.sticker
await message.reply(f'Sticker: {s.emoji}: {s.file_id}')
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.