content stringlengths 5 1.05M |
|---|
from setuptools import setup
setup(
package_dir={'trprimes': 'src/trprimes'},
packages=['trprimes'],
)
|
# Copyright 2016 Andreas Florath (andreas@florath.net)
#
# 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... |
DATA = 'a'
|
'''
Collection of classes to analyse Quantum efficiency measurements.
General procedure is:
- find factor 'a' of the quadratic scaling of the Single-Shot-Readout as a function of scaling_amp (see SSROAnalysis class)
- find sigma from the Gaussian fit of the Dephasing as a function of scaling_amp (see dephasingAnalysi... |
from gym.envs.registration import register
register(
id='reacher_custom-v0',
entry_point='reacher.envs:ReacherCustomEnv',
max_episode_steps=50,
reward_threshold=-3.75,
)
register(
id='reacher_custom-action1-v0',
entry_point='reacher.envs:ReacherCustomAction1Env',
max_episode_steps=50,
... |
from pathlib import Path
TESTS_DATA_PATH = Path(__file__).parent / 'data'
# These are the last 6 digits in the second line in the ".log" files:
EXPECTED_ACQ_TIME = 143828
|
from django.db import models
import secretballot
class Link(models.Model):
url = models.URLField()
secretballot.enable_voting_on(Link)
# used for testing field renames
class WeirdLink(models.Model):
url = models.URLField()
secretballot.enable_voting_on(WeirdLink,
votes_name='... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Run configuration page."""
# Third party imports
from qtpy.QtWidgets import (QButtonGroup, QGroupBox, QHBoxLayout, QLabel,
Q... |
from random import shuffle
from typing import List
from rest_framework.exceptions import APIException
from data.word_pairs import WORD_PAIRS
from game.constants import QUESTIONS_PER_GAME, ANSWERS_PER_QUESTION
from game.game_utils import GameUtils
from game.models import Question, Game
def create_word_questions(game... |
from PyQt5.QtWidgets import QListWidgetItem
class InputItem(QListWidgetItem):
pass |
# Copyright 2021 Zuva 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 writing, softwa... |
# -*- coding: utf-8 -*-
#===============================================================================
# Author : J.Chapman
# License : BSD
# Date : 4 August 2013
# Description : Python 3 REST server
#===============================================================================
from DefaultHTTPServ... |
from typing import List
def to_header_payload(headers) -> List[dict]:
return [
{'key': key, 'value': value, 'include': True}
for key, value in headers.items()
]
|
"""Cache functions and configuration for styles."""
import re
from datetime import timedelta
from typing import Tuple
from loguru import logger
from nitpick.enums import CachingEnum
REGEX_CACHE_UNIT = re.compile(r"(?P<number>\d+)\s+(?P<unit>(minute|hour|day|week))", re.IGNORECASE)
def parse_cache_option(cache_opti... |
from os import getenv, path
from .settings import get_settings
from base64 import b64encode
from datetime import datetime, date
from decimal import Decimal
import time
from .env import log, clean_html
from urllib.request import quote
from mako.template import Template
import webbrowser
class ArgsWrapper():
def __... |
from django.core.management.base import BaseCommand, CommandError
from ncdjango.models import Service, Variable, SERVICE_DATA_ROOT
from django.db import transaction
import os
import os.path
class Command(BaseCommand):
help = 'Delete an ncdjango service'
def add_arguments(self, parser):
parser.add_arg... |
import os
from shutil import copyfile
import socket
from setuptools import setup, find_packages, Command
from distutils.command.install import install
from distutils.command.sdist import sdist
here = os.path.dirname(os.path.abspath(__file__))
class InstallCommand(install):
user_options = install.user_options
... |
# Generated by Django 3.0.3 on 2020-08-06 15:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0063_auto_20200804_1403'),
]
operations = [
migrations.AlterModelTable(
name='salessubmissioncontent',
table='sales_s... |
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import json
import sys, traceback
#configs
load_dotenv("./config/.env")
TOKEN = os.getenv("token")
PREFIX = os.getenv("prefix")
bot = commands.Bot(command_prefix=f'{PREFIX}')
bot.remove_command('help')
@bot.event
async def on_r... |
#Exploit code by RegaledSeer
import sys
ADDRESS = "\xf4\x96\x04\x08"
SECOND_ADDRESS = "\xf6\x96\x04\x08"
DUMMY_STRING = "AAAA"
DUMMY_STRING_TWO = "BBBB"
FIRST_WRITE = 0x5544
SECOND_WRITE = 0x10102
def find_exploit():
payload = ""
payload += DUMMY_STRING
payload += DUMMY_STRING_TWO
payload += "%12$p"
... |
"""
Some functionality related to dataset
Copyright (C) 2016-2018 Jiri Borovec <jiri.borovec@fel.cvut.cz>
"""
import os
import logging
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from skimage.filters import threshold_otsu
from skimage.exposure import rescale_intensity
TISSUE_CONTENT = 0.01
... |
# -*- coding: utf-8 -*-
import yaml
import os
import numpy as np
import pprint
from core.utils import decode_name
def _decode_yaml_tuple(tuple_str):
return np.array(list(map(lambda x: list(map(int, str.split(x, ','))), tuple_str.split())))
def decode_cfg(path):
print('Loading config from', path)
if not... |
from unittest.mock import patch
import pytest
import harvey.app as app
@pytest.mark.parametrize(
'route',
[
'health',
'pipelines',
# 'pipelines/<pipeline_id>', # TODO: Figure out how to test endpoints with parameters
],
)
def test_routes_are_reachable_get(mock_client, route):
... |
import scrapy
from oslusiadasextract.utils import Utils
from oslusiadasextract.dbconnections.mongo_connection import MongoConnection
utils = Utils()
mongo_connection = MongoConnection()
class SpiderlusiadasSpider(scrapy.Spider):
name = 'spiderlusiadas'
start_urls = utils.generate_chants_links()
def pars... |
from bs4 import BeautifulSoup
import requests
from PIL import Image
from io import BytesIO
import os
def Start():
search=input("Search :")
params={"q":search}
dir_name=search.replace(" ","_").lower()
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
r=requests.get("https://www.bing.co... |
# pylint: skip-file
import ast
import inspect
import pathlib
import asttokens
# import black
def ForeignKey(
to,
on_delete,
related_name=None,
related_query_name=None,
limit_choices_to=None,
parent_link=False,
to_field=None,
db_constraint=True,
**kwargs,
):
pass
sig = inspe... |
from warnings import warn
import pandas as pd
import matplotlib.lines as mlines
from ..utils import make_iterable, SIZE_FACTOR, order_as_mapping_data
from ..exceptions import PlotnineWarning
from ..doctools import document
from ..aes import aes
from .geom import geom
from .geom_segment import geom_segment
@document... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Msticpy... |
# Databricks notebook source
# COMMAND ----------
stats_df = spark.read.parquet("/mnt/group07/final_data_product/classification_result/stats.parquet")
# COMMAND ----------
downloaded_df = spark.read.parquet("/mnt/group07/final_data_product/classification_result/downloaded.parquet")
# COMMAND ----------
downloade... |
import random, sys, time
import numpy as np
from .tournament import TeamTournament
class Optimizer(object):
"""docstring for Optimizer"""
#Population stats
pop_size = 60
runs = 1
elitism = True
#The mutation rate, in percent
mutation_rate = 3
def __init__(self):
super(Optim... |
# -*- coding: utf-8 -*-
import csv, json
import os
import traceback
import settings
import tools
diverse_matcher = {
"Very Diverse": 3, "Moderately Diverse": 2,
"Slightly Diverse": 1, "Not Diverse": 0
}
importance_matcher = {
"Very Important": 3,
"Moderately Important": 2,
"Slightly Important": ... |
from osgeo import gdal
import math
import matplotlib.pyplot as plt
import numpy as np
import os
from osgeo import gdal_array
import pandas as pd
import uuid
import warnings
from .pipesegment import PipeSegment, LoadSegment, MergeSegment
class Image:
def __init__(self, data, name='image', metadata={}):
se... |
import csv
import cv2
import numpy as np
import pandas as pd
import sys
from moviepy.editor import VideoFileClip
from DataGeneration import *
import concurrent.futures
def extract_process(args):
df = args['df']
basedir = args['basedir']
i = args['i']
for index, row in df.iterrows():
print('Pro... |
from abc import ABC, abstractmethod
from typing import List, Optional
import torch
from colossalai.utils import get_current_device
from colossalai.utils.memory import colo_device_memory_capacity
from colossalai.gemini.tensor_utils import colo_model_data_tensor_move_inline, colo_tensor_mem_usage
from colossalai.gemini.... |
n = input("Enter a number: ")
sum = 0
for i in range(1,n+1):
if ((i % 3)==0) or ((1 % 5)==0):
print i
sum = sum + i
print("The sum of 1 to %d, was %d" % (n, sum)) |
from database import Database
from database.users import User
class UserDatabase(Database):
def get_user(self, user: User):
query = (f"SELECT * from {self.database}.discord_users "
f"WHERE discord_id = {user.discord_id};")
with self:
self.cursor.execute(query)
... |
from __future__ import absolute_import
import numpy as np
from .Node import Op
from ..gpu_links import reduce_mean
class ReduceMeanOp(Op):
def __init__(self, node_A, axes, keepdims=False, ctx=None):
super().__init__(ReduceMeanOp, [node_A], ctx)
if axes is not None:
if isinstance(axes, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests the Azure logging collector."""
import unittest
import unittest.mock as mock
from azure.core import exceptions as az_exceptions
from dftimewolf.lib import state
from dftimewolf import config
from dftimewolf.lib.collectors import azure_logging
from dftimewolf.lib... |
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2013 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.... |
import argparse
import glob
import os
import re
import sys
import numpy as np
import pandas as pd
from tqdm import tqdm
NUMBER_OF_ORPH_PER_INDEX = [1, 2, 3, 4, 5, 10, 20, 35, 50, 75, 100, 150, 200]
HIGH_T = 0.75
LOW_T = 0.25
sys.path.append(os.getcwd())
sys.path.append("/cs/usr/drordod/Desktop/project/proj_scwgbs")... |
import unittest
from migrate import Product, Migrate, BaseReadDB, BaseOutputWriterDB
class ProductTestCase(unittest.TestCase):
def test_create_product_instance(self):
product = Product(description='desc', price=123)
self.assertEqual(product.description, 'desc')
self.assertEqual(product.p... |
# -*- coding: utf-8 -*-
MSG = """
%prog <-y> -s filter1 <-s filter2 <-s ...>> -f filterfile file1 file2 file3...
Target files could be pattern strings for globing.
Created on Thu Jun 28 21:10:14 2012 for LSC, MJF, LBH and YSX.
This script was designed for LSC's work on evolution of ST&RM systems in
cya... |
# Bextest.py tests binning algoritms against an existing .sbn file
#
import shapefile
from hasbeen import HasBeen
from bextree import Tree
from mapper import mapshapefile
from spatialindex import SBN
import sys
if len(sys.argv) > 1:
shpfile = sys.argv[1]
else:
print "Usage: bextest.py [shapefile]"
print "... |
from flask import Flask, request, render_template
from indexer import *
from searcher import *
app = Flask(__name__)
init_flag = 0
@app.route('/')
def default():
return render_template('main.html')
@app.route('/', methods=['POST'])
def my_form_post():
query = request.form['query']
if not query:
... |
from cvxopt import matrix, solvers
import numpy as np
def irl(n_states, n_actions, transition_probability, policy, discount, Rmax, l1):
A = set(range(n_actions))
# shape (A, N, N).
transition_probability = np.transpose(transition_probability, (1, 0, 2))
def T(a, s):
"""
Shorthand for ... |
""" Functionality to analyse bias triangles
@author: amjzwerver
"""
# %%
import numpy as np
import qtt
import qtt.pgeometry
import matplotlib.pyplot as plt
from qcodes.plots.qcmatplotlib import MatPlot
from qtt.data import diffDataset
def plotAnalysedLines(clicked_pts, linePoints1_2, linePt3_vert, linePt3_horz, l... |
from rest_framework import serializers
from apps.civic_pulse.models import Agency, Entry
class AgencySerializer(serializers.ModelSerializer):
class Meta:
model = Agency
fields = ['id','name','website','twitter','facebook','phone_number','address','description','last_successful_scrape','scrape_coun... |
# -*- coding: utf-8 -*-
"""
This modual is used for all of the functions related to videos
"""
import cv2
import numpy as np
class Video(object):
"""
This class is used to create the functions that are used for each of the
videos
"""
def __init__(self, path_to_video=0):
self.video = list()... |
"""VISA communication interface for SCPI-based instrument remote control.
:version: 1.18.0.73
:copyright: 2020 by Rohde & Schwarz GMBH & Co. KG
:license: MIT, see LICENSE for more details.
"""
__version__ = '1.18.0.73'
# Main class
from RsInstrument.RsInstrument import RsInstrument
# Bin data format
fro... |
#!/usr/bin/env python2.6
import os
import pytest
from UnofficialDDNS import __doc__ as uddns_doc
from UnofficialDDNS import __version__ as uddns_ver
from docopt import docopt
import libs
def test_config_file_only_with_invalid_binary_data(config_file):
config_file.write(os.urandom(1024))
config_file.flush()
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-11-29 12:13
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('initiatives', '0021_auto_20191129_1132'),
]
operations = [
migrations.RemoveField(... |
from django.contrib import admin
from cms.extensions import PageExtensionAdmin
from .models import MetaAttributes
class MetaAttributesAdmin(PageExtensionAdmin):
exclude = ['plugins']
admin.site.register(MetaAttributes, MetaAttributesAdmin) |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-06 11:51
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):
initial = True
dependencies = [
migratio... |
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from agents.common.networks import *
class Agent(object):
"""An implementation of the Advantage Actor-Critic (A2C) agent."""
def __init__(self,
env,
args,
device,
... |
#version 1
#
#
#Setup data structure
#Made timer that includes fps
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import pyqtgraph as pg
import numpy as np
import random
#import time
from pyqtgraph.ptime import time
import functools
app = QtGui.QApplication([])
w = gl.GLViewWidget()
w.show()
... |
import numpy as np
#differnt operation of numpy library
#ndim is a function which determin about the dimention of the array
#1 dimention array
a= np.array([1,2,3,4,5])
print(a.ndim)
#2 dimention array
a=np.array([(1,2,3),(1,6,5)])
print(a.ndim)
#printing the datatype of an array
a=np.array([("sandip","aditi"),("... |
import asyncio
import logging
import collections
import socket
import ctypes
from functools import partial
from . import constants
from .utils import detect_af
from .baselistener import BaseListener
BUFSIZE = constants.BUFSIZE
def detect_af(addr):
return socket.getaddrinfo(addr,
N... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-24 03:41
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('frbb', '0007_userprofile_withdrawn'),
... |
"""Test data_utils
"""
import pytest
from pytest import fixture
from kipoi.data import PreloadedDataset
import numpy as np
@fixture
def data():
return {"a": [np.arange(3)],
"b": {"d": np.arange(3)},
"c": np.arange(3).reshape((-1, 1))
}
@fixture
def bad_data():
return {"a... |
import time, httplib, urllib2, socket
from lxml import etree
from lxml import objectify
class SruObject:
""" Abstract class for objectifying SRU XML
ZSI attrs: name, typecode
"""
tree = None
def __dir__(self):
attrlist = dir(self)
attrlist.extend(['name', 'typecode'])
... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from mptt_graph.models import GraphModel, TreeNode
@admin.register(GraphModel)
class UrlTreeAdmin(admin.ModelAdmin):
list_display = ["title", "model_path", "model_pk"]
@admin.register(TreeNode)
class TreeNodeAdmin(MP... |
class Grating:
"""A class that describing gratings. Sigma should be in lines/mm and the
units of the dimensions should be mm.
"""
def __init__(self, name='', spacing=600, order=1, height=100, width=100,
thickness=100, blaze=0, type='transmission'):
# define the variables... |
import argparse
import os
import subprocess
VENV_DIR = 'PRE_COMMIT_VENV'
def create_venv_dir():
"""
Create virtualenv for running unit tests
"""
SHELL_EXEC = []
SHELL_EXEC.append(F'set -e')
SHELL_EXEC.append(F'virtualenv {VENV_DIR}')
return_code = os.system(';'.join(SHELL_EXEC))
ret... |
# _*_ coding: utf-8 _*_
"""
@Date: 2021/5/2 4:08 下午
@Author: wz
@File: AssignCookies.py
@Decs:
"""
'''
question:
有一群孩子和一堆饼干,每个孩子有一个饥饿度,每个饼干都有一个大小。
每个孩子只能吃一个饼干,且只有饼干的大小不小于孩子的饥饿度时,这个孩子才能吃饱。求解最多有多少孩子可以吃饱。
example:
输入两个数组,分别代表孩子的饥饿度和饼干的大小。输出最多有多少孩子可以吃饱的数量。
Input: [1,2], [1,2,3]
Output: 2
'''
class Solut... |
from pdb import set_trace as T
import numpy as np
from matplotlib import pyplot as plt
import torch
from visualize import visualize, visGANGAN
from gan import SimpleGAN
gandir = 'data/gan/0/'
gangandir = 'data/gangan/'
fig = plt.figure(frameon=False)
#fig.set_size_inches(16, 4)
ax = plt.Axes(fig, [0., 0., 1., 1.])
... |
# -*- coding: utf-8 -*-
from pandas import DataFrame, Series
from pandas_ta.overlap import ema
from pandas_ta.utils import get_offset, non_zero_range, verify_series
def stc(close, tclength=None, fast=None, slow=None, factor=None, offset=None, **kwargs):
"""Indicator: Schaff Trend Cycle (STC)"""
# Vali... |
from django.contrib import admin
from . models import Message
# Register your models here.
admin.site.register(Message)
|
###############################################################
# Autogenerated module. Please don't modify. #
# Edit according file in protocol_generator/templates instead #
###############################################################
from typing import Dict
from ...structs.api.alter_replica_log_... |
from .base import APIException
class ActivationFinishedException(APIException):
message = "ACTIVATION_ALREADY_FINISHED"
description = "number activation has already been completed"
def __init__(self, response):
super(ActivationFinishedException, self).__init__(description=self.description)
clas... |
# Copyright James Hensman and Max Zwiessele 2014, 2015
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from . import linalg
from .config import config
try:
from GPy_0_8_8.util import choleskies_cython
config.set('cython', 'working', 'True')
except ImportError:
config.set('cy... |
import miniproxypool
import logging
import sys
import time
import requests
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='[%(name)20.20s] [%(asctime)s] [%(levelname)7.7s] [%(threadName)10s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S',)
logging.getLogger('requests').setLevel(logging.WARNING) # su... |
from rpg.items.consumables import Consumable
class Food(Consumable):
config_filename = "consumables/food.yaml"
|
# server code for people to play on
import socket, threading
from queue import Queue
# sockets server famework based on framework from Rohan Varma and Kyle Chin
HOST = ""
PORT = 50003
BACKLOG = 4
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(BACKLOG)
print("waiti... |
import random
from base import BaseMatcher
class VolunteerMatcher(BaseMatcher):
all_text = "volunteer someone"
all_text_other = "volunteer someone else"
dev_text = "volunteer a dev"
dev_text_other = "volunteer another dev"
dev_candidates = ['sjl', 'arthurdebert', 'honza', 'fernandotakai', 'nickse... |
testinfra_hosts = ['clients']
def test_correct_package_versions_are_installed(host):
v = host.ansible.get_variables()
indy_cli = host.package('indy-cli')
assert indy_cli.is_installed
assert indy_cli.version == v['indy_cli_ver']
libindy = host.package('libindy')
assert libindy.is_installed
... |
#!/usr/bin/env python
import readingapi
import argparse
# Arguement parser
parser = argparse.ArgumentParser(description='Summarize reading list data.')
parser.add_argument('-g', '--graph', action="store_true", help='Produces a graph for each year.')
parser.add_argument('-y', '--year', help='A year or comma-separated ... |
import numpy as np
from sklearn.metrics import adjusted_rand_score as sklearn_ari
from clustermatch.sklearn.metrics import (
adjusted_rand_index,
get_contingency_matrix,
get_pair_confusion_matrix,
)
def test_get_contingency_matrix_k0_equal_k1():
part0 = np.array([0, 0, 1, 1, 2, 2])
part1 = np.arr... |
"""
Constants.
Constants for feeds and feed entries.
"""
ATTR_ALERT = "alert"
ATTR_ATTRIBUTION = "attribution"
ATTR_CATEGORY = "category"
ATTR_DESCRIPTION = "description"
ATTR_ID = "id"
ATTR_GUID = "guid"
ATTR_MAG = "mag"
ATTR_PLACE = "place"
ATTR_PUB_DATE = "pubDate"
ATTR_STATUS = "status"
ATTR_TIME = "time"
ATTR_TI... |
#!/usr/bin/python
import json
from ansible.module_utils.basic import AnsibleModule
def main():
fields = {
"project": {"required": True, "type": "str"},
"repository": {"required": True, "type": "str"},
"image_id": {"required": True, "type": "str"},
"state": {
"default":... |
'''
Main entry
'''
from __future__ import absolute_import
import argparse
from py_template.modules.manager import Manager
def menu():
'''
The Menu is here
'''
parser = argparse.ArgumentParser(
description='py_template')
parser.add_argument('-o',
action="store",
... |
"""
Plot comparisons between SIT and SIC modeling experiments using
WACCM4. Subplot includes FIT, HIT, FICT. Composites are
organized by QBO-E - QBO-W
Notes
-----
Author : Zachary Labe
Date : 31 January 2018
"""
### Import modules
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basema... |
# ___declarations in `utilities.py`___
# do update in `utilities.py` if you do any change
#_________________________________________________________________________
import fileinput
from contextlib import contextmanager
@contextmanager
def line_bind(line, *ctors, splitter=lambda l: l.split(' '), do=None):
'''
... |
#!/usr/bin/env python
import sys
import sqlite3
import threading
import json
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
if (sys.version_info > (3, 0)):
import configparser
config = configparser.ConfigParser()
config.read('config.txt')
else:
import ConfigParser
config = ConfigParser.Config... |
from typing import List
from entities.word_evaluation import WordEvaluation
class WordNeighbourhoodStats:
def __init__(
self,
target_word: str,
neighbourhoods: List[List[WordEvaluation]]):
self._target_word = target_word
self._neighbourhoods = neighbourhoods
... |
from misc import util
from collections import namedtuple
import numpy as np
import os
from PIL import Image
import sys
import json
import scipy
import gflags
FLAGS = gflags.FLAGS
USE_IMAGES = False
#N_EX = 6
N_EX = 4
sw_path = os.path.join(sys.path[0], "data/shapeworld")
Fold = namedtuple("Fold", ["hints", "exampl... |
"""
created by ldolin
"""
import sys
import scrapy
from scrapy_demo.tutorial.tutorial.items import MaoyanreyingItem
# sys.path.append('..')
# from items import MaoyanreyingItem
class MaoyanSpider(scrapy.Spider):
name = 'maoyan'
allowed_domains = ['maoyan.com']
start_urls = ['http://maoyan.com/board/7/']
... |
import cv2
import gym
import numpy as np
class MixedGrayscaleColorFrameStack(gym.ObservationWrapper):
"""Stacks the latest frame as color and previous frames as grayscale."""
def __init__(self, env, num_prev_frames=1):
super().__init__(env)
self.num_prev_frames = num_prev_frames
w, h,... |
# -*- coding: utf-8 -*-
import tempfile
import typing
from preview_generator.exception import BuilderDependencyNotFound
from preview_generator.exception import UnsupportedMimeType
from preview_generator.extension import mimetypes_storage
from preview_generator.preview.builder.image__pillow import ImagePreviewBuilder... |
"""
Dubins Rejoin Agent Plant
dubinplant.py
Taken from
> Umberto Ravaioli, James Cunningham, John McCarroll, Vardaan Gangal, Kerianne Hobbs,
> "Safe Reinforcement Learning Benchmark Environments for Aerospace Control Systems,"
> IEEE Aerospace, Big Sky, MT, March 2022.
"""
import numpy as np
def model_output(model... |
#!/usr/bin/env python
from __future__ import print_function
import sys
if __name__ == '__main__':
if len(sys.argv) == 1:
print("Usage: {} <bitboard>".format(sys.argv[0]))
sys.exit(0)
bbrd = int(sys.argv[1])
print(bbrd)
sys.stdout.write('+---+---+---+---+---+---+---+---+\n')
for r... |
import firebase_admin
from firebase_admin import db
from firebase_admin import credentials
import json
import math
import random
from time import sleep as s
from time import time as t
cred = credentials.Certificate("serviceAccount.json")
fb = firebase_admin.initialize_app(cred, options={
"databaseURL": "https://su... |
from homeassistant.const import TEMP_CELSIUS
def field_mask(str_value, from_start=0, from_end=0):
str_mask = "x" * (len(str_value) - from_start - from_end)
return f"{str_value[:from_start]}{str_mask}{str_value[-from_end:]}"
def convert_temp_value(temp_unit, service_code, target_value):
"""Convert from C... |
import json
from collections import OrderedDict
with open("pop_fandoms.json", "r") as f:
temp_list = json.load(f)
mem = []
final = []
for record in temp_list:
url = record["fandom_link"]
if url not in mem:
mem.append(url)
final.append({"fandom": record["fandom"... |
# Usage::
#
# {{thumbnail:.files/img/favicon.png 200x100 exact_size}}
#
# where width = 200 & height = 100
#
# By default, the macro preserves the aspect ratio of the image. If you set 'exact_size', then the generated thumbnail
# will be of the same passed size exactly. 'exact_size' is optional
import os
... |
tags = list()
ticks = list()
urls = list()
#Contain specific info for each video
#CREATOR, VIEWS, TAGS, DATE PUBLISHED
video_info = list()
YOUTUBE = "https://www.youtube.com"
STARTING = "https://www.youtube.com/watch?v=fzQ6gRAEoy0" |
from private.http import Http
from private.cookie import Cookie
class Profile:
def __init__(self):
self.Cookie = Cookie()
self.Http = Http()
def IsAuthorized(self):
if not self.Cookie.GetCookie("Auth"):
print("not logged in")
self.Http.Redirect(303, '/signin')
... |
import argparse
import torch
from bitpack.pytorch_interface import load_quantized_state_dict
parser = argparse.ArgumentParser(description='To unpack models that are packed by BitPack')
parser.add_argument('--device',
type=int,
default=-1,
help='index ... |
#!/usr/bin/env python3
import unittest
from unittest.mock import Mock
from sap.rfc.bapi import (
bapi_message_to_str,
BAPIReturn,
BAPIError
)
def create_bapiret(typ:str=None, message:str=None, msg_class:str=None, msg_number:str=None):
return {'TYPE': typ, 'ID': msg_class, 'NUMBER': msg_number, 'MESS... |
import numpy as np
import numexpr as ne
import numba
from ..misc.numba_special_functions import numba_k0, _numba_k0#, numba_k0_inplace
def generate_modified_helmholtz_functions(k):
@numba.njit("f8(f8,f8,f8,f8)")
def modified_helmholtz_eval(sx, sy, tx, ty):
return _numba_k0(k*np.sqrt((tx-sx)**2 + (ty-sy... |
"""JSON Keys core functions.
JSON Key definition:
An ordered sequence of one or more JSON pointer reference tokens
(Object member key or array index) starting with a root-level
key/index and ending with a reference to some value within the
document.
The last key can optionally be Python slice synt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.