content stringlengths 5 1.05M |
|---|
import logging
import sys
import pyModeS as pms
from pyModeS.extra.rtlreader import RtlReader
class RtlSdrSource(RtlReader):
def __init__(self):
super(RtlSdrSource, self).__init__()
def handle_messages(self, messages):
if self.stop_flag.value is True:
self.sdr.close()
... |
import numpy
verbose = False
def ride_of_fortune(artifact, explorers):
artifact_object = Artifact(artifact)
if verbose:
print(artifact_object.artifact)
results = []
for explorer_start_row in explorers:
if verbose:
print("====")
explorer_object = Explorer(y=explorer... |
# Copyright 2018 eShares, Inc. dba Carta, 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
# SPDX-FileCopyrightText: 2021 Genome Research Ltd.
#
# SPDX-License-Identifier: MIT
from main.service import AssemblyService
from main.swagger import AssemblySwagger
from .base import BaseResource, setup_resource
api_assembly = AssemblySwagger.api
@setup_resource
class AssemblyResource(BaseResource):
class M... |
import unittest
import numpy
import tempfile
from pyscf import lib, gto
class KnowValues(unittest.TestCase):
def test_save_load_mol(self):
mol = gto.M(atom=[['H', (0,0,i)] for i in range(8)],
basis='sto3g')
fchk = tempfile.NamedTemporaryFile()
lib.chkfile.save_mol(mol, f... |
import sqlite3
from message import Message
from friend import Friend
'''
Created on Nov 14, 2013
@author: andyisaballa
'''
STICKERS_ENABLED = 0
STICKERS_DISABLED = 1
STICKERS_ONLY = 2
def getMessagesByFriend(db, name, stickers=STICKERS_DISABLED):
conn = sqlite3.connect(db)
cursor = conn.cursor()
if is... |
# The MIT License (MIT)
#
# Copyright (c) 2016 Russell Barlow III
#
# 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, co... |
from abc import ABC, abstractmethod
from boltons.cacheutils import cachedproperty
class BaseEnv(ABC):
"""
Abstract base class used for implementing new environments.
"""
def __init__(self):
self.env = self._create_env()
def __str__(self):
return "<{}>".format(type(self).__name__)... |
# -------------------------------------------------------------------------------
# (c) 2020 Siemens AG
# All Rights Reserved.
# Author: thomas.graf@siemens.com
#
# Licensed under the MIT license.
# SPDX-License-Identifier: MIT
# -------------------------------------------------------------------------------
import s... |
# Generated by Django 2.2.5 on 2019-12-02 00:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0012_auto_20191202_0038'),
]
operations = [
migrations.RenameField(
model_name='boleto',
old_name='user_id',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 8 16:58:10 2020
@author: nephilim
"""
import keras
import numpy as np
import my_Im2col
from matplotlib import pyplot,cm
import skimage.transform
import T_PowerGain
import DataNormalized
import Reshape2Encoder
def GetPatch(Image,patch_size,sliding... |
# Copyright 2018 Telefonica
#
# 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 ... |
r"""
Utils are utils.
"""
from sys import version_info as v
import subprocess
from datetime import datetime
def run_cmd(cmd: str) -> str:
r"""Executes and returns custom command output.
"""
return subprocess.getoutput(cmd)
def get_gpu_usage() -> str:
r"""Returns current gpu usage.
"""
cmd_u... |
import sys
import glob
import serial
import datetime
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import os
import popart
import numpy as np
import torch
import onnx
from onnx import numpy_helper
import math
import pytest
# `import test_util` requires adding to sys.path
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.... |
# Generated by Django 3.1.5 on 2021-01-14 08:31
import django.contrib.postgres.indexes
import django.contrib.postgres.search
from django.db import migrations, models
def parse_description_json_to_string(description):
string = ""
blocks = description.get("blocks")
if not blocks or not isinstance(blocks, l... |
from .concat_dataset import ConcatDataset
from .dataset_wrapper import DatasetWrapper
from .image_collection_dataset import ImageCollectionDataset
from .segmentation_dataset import SegmentationDataset
from .sampler import MinForegroundSampler
|
# Generated by Django 2.0.4 on 2019-07-17 11:36
from django.core.management import call_command
from django.db import migrations
from events.helpers.permissions import (
create_organizer_group_migrations_wrapped,
remove_organizer_group
)
def update_permissions(schema, group):
call_command('update_permiss... |
# PLASMA is a software package provided by:
# University of Tennessee, US,
# University of Manchester, UK.
from __future__ import print_function
# standard python modules
import os
import sys
import re
import shlex
import subprocess
from subprocess import PIPE
# local modules
from environment import Environment
... |
from .code import Code
from .docstring import DocString
from .value import NamedValue, UnnamedValue
from .function import Function
from .proptypes import PropTypes
from .klass import Class
from .module import Module
|
#!/usr/bin/env python
from setuptools import setup, find_packages
"""
Documentation can be found at https://docs.python.org/2/distutils/index.html,
but usually you only need to do the following steps to publish a new package
version to PyPI::
# Update the version tag in this file (setup.py)
python setup.py sd... |
# Program to automatically send email when something goes down
# by calling the function email()
# like this --> email(["example@somewhere.com","somewhereelse@other.com"])
import smtplib # Necessary modules
from email.mime.text import MIMEText
xhoni = "xhp1@pitt.edu"
def sendMail(recievers,content,subject="Alert"):
... |
src = Split('''
src/mbedtls_net.c
src/mbedtls_alt.c
src/mbedtls_auth.c
''')
aos_global_config.set("DEBUG", "yes")
component = aos_component('itls', src)
component.add_global_includes('include')
component.add_macros('CONFIG_PLAT_AOS')
component.add_macros('CONFIG_KEY_OTP_ENABLED')
if aos_global_config.g... |
import boto3
from os import walk
from datetime import datetime
client = boto3.client('s3')
# Create s3 bucket
now = datetime.now()
date_time = now.strftime("%m-%d-medium-datasets")
response = client.create_bucket(
Bucket=date_time
)
print(response)
#
s3 = boto3.resource('s3')
# Upload files to bucket
mypath =... |
from clinical_records import settings
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, Field, Layout, Submit
from django import forms
from django.forms import DateField
from django.forms import ModelForm
from patients.models import CIE10
from patients.models import ClinicalHistory
from pa... |
import os
import unittest
from io import StringIO
from datetime import timedelta
from urllib.parse import quote
from django.conf import settings
from django.contrib import auth
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from oauth2_provider.mode... |
import pytest
from pyroll.core import Transport
class Specs:
@Transport.hookspec
def hook1(self, transport):
""""""
Transport.plugin_manager.add_hookspecs(Specs())
def test_hook_not_present():
transport = Transport(time=1)
with pytest.raises(AttributeError):
print(transport.does_... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from delivery import deli, tasks
urlpatterns = [
url(r'^$', deli.delivery_list, name='delivery'),
url(r'^add/$', deli.delivery_add, name='delivery_add'),
url(r'^ist/$', deli.delivery_list, name='delivery_list'),
url... |
from distutils.core import setup
import os
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.md')) as f:
CHANGES = f.read()
setup(name='django-cli',
packages=['django-cli'],
version='0.0.1',
... |
# -*- coding: utf-8 -*-
from irc3.testing import BotTestCase, MagicMock
from irc3.plugins.autojoins import AutoJoins
class TestAutojoin(BotTestCase):
def test_autojoin_without_diese(self):
bot = self.callFTU(autojoins=['foo'])
bot.notify('connection_made')
bot.dispatch(':hobana.freenode.... |
"""
My fun little python script to autoclick in cookie clicker
#Only functions on Windows right now
"""
from ctypes import windll, Structure, c_long, byref, wintypes
import keyboard
import time
import sys
from msvcrt import kbhit, getch
click = False
pressed = False
running = True
setx = 0
sety = 0
offstr = "OFF"
o... |
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def run_in_executor(method):
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, method)
return result |
from time import sleep
from loguru import logger
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import Selec... |
# _*_ coding: utf-8 _*_
import json
import uuid
from datetime import datetime
from multiprocessing import Process
import redis
__author__ = 'Arun KR (@kra3)'
class SimpleJobQueue(object):
SCHEDULED, IN_PROGRESS, DONE, FAILED = (
'SCHEDULED', 'IN_PROGRESS', 'DONE', 'FAILED')
TIMESTAMP, PAYLOAD, STATU... |
l=[]
for i in range(int(input())):
l.append(input().split())
ans=[]
for i in l:
if i[1]=='rat':
ans.append(i[0])
for i in l:
if i[1]=='woman' or i[1]=='child':
ans.append(i[0])
for i in l:
if i[1]=='man':
ans.append(i[0])
for i in l:
if i[1]=='captain':
ans.append(i[0... |
#! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Tue Feb 2 21:18:10 CET 2010
import cStringIO
import syncless.coio
import socket
import unittest
# TODO(pts): Test reverse lookup without canonical name.
# TODO(pts): Test for IPv6 addresses:
# print syncless.coio.dns_resolve_ipv6('www.ipv6.org')
#: <dnsresult ... |
from pygraphblas import Matrix, BOOL, lib
def rpq(g, r):
kron = g.get_intersection(r)
closure_matrix = Matrix.sparse(BOOL, kron.size, kron.size)
for label in kron.matrices:
if kron.matrices[label].nrows < kron.size:
kron.matrices[label].resize(kron.size, kron.size)
closure_mat... |
'''
This file implements the Schlaufen Detection algorithm in the paper:
Testing Strategic Interaction in Networks
'''
from ugd.schlaufen_construction.di_schlaufen_construction_util import mark_edge, mark_node, cycle_found, random_draw
from ugd.help_function.util import rand_element_of_set, del_nodes_mark
def add... |
import pytest
from asynctest import (
mock as async_mock,
TestCase as AsyncTestCase,
)
from aries_cloudagent.messaging.request_context import RequestContext
from aries_cloudagent.messaging.responder import MockResponder
from aries_cloudagent.transport.inbound.receipt import MessageReceipt
from aries_cloudagent... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 07:06:38 2020
@author: daskalot
"""
#from doc_embedders import TfIdfTransformer as tfidf
from sklearn.feature_extraction.text import CountVectorizer
import string
from sklearn import preprocessing
import graphvite as gv
import numpy as np
from... |
from streamlit.components.v1 import html
try:
from keywords import SHARE_KEYWORD
from keywords import check_keyword
except:
from .keywords import SHARE_KEYWORD
from .keywords import check_keyword
def share_parser(lines):
"""Parses a list of lines into a dictionary with the parsed values.
:p... |
"""
This file demonstrates writing tests using the pytest module. These will pass
when you run "./bin/pytest app/tests.py".
Replace this with more appropriate tests for your application.
"""
# -*- coding: utf-8 -*-
import pytest
class TestSuite(object):
def test_run(self):
pytest.skip('todo')
|
import textwrap
import uuid
from moviepy.editor import *
TITLE_FONT_SIZE = 30
FONT_SIZE = 30
TITLE_FONT_COLOR = 'white'
BGM_PATH = 'assets/bgm.mp3'
STATIC_PATH = 'assets/static.mp4'
SIZE = (1280, 720)
BG_COLOR = (16,16,16)
VIDEO_PATH = ""
FONT = 'Amiri-regular'
def generate_title(text, audio_path):
color_clip = C... |
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'password']
def create(self, validated_data):
user = User(username=validated_data.get('usern... |
from anet.utils.format import MultiObssPreprocessor
from anet.utils.log import configure_logging
from anet.utils.optimizer import load_optimizer, save_optimizer
|
import sys
import pandas as pd
import numpy as np
import re
import pickle
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem imp... |
class ListSecure(list):
def get(self, index, default=None):
try:
return self.__getitem__(index)
except IndexError:
return default
|
"""common functions for client and server"""
def send_msg(socket, msg):
"""send message to a socket"""
socket.send(bytes(str(msg), 'utf8'))
def recv_msg(socket):
"""receive a message from a socket"""
return socket.recv(4096).decode('utf8')
|
# -*- coding: utf-8 -*-
import pickle
import os
import string
import numpy as np
import tempfile
import pandas as pd
import sys
import hashlib
import errno
import time
import shutil
from sklearn.datasets.base import Bunch
TRANS = str.maketrans('', '', string.punctuation.replace('-', ''))
TEMP = tempfile.gettempdir()
... |
# Copyright 2016 Internap
#
# 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... |
import concurrent.futures
import sqlite3
import pytest
from yesql.drivers.sio import sqlite
pytestmark = pytest.mark.asyncio
@pytest.fixture(autouse=True)
def connection(MockSQLiteConnection):
conn = MockSQLiteConnection.return_value
yield conn
MockSQLiteConnection.reset_mock()
sqlite3.connect.rese... |
import psycopg2
from flask import render_template, request, jsonify
from giraffe_api import app, db
q_metric = "select giraffe.init_metric(%(name)s, %(description)s)"
q_metric_value = "insert into giraffe.metric_value" \
"(db_timestamp, cluster, db, metric_id, integer_value, numeric_value) " \
... |
from turtle import Turtle
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.l_score = 0
self.r_score = 0
self.color('white')
self.hideturtle()
self.penup()
self.sety(200)
def increase_r_score(self):
self.r_score += 1
def... |
import cv2
import os
# source: https://stackoverflow.com/a/44659589
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are N... |
from __future__ import absolute_import
from .uploader import GraphiteUploader
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-26 08:15
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('portal', '0006_auto_2016022... |
import json
from rentomatic.serializers import storageroom_serializer as srs
from rentomatic.domain.storageroom import StorageRoom
def test_serialize_domain_storageroom():
room = StorageRoom(
'f853578c-fc0f-4e65-81b8-566c5dffa35a',
size=200,
price=10,
longitude='-0.0999... |
from django.shortcuts import get_list_or_404, get_object_or_404
from rest_framework.serializers import ModelSerializer, Serializer
from shop.models import Image, Product
from rest_framework import fields
class ImageSerializer(ModelSerializer):
mid_size = fields.ImageField()
class Meta:
model = Im... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, unicode_literals, print_function
import copy
import numpy as np
import warnings
from astropy.extern import six
from astropy.modeling.core import Model
from astropy.modeling.parameters import Parameter
fr... |
import colorama, os, ctypes, re, glob
from colorama import Fore
from sys import exit
def cls():
os.system("cls" if os.name=="nt" else "clear")
def fexit():
input(f"\n{Fore.RESET}Press Enter button for exit")
exit()
os.system("cls")
if __name__ == "__main__":
os.system("cls")
ctypes.... |
# coding: utf-8
"""
"""
import torch
import torch.optim as optim
import torch.nn as nn
import os
import time
import copy
import numpy as np
import torch.nn.functional as F
from tensorboardX import SummaryWriter
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_auc_score, f1_score
from visua... |
# Author: Andrew Sainz
#
# Purpose: XMLAnalyze is designed to iterate through a collection of Post data collected from Stack Overflow
# forums. Data collected to analyze the code tagged information to find the language of the code
# being utilized.
#
# How to use: To run from command line input "pytho... |
from .bindings import so, FPDF_PATH_POINT, FPDF_RECT
from ctypes import pointer
class Glyph:
'''Represents Glyph drawing instructions'''
LINETO = 0 #: LineTo instruction
CURVETO = 1 #: CurveTo instruction
MOVETO = 2 #: MoveTo instruction
def __init__(self, glyph, parent):
self._glyp... |
n = int(raw_input())
comportadas = 0
children = []
for i in range(n):
ent = map(str, raw_input().split())
children.append(ent[1])
if ent[0] == "+":
comportadas += 1
children.sort()
for child in children:
print child
print "Se comportaram: %d | Nao se comportaram: %d" % (comportadas, n - co... |
import sys
from mpc_func import *
try:
poses = load_poses(sys.argv[1])
except:
print('Please use the right .csv file!')
sparseness = 100
sparse_poses = poses[1::sparseness, 1:3]
path = [148, 150, 151, 153, 154, 156, 158, 160, 162, 163]
dt = 1 # [s] discrete time
lr = 1.0 # [m]
T = 6 # nu... |
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('home/',views.home,name = 'home'),
path('maps/',views.maps, name = 'maps'),
path('maps/3dmap',views.mapsd, name = 'mapsd'),
path('accounts/login/', views.loginpage , name = ... |
import os
import sys
import unittest
if __name__ == "__main__":
# add the path to be execute in the main directory
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
testmodules = [
'tests.test_nsga2',
#'pymoo.usage.test_usage'
]
suite = unittest.Tes... |
import logging
import os
from peek_plugin_base.PeekVortexUtil import peekStorageName
logger = logging.getLogger(__name__)
class StorageTestMixin:
def __init__(self):
self._dbConn = None
def setUp(self) -> None:
from peek_storage._private.storage import setupDbConn
from peek_storage.... |
# -*- coding: utf-8 -*-
"""
654. Maximum Binary Tree
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right sub... |
import torch
import math
import numpy as np
from torch.distributions.multivariate_normal import MultivariateNormal
from spirl.utils.pytorch_utils import ten2ar
from spirl.utils.general_utils import batch_apply
class Gaussian:
""" Represents a gaussian distribution """
# TODO: implement a dict conversion fun... |
#-*- coding: utf-8 -*-
""" Use name to identify share isin by using fondout db and google """
"""
1. Lista pa okända shares vi vill söka isin på.
2. Traversera lista.
3. Kontrollera mot shares
4. Kontrollera mot share_company
5. Kontrollera mot shares LIKE från båda håll min chars 5
6. Kontrol... |
"""Provides conversion for transaction data into an exchange format."""
import textwrap
import time
from powl import exception
class TransactionConverter(object):
"""
Provides methods to convert data into a financial exchange format.
"""
def convert(self, date, debit, credit, amount, memo):
""... |
#!/usr/bin/env python
# pylint: disable=wrong-import-position
import os
import subprocess
import sys
import tempfile
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
from xv_leak_tools.helpers import current_os
if len(sys.argv) != 2:
sys.stderr.write("USAGE: setup_python.py virt... |
from otd.skosnavigate import SKOSNavigate
from similarity.csv_parse import get_fragment
from utils.graph import create_bound_graph
def sort_turtle(prefix, identifiers, file_in, file_out):
with open(file_in, encoding='utf8') as fd:
line_iter = iter(fd)
entities = dict()
preamble_finished =... |
import pytest
from ee.clickhouse.queries.groups_join_query import GroupsJoinQuery
from posthog.models.filters import Filter
def test_groups_join_query_blank():
filter = Filter(data={"properties": []})
assert GroupsJoinQuery(filter, 2).get_join_query() == ("", {})
def test_groups_join_query_filtering(snaps... |
import sys
from tkinter import *
from slideShow import SlideShow
if len(sys.argv) == 2:
picdir = sys.argv[1]
else:
picdir = '../gifs'
root = Tk()
Label(root, text="Two embedded slide shows: each side uses after() loop").pack()
SlideShow(msecs=200,
parent=root, picdir=picdir, bd=3, relief=SUNKEN).pa... |
class Transform(object):
"""Transform coordinate systems: scale / translate"""
def __init__(self, scale, translate):
"""Set up the parameters for the transform"""
self.scale = scale
self.translate = translate
def forward(self, pt):
"""From the original box to (-1,-1),(1,1) ... |
from facenet_pytorch import InceptionResnetV1
class SiameseNet(nn.Module):
def __init__(self):
super().__init__()
self.encoder = InceptionResnetV1(pretrained='vggface2')
emb_len = 512
self.last = nn.Sequential(
nn.Linear(4*emb_len, 200, bias=False),
... |
Import("env")
from SCons.Script import COMMAND_LINE_TARGETS
def buildWeb(source, target, env):
env.Execute("cd web; pnpm build")
print("Successfully built webui")
def convertImages(source, target, env):
env.Execute("cd converter; go run .")
print("Successfully converted images")
env.AddPreAction("bui... |
from . import tables
from . unquote import unquote as _unquote
__all__ = 'Quote', 'unquote'
SHORT_ASCII = '\\u{0:04x}'
LONG_ASCII = '\\u{0:04x}\\u{1:04x}'
def Quote(b):
return _QUOTES[bool(b)]
def unquote(s, strict=True):
return _QUOTES[s[0] == tables.SINGLE].remove(s, strict)
class _Quote:
def __in... |
""" predict.py
Predict flower name from an image with predict.py along with the probability of
that name. That is, you'll pass in a single image /path/to/image and return the
flower name and class probability.
Basic usage:
python predict.py /path/to/image checkpoint
Args:
--img
--checkpoint
--top_k
... |
import accounting.config
import pytransact.testsupport
def pytest_configure(config):
global unconfigure
unconfigure = pytransact.testsupport.use_unique_database()
accounting.config.config.set('accounting', 'mongodb_dbname',
pytransact.testsupport.dbname)
def pytest_unconf... |
#!/usr/bin/python3
import math
#Generate the ovsf tree
def ovsfGenerator(numberOfMobile):
#calculate the depth of the OVSF code tree
numberOfColumn = math.ceil(math.log(numberOfMobile,2))
column = [1]
#Generation of the list of codes
for i in range (0,numberOfColumn):
newColumn=[]
xornu... |
from pprint import pprint as pp
from funcs import *
import time
import random
import ConfigParser
config= ConfigParser.ConfigParser()
config.read('config.cfg')
PERIOD = int(config.get('Run','period'))
## currently set to make it so we don't hit window
## rate limits on friendship/show
## should be able to increase t... |
#!/usr/bin/env python3.6
#
# uloop_check.py
#
# Gianna Paulin <pauling@iis.ee.ethz.ch>
# Francesco Conti <f.conti@unibo.it>
#
# Copyright (C) 2019-2021 ETH Zurich, University of Bologna
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
"""Cron job code."""
from google.appengine.ext import ndb
import cloudstorage
import datetime
import logging
from api import PermissionDenied
from model import (Email, ErrorChecker, Indexer, User)
import config
import util
class Cron:
"""A collection of functions and a permission scheme for running cron jobs.
... |
######################################################################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
"""
Operators with arity 2.
Take 2 colors and mix them in some way. Owns two 0/1 arity operators,
which calculate the initial colors.
Adds a shift by colors, that is, for two colors [rgb] + [RGB] can mix as
([rR gG bB], [rG gB bR], [rB gR bG]).
"""
from abc import ABC, abstractmethod
from .base import Operator, ope... |
from urllib.parse import urlparse
def parse_link(link):
href = link.attrs.get("href")
return href and urlparse(href)
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown] slideshow={"slide_type": "slide"}
# ... |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def ani_easy(tas, cmap='BrBG'):
# Get a handle on the figure and the axes
fig, ax = plt.subplots(figsize=(12,6))
# Plot the initial frame.
cax = tas[0,:,:].plot(
add_colorbar=True,
cmap=cmap,
#cmap='BrBG',
#cmap='m... |
from collections import ChainMap, defaultdict
from itertools import chain
import pathlib
import re
from cldfbench import Dataset as BaseDataset, CLDFSpec
from pybtex.database import parse_string
from pydictionaria.sfm_lib import Database as SFM
from pydictionaria.preprocess_lib import marker_fallback_sense, merge_mar... |
import requests
from django.conf import settings
DEBUG = getattr(settings, 'DEBUG')
class AppleService(object):
def __init__(self, base_url):
self.base_url = base_url
def notify_all(self, resources, message):
for resource in resources:
data = '{"resource": "' + resource +... |
from keepkeylib.client import proto, BaseClient, ProtocolMixin
from ..trezor.clientbase import TrezorClientBase
class KeepKeyClient(TrezorClientBase, ProtocolMixin, BaseClient):
def __init__(self, transport, handler, plugin):
BaseClient.__init__(self, transport)
ProtocolMixin.__init__(self, transpo... |
userInput = ('12')
userInput = int(userInput)
print(userInput)
|
import json
import os
from typing import Any, Dict, List, Union
here = os.path.abspath(os.path.dirname(__file__))
def _load_list(paths: List[str]) -> dict:
content: Dict[str, Any] = {}
for p in paths:
with open(p) as h:
t = json.load(h)
content.update(t)
return content
d... |
'''
Copyright (c) 2018 Modul 9/HiFiBerry
2020 Christoffer Sawicki
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,... |
# Module fwpd_histogram
import ctypes as ct
import time
from modules.example_helpers import *
def enable_characterization(ADQAPI, adq_cu, adq_num, channel, enable, only_metadata):
# Enable logic and release reset
assert (channel < 5 and channel > 0), "Channel must be between 1-4."
# Lookup base ... |
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
import pytest
import mlos.global_values
from mlos.OptimizerEvaluationTools.ObjectiveFunctionFactory import ObjectiveFunctionFactory, objective_function_config_store
from mlos.Optimizers.RegressionModels.GoodnessOfFitMetrics import Dat... |
from allauth.account import signals
from allauth.account.views import SignupView
from allauth.account.utils import send_email_confirmation
from allauth.exceptions import ImmediateHttpResponse
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.