content stringlengths 5 1.05M |
|---|
""" A class to send updateable content messages to Telegram. """
import os
import json
import imghdr
from uuid import uuid4
from io import BytesIO
from concurrent.futures import ThreadPoolExecutor
from urllib3 import PoolManager
class TelegramMessage:
""" Class to send a message with text or image (either a mat... |
from setuptools import setup
import setuptools, os
descr = 'Image process framework based on plugin like imagej, it is esay to glue with scipy.ndimage, scikit-image, opencv, simpleitk, mayavi...and any libraries based on numpy'
def get_data_files():
dic = {}
for root, dirs, files in os.walk('imagepy', True):
... |
import torch
import torchvision
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
# Writer will output to ./runs/ directory by default
writer = SummaryWriter()
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
trainset = datasets... |
#!/usr/bin/env python
# Execute this script to run through all tests (wrap, build, run).
# Check that the correct Fortran compiler is set in Tests.mk. If
# necessary, add "-c gfortran" to OPTS below (gfortran name mangling
# is currently the default)
from __future__ import print_function
import sys
import os
import ... |
from dataclasses import dataclass
from typing import List
@dataclass
class InceptionConfiguration:
smiles: List[str]
memory_size: int
sample_size: int
|
# Solution of MarchCode Day 3
print("""Choose a number corresponding to the month
1. January
2. February
3. March
4. April
5. May
6. June
7. July
8. August
9. September
10. October
11. November
12. December""")
n =int(input("Enter the number here: \n"))
if (n == 1 or n == 3 or n == 5 or n == 7 or n == 8 or n == 10 o... |
from libai.config import LazyCall
from omegaconf import OmegaConf
from libai.data import build_nlp_test_loader, build_nlp_train_val_test_loader
from libai.data.datasets import GPT2Dataset
from libai.data.data_utils import get_indexed_dataset
from libai.tokenizer import GPT2Tokenizer
tokenization = OmegaConf.create()... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
''' Computational semantics course @ RUG-2019
Lecturer: L.Abzianidze@rug.nl
Assignment 4: Natural language inference with first-order logic theorem proving
'''
def codalab_html(scores, cm, filename):
'''Write an html file with scores and a confusion matrix
... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or '**************'
MYSQL_USER = os.environ.get('MYSQL_DATABASE_USER') or 'root'
MYSQL_PASSWORD = os.environ.get('MYSQL_DATABASE_PASSWORD') or ''
MYSQL_DB = os.environ.get('MY... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import ctypes
import random
from . import BaseExecutableDriver
from .helper import array2pb, pb_obj2dict, pb2array
class BaseCraftDriver(BaseExecutableDriver):
"""Drivers inherited from this Driver will bind :m... |
from flask import Flask, request, redirect, render_template, flash, jsonify
from flaskmogrify.forms import TransmogrificationForm
__author__ = 'Daniel Langsam'
__email__ = 'daniel@langsam.org'
__version__ = '0.0.16'
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
SECRET_KEY='super... |
from liesym import F4, E, Basis
from sympy import Matrix, Rational, S
def test_F4():
F4_ = F4()
# test subclass items
assert F4_.dimension == 4
assert F4_.n_pos_roots == 24
assert F4_.simple_roots == [
Matrix([[1, -1, 0, 0]]),
Matrix([[0, 1, -1, 0]]),
Matrix([[0, 0, 1, 0]... |
import typing
from eth2spec.fuzzing.decoder import translate_typ, translate_value
from eth2spec.phase0 import spec
from eth2spec.utils import bls
from eth2spec.utils.ssz.ssz_impl import serialize
from preset_loader import loader
# TODO(gnattishness) fix config path difficult to do unless we assume the eth2spec
# modu... |
import re
from wedc.domain.core.data import cleaner
from wedc.domain.vendor.crf.crf_tokenizer import CrfTokenizer
def parse(text):
text = text_preprocessing(text)
t = CrfTokenizer()
t.setRecognizeHtmlEntities(True)
t.setRecognizeHtmlTags(True)
t.setSkipHtmlTags(True)
tokens = t.tokenize(text)... |
a = [1,9,8,7]
b = a[:]
b[2] = 7
print(f'Lista A: {a}')
print(f'Lista B: {b}') |
class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
str_ = str.split(" ")
dic_s = {}
dic_p = {}
res_s = []
res_p = []
for i in range(len(str_)):
if str... |
import unittest
from katas.kyu_7.tube_strike_options_calculator import calculator
class TubeStrikeTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(calculator(5, 6, 1), 'Bus')
def test_equals_2(self):
self.assertEqual(calculator(4, 5, 1), 'Walk')
def test_equals_3(sel... |
"""
Copyright (c) 2013, SMART Technologies ULC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the fo... |
# Copyright 2018 Ildar Nasyrov <https://it-projects.info/team/iledarn>
# License MIT (https://opensource.org/licenses/MIT).
from odoo.tests.common import TransactionCase
class TestDeliveryCarrierSecurity(TransactionCase):
at_install = True
post_install = True
def setUp(self):
super(TestDeliveryCa... |
#!/usr/bin/env python
import json
from os import path
import sys
from time import time_ns
from gpiozero import DigitalOutputDevice
def load_data(command):
with open(path.join(path.dirname(path.realpath(__file__)), 'commands', command + '.json')) as file:
return json.load(file)
def transmit_data(data):
... |
import configparser
import sys
import requests
import yara
ERROR_CODE = 1
def DownloadFile(url, rulefile):
r = requests.get(url, stream=True)
with open(rulefile, 'wb') as f:
for chunk in r.iter_content(chunk_size=(100*1024)):
if chunk:
f.write(chunk)
def main():
""" M... |
import os
genDir = os.path.join(os.path.dirname(os.path.relpath(__file__)),"../")
dir_name = 'run'
folders = os.listdir(genDir + "./%s"%(dir_name))
current = os.getcwd()
print("Temp,Frequency,Power,Error")
#print(current)
for folder in folders:
os.chdir("%s/%s/%s"%(current,dir_name,folder))
os.system("source cal_res... |
from . import core
from . import random
from .core import *
from .random import *
|
'''
Created on Dec 12, 2020
@author: liu.zhengr
'''
import socket
import os
import sys
import struct
class ImageSocketConnector():
def __init__(self):
self.address = ('127.0.0.1', 5612)
def send(self, filePath:str):
"""Send picture to server
param: filePath File path
""... |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""
Given an array nums of n integers, are there elements
a, b, c in nums such that a + b + c = 0? Find all unique
triplets in the array which gives the sum of zero.
Notice that the solution s... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------------------------------------------------
# arclytics_sim
# utilities.py
#
# Attributions:
# [1]
# ----------------------------------------------------------------------------------------------------------------------... |
import tensorflow as tf
from tensorflow.keras import layers, Sequential, Model
class BasicBlock(layers.Layer):
def __init__(self, kernels, stride=1):
super(BasicBlock, self).__init__()
self.features = Sequential([
layers.Conv2D(kernels, (3, 3), strides=stride, padding='same'),
... |
from six.moves import cStringIO
from pysmt.smtlib.parser import SmtLibParser
from pysmt.shortcuts import get_model, Solver
import types
DEMO_SMTLIB= \
"""
(set-logic QF_AUFBV )
(declare-fun A-data () (Array (_ BitVec 32) (_ BitVec 8) ) )
(assert (and (= (_ bv108 8) (select A-data (_ bv2 32) ) ) (= (_ bv101 8) (select ... |
"""
Module dependencies:
all - {core, files_management, utils} -> prepostprocessing
"""
import datetime
import logging
import urllib
import urllib.request
import urllib.response
from typing import Tuple
import lxml
import lxml.etree
import lxml.html
import retrying
import core
import files_management as fm
lo... |
# Test Helpers
from django.test import TestCase, Client
from django.urls import reverse
import json
# Models
from ...models.author import Author
from ...models.signupRequest import Signup_Request
class TestAuthView(TestCase):
def setUp(self):
self.client = Client()
# Urls
self... |
import streamlit as st
import visao_geral
import estacao
import responsavel
# Hide Menu
hide_streamlit_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
st.image("imgs/smtr-logo.jpeg")
st.title("Avaliação das estaç... |
# Feel free to modify and use this filter however you wish. If you do,
# please give credit to SethBling.
# http://youtube.com/SethBling
from pymclevel import TAG_List
from pymclevel import TAG_Byte
from pymclevel import TAG_Int
from pymclevel import TAG_Compound
from pymclevel import TAG_Short
from pymclevel import T... |
from websiteapp import models
from rest_framework.serializers import ModelSerializer,SerializerMethodField
class IconSerializer(ModelSerializer):
handle_link = SerializerMethodField()
class Meta:
model = models.WebSite
fields = ['icon','handle_link']
def get_handle_link(self, instance):
... |
from bs4 import BeautifulSoup
from IPython import embed
def generate_html():
return """
<html>
<head></head>
<body>
<a href="/a.html">A</a>
<a href="/b.html">B</a>
<a href="/c.html">C</a>
<a href="/d.html">D</a>
... |
import os
from sqlalchemy import create_engine
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import jinja2
import requests, json
from datetime import datetime
# Finding all our directories for this template
base_dir = os.path.abspath(os.path.join(os.path.dirname( ... |
import json
from typing import List
from odm2_postgres_api.schemas.schemas import (
SamplingFeaturesCreate,
MethodsCreate,
VariablesCreate,
ControlledVocabularyCreate,
AnnotationsCreate,
DirectivesCreate,
)
def mass_spec_annotations() -> List[AnnotationsCreate]:
mass_spec_annotations_list... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Donny You(youansheng@gmail.com)
# Loss function for Image Classification.
import torch.nn as nn
from model.pose.loss.mse_loss import MseLoss
BASE_LOSS_DICT = dict(
mse_loss=0,
)
class Loss(nn.Module):
def __init__(self, configer):
super(Loss,... |
#
# Copyright (c) 2017 Electronic Arts Inc. All Rights Reserved
#
import datetime
import urllib2
import json
import time
import os
import logging
from ava.settings import BASE_DIR
from base64 import b64encode, b64decode
from rest_framework import viewsets
from models import CaptureNode, Camera, CaptureLocation
fr... |
import re
import torch
from .encode import EncodedParam, EncodedModule
from ..utils import AverageMeter
class Codec(object):
def __init__(self, rule):
"""
Codec for coding
:param rule: str, path to the rule file, each line formats
'param_name coding_method bit_leng... |
# 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 agreed to in writing... |
import unittest
from unittest.mock import patch
from tmc import points
from tmc.utils import load, load_module, reload_module, get_stdout, check_source
from functools import reduce
import os
import textwrap
from random import randint
exercise = 'src.items_multiplied_by_two'
function = 'double_items'
@points('5.doub... |
from .conv_expanded_weights import ConvPerSampleGrad
from .embedding_expanded_weights import EmbeddingPerSampleGrad
from .linear_expanded_weights import LinearPerSampleGrad
from .expanded_weights_impl import ExpandedWeight
__all__ = ['ExpandedWeight']
|
import os
import sys
import re
import _bibtex
f = _bibtex.open_file(sys.argv[1], True)
l = []
while 1:
entry = _bibtex.next_unfiltered(f)
if entry is None:
break
if entry[0] != 'entry':
# skip
continue
l.append(entry)
pubs = ""
for entry in l:
name = entry[1][0]
en... |
from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts imp... |
from functools import reduce
from rnnr import Event
from rnnr.attachments import LambdaReducer
def test_ok(runner):
outputs = [4, 2, 1, 5, 6]
batches = range(len(outputs))
@runner.on(Event.BATCH)
def on_batch(state):
state["output"] = outputs[state["batch"]]
r = LambdaReducer("product",... |
"""
Your task is to find the first element of an array that is not consecutive.
By not consecutive we mean not exactly 1 larger than the previous element of the array.
E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number.
If ... |
import apsw
from time import time
from itertools import product
from CONFIGURATION import *
from hasher import *
letter = "abcdefghijklmnopqrstuvwxyz "
print("\nCreating New Rainbow Table\n\nEnter Security Code:")
securecode = input()
memdb = apsw.Connection(":memory:")
memdbc = memdb.cursor()
memdbc.execute("CREATE... |
"""
The yelp dataset *business.json file has lat and long as a separate keys, however MongoDB wants
them to be under the same key to create a 2D index
The data generated here can be imported as:
mongoimport --db yelpdata --collection business --jsonArray --file out.json
"""
import json
def main(f, o):
"""
f... |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# pool2d paddle model generator
#
import numpy as np
from save_model import saveModel
import sys
def paddle_dropout(name : str, x, p, paddle_attrs):
import paddle
paddle.enable_static()
with paddle.static.program_gua... |
# $Id$
#
# @rocks@
# Copyright (c) 2000 - 2010 The Regents of the University of California
# All rights reserved. Rocks(r) v5.4 www.rocksclusters.org
# https://github.com/Teradata/stacki/blob/master/LICENSE-ROCKS.txt
# @rocks@
#
# $Log$
# Revision 1.4 2010/09/07 23:52:54 bruno
# star power for gb
#
# Revision 1.3 20... |
burger = []
drink = []
a = int(input())
burger.append(a)
b = int(input())
burger.append(b)
c = int(input())
burger.append(c)
d = int(input())
drink.append(d)
e = int(input())
drink.append(e)
burger.sort()
drink.sort()
print(burger[0] + drink[0] - 50)
|
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template("landing_page.html")
@app.route('/ninjas')
def ninjas():
return render_template("ninjas.html")
@app.route('/dojo')
def dojo():
return render_template("dojo.html")
app.run(debug=True) |
# Copyright 2016 The Closure Rules 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 appli... |
from main.classes.SQLIOHandler import SQLIOHandler
from os import sys
if __name__ == "__main__":
# alphaAPIHTTPHandler = AlphaAPIHTTPHandler("symbols", "SYMBOL")
# alphaAPIHTTPHandler.GenerateJsonSymbolOverviewRepository()
sQLIOHandler = SQLIOHandler()
sQLIOHandler.ProcessAllJsonFilesIntoDatabase()... |
import sys
import matplotlib.pyplot as plt
import numpy as np
training_data_path = '../resources/training_data.txt'
plot_path_g = '../resources/training_data_g.jpg'
plot_path_t = '../resources/training_data_t.jpg'
generations, time_stamps, best_durations, average_durations = np.loadtxt(training_data_path, u... |
from .CheckCase import CheckCase
from .CheckCommandLineArguments import CheckCommandLineArguments
|
from django.db import models
from drf_yasg import openapi
from rest_framework import serializers
SessionParameter = [
openapi.Parameter(
name='Cookie', in_=openapi.IN_HEADER,
type=openapi.TYPE_STRING,
description="Cookie",
required=True,
default=""
),
openapi.Paramet... |
import pytest
import numpy as np
from dftfit.io.siesta import SiestaReader
@pytest.mark.siesta
def test_siesta_reader():
filename = 'd3_o_20ev.xml'
directory = 'test_files/siesta'
calculation = SiestaReader.from_file(directory, filename)
assert np.all(np.isclose(calculation.energy, -104742.133616))
... |
import pytest
from dethinker.users.models import User
from dethinker.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> User:
return UserFactory()
|
# -*- test-case-name: xquotient.test.historic.test_filter3to4 -*-
"""
Stub database generator for version 3 of L{Filter}.
"""
from axiom.test.historic.stubloader import saveStub
from axiom.dependency import installOn
from xquotient.spam import Filter
USE_POSTINI_SCORE = True
POSTINI_THRESHHOLD = 0.5
def createDat... |
import pandas as pd
import zipfile
from os.path import splitext
import numpy as np
from .timers import Timer
class FixedSizeEventReader:
"""
Reads events from a '.txt' or '.zip' file, and packages the events into
non-overlapping event windows, each containing a fixed number of events.
"""
def __i... |
from __future__ import print_function
import argparse
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from utils.prior_box import PriorBox
import cv2
from models.model.retinatrack import RetinaTrackNet
from config.config import cfg_re50
from utils.box_utils import decode
import time
import torchvis... |
# -*- coding: utf-8 -*-
"""
* TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-蓝鲸 PaaS 平台(BlueKing-PaaS) 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 co... |
#!/usr/bin/env python
# coding: utf-8
r"""STEP morphing example"""
import logging
import pygem as pg
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s :: %(levelname)6s :: '
'%(module)20s :: %(lineno)3d :: %(message)s')
han... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright(c) 2018 Nippon Telegraph and Telephone Corporation
import eventlet
eventlet.monkey_patch()
import argparse
import errno
import json
import logging
import os
import socket
import subprocess
import spp_proc
import spp_webapi
LOG = logging.getLogger(__name__)
MSG_S... |
import numpy as np
class Stats:
def __init__(self, workers, total_requests, total_time_sec, times, error_count):
self.workers = workers
self.total_requests = total_requests
self.total_time_sec = total_time_sec
self.times = times
self.error_count = error_count
def print... |
from .boolalg import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, Implies,
Equivalent, ITE, POSform, SOPform, simplify_logic,
bool_equal, bool_map, true, false)
from .inference import satisfiable
|
# -*- coding: utf-8 -*-
from classes.om import ObjectManager
from classes.ui import UIManager
#
from classes.om import Well
from classes.om import DataIndex
from classes.om import DataIndexMap
from classes.om import Log
from classes.om import CurveSet
from classes.om import Seismic
from classes.om import Spectogram
fr... |
from django.contrib import admin
from . import models
class QuestionAdmin(admin.ModelAdmin):
list_display = ('content', 'answer', 'category',
'created_at', 'updated_at')
list_filter = ('category', 'created_at')
search_fields = ('content',)
# Limit the dropdown choices of category... |
from mergeit.extras.filters import RedmineFilter
class VersionRedmineFilter(RedmineFilter):
def run(self, source_match, source_branch, target_branch):
task = self.get_task(source_match.groupdict()['task_id']) # TODO: compare commit message task with branch name?
return target_branch.format(redmin... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014, Almar Klein
""" Simple IPC based on a persistent socket pair.
"""
import os
import sys
import time
import socket
import threading
# Python 2.x and 3.x compatibility
if sys.version_info[0] >= 3:
string_types = str,
else:
string_types = basestring,
## Constants
#... |
# <p>
__title__ = 'pnbp'
__description__ = 'pretty notebook parser'
__url__ = 'https://github.com/prettynb/pnbp'
__version__ = '0.8.6'
__build__ = 0x111000
__author__ = 'Ellenurb Sitruc'
__author_email__ = 'ellenurbsitruc@gmail.com'
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2021 prettynb'
# <script>
__... |
######################################
# Thank You Allah Swt.. #
# Thanks My Team : Hacker Cyber Team Tegal #
# Thnks You All My Friends me. #
# Thanks All Member BCC : #
# Leader : Hamdhan channel97 #
# CO Founder : Mr.Hamdan #
# CO Leader : Tegal ... |
def get_headers(http_resp):
spisok = http_resp.split("\n")
del spisok[0]
del spisok[spisok.index("") :]
slovar = {}
for chast in spisok:
head = chast.split(": ")
slovar[head[0]] = head[1]
return slovar
|
import sys, collections
def solution(L):
P = collections.defaultdict(int)
for (x, y), (x2, y2) in L:
P[x, y] += 1
dx, dy = (x2 > x) - (x2 < x), (y2 > y) - (y2 < y) # cmp
while x != x2 or y != y2:
x += dx; y += dy
P[x, y] += 1
return sum(p > 1 for p in P.v... |
import json
import requests
import time
from merkato.exchanges.exchange_base import ExchangeBase
from merkato.constants import MARKET
from binance.client import Client
from binance.enums import *
from math import floor
import logging
from decimal import *
from requests.adapters import HTTPAdapter
s = requests.Session(... |
"""
Tests for coroutines, for Python versions that support them.
"""
import sys
if sys.version_info[:2] >= (3, 5):
from .corotests import CoroutineTests, ContextTests
__all__ = ["CoroutineTests", "ContextTests"]
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 15:02:49 2018
@author: jingliang, hu
"""
# Last modified: 03.07.2018 00:08:28 Yuanyuan Wang
# Improved logging and exit code
# Last modified: 09.07.2018 12:01:00 Jingliang Hu
# update function 'getTiffExtent' to get EPSG code from tiff ROI
# Last modified: 10.07.2... |
import librosa as lc
import matplotlib.pyplot as plt
import numpy as np
fs = 16000
n_fft = 512
f = fs*np.array(range(int(1+n_fft/2)))/(n_fft/2)
def stft(path):
# Load a file
data = lc.load(path,sr=None)
length = len(data[0])
spec = np.array(lc.stft(data[0], n_fft=512, hop_length=160, win_length=400... |
"""
binalyzer_core.extension
~~~~~~~~~~~~~~~~~~~~~~~~
This module supports the creation of Binalyzer extensions.
"""
from binalyzer_core import (
BinalyzerExtension,
TemplateFactory,
ValueProviderBase,
value_cache,
)
class UtilityExtension(BinalyzerExtension):
def __init__(self, binal... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("createlisting", views.createListing, name=... |
from pathlib import Path
from unittest.mock import patch
import pytest
from zenithml.data import BQDataset
from zenithml.data import ParquetDataset
from zenithml.preprocess import Numerical, StandardNormalizer
from zenithml.preprocess import Preprocessor
def test_parquet_dataset(test_df, datasets, tmp_path):
te... |
# 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 agreed to in writing, software
# distributed under t... |
import os
def processFiles(dirPath, dstFilePath):
new_f = open(dstFilePath, 'w')
for file in os.listdir(dirPath):
file_path = os.path.join(dirPath, file)
f = open(file_path, 'r')
line = f.readline()
while (line):
new_f.write(line)
line = f.readline()
... |
from django.test import TestCase, tag
from smart_meter.models import GroupParticipant
from smart_meter.tests.mixin import MeterTestMixin
@tag('model')
class TestGroupParticipantModel(MeterTestMixin, TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.user = cls.create_... |
import numpy as np
from typing import Tuple, Iterable, Generator
# A little bit of sugar for type hints
Array = np.ndarray
def all_equals(iterable: Iterable) -> bool:
"""Return `True` if all elements of a given `iterable` are equals,
otherwise return `False`.
"""
return len(set(iterable)) <= 1
def... |
# Copyright (C) 2015-2021 Regents of the University of California
#
# 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 app... |
def checkAll(s, str, res, v):
new_str = str
for c in s:
temp = new_str.replace(c, "", 1)
if len(new_str) is len(temp):
return str
new_str = temp
res.append(v)
return new_str
def check(s):
l = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT... |
from src.multi_agent.agent.agent_interacting_room_camera import AgentCam
from src.my_utils.my_IO.IO_data import *
from src.my_utils.my_math.MSE import error_squared_list, error_squared_x_y_list
from src.plot_functions.plot_toolbox import plot_graph_x_y
from src.my_utils.my_math.MSE import *
from src.plot_functions.plot... |
import socket
def check_port(port: int):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
s.connect(("127.0.0.1", port))
s.shutdown(2)
|
from model.ModelSqlite import db, Task, Action, Order, TaskType
from sqlalchemy import and_, func
def save(task):
db.session.add(task)
db.session.commit()
return task
def load_by_date(sumary_date):
query = db.session.query(Task, Action, TaskType, Order) \
.join(Action, Action.task_id == Tas... |
import requests
import json
""" get Token """
def get_token(APIC):
url = f"https://{APIC}/api/aaaLogin.json"
""" sandbox aa credentials """
payload = {
"aaaUser": {
"attributes": {
"name":"admin",
"pwd":"C1sco12345"
}
}
}
headers = {
"Content-Type" : "appli... |
# Python > Sets > Symmetric Difference
# Learn about sets as a data type.
#
# https://www.hackerrank.com/challenges/symmetric-difference/problem
#
m = int(input())
M = set(map(int, input().split()))
n = int(input())
N = set(map(int, input().split()))
a = (M - N).union(N - M)
for i in sorted(a):
print(i)
|
from mpmath import mpf, mp, mpc
from UnitTesting.standard_constants import precision
mp.dps = precision
trusted_values_dict = {}
# Generated on: 2019-11-26
trusted_values_dict['GRMHD__generate_everything_for_UnitTesting__globals'] = {'GRHDT4UU[0][0]': mpf('-2.3394549490075809540461930203703'), 'GRHDT4UU[0][1]': mpf('... |
import json
import logging
import os
import subprocess
import sys
from multiprocessing.connection import Listener
from queue import Queue
from threading import Thread
from decouple import config
logger = logging.getLogger('pytest_gui.backend.main')
TEST_DIR = config("PYTEST_GUI_TEST_DIR", default=".")
if len(sys.ar... |
import turtle
import math
bob = turtle.Turtle()
def polygon(t,n,length):
angle = 360/n
for i in range(n):
bob.fd(length)
bob.lt(angle)
def circle(t,r):
circumference = 2 * math.pi * r
n= int(circumference/3) + 3
length = circumference / n
polygon(t,n,length)
circle(bob,80)
turtle.mainloop() |
import re
VALIDATOR_REGEX = re.compile(
r'\s*([rnbqkpRNBQKP1-8]+\/){7}([rnbqkpRNBQKP1-8]+)' +
r'\s[bw-]\s(([a-hkqA-HKQ]{1,4})|(-))\s(([a-h][36])|(-))\s\d+\s\d+\s*'
)
def validate_fen(fen: str) -> bool:
"""Check the validity of a given FEN string."""
match_obj = re.match(VALIDATOR_REGEX, fen)
if match_obj is N... |
"""
# Created on Sat Aug 28 12:52:52 2021
# AI and deep learnin with Python
Control Flow
Quiz List and comprehension
"""
# Problem 1:
"""Use a list comprehension to create a new list first_names containing
just the first names in names in lowercase.
"""
names = ["Rick Sanchez", "Morty Smith", "Summer Sm... |
#!/usr/bin/env python
# Copyright 2019 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.
"""
Unit tests for the contents of cpu_temperature.py
"""
# pylint: disable=unused-argument
import logging
import unittest
from devil... |
#!/usr/bin/env python2
import os
from argparse import ArgumentParser
from glob import glob
import numpy as np
parser = ArgumentParser()
parser.add_argument("runs_dir", help="location to Runs folder")
args = parser.parse_args()
# csv_files here only used to find valid directories (faults)
csv_files = glob(os.path.jo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.