content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
import argparse
import configparser
import getpass
import logging
import os
import requests
import requests_toolbelt
import sys
import urllib3
CURRENT_DIRECTORY = os.path.dirname( os.path.abspath(__file__) )
SOURCE_DIRECTORY = os.path.join( CURRENT_DIRECTORY, 'src' )
sys.path.append( SOURCE_DIRE... |
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distr... |
import pandas as pd
import numpy as np
np.random.seed(101)
df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'.split())
df
print(df)
print('\n')
print(df['W'])
print('\n')
print(df[['W', 'Z']])
|
import duckdb
from datetime import date
from dateutil.relativedelta import relativedelta
import os
import shutil
con = duckdb.connect(database='ldbc.duckdb', read_only=False)
# batches are selected from the [network_start_date, network_end_date) interval,
# each batch denotes a [batch_start_date, batch_end_date) wher... |
import clr
clr.AddReference('System.Management')
clr.AddReference('System')
from System.Management import *
from System import *
class WMISearcher:
def __init__(self, key, attr, objname=None):
self.key = key
self.attributes = attr
self.objname = objname
def get(self, key=None, value=... |
from .urls import LazyUrl
from ..utilities.verify import is_type_of
def is_lazy_url(obj, ignore=False):
""" Check if an object is type LazyUrl """
return is_type_of(obj, LazyUrl, ignore)
|
"""
Test for an education/gender interaction in wages
==================================================
Wages depend mostly on education. Here we investigate how this dependence
is related to gender: not only does gender create an offset in wages, it
also seems that wages increase more with education for males than
f... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('assessments', '0006_question_behavioral_trait'),
]
operations = [
migrations.AddField(
model_name='behavioraltra... |
# This approach doesn't really work but documented anyway
# See for more: https://github.com/openstenoproject/plover/issues/867
import time
import sys
import json
from pythonosc import dispatcher
from pythonosc import osc_server
import pykeyboard
k = pykeyboard.PyKeyboard()
from pynput.keyboard import Key, Controlle... |
import pygame
class Settings:
""" Una clase para almacenar la configuración de celdaTP """
def __init__(self):
""" Inicializa la configuración del juego """
# Configuración de pantalla
self.screen_width = 960
self.screen_height = 540
self.screen = pygame.display.set_mod... |
import random
from discord.ext import commands
class Text():
def __init__(self, bot):
self.bot = bot
@commands.command()
async def clap(self, *, message : str):
"""Repeats the message back with claps in between each word."""
await self.bot.say('👏 {0} 👏'.format(message.replace(' '... |
from datetime import datetime
from volunteercore import db
from volunteercore.mixins import PagininatedAPIMixin
import flask_whooshalchemyplus
tags = db.Table(
'tags',
db.Column('opportunity_id', db.Integer, db.ForeignKey('opportunity.id')),
db.Column('tags_id', db.Integer, db.ForeignKey('tag.id'))
)
cla... |
"""
LC 566
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
The... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2013-2016 Frantisek Uhrecky
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, includ... |
from pathlib import Path
import os, sys, shutil
import subprocess
import pandas as pd
import string
if len(sys.argv) != 2:
print("Usage: ./extract_gps.py <video dir>")
sys.exit()
def convert_latlong(in_str):
split_latlong = in_str.split(' ')
return float(split_latlong[0]) + float(split_latlong[2][:-1]... |
import xml.etree.ElementTree as ET
from os import getcwd
import os
dataset_train = 'data\\Dataset\\train\\'
dataset_file = 'CLASS_test.txt'
classes_file = dataset_file[:-4]+'_classes.txt'
CLS = os.listdir(dataset_train)
classes = [dataset_train+CLASS for CLASS in CLS]
wd = getcwd()
def test(fullname):
bb = ""... |
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
from extorch.nn.modules.operation import ConvBNReLU, Identity, ConvBN
__all__ = [
"ResNetBasicBlock",
"ResNetBottleneckBlock"
]
class ResNetBasicBlock(nn.Module):
r"""
ResNet basic block (`Link`_).
Args:
... |
from django.db import models
class ExampleStory(models.Model):
"""
(ExampleStory description)
"""
headline = models.CharField(max_length=200)
body = models.TextField()
class Meta:
verbose_name_plural = 'example stories'
def __unicode__(self):
return self.headline |
from rest_framework import viewsets, mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Stores, ProductContainer, Products
from stores import serializers
class BasicViewSet(viewsets.GenericViewSet,
m... |
from dialog_bot_sdk.entities.media.FileLocation import FileLocation
from dialog_api import media_and_files_pb2
class AvatarImage:
def __init__(self, file_location: FileLocation, file_size: int, height: int, width: int) -> None:
self.file_location = file_location
self.file_size = file_size
... |
#
# BokehHelp.py -- help classes for Bokeh drawing
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
from ginga import colors
class Pen(object):
def __init__(self, ... |
import string
from unidecode import unidecode
def return_lines(inpath, outpath, term_list, num_lines=3, encoding='utf-8', debug=False):
'''
Takes a file containing text as input. Searches through file for terms in term_list. When a term
is found, takes that line as well as num_lines surrounding that l... |
from ..externals import ExternalAlgorithm
import pypipegraph as ppg
from pathlib import Path
from ..util import download_file
import hashlib
class Salmon(ExternalAlgorithm):
def __init__(self, accepted_biotypes, version="_last_used", store=None):
"""@accepted_biotypes may be a set, or None to use all"""
... |
import json
import logging
from bs4 import BeautifulSoup
from infocrawler.extractor import Extractor
from infocrawler.retrivefeed import retrieve_feed
logger = logging.getLogger(__name__)
def parse_description(description):
"""
Returns a dictionary with serialized description content(images, links and not... |
import math
f = open("p099_base_exp.txt",'r')
curr = 0
linenumber = 0
for index,elem in enumerate(f.readlines()):
base = int(elem.split(',')[0])
exp = int(elem.split(',')[1][:-1])
if exp*math.log(base) > curr:
curr = exp*math.log(base)
linenumber = index
print(curr,linenumber + 1) |
import numpy as np
from py_diff_stokes_flow.env.env_base import EnvBase
from py_diff_stokes_flow.common.common import ndarray
from matplotlib import collections as mc
class FluidicForceDensityEnv2d(EnvBase):
def __init__(self, seed, folder):
np.random.seed(seed)
cell_nums = (64, 48)
E = 1... |
"""Solutions to day 4 parts 1 and 2."""
def load(day):
"""Open specified days input file."""
filename = 'input_{}.txt'.format(str(day).zfill(2))
return open(filename).read()
def is_passphrase_valid(passphrase):
"""Checks if passphrase is valid by checking for
any repeated words."""
valid = Tru... |
# GLOBAL IMPORT (PYTHON PACKAGES)
import logging
# LOCAL IMPORTS
from DecksHandler.deckshandler import DecksHandler # all decks visualization
from Deck.deck import Deck # operations on specific deck
from Session.session import DailySession # session on specific deck
logger=logging.getLogger('flashcards.menu')
de... |
# Generated by Django 3.0.5 on 2020-05-05 07:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0003_contact_date_of_sub'),
]
operations = [
migrations.RenameField(
model_name='contact',
old_name='date_of_sub',
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Shreyas Kulkarni (shyran@gmail.com)
#
# 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 right... |
"""ArangoDB api."""
from functools import wraps, partial
from itertools import chain
from six.moves import map
from six import iteritems
import requests
import requests.adapters
from . import exc
import logging
LOG = logging.getLogger(__name__)
def json_result():
"""Decorate an arango response call to extr... |
from copy import deepcopy
import torch
import torch.nn as nn
from FrEIA.modules import InvertibleModule
class Split(InvertibleModule):
"""Invertible split operation.
Splits the incoming tensor along the given dimension, and returns a list of
separate output tensors. The inverse is the corresponding mer... |
import struct
import binascii
import hashlib
import os
from bitcoinrpc.authproxy import AuthServiceProxy
def get_rpc_connection(rpc_user, rpc_password, rpc_port):
return AuthServiceProxy("http://%s:%s@127.0.0.1:%s"
% (rpc_user, rpc_password, rpc_port))
def uint1(stream):
return ... |
from flask.globals import request
from flask import Blueprint, render_template, flash, redirect
from . import logger
from ..forms.create_filewatch import CreateFileWatch
from ..models import Settings, Watchers
from .. import db, watcher
watch = Blueprint("watch", __name__, template_folder="templates")
@watch.route("/... |
import datetime as dt
from typing import TypedDict
class IGenDailyDataRecord(TypedDict):
genId: int
name: str
vc: float
fuelType: str
targetDt: dt.datetime
avgPuCap: float
tmPu: float
rUpPu: float
rDnPu: float
|
class Email:
def get_email(self, items):
email_string = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; char... |
def load_air_quality_data(dt_unit: str) -> 'DataFrame':
"""
This dataset comes from the
[UCI Machine Learning Data Repository](https://archive.ics.uci.edu/ml/datasets/Beijing+Multi-Site+Air-Quality+Data).
It includes data on air pollutants and weather from 12 sites.
Daqing Chen, Sai Liang Sain, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
@Name: forms.py
@Desc:
@Author: CE SLT-Auto
@Create: 2019.07.04 14:21
-------------------------------------------------------------------------------
@Change: ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ForceRampGUI.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore,... |
# If stdlib threading is imported *BEFORE* monkey patching, *and*
# there is a native thread created, we can still get the current
# (main) thread, and it's not a DummyThread.
# Joining the native thread also does not fail
import threading
from time import sleep as time_sleep
import gevent.testing as greentest
class... |
import matplotlib.pyplot as pl
import numpy as np
from collections import Counter
from smallworld import get_smallworld_graph
from smallworld.theory import get_degree_distribution
from time import time
def get_counter_hist(ks):
c = Counter(ks)
kmax = np.max(ks)
k = np.arange(kmax+1,dtype=int)
s = 0
... |
import re
class Rule:
def __init__(self, lower_range: range, upper_range: range):
self.vals = [i for i in lower_range] + [i for i in upper_range]
class Day16Solution:
def __init__(self):
file = open("day16.txt", "r")
def readline() -> str:
return file.readline()[:-1]
... |
import json
import os
import numpy as np
import matplotlib.pyplot as plt
def _load_dataset_file(dataset_file, split_percentage=0.7):
dataset = np.load(dataset_file).get('data')
labels = np.load(dataset_file).get('labels')
classes = np.load(dataset_file).get('classes')
items = np.asarray([
[d... |
import unittest.mock
import pytest
from .. import admin
from .. import models
from . import factories
class TestAdminUserChangeForm:
def test_clean_password(self):
user = factories.UserFactory.build()
form = admin.AdminUserChangeForm(instance=user)
assert form.clean_password() == user.pas... |
import itertools
with open('day01.input') as f:
data = [int(x) for x in f]
def part1():
return sum(data)
def part2():
current = 0
known_frequencies = {0}
for offset in itertools.cycle(data):
current = current + offset
if current in known_frequencies:
return current
... |
# -*- coding: utf-8 -*-
import uuid
import os.path
import re
from importlib import machinery
def rev_id():
# Took from Alembic...
val = int(uuid.uuid4()) % 100000000000000
return hex(val)[2:-1]
def import_file_as_py(filepath, module_id=None):
"""Load a file from the given path as a Python module.""... |
#!/usr/bin/python3
#
# Id:
#
# We test a bit of the atrshmlog here.
#
# This is for the first starter, so only the basic things.
import sys
import atrshmlog
result = atrshmlog.attach()
n = 1000000
while n > 0:
t1 = atrshmlog.gettime()
atrshmlog.sleep_nanos(n)
t2 = atrshmlog.gettime()
print('sleep n... |
# -*- coding: utf-8 -*-
# # #############################################################################
# Copyright (C) 2022 manatlan manatlan[at]gmail(dot)com
#
# MIT licence
#
# https://github.com/manatlan/htag
# #############################################################################
from .. import Tag
from ... |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... |
"""update project_id column of vrid table as owner
Revision ID: 873ee83aef63
Revises: 9bfc38df2582
Create Date: 2021-06-19 12:39:14.671476
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '873ee83aef63'
down_revision = '9bfc38df2582'
branch_labels = None
depends... |
import os
from invoke import task, run
import yaml
from . import dirs
def plotter_cmd(mode):
if mode == 'development':
cmd = 'python ' + os.path.join(dirs.parent_dir(), 'seaice.tools',
'plotter', 'monthly_extent.py')
else:
cmd = 'plot_monthly_ice_extent... |
# Generated by Django 2.2.6 on 2019-11-18 22:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data_driven_acquisition', '0015_packageproperty_tab'),
]
operations = [
migrations.AlterField(
model_name='packageproperty',
... |
#!/usr/bin/env python3
# pylint: disable=W1401
"""
+---------------------------------------------------------------------+
| _ |
| __ _ _ _ __| |___ __ _ __ _ ___ _ _ |
| / _` | '_|_ / / _ \/ _` / _` / -_) ... |
import random
from ..utils import lazy_set_generator, lerp
class Hex(object):
_addition_error = NotImplementedError(
f'You must provide a Hex subclass for addition.')
_multiplication_error = NotImplementedError(
f'This Hex can only be multiplied by a scalar.')
def __init__(self, q, r):
... |
# (C) Datadog, Inc. 2010-2017
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
from __future__ import unicode_literals
from datetime import timedelta
from Queue import Empty, Queue
import re
import ssl
import time
import traceback
from pyVim import connect
from pyVmomi import vim # pylint: ... |
#!/usr/bin/env python3
import fileinput
from itertools import permutations
from threading import Thread
from queue import Queue
class Intcode(Thread):
def __init__(self, memory, input_queue, output_queue):
super(Intcode, self).__init__()
self.ic = 0
self.memory = memory
self.input_q... |
# ------------------------------
# 353. Design Snake Game
#
# Description:
# Design a Snake game that is played on a device with screen size = width x height. Play
# the game online if you are not familiar with the game.
#
# The snake is initially positioned at the top left corner (0,0) with length = 1 unit.
# You a... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
# 同一批数据分两个,毕竟是来自不同的请求
# 之后 pipeline 处理的时候合并
class PositionItem(scrapy.Item):
""" 和 json 中的键名保持一致
"""
positionId = scrapy.Field() ... |
from .mbqvi import MBQVIAgent
|
import serial
|
import iraf
no = iraf.no
yes = iraf.yes
from axe import axesrc
#import axesrc
# Point to default parameter file for task
_parfile = 'axe$gol2af.par'
_taskname = 'gol2af'
######
# Set up Python IRAF interface here
######
def gol2af_iraf(grism,
config,
mfwhm,
back,
... |
# Created by Mert Sevindik 08.08.2020
# A dict with key = question and value = vector
class DataModel:
import numpy as np
import json
with open('answers.json') as f:
data=json.load(f)
buildings = 1
math = 1
science = 1
garedening = 1
biology = 1
nature = 1
planning = ... |
#!env python3
'''
PDF encrypter with PyPDF2
'''
import os
import sys
import PyPDF2
def walk_tree(folder):
for folder, subfolders, filenames in os.walk(folder):
for filename in filenames:
filepath = ''.join( (folder,"/",filename) )
print(filepath)
pdfreader = PyPDF2.PdfFi... |
import pandas as pd
import matplotlib.pyplot as plt
from time import sleep
from random import randrange
df = pd.read_csv("data.csv")
data = [[row[1], row[2], int(row[3]), row[4]] for index, row in df.iterrows()]
data.sort()
# find neighbor points
def find_neighbors(x, y, point_locs):
# calculate with radius of 3... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:/Users/royal state/PycharmProjects/Arduino-Oscilloscope/src/MainWindowFrontEnd.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class... |
# movida_reg.py.py
"""A script designed to update the registration messages for a set location"""
import json
import requests
import os
import socket
from pathlib import Path
import sys
sys.path.append(str(Path(__file__).absolute().parents[3]))
from WP5.KU.definitions import KU_DIR
import WP5.KU.SharedResources.loader_... |
import os
import io
from paradox import GLOVE_FOLDER
def map_dim_to_file(dim=200):
if dim == 50:
return os.path.join(GLOVE_FOLDER, "glove.6B.50d.txt")
elif dim == 100:
return os.path.join(GLOVE_FOLDER, "glove.6B.100d.txt")
elif dim == 200:
return os.path.join(GLOVE_FOLDER, "glove.6... |
from enum import Enum
def from_short_name(short_name: str):
for typeofword in TypeOfWord:
value = typeofword.value().get('short_name')
if value == short_name:
return typeofword
class TypeOfWord(Enum):
CC = {'full_name': "coordinating conjunction", 'short_name': "CC", 'example': "... |
from django.apps import AppConfig
class VposConfig(AppConfig):
name = 'vpos'
verbose_name = 'Django vPOS'
def ready(self) -> None:
from vpos.configs import conf
conf.validate()
|
#!/usr/bin/env python
# MPI_TAG_UB >= 32767
# Update: the tag is no longer stored using the tag argument.
# It is stored in the buffer.
import random
# max = 32767
# the maximum value of a int is 2147483647
max = 4194304
value = random.randint(0, max)
hexadecimal = hex(value).replace('x', '')
#print("DEBUG " + hex... |
import csv
import os
from datetime import datetime, date
import xml.etree.ElementTree as ET
from django.db import models
from django.utils.timezone import now
from django.core.validators import FileExtensionValidator
from django.utils.translation import gettext as _
from .choices import CAT
class Invoice(models.Mode... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Siddhant and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
import ast
from datetime import date
class EnrollChildren(Document):
pass
def create_invoice... |
"""
título: conjuntos_adyacentes.py
descripción: calcula todos los conjuntos que se pueden generar siguiendo la relación de adyacencias
(no reflexiva)
autor: -h
fecha: 2019-06
"""
def conjuntos_adyacentes(componentes, adyacencias):
conjuntos = []
for cmpt in componentes:
conjuntos.append([cmpt])
fo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Yuki Furuta <furushchev@jsk.imi.i.u-tokyo.ac.jp>
from __future__ import print_function
import argparse
import cv2
import os
import rospy
import sys
import time
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
from SocketServ... |
#!/usr/bin/env python
"""
Lynxmotion.py: Manual control module for Lynxmotion 4WD3 rover.
Bluetooth gamepad is used for input and RasPiRobot board v3
provides interface with motors.
"""
__author__ = "Murray Ireland"
__email__ = "murray@murrayire.land"
__date__ = "20/01/17"
import time
from adafruitDriver impor... |
"""Customized configuration from pydantic to work with models and schemas."""
import datetime
import bson
import pydantic
import pydantic.json
try:
import orjson
json_dumps = orjson.dumps
json_loads = orjson.loads
except ImportError:
import json
json_dumps = json.dumps
json_loads = json.load... |
from anonymizer.anonymization.anonymizer import Anonymizer
__all__ = ['Anonymizer']
|
# coding: latin-1
calendario = {1: 'janeiro', 2: 'fevereiro', 3: 'março', 4: 'abril', 5: 'maio', 6: 'junho', 7: 'julho', 8: 'agosto', 9: 'setembro', 10: 'outubro', 11: 'novembro', 12: 'dezembro'}
aniversario = {1: 'Mário', 2: 'Pedro', 3: 'Gustavo', 4: 'Altair', 5: 'Joaquim', 6: 'Alfredo', 7: 'Manoel', 8: 'Eduardo', 9:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'valerio cosentino'
import multiprocessing
import time
def empty_queue(q):
while not q.empty():
q.get()
def check_queue_size(q, max_q, sleep_time):
while q.qsize() > max_q:
time.sleep(sleep_time)
def add_poison_pills(num_consumers... |
from bluebottle.initiatives.tests.factories import InitiativeFactory
from django.contrib.admin.sites import AdminSite
from bluebottle.bb_follow.admin import FollowAdmin
from bluebottle.bb_follow.models import Follow
from bluebottle.test.factory_models.accounts import BlueBottleUserFactory
from bluebottle.test.factory_... |
#! /usr/bin/env python
# setup.py
# Install script for unittest2
# Copyright (C) 2010 Michael Foord
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# This software is licensed under the terms of the BSD license.
# http://www.voidspace.org.uk/python/license.shtml
import os
import sys
from unittest2 import __version__ a... |
import sys
from scapy.all import *
interface = "en0"
def callBackParser(packet):
if IP in packet:
source_ip = packet[IP].src
destination_ip = packet[IP].dst
if packet.haslayer(DNS) and packet.getlayer(DNS).qr == 0:
print("From : " + str(source_ip) + " to -> " + str(destination_... |
import os
import tvm
from tvm.contrib import cc, util
def test_add(target_dir):
n = tvm.var("n")
A = tvm.placeholder((n,), name='A')
B = tvm.placeholder((n,), name='B')
C = tvm.compute(A.shape, lambda i: A[i] + B[i], name="C")
s = tvm.create_schedule(C.op)
bx, tx = s[C].split(C.op.axis[0], f... |
#!/bin/usr/python3 -B
# -*- coding: utf-8 -*-
'''This class handles the reading and possibly writing of the config file.
'''
import os
import configparser
class Configurator():
'''The Configurator handles the config file things for Beep Inn
'''
configpath = ''
config = configparser.ConfigParser()
def __init__(... |
import torch
from overrides import overrides
from summarize.modules.generate_probability_functions import GenerateProbabilityFunction
@GenerateProbabilityFunction.register('onmt')
class ONMTGenerateProbabilityFunction(GenerateProbabilityFunction):
"""
Computes the generation probability according the functio... |
from gym import error
from gym.utils import seeding
def test_invalid_seeds():
for seed in [-1, "test"]:
try:
seeding.np_random(seed)
except error.Error:
pass
else:
assert False, "Invalid seed {} passed validation".format(seed)
def test_valid_seeds():
... |
# -*- coding: utf-8 -*-
# http://www.apache.org/licenses/LICENSE-2.0.txt
#
# Copyright 2016 Intel Corporation
#
# 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/lic... |
from characters.base import Character
from random import randint
class Medic(Character):
def __init__(self, health, power):
super().__init__(health, power, bounty=10)
def attacked_response(self):
"""the medic has a 20% chance of healing self"""
if randint(0, 100) < 20:
... |
from struct import pack, unpack
from bisect import bisect_right as bisect
from google.protobuf.message import Message
from google.protobuf.descriptor import Descriptor, FileDescriptor, FieldDescriptor, EnumDescriptor, EnumValueDescriptor
from google.protobuf.descriptor_pb2 import FileDescriptorProto
from a4.io.A4Stre... |
"""
TGStreamingBot, Telegram Video Chat Bot
Copyright (c) 2021 Jins Mathew
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... |
import sys, subprocess, os.path
from os import path
if len(sys.argv) > 2:
prefix = sys.argv[1]
targetLanguage = sys.argv[2]
else:
print("please provide the prefix and the target language")
exit(-1)
print("## move, prefix: " + prefix + ", targetLanguage: " + targetLanguage)
filePath = "build/" + prefi... |
"""Quarg: Zero-effort CLI generation.
To add basic automatic parsing to a script, import this module and add
the following at the end:
quarg.main()
This function will process command line arguments only when the file
is run as a script, not when imported as a module. See the README file
for more details.
"""
fr... |
__author__ = 'Mohammad Yousuf Ali, aliyyousuf@gmail.com, fb.com/aliyyousuf'
# Write a function named calculate_expenses that receives a filename as argument. The file contains the information
# about a person's expenses on items. Your function should return a list of tuples sorted based on the name of the items.
# Ea... |
from typing import Generator
import pytest
import shutil
from mlrun.api.db.filedb.db import FileDB
from mlrun.api.db.session import create_session, close_session
from mlrun.api.db.sqldb.db import SQLDB
from mlrun.api.db.sqldb.session import _init_engine
from mlrun.api.initial_data import init_data
from mlrun.api.util... |
#!/usr/bin/python3
input = []
with open('09/input.txt', 'r') as f:
for line in f.readlines():
row = [int(x) for x in line.strip()]
input.append(row)
risk_levels = []
for j in range(0, len(input)):
row = input[j]
for i in range(0, len(row)):
isLow = True
if i > 0:
... |
# -*- coding:utf-8 -*-
import os
import sys
class PSC:
def __init__(self, file, version=3):
# Get path and filename.
self.path, self.file = os.path.split(file)
if self.path == '':
self.path = os.getcwd()
# Initialization.
self.content = []
self.version =... |
"""
Copyright 2021 Inmanta
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 ... |
from django.db import IntegrityError
from django.db.models import Prefetch
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from treeckle.common.exceptions import BadRequest
from treeckle.common.parsers import parse_ms_timestamp_to_datetime
from t... |
# encoding: utf-8
# pylint: disable=missing-docstring
import pytest
from app import create_app
@pytest.mark.parametrize('flask_config', ['production', 'development'])
def test_create_app(flask_config):
create_app(flask_config=flask_config)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.