content stringlengths 5 1.05M |
|---|
from faker import Faker
import attr
from fixtures.base import BaseClass
fake = Faker()
@attr.s
class RegisterUser(BaseClass):
username: str = attr.ib(default=None)
password: str = attr.ib(default=None)
@staticmethod
def random():
return RegisterUser(username=fake.email(), password=fake.pass... |
import numpy as np
import ast
import json
from utils import regresiveSustitution
from utils import rowOps
from utils import getMultipliers
from utils import swapRows
from utils import swapCols
from utils import isSquared
def gaussTotal(A,b):
A = ast.literal_eval(A)
b = ast.literal_eval(b)
res = {}
pivo... |
import math
import cupy
from cupy.core import internal
from cupyx.scipy import fft
from cupyx.scipy.ndimage import filters
from cupyx.scipy.ndimage import _util
def _check_conv_inputs(in1, in2, mode, convolution=True):
if in1.ndim == in2.ndim == 0:
return in1 * (in2 if convolution else in2.conj())
if... |
"""GUI"""
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
from shiftscheduler.gui import lower_frame as lower
from shiftscheduler.gui import upper_frame as upper
from shiftscheduler.gui import util
from shiftscheduler.i18n import gettext
_ = gettext.GetTextFn('gui/gui')
def CreateGUI(... |
"""Work with the graph of FamPlex entities and relations."""
from typing import Container, Dict, Generator, List, Tuple
from collections import defaultdict, deque
from famplex.load import load_entities, load_equivalences, load_relations
class FamplexGraph(object):
"""Provides methods for working with graph of F... |
import mock
from appdaemon.plugins.hass.hassapi import Hass
def patch_hass():
"""
Patch the Hass API and returns a tuple of:
- The patched functions (as Dict)
- A callback to un-patch all functions
"""
#### Non-actionable functions ####
# Patch the __init__ method to skip Hass initialisati... |
import csv
import jieba
import pymongo
import re
from findpath import nlppath
from parseutil import parse, parseNum
genset = set(('一代', '二代', '三代', '四代'))
number_re = re.compile('(\d+\.\d+|\d*)[wkq]?\d*')
id_re = re.compile('[a-z0-9]{3,}')
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 26 13:13:19 2019
@author: Florian Ulrich Jehn
"""
import pandas as pd
import os
import numpy as np
import math
# Get the location of this file
file_dir = os.path.dirname(os.path.abspath(__file__))
def read_attributes():
att_df = pd.read_csv("all_catchment_attribute... |
#!flask/bin/python
from flask import Flask, jsonify, abort
from dictionary_reader import search
import sys
import pika
import logging
import platform
app = Flask(__name__)
@app.route('/dictionary/api/v1.0/words/<string:word>', methods=['GET'])
def getSentimentValue(word):
logger = logging.getLogger('Dictionary Se... |
from django.contrib import admin
from meetings.models import Meeting, Template
@admin.register(Meeting)
class MeetingAdmin(admin.ModelAdmin):
pass
@admin.register(Template)
class TemplateAdmin(admin.ModelAdmin):
pass
|
"""Base callback."""
import abc
import numpy as np
import mzcn as mz
class BaseCallback(abc.ABC):
"""
DataGenerator callback base class.
To build your own callbacks, inherit `mz.data_generator.callbacks.Callback`
and overrides corresponding methods.
A batch is processed in the following way:
... |
# import modules ----------------------------------------
import trimesh
from shapely.geometry import LineString
import numpy as np
import matplotlib.pyplot as plt
# Load in STL file --------------------------------------
stl_mesh = trimesh.load_mesh("3DBenchy.stl")
# Generte Intersection Rays -----------------------... |
""" file: test_history_cython.py
"""
import unittest
import numpy as np
from maxr.integrator.history import coefficients
from maxr.ext.coefficients import IntegratorCoeffs
class BaseHarness(unittest.TestCase):
"Base test class for history integrators"
order = 1
def test_equal_py_cy(self):
"Pyt... |
#!/usr/bin/python
####################################################################
# This module 'knightsmove' simulates a knight's move #
# from point A -> B such that it takes minimum number of steps #
# between A and B. It finds all the possible solutions. #
# Here are the stats: ... |
# -*- coding: utf-8 -*-
from typing import Any, Dict
from dateutil.relativedelta import relativedelta
from datetime import datetime
def compute_freelance_skills(payload: Dict[str, Any]) -> Dict[str, Any]:
"""
Receives the freelance payload and count the months experience with every skill
"""
result ... |
import os
import logging
from django.core.management.base import BaseCommand
from manti_by.apps.blog.models import Post
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Check posts state"
def handle(self, *args, **options):
checked = 0
for post in Post.objects.all()... |
from multiprocessing import Pool, TimeoutError
import json
import pika
import sys
from raw_replayer import RawReplayerFactory
from summary_replayer import SummaryReplayerFactory
from transfer_summary import TransferSummaryFactory
import toml
import argparse
import logging
class OverMind:
"""
Top level class ... |
#####
#
# visualize_incoming_annotations.py
#
# Spot-check the annotations received from iMerit by visualizing annotated bounding
# boxes on a sample of images and display them in HTML.
#
# Modified in 2021 March to use the new format (iMerit batch 12 onwards), which is a
# COCO formatted JSON with relative coordinate... |
from enum import IntFlag
from .chinese.extractors import *
from recognizers_text import *
from .english.extractors import *
from .english.parsers import *
from .models import *
from .parsers import *
class SequenceOptions(IntFlag):
NONE = 0
class SequenceRecognizer(Recognizer[SequenceOptions]):
def __init__... |
from config import *
# Position Evaluation Matrices
wp = [900, 900, 900, 900, 900, 900, 900, 900,
50, 50, 50, 50, 50, 50, 50, 50,
10, 10, 20, 30, 30, 20, 10, 10,
5, 5, 10, 25, 25, 10, 5, 5,
0, 0, 0, 20, 20, 0, 0, 0,
5, -5,-10, 0, 0,-10, -5, 5,
5, 10, 10,-20,-20, 10, 10, 5,
0, 0, 0, 0, ... |
from dedoc.attachments_handler.attachments_handler import AttachmentsHandler
from dedoc.converters.concrete_converters.docx_converter import DocxConverter
from dedoc.converters.concrete_converters.excel_converter import ExcelConverter
from dedoc.converters.concrete_converters.pptx_converter import PptxConverter
from de... |
__author__ = 'thatcher'
|
# Copyright (c) Facebook, Inc. and its affiliates.
from .cityscapes_evaluation import CityscapesInstanceEvaluator, CityscapesSemSegEvaluator
from .cityscapes_evaluationJ_forHumanEval import CityscapesSemSegEvaluatorJ_forHumanEval # i.21.4.22.10:12) 사람의결과 이밸류에이션위해 추가.(사람vs모델 해보려고).
from .coco_evaluation import COCOE... |
import collections
import torch
import copy
import torch.nn as nn
def intable(value):
try:
int(value)
return True
except:
return False
# change with _module
def get_object(model, name):
if isinstance(
model, (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
... |
from typing import List
import unittest
from src.profile import Profile
class ProfileTest(unittest.TestCase):
def test_calculate_simple_motif(self):
profile = Profile("A", "name")
self.assertDictEqual({
"A": [1],
"C": [0],
"G": [0],
"T": ... |
from django.urls import path, include
from .views import home_view
app_name = 'pages'
urlpatterns = [
# path('', home_view, name='home_view'),
]
|
from physDBD import Params0Gauss, ImportHelper, Params0GaussTraj
import numpy as np
import os
import tensorflow as tf
class TestParams0Gauss:
fnames = [
"../data_test/0000.txt",
"../data_test/0001.txt",
"../data_test/0002.txt",
"../data_test/0003.txt",
"../data_test/0004.tx... |
import os, glob
import json
import re
import numpy as np
from shutil import copy
from AlphagoZero.ai import MCTSPlayer
import AlphagoZero.go as go
from AlphagoZero.models.policy_value import PolicyValue
from AlphagoZero.util import flatten_idx, pprint_board
class Human(object):
def __init__(self,board_size):
... |
class RPY:
to_card = {(False, False): "!", (False, True): "+", (True, False): "?", (True, True): "*"}
from_card = {"!": (False, False), "+": (False, True), "?": (True, False), "*": (True, True)}
symbol_unique = '-u'
symbol_private = '-p'
symbol_static = '-s'
@classmethod
def rpy_to_cfg(cls... |
def aumentar(n, porcentagem, f=False):
nv = n * (1 + porcentagem/100)
if f:
nv = moeda(nv)
return nv
def diminuir(n=0, porcentagem=0, f=False):
nv = n * (1 - porcentagem/100)
if f:
nv = moeda(nv)
return nv
def dobro(n=0, f=False):
n *= 2
if f:
n = moeda(n)
... |
# SPDX-FileCopyrightText: 2020 Luke Granger-Brown
#
# SPDX-License-Identifier: Apache-2.0
import scapy.packet
def tagged_layer(parent_packet, tag_name):
def tagged(tag):
def _wrap(cls):
scapy.packet.bind_layers(parent_packet, cls, **{tag_name: tag.value})
return cls
retur... |
from flask import jsonify
from lin.redprint import Redprint
from app.libs.jwt_api import member_login_required, get_current_member
from app.libs.utils import offset_limit
from app.models.classic import Classic
from app.models.like import Like
classic_api = Redprint('classic')
@classic_api.route('/latest', methods=[... |
import os
__all__ = ['NvidiaSMI', 'DebugCUDA']
class NvidiaSMI(object):
def __init__(self):
if 'PROGRAMFILES' in os.environ.keys():
nvidia_smi_path = os.path.join(
os.environ['PROGRAMFILES'],
'NVIDIA Corporation',
'NVSMI'
)
... |
"""Additional helper functions dealing with transient-CW F(t0,tau) maps.
See Prix, Giampanis & Messenger (PRD 84, 023007, 2011):
https://arxiv.org/abs/1104.1704
for the algorithm in general
and Keitel & Ashton (CQG 35, 205003, 2018):
https://arxiv.org/abs/1805.05652
for a detailed discussion of the GPU implementation.... |
import os
from abc import ABC, abstractmethod
from pathlib import Path
BASE_PATH = Path.home().joinpath("re")
if not os.path.isdir(BASE_PATH):
os.mkdir(BASE_PATH)
class DownloadTarget(ABC):
@abstractmethod
def get_source(self):
pass
@abstractmethod
def get_target(self):
pass
|
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
i = 0
for j in range(1, len(nums)):
if nums[i] != nums[j]:
i += 1
nums[i] =... |
#!/usr/bin/env python
#coding:utf-8
# Author: mozman
# Purpose: examples for dxfwrite usage, see also tests for examples
# Created: 09.02.2010
# Copyright (C) 2010, Manfred Moitzi
# License: MIT License
import sys
import os
try:
import dxfwrite
except ImportError:
# if dxfwrite is not 'installed' append pare... |
# Copyright The IETF Trust 2019, All Rights Reserved
# Copyright 2018 Cisco and its affiliates
#
# 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... |
"""
Copyright (c) 2022 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/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... |
from transformers import pipeline
classifier = pipeline('sentiment-analysis')
# classifier('We are very happy to show you the 🤗 Transformers library.')
def sentiment_analysis(input_text):
result_sent = classifier(input_text)
return result_sent
# print(classifier('We are very happy to show you the 🤗 Tran... |
#!python
import string
# Hint: Use these string constants to encode/decode hexadecimal digits and more
# string.digits is '0123456789'
# string.hexdigits is '0123456789abcdefABCDEF'
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# string.ascii_letters ... |
import re
from typing import Dict
non_printing_characters_re = re.compile(
f"[{''.join(map(chr, list(range(0,32)) + list(range(127,160))))}]"
)
digits_re: re.Pattern = re.compile(r"\d")
unicode_punctuation: Dict[str, str] = {
",": ",",
"。": ".",
"、": ",",
"„": '"',
"”": '"',
"“": '"',
... |
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth.forms import UserCreationForm
from .models import Hall
def home(request):
return render(request, 'halls/home.html')
class SignUp(generic.CreateView):
form_class = UserCr... |
def first_last(s):
if len(s) <= 1:
ret = ""
else:
ret = s2 = s1[:2] + s1[-2:]
return ret
s1 = "spring"
print first_last(s1)
s1 = "hello"
print first_last(s1)
s1 = "a"
print first_last(s1)
s1 = "abc"
print first_last(s1)
|
import time
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
from utils import *
import os
import sys
import matplotlib.pyplot
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = ... |
# Copyright 2021, 2022 Cambridge Quantum Computing Ltd.
#
# 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 la... |
"""Fixtures for CLI tests"""
import pathlib
import pytest
from scout.demo.resources import demo_files
from scout.server.app import create_app
#############################################################
###################### App fixtures #########################
###################################################... |
#
# License: BSD
# https://raw.githubusercontent.com/splintered-reality/py_trees/devel/LICENSE
#
##############################################################################
# Documentation
##############################################################################
"""
Package version number.
"""
#############... |
# CPU: 0.06 s
from math import hypot
n, width, height = list(map(int, input().split()))
longest = hypot(width, height)
for _ in range(n):
print('DA' if int(input()) <= longest else 'NE')
|
import math
from random import *
from copy import copy
def printField(f):
for i in range(3):
for j in range(3):
for k in range(3):
print f[i*3 + j * 9 + k],
print "|",
print "\n",
if(i==2 or i==5):
print "------------------"
for i in r... |
"""models.py
"""
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data as data
import torch.backends.cudnn as cudnn
from torch.nn import functional as F
import torch.optim
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.models as models
import torchvision... |
"""Interface for the application
This file can be run, and will properly initialize interface (and rest of the
app) in your terminal.
Battle-tested on Solarized color scheme and under tmux.
"""
from contextlib import contextmanager
from datetime import datetime
import os
import os.path
import random
import sys
import... |
from requests.exceptions import HTTPError
from graph_notebook.system.database_reset import initiate_database_reset, perform_database_reset
from test.integration import IntegrationTest
class TestStatusWithoutIAM(IntegrationTest):
def test_do_database_reset_initiate(self):
result = initiate_database_reset(s... |
from typing import Optional
from pydantic import Field
from pystratis.api import Model
from pystratis.core.types import Address, Money
# noinspection PyUnresolvedReferences
class OfflineWithdrawalFeeEstimationRequest(Model):
"""A request model for the coldstaking/estimate-offline-cold-staking-withdrawal-tx-fee en... |
class Db(object):
def __init__(self, web3):
self.web3 = web3
def putString(self, *args, **kwargs):
raise DeprecationWarning("This function has been deprecated")
def getString(self, *args, **kwargs):
raise DeprecationWarning("This function has been deprecated")
def putHex(self,... |
import subprocess
import os
import time
def soft_reset():
from picar_4wd.pin import Pin
soft_reset_pin = Pin("D16")
# print('soft_reset')
soft_reset_pin.low()
time.sleep(0.001)
soft_reset_pin.high()
time.sleep(0.001)
def mapping(x,min_val,max_val,aim_min,aim_max):
x = aim_min + abs((... |
# -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc... |
from django.db import models
from django.db.models import Sum, Avg, Count, Func
from django.db.models.signals import pre_save
from django.utils.text import slugify
from django.dispatch import receiver
def dict_pop(d, to_pop):
return {k: v for k, v in d.items() if k not in to_pop}
class Round(Func):
function... |
"""
Payout Creation Exception gets raised when request for payout batch creation gets failed.
"""
from .payout_exception import PayoutException
class PayoutBatchCreationException(PayoutException):
"""
PayoutBatchCreationException
"""
__bitpay_message = "Failed to create payout batch"
__bitpay_cod... |
import math
from keras_frcnn.configurations.FasterRcnnConfiguration import FasterRcnnConfiguration
class OriginalPascalVocConfig(FasterRcnnConfiguration):
"""The original configuration that was provided along the keras_frcnn sample implementation """
def __init__(self):
super().__init__(anchor_box_s... |
#!/usr/local/python/bin/python
"""
grab all the actions from 1 day ago, split according to camera
go to last action and get the last image
only make pngs and upload to webserver if needed
"""
import os
import sys
import glob as g
from datetime import datetime
import pymysql
from create_movie import create_movie
# pyli... |
# pylint: disable=E1101,E1103,W0232
""" manage legacy pickle tests """
from datetime import datetime, timedelta
import operator
import pickle as pkl
import nose
import os
import numpy as np
import pandas.util.testing as tm
import pandas as pd
from pandas import Index
from pandas.sparse.tests import test_sparse
from ... |
"""
A few utility functions related to client windows. In
particular, getting an accurate geometry of a client window
including the decorations (this can vary with the window
manager). Also, a functon to move and/or resize a window
accurately by the top-left corner. (Also can change based on
the currently running wind... |
from django.contrib.auth import login, get_user_model
from django.shortcuts import render, redirect
from users.forms import CustomUserCreationForm
def signup(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def duplicateZeros(self, arr):
"""
:type arr: List[int]
:rtype: None Do not return anything, modify arr in-place instead.
"""
shift, i = 0, 0
while i+shift < len(arr):
shift += int(arr[i] == 0)
... |
class RootLogger:
def info(self, message: str):
assert not hasattr(super(), 'info')
def verbose(self, message: str, color: str):
assert not hasattr(super(), 'verbose')
def find(self, scanner: str, message: str, color:str):
assert not hasattr(super(), 'find')
def warn(self, ... |
#!/usr/bin/python -S
"""
os_path_test.py: Tests for os_path.py
"""
from __future__ import print_function
import unittest
from pylib import os_path # module under test
class OsPathTest(unittest.TestCase):
def testPathExists(self):
self.assertEqual(True, os_path.exists('/'))
self.assertEqual(False, os_pat... |
import numpy as np
import tensorflow as tf
from imutils import paths
import cv2
from subprocess import PIPE, Popen
"""
This is the quantization script for tflite model float32 to int8 model.
I use the original dataset by Wang Yifan for calibration purpose https://drive.google.com/drive/folders/1w-zoOuSauw5xBhOrfZpjcgl... |
#
# It is possible to log HART transactions.
# For example log a bursting device or log transactions with other masters
# by connecting a second HART modem.
#
#
# Standard import. Append the path of PyHART. Since this file is in the folder PyHART_tutorial,
# just go back one folder.
#
import sys
sys.path.... |
# Copyright 2011 Nicholas Bray
#
# 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... |
#!/usr/bin/env python3
# encoding: utf-8
# @Time : 2018/8/2 上午11:48
# @Author : yuchangqian
# @Contact : changqian_yu@163.com
# @File : logger.py
import os
import sys
import logging
# from utils import pyt_utils
# from utils.pyt_utils import ensure_dir
_default_level_name = os.getenv('ENGINE_LOGGING_LEVEL', 'I... |
import asyncio
import aiohttp
import time
import logging
from selenium import webdriver
from selenium.webdriver.firefox import options
from selenium.common.exceptions import NoSuchElementException
try:
import uvloop
uvloop.install()
except ImportError:
pass
logger = logging.getLogger("rend... |
import re
import json
import subprocess
def run_shell_command(command, cwd=None, env=None, shell_mode=False):
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell_mode,
cwd=cwd,
env=env,
)
stdout, stderr = proc.commun... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from .Contract import *
from .Receivable import *
from .Receipt import *
from .Shop import *
from .Statement import *
from .Application import * |
'''
到最近的人的最大距离
给你一个数组 seats 表示一排座位,其中 seats[i] = 1 代表有人坐在第 i 个座位上,
seats[i] = 0 代表座位 i 上是空的(下标从 0 开始)。
至少有一个空座位,且至少有一人已经坐在座位上。
亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。
返回他到离他最近的人的最大距离。
示例 1:
输入:seats = [1,0,0,0,1,0,1]
输出:2
解释:
如果亚历克斯坐在第二个空位(seats[2])上,他到离他最近的人的距离为 2 。
如果亚历克斯坐在其它任何一个空位上,他到离他最近的人的距离为 1 。
因此,他到离他最近的人... |
# До словника з 1 вправи потрібно додати нового автобота. "Сентінел Прайм" - "Пожежна машина".
# Вивести новий словник на консоль
carsdict = {
"Оптімус Прайм" : "Грузовик Peterbilt 379",
"Бамблбі" : "Chevrolet Camaro",
"Джаз" : "Porsche 935 Turbo"
}
carsdict["Сентінел Прайм"] = "Пожежна машина"
print... |
from dependency_injector import containers, providers
from fdap.app.kiwoom.kiwoom_service import KiwoomService
from fdap.app.opendart.opendart_service import OpenDartService
from fdap.app.refine.refine import Refine
from fdap.database.database import db_session
from fdap.app.repositories.post_repository import PostsRep... |
"""
Split entire data set into train/test in balanced way of labels
"""
import os
import numpy as np
import json
import random
from utils.misc.json import write_json_line_by_line
def count_total(entire_data):
"""
Get entire json and return how many lines it holds.
"""
num_lines = sum(1 for line in op... |
#!/usr/bin/env python2.6
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in ... |
import nltk
class EntityExtractor:
def __init__(self):
pass
def get_people(self):
pass
def get_organizations(self):
pass
def get_money(self, taggedText):
#Pattern = $3.2 billion or 50 billion dollars or 50 Dollars
pattern = """
MONEY:
{<\$>?<CD>+<NNP|NNS|NN>?}
"""
MoneyChunker = nlt... |
import numpy as np
import typing as tg
import sklearn.cluster as sklc
import scipy.spatial.distance as spsd
import scipy.signal as spsn
import heapq as hq
import matplotlib.pyplot as plt
def SimpleHierachicalCluster(X: np.ndarray, weight: tg.Optional[np.ndarray]=None) -> np.ndarray:
"""My version of Hierachical C... |
from .completion_cross_entropy import CompletionCrossEntropyCriterion
from .completion_lifelong_kd_cross_entropy_loss import LifeLongKDCrossEntropyCriterion
|
#!/usr/bin/env python
import difflib
import hashlib
import os
import pathlib
import re
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
from urllib.request import urlopen
import zipfile
import click
import git
import pkg_resources
import yaml
from dataclasses import dataclass, fiel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Download data from http://lda.data.parliament.uk"""
from __future__ import division, print_function, absolute_import
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import codecs
import logging
from os import mkdir, path
import requests
import sys
f... |
from mmstructlib.sas.nsc import DoubleArray, nsc_atom_sas, nsc_total_sas, nsc_total_volume
def run_nsc(atoms, probe, dots, func):
"""
"""
num = len(atoms)
coords = DoubleArray(num*3)
radii = DoubleArray(num)
for i, a in enumerate(atoms):
atom_index = i*3
coords[atom_index] = a.... |
from __future__ import absolute_import, division, print_function
from cctbx import crystal, sgtbx, xray
from cctbx import geometry_restraints
from cctbx.array_family import flex
import iotbx.cif.restraints
from libtbx.test_utils import show_diff
from six.moves import cStringIO as StringIO
def exercise_geometry_restra... |
import math
import os
import random
from pathlib import Path
from collections import defaultdict
import torch
import torch.utils.data
import torchaudio
import numpy as np
import librosa
from librosa.util import normalize
from scipy.io.wavfile import read
from librosa.filters import mel as librosa_mel_fn
def load_wa... |
from django.contrib import admin
from .models import (
Question,
Answer,
)
admin.site.register(Question)
admin.site.register(Answer)
|
import os
import numpy as np
import streamlit as st
from sklearn.metrics.pairwise import cosine_similarity
from ..utils import get_word_embeddings
@st.cache(persist=eval(os.getenv("PERSISTENT")))
def compute_similarity_matrix_keywords(
model_path,
keywords=[],
all_model_vectors=False,
return_unk_sim... |
from setuptools import setup, find_packages
setup(
name='IPBot Telegram',
version='0.1',
long_description=__doc__,
py_modules=('ipbot',),
install_requires=['DepyTG', 'requests'],
dependency_links=[
"https://github.com/Depau/DepyTG/archive/wip.zip"
],
entry_points={
'cons... |
#!/bin/python3
import sys
n = int(input().strip())
a = list(map(int, input().strip().split(" ")))
# Write Your Code Here
numberOfSwap = 0
for i in range(n):
for j in range(n - i - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
numberOfSwap += 1
if numberOfSwap ... |
# Copyright 2021 The PyMC Developers
#
# 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 ag... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint
label_writer_450 = Blueprint(
'label_writer_450', __name__, template_folder='templates', static_folder='static'
)
from . import views
from . import zpl
|
import dwavebinarycsp
import dimod
csp = dwavebinarycsp.factories.random_2in4sat(8,4 ) # 8 variables, 4 clauses
bqm = dwavebinarycsp.stitch(csp)
resp = dimod.ExactSolver().sample(bqm)
for sample, energy in resp.data(['sample', 'energy']):
print(sample, csp.check(sample), energy)
|
# Copyright 2014 Google Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE filters or at
# https://developers.google.com/open-source/licenses/bsd
{
'includes': [
'../../common.gypi',
],
'targets': [
{
'target_name': 'filters',... |
#!/usr/bin/env python
'''
**********************************************************************
* Filename : L298N.py
* Description : A driver module for L298N
* Author : Cavon
* Brand : SunFounder
* E-mail : service@sunfounder.com
* Website : www.sunfounder.com
* Update : Cavon ... |
import util
import re
import soupsieve
from bs4 import BeautifulSoup
class DiffParser():
def __init__(self, handler):
self.handler = handler
def _handle_new_revision(self, id, desc, body):
username = util.get_regex_match(body, ">([^>]+) created this revision")
if username is not None:... |
import numpy as np
from .decision_templates_base import make_decision_profiles, make_decision_templates
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.utils.multiclass import unique_labels
from sklearn.cluster import OP... |
#coding=utf-8
from django.db import models
from aops.settings import INT_CHOICES
from cmdb import signals
from cmdb.models.idc import Idc
from cmdb.models.contract import Contract
from django.db import IntegrityError
class IdcContract(models.Model):
idc = models.ForeignKey(Idc)
contract = models.ForeignKey(Co... |
commands = []
while True:
try: line = input()
except: break
if not line: break
commands.append(line.split())
for starting_a in range(155, 160):
d = {'a': starting_a, 'b': 0, 'c': 0, 'd': 0}
i = 0
out = []
while len(out) < 100:
if commands[i][0] == 'inc' and commands[i+1][0] == ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.