content stringlengths 5 1.05M |
|---|
class Clause(object):
def __init__(self, clause):
"""Initializes a clause. Here, the input clause is either a list or set
of integers, or is an instance of Clause; in the latter case, a shallow
copy is made, so that one can modify this clause without modifying the
original clause.
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
from importlib import import_module
from thumbor.utils import logge... |
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
return (set(range(n+1)) - set(nums)).pop()
|
import sys
import os
import re
import time
import datetime
import subprocess
currentTime = time.time()
# CONVERT UNIX DATE INTO NORMAL HUMAN READABLE DATE
humanDate = datetime.datetime.fromtimestamp(currentTime).strftime('%Y_%m_%d_%H_%M_%S')
# DIRECTORY WE GOING TO STORE THE DATABASE BACKUPS IN
director... |
import torch
import copy
from typing import Dict, Any
_supported_types = {torch.nn.Conv2d, torch.nn.Linear}
def max_over_ndim(input, axis_list, keepdim=False):
''' Applies 'torch.max' over the given axises
'''
axis_list.sort(reverse=True)
for axis in axis_list:
input, _ = input.max(axis, keepd... |
# PIC Exceptions
class HedronMatchError(Exception):
"""Cannot find hedron in residue for given key."""
pass
class MissingAtomError(Exception):
"""Missing atom coordinates for hedron or dihedron."""
pass
|
#!/usr/bin/env python3
import csv
import random
from collections import defaultdict
import numpy
def poem(mapping):
MAX_LENGTH = 8
summa = sum(mapping[''].values())
i = 0
p = []
word = ''
while word != "." and i < MAX_LENGTH:
i += 1
res = [
(y, x)
... |
# -*- encoding: utf8 -*-
# Some code used in this module was taken from the python documentation and
# can be found in http://docs.python.org/2/library/csv.html
# Modified by Caktus.
from __future__ import unicode_literals, absolute_import
__all__ = ["DictReader", "DictWriter"]
from csv import DictReader as BaseDic... |
# -*- coding: utf-8 -*-
# Author: Icy(enderman1024@foxmail.com)
# OS: ALL
# Name: Log Writer
# Description: This function is used for recording logs
# Used Librarie(s): time, sys
# Version: 1.3
import time
import sys
class Logger: # Logger
def __init__(self, filename=None, line_end="lf",
date_fo... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 10:33:41 2020
@author: Alden Porter
"""
# =============================================================================
# Import Libraries
# =============================================================================
import numpy as np
from numba import... |
#!/usr/bin/env python3
# -*-coding:utf-8-*-
# @Time : 2017/11/1 ~ 2019/9/1
# @Author : Allen Woo
import os
try:
shcmd = """ps -ef | grep uwsgi_run.ini | awk '{print $2}' | xargs kill -9"""
r = os.system(shcmd)
print("Kill uwsgi.")
except Exception as e:
print(e)
try:
shcmd = """ps -ef | grep celery... |
from django.conf import settings
from django.core import mail
from users.services import send_mail_notification
def test_mail_notification() -> None:
"""Тестирует отправку письма о новом пользователе"""
send_mail_notification(first_name='Тест', total_users=10)
assert len(mail.outbox) == 1
assert mail... |
import utils
# exec(open("test_dash.py").read())
import imp
imp.reload(utils)
from utils import *
server = Flask(__name__)
external_scripts =['https://proteinpaint.stjude.org/bin/proteinpaint.js']
app = dash.Dash(
__name__,
meta_tags=[{"name": "viewport", "content": "width=800px, initial-scale=1"}],
server=server... |
from tkinter import *
# Configuración de la raíz
root = Tk()
root.title("Hola mundo")
root.resizable(1,1)
root.iconbitmap('hola.ico')
frame = Frame(root, width=480, height=320)
frame.pack(fill='both', expand=1)
frame.config(cursor="pirate")
frame.config(bg="lightblue")
frame.config(bd=25)
frame.config(relief="sunken... |
from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer
class UserConsumer(JsonWebsocketConsumer):
def connect(self):
user = self.scope['user']
if user.is_authenticated:
self.accept()
group = 'user-{}'.format(user.id)
... |
#URL: https://www.hackerrank.com/challenges/equal-stacks/problem
def equalStacks(h1, h2, h3):
# Write your code here
n1 = 0
n2 = 0
n3 = 0
s1 = sum(h1)
s2 = sum(h2)
s3 = sum(h3)
while True:
print(s1,s2,s3)
if s1>s2 or s1>s3:
s1 = s1 - h1[n1]
n1+=... |
from .h import *
trackingVectorId = "b732b3fe" # hashlib.md5("tracking-vector").hexdigest()[0:8], to minimize chance of collision
def addTrackingVector(doc):
if doc.md.trackingVectorClass is None:
return
els = findAll("[tracking-vector]", doc)
if len(els) == 0:
return
if doc.md.tr... |
# -*- coding: utf-8 -*-
########## THIS FITTING PROGRAM IS MEANT TO FIT sinusoids to 'mitral responses to sinusoids'!
## USAGE: python2.6 fit_odor_morphs.py ../results/odor_morphs/2011-01-13_odormorph_SINGLES_JOINTS_PGS.pickle
from scipy import optimize
from scipy.special import * # has error function erf() and inver... |
#!/usr/bin/env python3
from hdwallet import BIP44HDWallet
from hdwallet.cryptocurrencies import EthereumMainnet
from hdwallet.derivations import BIP44Derivation
from hdwallet.utils import generate_mnemonic
from hdwallet import HDWallet
from typing import Optional
import random, requests
from hdwallet.symbols ... |
from rest_framework import serializers
from users.models import CustomUser
class CustomUserSerializer(serializers.ModelSerializer):
"""
Serializer Class for CustomUser Model
"""
email = serializers.EmailField(required=True)
username = serializers.CharField(required=True)
password = serializers... |
#
# PySNMP MIB module IANA-MAU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-MAU-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:49:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
print('{{')
for y in range(14):
print('\t{ ', end='')
for x in range(18):
print(hex(0x4100 + x + y * 18) + ', ', end='')
print(' },')
print('},{')
for y in range(14):
print('\t{ ', end='')
for x in range(18):
print(hex(0x6200 + x + y * 18) + ', ', end='')
print(' },')
print('}};')
|
s = 'A Big Cat'
print(s.istitle())
s = 'A BIG Cat'
print(s.istitle())
s = 'A big Cat'
print(s.istitle())
s = 'a big cat'
print(s.istitle())
s = 'A'
print(s.istitle())
s = ''
print(s.istitle())
s = '2019'
print(s.istitle())
# special characters
s = 'Â Ɓig Ȼat'
print(s.istitle())
import unicodedata
count = 0
fo... |
import config_main
from Application.Schedulers.simple_RR import run_rr
from Application.Frame.transferJobPorts import prepare_ports_new_wave, log_to_console_exchange_ports
from Utils.log_handler import log_to_console, log_setup_info_to_console
from Application.Utils.TimeLogger import Timer
from Application.Utils.parse... |
# -*- coding: utf-8 -*-
from abc import ABC
from dataclasses import dataclass, field
from enum import Enum
from immutabledict import immutabledict
@dataclass(frozen=True)
class VariableFactory:
"""Creation of related Variables based on given shifts (in months)."""
rank: int
name: str
units: str
... |
import os
from pprint import pprint
from invoke import run, task
# You can edit these variables
SETTINGS = dict(
SPHINXOPTS="",
SPHINXBUILD="sphinx-build",
SOURCEDIR=".",
BUILDDIR="_build",
SPHINXINTL="sphinx-intl",
LOCALE="ja",
LOCALEDIR="_locales",
)
@task(help={"target": "target used ... |
from rlkit.misc.data_processing import Experiment
import matplotlib.pyplot as plt
import numpy as np
def main():
ddpg_trials = Experiment(
"/home/vitchyr/git/railrl/data/doodads3/12-23-ddpg-nupo-sweep-ant/",
criteria={
'exp_id': '16',
},
).get_trials()
her_andrychowicz_t... |
from app import app
from flask import render_template
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/contato.html')
def contato():
return render_template('contato.html')
@app.route('/features.html')
def features():
return render_template('features.htm... |
#!/usr/bin/env python3
import numpy as np
import ot
from numba import njit
from scipy.spatial.distance import cdist
from sklearn.utils import check_array
from .transmorph import Transmorph
from .tdata import TData
from .density import kernel_H
def sigma_analysis(dataset,
layer='raw',
... |
# importa tus librerias
import altair as alt
from vega_datasets import data
# tus datos
source = data.us_employment()
# crea una visualización
alt.Chart(source).mark_bar().encode(
x="month:T",
y="nonfarm_change:Q",
color=alt.condition(
alt.datum.nonfarm_change > 0,
alt.value("steelblue"), ... |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
class jkweb():
def __init__(self):
#get all widget from PyQt5
self.window = QWidget()
#set the title of web browser
self.window.setWindowTitle("JehanKandy... |
"""Compute optimal and average improvement for different parameters."""
import csv
from warnings import warn
import numpy as np
from bound_evaluation.change_enum import ChangeEnum
from bound_evaluation.manipulate_data import remove_full_nan_rows
from bound_evaluation.mc_enum import MCEnum
from bound_evaluation.mc_enu... |
import torch.nn as nn
from torch.nn.utils import weight_norm
from torch.nn import functional as F
import torch
from model.TemporalBlock import TemporalBlock
class pulsar_encoder_block(nn.Module):
# Single block of the pulsar encoder
def __init__(self, n_inputs, n_outputs, kernel_size, stride=2, pool=1, conv_g... |
def input():
return int(raw_input())
number = input()
if number == 8:
print "Oxygen"
elif number == 1:
print "Hydrogen"
elif number == 2:
print "Helium"
elif number == 11:
print "Sodium"
else:
print "I have no idea what %d is" % number
# Alternative solution
number = input()
db = {
1: "Hy... |
from django.contrib.admin import register, ModelAdmin
from {{project_name}}.apps.employee.models import EmployeeModel
@register(EmployeeModel)
class EmployeeAdmin(ModelAdmin):
list_display = ('dni', 'phone_number', 'labor_specialty')
|
import datetime
import unittest
from rdr_service import singletons
from rdr_service.clock import FakeClock
TIME_1 = datetime.datetime(2016, 1, 1)
TIME_2 = datetime.datetime(2016, 1, 2)
TIME_3 = datetime.datetime(2016, 1, 4)
# TODO: represent in new test suite
class SingletonsTest(unittest.TestCase):
foo_count ... |
import os
import pickle
import tkinter
from tkinter import ttk
import cv2
import random
import string
import shutil
import filedialog
import tkinter.messagebox
import threading
import PIL
import PIL.ImageTk
import time
class define():
def GetRandomStr(num):
dat = string.digits + string.ascii_lowercase + st... |
__author__ = 'Alex Ge, alexgecontrol@qq.com' |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
def cuda_detect():
'''Attempt to detect the version of CUDA present in the operating system.
On Windows and Linux, the CUDA library is installed by the NVIDIA
driver package, and is typically found in the st... |
import itertools
from helper import get_input
def main():
data = [x.split(' = ') for x in get_input(14).split('\n') if x]
one_mask = int('000000000000000000000000000000000000', 2)
x_positions = []
mem = {}
for operation, value in data:
if operation == 'mask':
tmp_one_mask = [x... |
# This file is part of the P3IV Simulator (https://github.com/fzi-forschungszentrum-informatik/P3IV),
# copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)
from __future__ import division
import os
import yaml
from datetime import datetime
pkg_path = o... |
from __future__ import print_function
import os
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cdutil
import matplotlib
import numpy as np
import scipy.stats
from cartopy.mpl.ticker import LatitudeFormatter, LongitudeFormatter
from e3sm_diags.derivations.default_regions import regions_specs
fro... |
import sys
import csv
# Set up CL args
# Define header
def main():
rows = []
# Read in rows
# Process rows
# Write rows to file
pass
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
"""Top-level package for Trips."""
__author__ = """Anders K. Pettersen"""
__email__ = 'andstatical@gmail.com'
__version__ = '0.1.0'
|
"""
django_simple_slack_app URL Configuration
"""
from django.conf import settings
from django.urls import path
from django.views.generic import TemplateView, RedirectView
from django_simple_slack_app.views import SlackCommandView, SlackEventView, SlackOAuthView
event_url = getattr(settings, "SLACK_EVENT_URL", "event... |
import logging
from kubernetes import client
from kube_api.config import core_v1_api as api
from .utils import api_request, get_dict_value
logger = logging.getLogger(__name__)
class VolumeClaim:
"""Represents a volume claim.
"""
def __init__(self, claim_name, disk_space, namespace='default', storage_class... |
import pytest
from requests import Request
from trycourier.session import CourierAPISession
@pytest.fixture
def _request():
return Request('GET', 'http://someurl')
def test_request_headers(_request):
s = CourierAPISession()
s.init_library_version('1.0.0')
r = s.prepare_request(_request)
assert... |
#!/usr/bin/env python
"""
futurize.py
===========
This script is only used by the unit tests. Another script called
"futurize" is created automatically (without the .py extension) by
setuptools.
futurize.py attempts to turn Py2 code into valid, clean Py3 code that is
also compatible with Py2 when using the ``future``... |
from arrview.tools.base import MouseButtons, MouseState, ToolSet
from arrview.tools.colormap import ColorMapTool
from arrview.tools.cursor_info import CursorInfoTool
from arrview.tools.pan_zoom import PanTool, ZoomTool
from arrview.tools.roi import ROITool
|
from common_utils_py.agreements.service_agreement import ServiceAgreement
from common_utils_py.agreements.service_agreement_template import ServiceAgreementTemplate
from common_utils_py.agreements.service_types import ServiceTypes, ServiceTypesIndices
from common_utils_py.agreements.utils import get_sla_template
from c... |
'''
@Author: Yingshi Chen
@Date: 2020-04-27 18:30:01
@
# Description:
'''
from torch import nn
import torch.nn as nn
import torch.nn.functional as F
from operations import *
from sparse_max import sparsemax, sparsemoid, entmoid15, entmax15
from genotypes import Genotype
import time
from MixedOp import *
from torch.au... |
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import spacy
import re
from gensim.corpora import Dictionary
class ElasticCorpus:
def __init__(self, host=None, port=None, username=None, password=None, index=None, debug_limit=None,
dictionary=Dictionary()):
if h... |
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, 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 requi... |
from setuptools import setup, find_packages
with open("README.md", "r") as readme_file:
readme = readme_file.read()
requirements = ["casbin==0.8.4", "psycopg2-binary==2.8.6", "black==20.8b1"]
setup(
name="casbin-postgresql-watcher",
version="0.0.1",
author="hsluoyz",
author_email="hslu... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file ui_hw_wipe_device_wdg.ui
#
# Created by: PyQt5 UI code generator
#
# 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,... |
import random
import shutil
import os.path as osp
from typing import Optional, Callable, List, Tuple
import torch
from torch_geometric.datasets import FAUST
from torch.utils.data import DataLoader
from torch_geometric.data import InMemoryDataset, Data, extract_zip
from torch_geometric.io import read_ply
class FullFA... |
"""
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
... |
#!/usr/bin/env python3
from __future__ import print_function
def main():
digits = 10
infile = 'input/Euler013.txt'
nums = parse_file(infile)
numsum = sum(nums)
print(str(numsum)[:digits])
def parse_file(path):
with open(path) as f:
return [int(num) for num in f.readlines()]
if __... |
from .linear_constraint import LinearConstraint, canlinear_colloc_to_interpolate
from ..constraint import DiscretizationType
import numpy as np
class JointTorqueConstraint(LinearConstraint):
"""Joint Torque Constraint.
A joint torque constraint is given by
.. math::
A(q) \ddot q + \dot q^\\top B... |
'''
EnzymeML (c) University of Manchester 2018
EnzymeML is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: neilswainston
'''
# pylint: disable=too-many-arguments
import re
import uuid
from libsbml import SBMLDocument, BIOLOGICAL_QUALIFIER, BQB_I... |
"""This module contains the general information for SesDiskSlotEp ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class SesDiskSlotEpConsts():
DISK_PRESENT_FALSE = "false"
DISK_PRESENT_NO = "no"
DISK... |
# -*- flake8: noqa -*-
from metrology.instruments.counter import Counter
from metrology.instruments.derive import Derive
from metrology.instruments.gauge import Gauge
from metrology.instruments.histogram import Histogram, HistogramUniform, HistogramExponentiallyDecaying
from metrology.instruments.meter import Meter
fro... |
# NLP written by GAMS Convert at 04/21/18 13:55:06
#
# Equation counts
# Total E G L N X C B
# 43 35 0 8 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... |
import traceback
class ErrorHandler:
def __init__(self, form_name):
self.form_name = form_name
def __call__(self, exctype, value, tb, *args, **kwargs):
for trace in traceback.format_tb(tb):
print(trace)
print('Exception Information')
print('Type:', exctype)
... |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# custom plot colors
GLD = [1.0, 0.698, 0.063]
# read in data
df = pd.read_csv(r'./data/Baltimore_City_Employees_Salaries.csv')
# included years in data, shorten FY20XX to FYXX
years = df['FiscalYear'].unique()
years = so... |
# Copyright 2022 Google.
#
# 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, soft... |
# -*- coding: utf-8 -*-
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import *
import json
import pytest
import requests
import requests_mock
from pkg_resources import resource_filename
from scriptabit.habitica_service import HabiticaService
from ... |
"""Read genome build configurations from Galaxy *.loc and bcbio-nextgen resource files.
"""
from six.moves import configparser
import glob
import os
import sys
from xml.etree import ElementTree
import toolz as tz
import yaml
from bcbio import utils
from bcbio.cwl import cwlutils
from bcbio.distributed import objectst... |
'''
Created on Jun 8, 2021
@author: mballance
'''
import os
import stat
from string import Template
class CmdInit(object):
def __init__(self):
pass
def __call__(self, args):
params = dict(
name=args.name,
version=args.version
)
# TODO: allow ... |
#!/usr/bin/env python3
import tempfile, sys, os, re
import traceback
import custom_arguments
from argparse_compat import argparse
from replace_imports import include_imports, normalize_requires, get_required_contents, recursively_get_requires_from_file, absolutize_and_mangle_libname
from import_util import get_file, ge... |
import pytest
from pages.BaseApp import BasePage
from selenium.webdriver.common.by import By
class YandexSeacrhLocators:
URL = "https://ya.ru/"
LOCATOR_YANDEX_SEARCH_FIELD = (By.ID, "text")
LOCATOR_YANDEX_SEARCH_BUTTON = (By.CLASS_NAME, "search2__button")
LOCATOR_YANDEX_NAVIGATION_BAR = (By.CSS_SELECTO... |
__all__ = ['pca']
import numpy as np
from sklearn.decomposition import PCA
def pca(data, *, n_components):
"""the PCA dimensionality reduction algorithms
Parameters
----------
data: tuple
conclude the train set and test set
n_components: int
the parameter of the pca
Returns
... |
import datetime
from database_setup import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///catalog.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
session.query(Catagory).delete()
session.query(Items).delet... |
class FileInfo:
def __init__(self, file_info):
self.components = file_info["components"]
self.parent = file_info["parent"]
self.name = file_info["name"]
self.extension = file_info.get("extension","")
self.toString = file_info["toString"]
def _get_components(self):
... |
import os
import build_utils
import build_config
import shutil
def get_supported_targets(platform):
if platform == 'win32':
return ['win32']
elif platform == 'darwin':
return ['macos']
else:
return []
def get_dependencies_for_target(target):
return []
def build_for_target(t... |
from pycircuit.circuit import *
from myTabVCCS import myVCCS
import pylab
circuit.default_toolkit = numeric
Rs=50.
Vs=1e-4
def build_lna_degen_gm():
c = SubCircuit()
c['Rs'] = R(1, gnd, r=Rs)
c['vs'] = VS(2, 1, vac=Vs)
c['vccs'] = VCCS(2, 4, 3, 4, gm=0.1)
c['Cgs'] = C(2, 4, c=1e-9)
c['rl'] =... |
# -*- coding: UTF-8 -*-
from django.db import models
# Create your models here.
class Person(models.Model):
student_number = models.CharField(verbose_name = '学号', max_length = 12, unique = True)
name = models.CharField(verbose_name = '姓名', max_length = 10)
pinyin = models.CharField(verbose_name = '拼音', max_lengt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from nominal.chi_squared_test import ChiSquaredTest
from nominal.fisher_test import FisherTest
class UnpairedTwoSampleTestOfNominalScale:
def test(self, data):
# check data length
if len(data.keys()) != 2:
print "len(data.... |
# Module to draw circles, rectangles and lines
import cv2
image = cv2.imread('lena.jpg')
RED = (0, 0, 255)
GREEN = (0, 255, 0)
BLUE = (255, 0, 0)
cv2.line(image, pt1=(0, 0), pt2=(100, 200), color=GREEN)
cv2.line(image, pt1=(300, 200), pt2=(150, 150), color=RED, thickness=5)
cv2.rectangle(image, pt1=(20, 20), pt2=(120... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2018, Nigel Small
#
# 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
#
# Unle... |
#FastMGWR MPI Script
#Author: Ziqi Li
#Email: liziqi1992@gmail.com
import math
import numpy as np
from mpi4py import MPI
from scipy.spatial.distance import cdist,pdist
import argparse
from copy import deepcopy
from FastGWR import FastGWR
class FastMGWR(FastGWR):
"""
FastMGWR class.
Parameters
--... |
from aiogram.dispatcher import FSMContext
from aiogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
from data.text import text, confirm_payment_button_text
from keyboards.inline.plan_keyboards import plansMenu
from loader import dp, bot
from utils.paypal import create_token_paypal
from utils.... |
from bungiesearch.fields import DateField, StringField
from bungiesearch.indices import ModelIndex
from core.models import Article, ManangedButEmpty, User
class ArticleIndex(ModelIndex):
effective_date = DateField(eval_as='obj.created if obj.created and obj.published > obj.created else obj.published')
meta_da... |
from warnings import warn
import kts.stl.misc
from kts.validation.leaderboard import leaderboard as lb
from kts.validation.split import Refiner
from kts.validation.validator import Validator
def assert_splitters(exps):
"""
Args:
exps:
Returns:
"""
all_splitters = set()
for exp in ex... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views import generic
from django.conf import settings
from django.utils impo... |
"""module containing all testcases"""
|
import serial, pygame, json, os
with open("full_map_list.json", 'r') as fd:
mapping=json.load(fd)
pressed = []
shift_key = mapping["default"].index("shift")
code_key = mapping["default"].index("code")
text=""
with serial.Serial("COM10", 2000000) as conn:
conn.readline()
conn.readline()
while 1:
try:data = (l... |
#!/usr/local/bin/python3
import socket
from random import randint
print(0)
HOST = '' # Symbolic name meaning all available interfaces
print(1)
PORT = 50007 # Arbitrary non-privileged port
print(2)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(3)
s.bind((HOST, PORT))
print(4)... |
import logging
from functools import wraps
from bs4 import BeautifulSoup
from telegram import ParseMode, Update
from telegram.ext import CallbackContext
# Require x non-command messages between each /rules etc.
RATE_LIMIT_SPACING = 5
def get_reply_id(update):
if update.message and update.message.reply_to_messag... |
import numpy as np
import pickle
import glob
import cv2
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
'''
# Aplicando técnica EigenFaces na face de gatos
Algumas fontes de pesquisa:
https://www.youtube.com/watch?v=_lY74pXWlS8&list=PL... |
from tests.customlist_tests.base.customlist_test_base import CustomListTestBase
class CustomListUnderboundTests(CustomListTestBase):
def test_customListUnderbound_whenMultipleNumbers_shouldReturnTheIndexOfTheMinElement(self):
custom_list = self.setup_list(1, 2, 3)
result = custom_list.underbound()... |
#
# Copyright John Reid 2009
#
"""
Code to model transcriptional programs.
"""
from shared import *
import os, csv
def yield_genes_from_csv(f):
"""
Load the gene names from the file object.
"""
for l in csv.reader(f, delimiter=','):
yield l[0]
class BasicTranscriptionalProgram(object):
... |
# Two modes:
# (1) interactive: Everything runs in one thread. Long-running event handlers block the update.
# (2) separated: non-main thread for all non-mainloop code.
"""
We match the Tk hierarchy of classes onto the ACM hierarchy as follows:
Each application (i.e. instance of TkBackend) has exactly one Tk root (... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
version = {}
with open("./vortexasdk/version.py") as fp:
exec(fp.read(), version)
setuptools.setup(
name="vortexasdk",
version=version["__version__"],
author="Vortexa Developers",
author_email="developers@vortex... |
from anonymization.base_anonymization import BaseAnonymization
from PIL import ImageFilter, Image
def find_boxes(bbox):
nb = []
for i in bbox:
nb.append(i)
return nb
class DetectionAnonymization(BaseAnonymization):
def __init__(self):
pass
def blurring(self, image, response, deg... |
from django.contrib import admin
from .models import Search
@admin.register(Search)
class SearchAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'started_at', 'finished_at', 'failed',)
|
#!/usr/bin/env python
import rosbag
import argparse
parser = argparse.ArgumentParser(description='Extract vehicle data from ROS bag file, using python\'s rosbag API')
parser.add_argument('bag', action='store', type=str, help='Bag filename')
parser.add_argument('--output', type=str, default='out.txt', help='Output fil... |
# -*- coding:utf-8 -*-
from __future__ import division
import sys
sys.path.append('../../../../../rtl/udm/sw')
import time
import udm
from udm import *
sys.path.append('..')
import sigma
from sigma import *
def hw_test_dhrystone(sigma, dhrystone_filename):
print("#### DHRYSTONE TEST STARTED ####")
... |
# Copyright 2019-present MongoDB, 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 wri... |
#!/usr/bin/python
import logging
import csv
import re
import sys
# create logger
logger = logging.getLogger("extract_experience")
logger.setLevel(logging.INFO)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter
formatter = logging.Formatter("%(asct... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.