content stringlengths 5 1.05M |
|---|
import numpy as np
import pickle
import matplotlib.pyplot as plt
import random
from encoder import get_encoder_layer
from decoder import decoding_layer,process_decoder_input
import tensorflow as tf
import os
device_name = "/gpu:0"
#def corrupt_noise(traj, rate_noise, factor):
# new_traj={}
# for count, key in enu... |
from summarizer import commons, graph, keywords, pagerank_weighted, \
summarizer, syntactic_unit, textrank
|
#
# Licensed to Big Data Genomics (BDG) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The BDG licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this fil... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from franka_tut_reasoning.ontology_manager import TaskSemanticManager
from franka_tut_reasoning.main import Reasoning
from franka_tut_reasoning.grounding_action_server import GroundingActionServer
from franka_tut_reasoning.task_server import TaskActionServe... |
#!/usr/bin/python
'''
This script collects the running times of the tests present in the current
directory.
It does not run the tests but reads the already present output files.
Usage:
python performance.py
Dependencies:
gnuplot http://www.gnuplot.info/
'''
import time
from subprocess import check_output
f... |
# Generated by Django 2.2 on 2020-10-13 10:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='account',
... |
# Copyright 2020 The TensorFlow Authors. 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 required by applica... |
import pandas as pd
from gensim.models import Word2Vec
import os
import time
import datetime
def format_time(elapsed):
elapsed_rounded = int(round(elapsed))
return str(datetime.timedelta(seconds = elapsed_rounded))
train_data = pd.read_csv("../tianchi_datasets/track3_round1_newtrain3.tsv", sep="\t", header=N... |
from discord.ext import commands
from app import errors
from app.classes.bot import Bot
from app.i18n import t_
async def not_disabled(ctx: commands.Context) -> bool:
if ctx.guild is None:
return True
if ctx.channel.permissions_for(ctx.message.author).manage_guild:
return True
guild = awa... |
#!/opt/mvsd/bin/python3
## this script will take asset tags in DeviceWipeAsset.csv and using an API call
## to Snipe retrieve the serial numbers for those devices and put them in a new
## CSV, DeviceWipeSerial.csv then it takes the serial numbers from
## DeviceWipeSerial.csv and issues an API command to WS1 (Airwatch... |
import pytest
import time
from common.exceptions import PlenumTypeError, PlenumValueError
from stp_core.ratchet import Ratchet
from plenum.common.throttler import Throttler
def test_throttler_init_invalid_args():
for windowSize in (None, '5', [4]):
with pytest.raises(PlenumTypeError):
Throttl... |
import numpy as np
import torch
try:
from isaacgym import gymapi
from isaacgym import gymutil
from isaacgym import gymtorch
except Exception:
print("ERROR: gym not loaded, this is okay when generating docs")
from .helpers import load_struct_from_dict
from .gym_wrapper import GymWrapper
class Cartpol... |
import torch
import torch.nn as nn
from torch.autograd import Variable
from data_loading import *
from rdkit import Chem
'''
the model
'''
class generative_model(nn.Module):
def __init__(self, vocabs_size, hidden_size, output_size, embedding_dimension, n_layers):
super(generative_model, self).__init__()
... |
import os
CONFIG_FOLDER_PATH = os.path.dirname(__file__)
|
from django.conf import settings
def display_username(user: settings.AUTH_USER_MODEL) -> str:
return f"@{user.username}"
|
# Copyright 2017 Mycroft AI 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 writin... |
import json
import re
import os
import requests
import traceback
from datetime import datetime
from hashlib import md5
from pathlib import Path
from queue import Queue
from random import randint
from subprocess import call, PIPE
from threading import Thread, Lock
from time import sleep
from time import time
from types ... |
import configparser
import os
import unittest
import json
from joplin_api import JoplinApi
from jong_toolkit.core import JongToolKitCollector, JongToolKitImporter
class TestStringMethods(unittest.TestCase):
def setUp(self):
current_folder = os.path.dirname(__file__)
self.config = configparser.Conf... |
#!/usr/bin/python3
# vim: set fileencoding=utf-8 :
# Version 1.1.1
from os import path, readlink, remove, walk
from re import escape, match, sub
from subprocess import call
from sys import argv, exit
from uuid import uuid4 as uuid
from hashlib import md5
try:
from multiprocessing import Queue, Lock, Pool, cpu_coun... |
from aiopg.sa import create_engine
from sqlalchemy import (
MetaData, Table, Column, ForeignKey,
Integer, String, Date
)
meta = MetaData()
question = Table(
'question', meta,
Column('id', Integer, primary_key=True),
Column('question_text', String(200), nullable=False),
Column('pub_date', Date... |
mapping = {
"sf": "snowfall_m",
"sp": "pressure_pa",
"t2m": "temperature_k",
"tp": "precipitation_m",
"u10": "wind_ms"
}
era5_renamed = era5.rename(mapping)
era5_renamed |
from threading import Lock
global bot, cryptos_json, CMC_API_KEY, log_lock
log_lock = Lock()
def initilize(telebot, cryptos_json_other, cmc_api_key):
global bot, cryptos_json, CMC_API_KEY
bot = telebot
cryptos_json = cryptos_json_other
CMC_API_KEY = cmc_api_key
|
import pytest
class TestClassAddition():
@pytest.mark.parametrize(
"params,expected",
[
[
{
'a': 3,
'b': 3
},
9
]
]
)
def test_return(self, params, expected):
import tests.exam... |
#!/usr/bin/env python
import sys
from cbapi.response.models import Alert
from cbapi.example_helpers import build_cli_parser, get_cb_response_object
import time
def main():
parser = build_cli_parser("Bulk resolve alerts")
parser.add_argument("--query", action="store", default="", required=True,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Feb-01-20 06:51
# @Author : Your Name (you@example.org)
# @Link : https://www.kaggle.com/uysimty/keras-cnn-dog-or-cat-classification
import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator, load_img
from ke... |
import numpy as np
# dictionary describing options available to tune this algorithm
options = {
"peak_size": {"purpose": "Estimate of the peak size, in pixels. If 'auto', attempts to determine automatically. Otherwise, this should be an integer.",
"default": "auto",
"type": "i... |
"""This module contains the general information for FirmwareActivity ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class FirmwareActivityConsts:
SERVERS_POWER_STATE_NONE = "none"
SERVERS_POWER_STATE_OFF = "off"
SE... |
'''
Given a string A consisting of lowercase characters.
We need to tell minimum characters to be appended (insertion at end) to make the string A a palindrome.
Example Input
Input 1:
A = "abede"
Input 2:
A = "aabb"
Example Output
Output 1:
2
Output 2:
2
'''
def min_append_to_palindrome(A: str)... |
import os
try:
import catboost_dev as catboost
from catboost_dev import CatBoost, CatBoostRegressor, Pool
except:
import catboost
from catboost import CatBoost, CatBoostRegressor, Pool
## CatBoost tutorial: Categorical features parameters
#
#*Mastering the parameters you didn't know exist*
#
#| -Inbox|.*0-GitHUB)")
only_show_inbox = re.compile(r".*")
remove_gmail_folder = True
DEBUG = False
def get_inbox_statuses():
try:
emacsclient_output = subprocess.run(
... |
from django.conf.urls import url, handler404, handler500, handler403
# from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
import blog.views
from django.views import static
from DjBlog import settings
from blog import urls as blog_url
from users import urls... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette.by import By
from gaiatest import GaiaTestCase
from gaiatest.apps.browser.app import Browser
from gaiate... |
#####################################################################
# Code to produce statistical outputs
# For use with test / training datasets : HAPT-data-set-DU
# Author : Benjamin Jones, b.t.jones@durham.ac.uk, zkbb46
# Based on code from the CV2 open source library and code provided by Dr Toby Breckon... |
import os
from flask import Flask, request, g, url_for, json
from flask_cors import CORS
from flask_restful import reqparse, Resource, Api
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSig... |
from bs4 import BeautifulSoup as bs
class Scraper:
"""
Its only purpose is to get all links and titles from search results
"""
def __init__(self, site_string, service):
self.service = service
if len(site_string) > 0:
self.soup = bs(site_string, 'html.parser')
def get_... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 0.8.2
# kernel_info:
# name: python3
# kernelspec:
# display_name: Python 3
# language: python
# name: pyt... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import asyncio
import random
import discord
from discord.ext import commands
class Rolldice(commands.Cog):
def __init__(self, habbot):
self.habbot = habbot
#The command
@commands.command(pass_context=True, aliases=['roll'])
async def rolldice(self, ctx):
await ctx.send(f':game_... |
"""
Black Pearl: For twisted little pirates
"""
|
#!/usr/bin/env python
#
# slackClient.py
# --------------
#
# Mal Minhas <mal@kano.me>
# Copyright (c) 2018 Kano Computing. All Rights Reserved.
# Licence: GPLv3
#
# Installation:
# --------------
# You will need to create a Slack App first.
# You will need a one time OAuth flow to get hold of your Slack token:
# http... |
import os
import sqlite3
class SQLite():
def __init__(self, sqlite_path , sqlite_ddbbname, sqlite_tablename, delete=False):
self.__path = sqlite_path
self.__ddbbname = sqlite_ddbbname
self.__tablename = sqlite_tablename
self.__conn = None
if delete and os.path.isfile(sqlite... |
# test equality
print(None == None)
print(False == None)
print(False == False)
print(False == True)
print(() == ())
print(() == [])
print([] == [])
print(() == {})
print({} == ())
print(() == None)
print(() == False)
print(() == print)
print([] == None)
print([] == False)
print([] == print)
print({} == None)
prin... |
import cv2
# Read the original image
img = cv2.imread(r'C:\Users\harrizazham98\Desktop\OpenCVForPython\resources\Day 3\geometric-shape-names-types-definitions.png')
# Blur the image for better edge detection
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Gradient x is calculated:
# the depth of the ou... |
class Config(object):
TESTING = False
class ProductionConfig(Config):
DATABASE_URI = 'mysql://user@localhost/foo'
API_KEY =
class DevelopmentConfig(Config):
DATABASE_URI = "sqlite:////tmp/foo.db"
class TestingConfig(Config):
DATABASE_URI = 'sqlite:///:memory:'
TESTING = True
|
import os
def create_cell(first, second):
res = set()
if first == set() or second == set():
return set()
for f in first:
for s in second:
res.add(f+s)
return res
def read_grammar(filename="./grammar.txt"):
filename = os.path.join(os.curdir, filename)
wi... |
#!/usr/bin/env python2
"""
The GitHub user interface shows me a list of notifications, but it's full of
things I don't care about. This tries to automatically mark as read the
categories of notifications that I don't want to get.
Create `ghcreds.py` containing:
token="asdfjkl"
where token comes from https://github.c... |
#!/usr/bin/env python
# Copyright 2021 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 ... |
import keras
from keras.models import Sequential
from keras.layers import Conv2D, Dense, Activation, Dropout, Flatten, MaxPooling2D
from keras.optimizers import Adam
def build_model():
model = Sequential()
model.add(Conv2D(32, (3,3), activation="relu", input_shape=(1,112,92), data_format="channels_first"))
... |
import sys
import os
import csv
import music21
from indexer import client, indexers
from proto import smr_pb2, smr_pb2_grpc
CURDIR = os.path.abspath(os.path.dirname(__file__))
PROJROOT = os.path.join(CURDIR, os.pardir)
HELSINKI_TESTS = os.path.join(PROJROOT, "smr", "helsinki-ttwi", "tests")
TESTDATA = os.path.join(CUR... |
# Generated by Django 3.0.4 on 2020-04-20 09:17
import YourJobAidApi.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('YourJobAidApi', '0026_auto_20200420_0611'),
]
operations = [
migrations.AlterField(
model_name='post... |
# Code strings from the Galileo SIS ICD for the E1-B code
e1b_strings = {
1: "F5D710130573541B9DBD4FD9E9B20A0D59D144C54BC7935539D2E75810FB51E494093A0A19DD79C70C5A98E5657AA578097777E86BCC4651CC72F2F974DC766E07AEA3D0B557EF42FF57E6A58E805358CE9257669133B18F80FDBDFB38C5524C7FB1DE079842482990DF58F72321D9201F8979EAB159B26... |
import numpy as np
import pandas as pd
from prettytable import PrettyTable
from recourse.helper_functions import parse_classifier_args
from scipy.stats import gaussian_kde as kde
from scipy.interpolate import interp1d
# todo: replace percentiles with scikit-learn API
# todo: get_feasible_values/get_flip_actions should... |
import requests as re
import colorama
from colorama import Fore, Back, Style
import json
colorama.init()
print(f"""{Fore.LIGHTGREEN_EX}
█ █░ ██▓███ ██████ ▄████▄ ▄▄▄ ███▄ █ ███▄ █ ▓█████ ██▀███
▓█░ █ ░█░▓██░ ██▒ ▒██ ▒ ▒██▀ ▀█ ▒████▄ ██ ▀█ █ ██ ▀█ █ ▓█ ▀ ▓██ ▒ ██▒... |
#!/usr/bin/python
# coding: UTF-8, break: linux, indent: 4 spaces, lang: python/eng
'''
Convert common image formats to G-code.
Program is optimized for a lulzbut Mini with a 1W engraving laser and tested
with KiCad .svg and .png plots as input. Usage with anything else than that
may prove difficult.
See: {__url__}
... |
"""Functions to retrieve data from the Telraam API."""
import requests
import datetime as dt
from typing import Dict, Optional
from . import log
from tqdm.auto import tqdm
import os
TELRAAM_API_URL = "https://telraam-api.net/v1"
ENVVAR_TELRAAM_API_TOKEN = os.environ.get("TELRAAM_API_TOKEN")
def _response_is_healthy(... |
from MagniPy.paths import *
from MagniPy.Analysis.Statistics.singledensity import SingleDensity
import sys
from copy import deepcopy, copy
import numpy as np
from MagniPy.util import *
import pandas
def read_run_partition(fname):
with open(fname, 'r') as f:
lines = f.readlines()
Ncores = int(lines[1]... |
import os
from datetime import datetime
import numpy as np
import luigi
import nifty.tools as nt
# we don't need to bother with the file reader
# wrapper here, because paintera needs n5 files anyway.
import z5py
from ..cluster_tasks import WorkflowBase
from ..label_multisets import LabelMultisetWorkflow
from ..downs... |
from django.apps import AppConfig
class BalancesConfig(AppConfig):
name = 'balances'
|
raw_data = np.random.normal(10, 1, 100)
with tf.Session() as sess:
for i in range(len(raw_data)):
curr_avg = sess.run(update_avg , feed_dict = {curr_value:raw_data[i]})
sess.run(tf.assign(prev_avg, curr_avg)) |
""" Functions to create the circuit simulating the Pauli channel """
from qiskit import QuantumCircuit
import numpy as np
def pauli_channel_tanh(q, t, system, pauli_ancillae, eta=1, omega=1):
"""Construct the Pauli channel with rates
\\gamma_1(t) = \\eta/2
\\gamma_2(t) = \\eta/2
\\gam... |
import pygame, sys
from pygame.locals import *
pygame.init()
class Brick:
def __init__(self, x, y, color):
self.image = pygame.Surface([40, 13])
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
|
"""Item purchase models."""
# Python
from decimal import Decimal
# Django
from django.db import models
from django.db.models import Sum, F, FloatField, Max
from django.db.models.signals import post_save, pre_save
from django.db import transaction
from django.dispatch import receiver
from django.utils import timezone... |
# -*- coding: utf-8 -*-
"""
gagepy.utils
~~~~~~~~~~~~
Utility helper functions for gagepy.
:authors: 2016 by Jeremiah Lant, see AUTHORS
:license: United States Geological Survey (USGS), see LICENSE file
"""
import os
import numpy as np
import datetime
import re
def get_file_paths(dirname, file... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Raphaël Barrois
import sys
if sys.version_info[:2] < (2, 7): # pragma: no cover
import unittest2 as unittest
else: # pragma: no cover
import unittest
if sys.version_info[0] >= 3: # pragma: no cover
import unittest.mock as mock
else: # pragma: no cove... |
from __future__ import absolute_import, print_function
import errno
import os
import sys
import json
import time
from typing import TYPE_CHECKING
import psutil
MAX_ARGUMENTS_JSON_LENGTH = 65536
try:
import subprocess32 as subprocess
except ImportError:
import subprocess
import functools
import logging
impo... |
import sys
def main(fname):
allOps = {}
with open(fname, "r") as fileobj:
for line in fileobj.readlines():
stripped = line.strip().split(" ")[-1]
if stripped != "IN" and stripped != "OUT":
if stripped in allOps:
allOps[stripped] += 1
... |
from django.conf import settings
from django.conf.urls.static import static
from django.urls import include, path
from django.contrib import admin
from scaife_viewer.core.views import (
LibraryCollectionVectorView,
LibraryCollectionView,
LibraryInfoView,
LibraryPassageView,
LibraryView,
Reader... |
"""
This module contains class Model.
"""
# pylint: disable=bad-continuation
import torch
import torch.nn as nn
class ZSamplePredsMixin:
"""
This mixin adds a method to get predictions for a set of z-samples.
"""
# pylint: disable=too-few-public-methods
def get_z_sample_preds(self, x_pt, z_sampl... |
"""Contains base class for ``SqrtGGN{Exact, MC}`` module extensions."""
from __future__ import annotations
from typing import TYPE_CHECKING, Callable, List, Tuple, Union
from torch import Tensor
from torch.nn import Module
from backpack.core.derivatives.basederivatives import BaseDerivatives
from backpack.extensions... |
"""Program Created By Vivek Sharma http://doyl.in"""
import socket
def Main():
host='127.0.0.1'
port=7000
s=socket.socket() #socket Created
s.bind((host,port)) #Port Binded
s.listen(1) # Waiting
connection,addr=s.accept() #accept With Connection And Address
print('connectn fr... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with th... |
"""
HTTP Resource for displaying connection in OpenNSA.
Currently rather simple. No CSS, just raw html tables.
Author: Henrik Thostrup Jensen <htj@nordu.net>
Copyright: NORDUnet (2012)
"""
from twisted.web import resource, server
from opennsa import database
HTML_HEADER = """<!DOCTYPE html>
<html>
<head>
... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/8/10 下午12:31
@Auth : apecode.
@File : utili.py
@Software : PyCharm
@Blog : https://liuyangxiong.cn
"""
import time
def getTenAfter():
now = int(time.time() + 600)
# 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)
otherStyleTime = time.strftime... |
import random
import sqlalchemy as sa
from sqlalchemy.schema import MetaData
from sqlalchemy.ext.declarative import as_declarative
from falcon_helpers.sqla.core import utcnow
from falcon_helpers.sqla.utils import random_data_for_type
from falcon_helpers.sqla.db import session
convention = {
"ix": 'ix_%(column_0_la... |
# coding=utf8
from .data import DataBase
from huskar_api.models.dataware.zookeeper import config_client
class ConfigData(DataBase):
client = config_client
|
"""
Problem 4:
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_polindrome(n):
return str(n) == str(n)[::-1]
polindrome = 0
for i in range(100, 999):
for j in range(100, 999):
if is_polindrome(i * j) and i * j > polindrome:
polindrome = i * j
... |
import requests
from fake_useragent import UserAgent
from components.headers import get_headers
from components.proxies import getProxies
from components.login import login
from components.download import download
from arguments import wallhaven_argparse
ua = UserAgent(use_cache_server=False, path="components/fake_u... |
# Copyright 2015 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.
from string import Template
import optparse
import os
import sys
try:
grit_module_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..'... |
from marshmallow import fields, validate
from .base import BaseSchema
class PageSchema(BaseSchema):
page = fields.Integer(
required=True, validate=validate.Range(min=1), allow_none=False
)
|
from flask import Flask, request, render_template
from flask_assistant import Assistant, ask, tell
from steem import Steem
from steem.converter import Converter
from steem.blog import Blog
from steem.account import Account
from steem.amount import Amount
from steemconnect.client import Client
from steemconnect... |
import pytest
from ...renderer.VideoExporter import RendererVideoExporter
class TestVideoExporter:
# region __init__
def test_initRaisesErrorOnInvalidParameters(self):
with pytest.raises(TypeError):
RendererVideoExporter(0.2, 224, 224, 60)
with pytest.raises(TypeError):
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from playhouse.migrate import migrate
logger = logging.getLogger('data')
def forward(migrator):
# This migration may take some time to run.
# It adds indexes to integer fields that should have been indexed... |
#!/usr/bin/env python
"""botty.py: source code of sushi bot"""
import win32api, win32con, time
__author__ = "Asdf"
__copyright__ = "Copyright 2017, Planet Earth"
# global values for screen size on 130% zoom, get top right corner for x_pad and y_pad
# top left (x,y): 317, 292 and bot right (x,y): 1151, 917
x... |
from time import sleep
from pprint import pformat
from instrumentslib import (
get_instrument_cfg,
instrument,
)
cfg = get_instrument_cfg('bk_1686B')
_Parent = cfg['InstrumentParentClass']
resource_kwargs = cfg['resource_kwargs']
@instrument(resource_kwargs, 'bk_1686B')
class bk_1686B(_Parent):
def wr... |
buka = open('enc').read().split('\n')
enc = int(buka[0].split(': ')[1])
n = int(buka[1].split(': ')[1])
hint = int(buka[2].split(': ')[1])
z = ((hint - n) / 0xdeadbeef) - 0xdeadbeef # c = 0xdeadbeef
dist = z // 4
p = z // 2
q = z - p
print "p = {}".format(p)
print "q = {}".format(q)
print "p*q = {}".format(p*q)
prin... |
# plots of key continuous distributions
import numpy as np
import matplotlib.pylab as plt
N = 10000000
B = 100
x = np.arange(B)/B
# uniform
t = np.random.random(N)
u = np.histogram(t, bins=B)[0]
u = u / u.sum()
# normal
t = np.random.normal(0, 1, size=N)
n = np.histogram(t, bins=B)[0]
n = n / n.sum()
# gamma
t =... |
from django import forms
class ContatoForm(forms.Form):
titulo = forms.CharField(label='Title')
CHOICES = [('1', 'music'), ('2', 'entertainment'),('3', 'news'),('4','politics'),('5','games')]
tema = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
url = forms.CharField(label='YouTube URL Vi... |
def int_to_bin(number, width = 32):
if number < 0:
number += 1 << width
i = width - 1
bits = ["\x00"] * width
while number and i >= 0:
bits[i] = "\x00\x01"[number & 1]
number >>= 1
i -= 1
return "".join(bits)
_bit_values = {"\x00" : 0, "\x01" : 1, "0" : 0, "1" : 1}
d... |
rioe=4916520
icp=24396850
dunk="fmnsiue"
efjuvs=396
xafnzbm="psed"
ipuvj=01793846
lukdmn=4937
tdke="helvx"
nebqf=843279
ulfhsji=78416530
zrsfb=95
jgkcxls=24810379
cuni="slf"
puorwvm="rbcvzs"
vfespko=08153
vpuomi=6425901
cld="rmk"
sfyblmg=5863
ohyelq="xeitadl"
ckedwg=093647
xdjt="tfyc"
ezskl="vyp"
jeshdu="rteadg"
ecxi="... |
import gym
# noinspection PyUnresolvedReferences
import gym_multiplexer
from examples.acs2.boolean_multiplexer.utils import reliable_cl_exists
from lcs.agents import EnvironmentAdapter
from lcs.agents.acs2 import ACS2, Configuration
def mpx_metrics(pop, env):
return {
'population': len(pop),
'rel... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
data = get_data(filters)
columns = get_columns(filters)
return columns, data
def get_data(fil... |
#!/usr/bin/env python
import ConfigParser
import collections
import json
import logging
import os
import random
import re
import socket
import sys
import time
from datetime import datetime
from optparse import OptionParser
import requests
'''
This script gathers metric data from opentsdb and use http api to send to I... |
import streamlit as st
import pandas as pd
import numpy as np
st.title('Sea ice test')
DATE_COLUMN = 'Date'
DATA_URL = ('https://www.seaice.de/nh_awi_amsr2_regional_extent_area.csv')
@st.cache
def load_data():
data = pd.read_csv(DATA_URL)
lowercase = lambda x: str(x).lower()
data.rename(lowercase, axi... |
from dashboard.app import run_app
run_app(False)
|
import turtle
class Player :
# Drawing and positioning player and bullet
def __init__(self, dimension) :
# Window dimension
self.dimension = dimension
# Draw player
self.player = None
self.player = turtle.Turtle()
self.player.hideturtle()
self.player.color("blue")
self.player.shape("triangle")
sel... |
import secrets
from flask import Flask
from flask_caching import Cache
from flask_cors import CORS
app = Flask(__name__)
config = {
'DEBUG': True,
'CACHE_TYPE': 'SimpleCache',
'CACHE_DEFAULT_TIMEOUT': 300,
'SECRET_KEY': '9317f2b87044b56c44ca2502d3f945af',
'CORS_HEADERS': 'Content-Type'
}
app.confi... |
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from fastmsa.core import Command
@dataclass
class Allocate(Command):
orderid: str
sku: str
qty: int
@dataclass
class CreateBatch(Command):
ref: str
sku: str
qty: int
eta: Optional[datetime] = Non... |
import os
import asyncio
class Display:
"""A class displaying all stuff."""
def __init__(self):
super().__init__()
self.query = []
self.updating = False
async def printIn(self):
while 1:
if self.updating is True:
os.system('clear' if not Except... |
# coding: utf-8
import unittest
import warnings
import pronto
class TestDefinition(unittest.TestCase):
@classmethod
def setUpClass(cls):
warnings.simplefilter('error')
@classmethod
def tearDownClass(cls):
warnings.simplefilter(warnings.defaultaction)
def test_repr(self):
... |
def _bundle_file_impl(ctx):
out = ctx.actions.declare_file(ctx.attr.name + ".go")
ctx.actions.run(
outputs = [out],
inputs = [ctx.file._bundle_file, ctx.file.src],
executable = "python",
arguments = [
ctx.file._bundle_file.path,
ctx.file.src.path,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.