content stringlengths 5 1.05M |
|---|
import roslaunch
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import PoseStamped
import json
import thread
import os
class LocalController:
def __init__(self):
self.publisher = rospy.Publisher('move_base_simple/goal', PoseStamped, queue_size=10)
def launch(self):
self.pa... |
# INTERROMPENDO REPETIÇÕES WHILE COM BREAK
b = 0
while True:
print("I don't know!")
b = b + 1
if b == 20:
break
print('Oh! I see!!')
s = c = 0
while True:
n = int(input('Digite um valor qualquer: '))
if n == 0:
break
s = s + n
c = c + 1
#print('OK! Você digitou {} números e ... |
# Utilized Modules
import numpy as np
from orbital_analyses.Transform_State import TimeAdjust
from orbital_analyses.Transform_Coordinate import FK5_Precession
# Sun Position Vector Determination
def sunPosition(GD_UTC):
"""
Determines current lcation of the Sun
- Used for determiing if satellite is i... |
# Network parameters
NUM_DIGITS = 10
TRAIN_BEGIN = 101
TRAIN_END = 1001
CATEGORIES = 4
NUM_HIDDEN_1 = 512
NUM_HIDDEN_2 = 512
# Parameters
LEARNING_RATE = 0.005
TRAINING_EPOCHS = 50
BATCH_SIZE = 32
DECAY = 1e-6
MOMENTUM = 0.9 |
from Position import Position
import OperationTypes
import CellTypes
class Node:
'''
state: instancia da classe Position
operation: string com um dos valores do arquivo OperationTypes
gValue: valor correspondente a profundidade do no
previousNode: instancia da classe Node
'''
... |
API_TOKEN = ''
DEFAULT_REPLY = 'にゃんぱすー'
PLUGINS = ['plugins']
|
import pytest
def test_view(oh):
oh.config.load_str(
"""
[a]
x = 42
[c.d]
z = "asdf"
"""
)
with oh.config.enter("c.d"):
assert oh.config.z == "asdf"
with pytest.raises(AttributeError):
oh.config.a.x
assert oh.config.a.x == 42... |
# Python - 3.4.3
class Interpreter:
DEFAULT_RETURN_VALUE = -1
COMMENT_CHAR = ';'
QUOTES_CHAR = "'"
PARAM_SPLIT_CHAR = ','
LABEL_CHAR = ':'
TOKEN_SPLIT_CHARS = ' \t' + PARAM_SPLIT_CHAR + COMMENT_CHAR + LABEL_CHAR
SHORT_TOKEN_SPLIT_CHARS = PARAM_SPLIT_CHAR + COMMENT_CHAR
def __init__(sel... |
#!/usr/bin/env python3
""" Package solves the traveling salesperson problem using the simulated annealing optimization algorithm. """
# Luis Leal (2018)
######################################################### travel_MAIN: USAGE and error messages
error_message1 = ' \n \
USAGE: travel_MAIN <city_list.txt>\n ... |
"""
Data-Frame like functions. The idea of this module is to an extend
serve as an interface to specific implementation of dataframes. For now the support
is focused solely on Pandas.
"""
from functools import partial
from typing import Callable, Pattern, Union
import pandas as pd
from pandas.api.types import is_numer... |
import dask.array as da
import numpy as np
import xarray as xr
from xarray import DataArray, Dataset
def count_alleles(ds: Dataset) -> DataArray:
"""Compute allele count from genotype calls.
Parameters
----------
ds : Dataset
Genotype call dataset such as from
`sgkit.create_genotype_c... |
from tkinter import *
import random
import time
WIDTH = 500
HEIGHT = 400
tk = Tk()
canvas = Canvas(tk, width=WIDTH, height=HEIGHT)
tk.title("Drawing") # Title of window
canvas.pack() # Done with the settings and show window on screen
class Square:
def __init__(self,size):
self.shape = canvas.create_squar... |
# -*- coding: utf-8 -*-
import logging
import math
from StringIO import StringIO
import requests
from PIL import Image
LOG = logging.getLogger(__name__)
class FinnaClient(object):
API_ENDPOINT = 'https://api.finna.fi/v1/'
timeout = 10
organisation = None
material_type = None
def __init__(sel... |
#Shauna Byrne
#Iris Data Set Analysis 17/04/18
#https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
#https://matplotlib.org/users/pyplot_tutorial.html
import numpy
data = numpy.genfromtxt('data/iris.csv', delimiter=',')
import matplotlib.pyplot as plot
firstcol = data[:... |
def mynum(a): # the outside function.
def num(a): # This is a nested function.
return a + 1
result = num(a)
return result
print(mynum(4)) # 5 # this is line 3 + line 4
|
import numpy as np
from pylab import *
import string, os, sys
import datetime, types
from netCDF4 import Dataset
from subprocess import call
import mpl_util
import pandas as pd
import IOwrite
import prettyplotlib as ppl
import brewer2mpl
from mpl_toolkits.basemap import Basemap, interp, shiftgrid, addcyclic
import da... |
import os
import argparse
import pickle
import random
import colorsys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import mujoco_py as mjc
from rlkit.envs.blocks.mujoco.logger import Logger
import rlkit.envs.blocks.mujoco.utils as utils
from rlkit.envs.blocks.mujoco.XML... |
from nice_timings import *
class HanoiSolver(object):
'''The Generic Hanoi Solver Class, for the Hanoi Tower problem.
:param n: The number of towers (int).
:param m: The number of disks (int).
'''
def __init__(self, n, m):
self.n = n
self.m = m
self.strategy_name... |
"""Base class for the DDS CLI. Verifies the users access to the DDS."""
###############################################################################
# IMPORTS ########################################################### IMPORTS #
###############################################################################
# Stan... |
import time
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from torch.autograd import Variable
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from torch.utils.tensorboard.writer import SummaryWriter
from autoPyTorch.pipeline.c... |
#!./env/bin/python
from pbp.app import *
from pbp.models import *
db.create_all()
|
'''
leia o sexo mas só aceite os valores de 'm' ou 'f'
caso esteja errado peça novamente até ter um valor correto
'''
sexo = str(input("Diga o sexo"))
while sexo not in "fFmM":
sexo = str(input("Diga o sexo"))
print("O sexo foi", sexo) |
def reformat(li):
s = ""
max_col = []
temp_col = []
for i in range(10):
for j in range(10):
if li[j][i] != 0:
temp_col.append(len(str(li[j][i])))
else:
temp_col.append(-1)
max_col.append(max(temp_col))
temp_col = []
... |
import ast
import copy
from mutpy import utils
COVERAGE_SET_NAME = '__covered_nodes__'
class MarkerNodeTransformer(ast.NodeTransformer):
def __init__(self):
super().__init__()
self.last_marker = 0
def visit(self, node):
node.marker = self.last_marker
self.last_marker += 1
... |
import sys
import os
print(sys.platform)
|
#!/usr/bin/env python
import re
import json
import time
import hashlib
from lulu.util import log
from lulu.common import (
match1,
print_info,
get_content,
download_urls,
download_url_ffmpeg,
general_m3u8_extractor,
playlist_not_supported,
)
__all__ = ['douyutv_download']
site_info = '斗... |
from __future__ import division,print_function
#matplotlib inline
#load_ext autoreload
#autoreload 2
import sys
from tqdm import tqdm_notebook as tqdm
import random
import matplotlib.pyplot as plt
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim a... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# CREATED:2015-02-14 16:20:25 by Brian McFee <brian.mcfee@nyu.edu>
# unit tests for librosa cache
'''Tests for librosa.cache'''
import os
import sys
import tempfile
import shutil
import numpy as np
import matplotlib
matplotlib.use('Agg')
from nose.tools import with_se... |
#!/usr/bin/env python3
""" Display the contents of a kivaloo KVLDS server. """
import kivaloo.servers
import kivaloo.proto_kvlds
def main():
""" Dump the contents of a KVLDS server to stdout. """
lbs = kivaloo.servers.Server_lbs()
kvlds = kivaloo.servers.Server_kvlds()
proto_kvlds = kivaloo.proto_kv... |
def aumentar(preco = 0, taxa = 0):
res = preco + (preco * taxa/100) # 20% do preco
return res
def dimimuir(preco = 0, taxa = 0):
res = preco - (preco * taxa/100)
return res
def dobro(preco = 0):
res = preco * 2
return res
def metade(preco = 0):
res = preco / 2
return res
def moeda(pr... |
# Copyright 2016-2018 Iowa State University Research Foundation, 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 ... |
from functools import partial, wraps
from django.conf import settings
from .permissions import FunctionalLogicalPermission
from .storages import default_storage
def permission(func=None, label=None, register=None):
"""
Decorator for turning an ordinary function into a permission.
Args:
func (ca... |
from typing import Union
import us
from django.contrib.gis.db import models
from django.core.validators import RegexValidator
from django.db.models import QuerySet
class GeoModel(models.Model):
"""Base for new geo models."""
name = models.CharField(max_length=64)
geom = models.MultiPolygonField()
int... |
"""
Execution of expressions involving arithmetic, relational, logical,
and bitwise operators in the shell window of Python IDLE
Written by Sudipto Ghosh for the University of Delho
"""
x = 5
y = 2
# Arithmetic Operators
x + y
x - y
x * y
x / y
x // y
x % y
x ** y
# Relational Operators
x > y
x < y
x == y
x != y
x... |
#!/usr/bin/env python
from setuptools import setup
import sys
if sys.version_info[0] == 3 and sys.version_info[1] < 4:
sys.exit('Sorry, Python < 3.4 is not supported')
setup(
name='macke',
version='0.1-alpha',
packages=['macke'],
url="https://github.com/tum-i22/macke",
author="Saahil Ognawala... |
import torch
from logging import getLogger
from MOTSPEnv import TSPEnv as Env
from MOTSPModel import TSPModel as Model
from torch.optim import Adam as Optimizer
from torch.optim.lr_scheduler import MultiStepLR as Scheduler
from utils.utils import *
class TSPTrainer:
def __init__(self,
... |
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: Unlicense
"""
CircuitPython Adafruit IO Example for BME280 and LC709203 Sensors
"""
import time
import ssl
import alarm
import board
import digitalio
import wifi
import socketpool
import adafruit_requests
from adafruit_io.ad... |
from builtins import str
from builtins import object
import logging
import uuid as uid
from vnc_api import vnc_api
from cvfm import constants as const
from cvfm.exceptions import VNCVMICreationError
logger = logging.getLogger(__name__)
def generate_uuid(key):
return str(uid.uuid3(uid.NAMESPACE_DNS, key))
cla... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE:... |
import os, json
import shutil
from dataiku.fsprovider import FSProvider
from azure.datalake.store import core, lib
class ADLSFSProvider(FSProvider):
def __init__(self, root, config, plugin_config):
self.root = root
self.root_lnt = self.get_lnt_path(root)
self.client_id = config["client... |
import forca
import adivinhacao
def escolhe_jogo():
print("********************************")
print("Bem vindo ao jogos em Python")
print("Escolhe o seu jogo")
print("********************************")
print("(1) Forca (2) Adivinhação")
jogo = int(input("Qual jogo?"))
if jogo == 1:
... |
__license__ = "Apache 2.0"
__copyright__ = "Copyright 2008 nb.io"
__author__ = "Randy Reddig - ydnar@nb.io"
import django.conf
import datetime
import nbio.django.middleware
def settings(request):
return {
'now': datetime.datetime.now(),
'settings': django.conf.settings,
'request_counter': nbio.django.... |
import os
import csv
import pandas as pd
from datetime import datetime
def minutes_between_date(ini_date,end_date):
daysDiff = (end_date-ini_date).days
# Convert days to minutes
minutesDiff = daysDiff * 24 * 60
return minutesDiff
def update_param_value(dic,f1,f2):
for line in f1:
if line[0... |
# Copyright (c) 2021 Ayush Gupta, Kartikey Pandey, Pranjal Rastogi, Sohan Varier, Shreyansh Kumar
# Author: Ayush Gupta
if __name__ == "__main__":
import sys
print("\n\nDo not run this file!\nRun root/run_game.py instead!\n\n")
sys.exit()
from . import home_screen
import pygame
from ..utils.widgets import... |
# coding: utf-8
"""
Copyright (c) 2021 Aspose.Cells Cloud
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, ... |
import statistics
import math
import numpy as np
from osgeo import gdal
import rasterio
from rasterio.plot import show_hist, show
import matplotlib.pyplot as plt
from ipyleaflet import Map, Marker, basemaps, basemap_to_tiles, TileLayer, DrawControl, FullScreenControl, GeoJSON, Polygon
def plot_data(file_path, band_la... |
#!/bin/env python3
# Copyright 2020 Red Hat
#
# 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... |
from requests import get, post, delete, patch
from ..utils.request import fetch
from ..utils.api import endpoint, last_name, last_name_plural, api_json, from_api_json, cast_json_to_api_format
def get_page(sdk_version, host, api_version, user, resource, language, timeout, **query):
json = fetch(
host=host,... |
#!/usr/bin/env python
"""
Program to calculate order parameters when selecting spherical harmonics as basis
"""
import itertools
import os
import pickle
import shelve
from math import factorial, sqrt
import numpy as np
import pymatgen as mg
import scipy.special as sp
from scipy.integrate import tplquad
def sph_harm... |
#-*-coding:utf-8-*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from setuptools import setup
setup(
name='sly',
packages=['sly'],
version='0.1',
description='A lexer and parser library.',
autho... |
import os
from pathlib import Path
DEFAULT_ROOT_PATH = Path(os.path.expanduser(os.getenv("PEAS_ROOT", "~/.peas/mainnet"))).resolve()
DEFAULT_KEYS_ROOT_PATH = Path(os.path.expanduser(os.getenv("PEAS_KEYS_ROOT", "~/.peas_keys"))).resolve()
|
import argparse
import json
import requests
import sys
g_stat_names = {'avg': 'Average', 'max': 'Maximum'}
class Querier:
def __init__(self, token, url):
self.token = token
self.url = url
def query(self, query):
"""
Performs a Prometheus query
:param query: A Prometh... |
from .exceptions import NotEnoughResults
from typing import Tuple
from .searchresult import SearchResult
class SearchResponse:
"""Represents a Bing Response (not a search result response)
.. warning::
You must not manually initialize this!
"""
def __init__(self, data):
self.data = ... |
#!python3
# 7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
# При вызове функции должен создаваться объект-генератор.
# Функция должна вызываться следующим образом: for el in fact(n).
# Функция отвечает за получение факториала числа, а в цикле необходимо выводить тольк... |
'''
Author: Rashmeet Kaur Nayyar
Deep Deterministic Policy Gradient (DDPG)
'''
import torch
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Policy Network that maps states to actions
class Actor(torch.nn.Module):
def __init__(self, state_dim, action_dim, action_max_bound, action_offset, ... |
from rest_framework import serializers
from ..models import Workspace
from ..models import VisComponent
from ..models import ComponentInstance
import logging
logger = logging.getLogger(__name__)
class JSONSerializerField(serializers.Field):
"""Serializer for JSONField"""
def to_internal_value(self, data):
... |
print("play")
|
# Desafio 013 - Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento.
salario = float(input('\nDigite o valor do salário do funcionário: R$ '))
aumento = (salario * 15)/100
novoSalario = salario + aumento
print('O Novo salário do funcionário é R$ {:.2f}\n'.format(novoSal... |
from django.urls import path
from drjr import scheduler, views
from drjr.apps import DjangoRestJwtRegistrationConfig
from drjr.models import Token
DELETE_EXPIRED_TOKENS_INTERVAL = DjangoRestJwtRegistrationConfig.settings['DELETE_EXPIRED_TOKENS_INTERVAL']
urlpatterns = [
path('registration/', views.RegistrationA... |
from peewee import *
from consts import Consts
from settings import _Settings
s = _Settings()
db_type = s.get('database', 'type')
if db_type == 'sqlite':
db = SqliteDatabase(Consts.MOM_SQLITE_FILE)
elif db_type == 'mysql':
database_name = s.get('database', 'database')
database_ip = s.get('database', 'hos... |
from StringIO import StringIO
from django.core.management.base import CommandError
from go.base.management.commands import go_manage_http_api
from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper
class TestGoManageHttpAPICommand(GoDjangoTestCase):
def setUp(self):
self.vumi_helper = s... |
def solve():
t = int(input())
n = [int(input()) for _ in range(t)]
seq = [1, 1, 1, 2, 2] + [0] * 95
for i in range(5, max(n)):
seq[i] = seq[i - 1] + seq[i - 5]
print('\n'.join([str(seq[i - 1]) for i in n]))
solve()
|
"""
Save and load models
---
Model progress can be saved during and after training. This means a model can resume where
it left off and avoid long training times. Saving also means you can share your model and
others can recreate your work. When publishing research models and techniques, most machine
learning practitio... |
from conans.model import Generator
from conans.paths import BUILD_INFO_XCODE
class XCodeGenerator(Generator):
template = '''
HEADER_SEARCH_PATHS = $(inherited) {include_dirs}
LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs}
OTHER_LDFLAGS = $(inherited) {linker_flags} {libs}
GCC_PREPROCESSOR_DEFINITIONS = $(inheri... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
# SQLALCHEMY_DATABASE_URL = "sqlite:///./backend/app/db/db.sqlite3"
SQLALCHEMY_DATABASE_URL = os.environ['DATABASE_URL'].replace("://", "ql://", 1)
engine = create_engine(
S... |
from office365.sharepoint.client_context import ClientContext
from tests import test_client_credentials, test_team_site_url
ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
tasks_list = ctx.web.lists.get_by_title("Tasks")
items = tasks_list.items.get().select(["*", "Author/Id", "Author... |
import pytest
import logging
import time
from tests.common.dualtor.dual_tor_utils import get_crm_nexthop_counter # lgtm[py/unused-import]
from tests.common.helpers.assertions import pytest_assert as py_assert
from tests.common.fixtures.ptfhost_utils import run_garp_service
CRM_POLL_INTERVAL = 1
CRM_DEFAULT_POLL_INTE... |
import os
import sys
import argparse
import datetime
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
from model.config import cfg
from model.modeling.FinalNet import Net
from model.dataset.rscan_detection_dataset import RScanDetectionVotesDataset
from model.dataset.model_util_rscan i... |
"""
Dada uma String "str", retorne uma nova onde deverá seguir a seguinte lógica:
1° caractere, 3°, 5°, 7°, 9°...
"""
def string_bits(str):
return str[0::2]
# UM JEITO MAIS EXPLICADO E PASSO A PASSO
def string_bits_2(str):
result = ""
# Many ways to do this. This uses the standard loop of i on every cha... |
#!/usr/bin/env python3
"""===============================================================================
FILE: /Users/nailbiter/for/forpython/forhabits/kostil/note.py
USAGE: (not intended to be directly executed)
DESCRIPTION:
OPTIONS: ---
REQUIREMENTS: ---
BUGS: ---
NOTES: ---
... |
#!/usr/bin/env python3
# Copyright 2021 Sebastian Ahmed
# This file, and derivatives thereof are licensed under the Apache License, Version 2.0 (the "License");
# Use of this file means you agree to the terms and conditions of the license and are in full compliance with the License.
# You may obtain a copy of the Lice... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file accompa... |
"""Contains classes for loading and augmenting data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import division
import cv2
import abc
import numpy as np
import six
import multiprocessing
import logging
cityscapes_value_map = {0: 255, 1: 255, 2: 255, 3: 255, 4: 255, 5: ... |
import pytest
import open_cp.evaluation as evaluation
import open_cp.predictors
import open_cp.data
import numpy as np
def test_top_slice():
x = np.array([1,2,3,4,5,6])
mask = evaluation.top_slice(x, 0.7)
# 6 * 0.7 == 4.2
np.testing.assert_array_equal(x>2, mask)
mask = evaluation.top_slice(x, 0.6... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, cross_val_predict
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
import time
start = time.perf_counter()
#loading the dataset
dataset... |
# Copyright 2022 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, ... |
'''
It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride! There are a number of people queued up, and each person wears a sticker indicating their initial position in the queue. Initial positions increment by from at the front of the line to at the back.
Any person in the queue can bribe... |
import json
import os
import re
from time import sleep
from django.conf import settings
from django.db import models
from django.db.models import SET_NULL
from django.db.models.signals import post_save
import flickrapi
class TimeStampedModel(models.Model):
"""Abstract base class for self-updating ``created`` an... |
#!/bin/env python
#encoding=utf-8
import re
import lxml
import lxml.html
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from .tags_util import clean_tags_only, clean_tags_hasprop, clean_tags
from .region import Region
class PageModel(object):
def __init__(self, pa... |
import httplib
import json as _json
import logging
import os
import uuid
from urlparse import urlsplit, SplitResult
from pymemcache.client import Client as Memcached
from six.moves.urllib.parse import urlencode
logger = logging.getLogger()
_memcached = None
def get_memcached():
global _memcached
if _memcac... |
#! /usr/bin/env python
#! coding:utf-8
from elasticsearch import Elasticsearch
# connection
es = Elasticsearch(["connection"])
# search record
def search_record():
body = {
"query": {
"match_all": {}
}
}
res = es.search(index="test", body=body)
print(res)
|
hello=[1,20,0.5,10]
# Adding Elements(append,insert,extend)
# Deleting Elements(remove,pop,clear)
# Other Functions(index,count,sort)
print(hello.index(10))
|
import json
import zipfile
import os
import xlsxwriter
folder_path = './data' # folder path containing the GSTR2A zip files
excel_file_name = './data/GSTR2.xlsx'
workbook = xlsxwriter.Workbook(excel_file_name)
worksheet_b2b = workbook.add_worksheet('b2b-and-b2ba')
row = 0
worksheet_b2b.write_row(row,0,['Filing Per... |
# This script requires 1 command line argument : sample size
import sys
import numpy as np
from simulate import RVContinuous, Simulation
# unpack command-line arguments
sample_size = int(sys.argv[1])
# target probability distribution
def target_cdf(x):
if x < 1.0:
return (1- np.exp(-2*x) + 2*x)/3.0
el... |
import unittest
import networkx as nx
import pandas as pd
import numpy as np
from pgmpy.models import NaiveBayes
from pgmpy.independencies import Independencies
from pgmpy.extern import six
class TestBaseModelCreation(unittest.TestCase):
def setUp(self):
self.G = NaiveBayes()
def test_class_init_wi... |
#!/usr/bin/env python
# vim:set ts=4 sw=4 et:
#
#
# ****************************************************************************
# *
# * Copyright (c) 2015 UAVenture AG. All rights reserved.
# * Author: Simon Wilks <simon@uaventure.com>
# *
# * Redistribution and use in source and binary forms, with or without
# * ... |
import os
import quandl
import datetime
import pandas as pd
import numpy as np
quandl.ApiConfig.api_key = os.environ.get("SECRET_KEY")
quandl.get('BITCOINWATCH/MINING', start_date='2020-05-01', end_date=str(datetime.datetime.today()).split()[0])
|
"""
Defines classes
PySource - represents pure Python module
PyCModule - represents Python extension module
PyCFunction - represents Python extension function
PyCArgument - represents argument to Python extension function
PyCReturn - represents return value of Python extension function
PyCTypeSpec ... |
''' Stores information on tags and provides id lookup '''
_LEAF_TAGS = {
1: 'published_tag',
}
_PUBLICATION_TAGS = {
1: 'multi_author_tag',
2: 'multi_publisher_tag',
3: 'multi_language_tag',
4: 'multi_identifier_tag',
5: 'mutli_title_tag',
}
_TAG_TYPES = {
'leaf': _LEAF_TAGS,
'publica... |
"""Tile generation restriction by an Osm Change file and a polygon.
Read a compressed or uncompressed Osm Change file
Analyze the tiles that were modified at a given range of zoom levels.
Potentially perform the analysis on additional Osm Change files.
Restrict the tile generation within a polygon to changed tiles and... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dbmodels import db
from dbmodels import User
from dbmodels import Group
class UserGroupDoesNotExist(Exception):
def __init__(self, name):
msg = 'user group Group(%s) does not exist' % name
super(UserGroupDoesNotExist, self).__init__(msg)
class ... |
__author__ = 'tommaso'
# Imports OSM dumps in a db - in a multi threaded way :O
from Workflow import *
import subprocess
import Workflow
#import psycopg2
# Import settings
settings = ""
with open("settings.sh", "r") as file:
for line in file:
if not line.startswith("#"):
settings += line + ... |
from ..value_function import ValueFunction
from ...utils import check_random_state
_MEAN = 0.0
_STD = 0.3
class TabularVF(ValueFunction):
'''
Tabular Value Function.
Can be used for both state V(s) and state-action Q(s, a) values.
# Arguments
init: boolean. Wheter to return a randomly initi... |
# -*- coding: utf-8 -*-
# flake8: noqa
from sanskrit_parser import enable_console_logger, enable_file_logger
from sanskrit_parser.base.sanskrit_base import SLP1, DEVANAGARI
import sanskrit_parser.generator.sutra as sutra
from sanskrit_parser.generator.paninian_object import PaninianObject
from sanskrit_parser.generator... |
# -*- coding: utf-8 -*-
from django.db import models
from cms.models.pluginmodel import CMSPlugin
from allink_core.core.utils import get_additional_templates
class AllinkInfoBoxPlugin(CMSPlugin):
DISPLAY_DURATION = (
(0, 'Always visible'),
(1, '1x'),
(2, '2x'),
(3, '3x'),
... |
class ObjectPathlike:
def __init__(self, team: int, object_type: str, object_id: int):
self.team = team
self.object_type = object_type
self.object_id = object_id |
# -*- coding: utf-8 -*-
#
# Database upgrade script
#
# RLPPTM Template Version 1.3.0 => 1.4.0
#
# Execute in web2py folder after code upgrade like:
# python web2py.py -S eden -M -R applications/eden/modules/templates/RLPPTM/upgrade/1.3.0-1.4.0.py
#
#import datetime
import sys
from s3 import S3Duplicate
#from gluon.st... |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
"""
This script creates a corpus of documents from the November 2019 Common Crawl archive.
"""
from argparse import ArgumentParser
from collections import defaultdict
import gzip
import json
import logging
from mul... |
"""The main parsing routine."""
from docstring_parser.common import Docstring, ParseError
from docstring_parser.styles import STYLES, Style
def parse(text: str, style: Style = Style.auto) -> Docstring:
"""Parse the docstring into its components.
:param text: docstring text to parse
:param style: docstri... |
#!/usr/bin/env python
# coding: utf-8
import argparse
import os.path as osp
from pathlib import Path
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from ogb.nodeproppred import PygNodePropPredDataset, Evaluator
from torch_geometric.data import NeighborSampler
from torch_geom... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.