content stringlengths 5 1.05M |
|---|
"""
JSON-LD contexts.
"""
from .namespaces import ns_mgr, D
base = {
"@base": str(D),
"a": "@type",
"uri": "@id",
"label": "rdfs:label",
}
#set namespaces from the ns_mgr
for prefix, iri in ns_mgr.namespaces():
base[prefix] = iri.toPython()
#BCITE publications
publication = {
"title": "rdfs:l... |
import logging
import pytest
from piqe_ocp_lib import __loggername__
from piqe_ocp_lib.api.crd.local_storage_operator import (
LocalStorageOperator,
LocalVolume,
LocalVolumeDiscovery,
LocalVolumeSet,
)
from piqe_ocp_lib.api.resources.ocp_operators import ClusterServiceVersion
logger = logging.getLogg... |
#!/usr/bin/env python3
import sys
import os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')
from gencoor.exceptions import ChromosomeNotStrError, PositionNotIntegerError, NameNotStrError,\
StrandNotStrError, CoordinateFlipError
from gencoor.coordina... |
N = list(map(int, input()))
if ((N[0]*100+N[1]*10+N[2]) < (N[0]*100+N[0]*10+N[0])):
print(N[0]*100+N[0]*10+N[0])
elif ((N[0]*100+N[1]*10+N[2]) > (N[0]*100+N[0]*10+N[0])):
print((N[0]+1)*100+(N[0]+1)*10+(N[0]+1))
else:
print(N[0]*100+N[1]*10+N[2])
|
# Copyright 2018 The TensorFlow 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 applic... |
import streamlit as st
import tensorflow as tf
st.set_option("deprecation.showfileUploaderEncoding",False) # whenever installing streamlit app it shows warning to avoid it we put it false
# when we load our big model and if there exist some changes it reloads it which is time consuming so function wriiten below will ... |
from azext_iot.central.models.v1_1_preview.device import Device as DeviceV1_1_preview
from azext_iot.central.models.v1_1_preview.device_group import (
DeviceGroup as DeviceGroupV1_1_preview,
)
from azext_iot.central.models.v1_1_preview.template import (
Template as TemplateV1_1_preview,
)
from azext_iot.central... |
import logging
import urllib
from django.utils import simplejson
from dateutil.parser import parse
from money.Money import Money, Currency
from pytz import utc
from constants import *
from paypaladaptive import settings
from paypaladaptive.api.errors import IpnError
from paypaladaptive.api.httpwrapper import UrlReq... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class TestPackageConan(ConanFile):
def test(self):
self.output.info("Version:")
self.run("doxygen --version")
|
import numpy as np
import Simulators, Logger, Evaluators
import warnings
import argparse
import pickle
import sys
class OfflineExp(object):
def __init__(self, n=1000, K=10, L=5, dataset="synth", feat_noise=0.25, reward_noise=1.0):
self.n = n
self.K = K
self.L = L
self.weight = np.ar... |
import npyscreen
class NotifyConfirmExample(npyscreen.Form):
def create(self):
key_of_choice = 'p'
what_to_display = 'Press {} for popup \n Press escape key to quit'.format(key_of_choice)
self.add_handlers({key_of_choice: self.spawn_notify_popup})
self.how_exited_handers[npyscreen... |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
"""Extract all special pages mapped by Linux kernel into process memory"""
import ctypes
import ctypes.util
import errno
import sys
if sys.version_info < (2, 7):
sys.stderr.write("This program cannot be run in Python<2.7 mode.\n")
sys.exit(0)
libc = ctypes.CDLL(c... |
# -*- coding: utf-8 -*-
"""Module for file repository backend implementations."""
# AUTO-GENERATED
# yapf: disable
# pylint: disable=wildcard-import
from .abstract import *
from .disk_object_store import *
from .sandbox import *
__all__ = (
'AbstractRepositoryBackend',
'DiskObjectStoreRepositoryBackend',
... |
import os
import shlex
import subprocess
import sublime
import sublime_plugin
import webbrowser
class WebdevshellCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.settings = sublime.load_settings('WebDevShell.sublime-settings')
if self.settings.get('override_panel_setting... |
#!/usr/bin/python
from __future__ import print_function
import uuid
import json
import random
import time
import sys
import getopt
users = [
{ "name" : "ojouglad", "tweet_prob" : 1, "pos" : 0.8, "neg" : 0.85 },
{ "name" : "lkarforless", "tweet_prob" : 0.75, "pos" : 0.5, "neg" : 0.6 },
{ "name"... |
'''
#pdfbaseCrawler pdf爬虫的基类
主要方法:
crawl
parse_menu
parse_body
download
htmls2pdf
control
'''
#-*-coding=utf-8-*-
import os
import shutil
import time
import pdfkit
import requests
from Crawl2PDF.config import OPTIONS
class Crawler(object):
"""
爬虫基类,所有爬虫都应该继承此类
"""
name = None
... |
import sys
from thread import get_ident
from peak.util.decorators import rewrap, cache_source, classy, decorate
__all__ = [
'Service', 'replaces', 'setting', 'InputConflict', 'DynamicRuleError',
'State', 'Action', 'resource', 'registry', 'new', 'empty',
'lookup', 'manager', 'reraise', 'with_', 'call_with',... |
from collections import Mapping, Sequence
def recursive_mapping_update(mapping, **updates):
""" Recursively update a dict-tree without clobbering any of the nested dictionaries.
:param mapping: a dict-like object to perform updates on
:type mapping: dict
:returns: the updated mapping
"""
for k... |
import os.path as osp
from mmcv import Config
from utils import rm_suffix
from vegcn.extract import extract_gcn_v
# data locations
prefix = './data/SOP_dedup_test_global'
test_name = 'part0_train'
knn = 5
knn_method = 'faiss'
th_sim = 0. # cut edges with similarity smaller than th_sim
# gcn_v configs
_work_dir = 'wo... |
# Create your views here
from django.http import HttpResponse, Http404
from opendata.models import *
from opendata.views import send_email
from suggestions.models import Suggestion
from datetime import datetime
from encoder import *
from rest import login_required
from django.views.decorators.csrf import csrf_exempt
d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 13 07:58:20 2017
@author: Developer
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import colors
def plot(X,Y,pred_func):
# determine canvas borders
mins = np.amin(X,0);
mins = mins - 0.1*np.abs(mins);
... |
import argparse
import gzip
import math
import numpy
import re
import sys
from collections import defaultdict
from copy import deepcopy
import numpy as np
isNumber = re.compile(r'\d+.*')
def norm_word(word):
if isNumber.search(word.lower()):
return '---num---'
elif re.sub(r'\W+', '', word) == '':
return '-... |
#!/usr/bin/env python
"""
@author Jesse Haviland
"""
import swift
import roboticstoolbox as rtb
import spatialgeometry as sg
import spatialmath as sm
import numpy as np
import time
env = swift.Swift()
env.launch(realtime=True)
omni = rtb.models.ETS.Omni()
omni.grippers[0].tool = (
sm.SE3(-0.15, -0.1, 0.35) * sm.... |
# -*- coding: utf-8 -*-
"""
Sample Module.
Example of Market Data manipulation using the library.
The code show how to get different market data for an instrument and
how to get historical trade data using pyRofex.
Go to the official Documentation to check the API Responses.
Steps:
1-Ini... |
# TODO Do not edit this file directly! Instead, create a new file called
# TODO a03_username.py and copy this code into it!
#################################################################################
# Author: Matthew Foti
# Username: Fotim
#
# Assignment: A03: A Pair of Fully Functional Gitty Psychedelic Robot... |
import os
from cadnano import app
from .selecttool import SelectTool
from .penciltool import PencilTool
from .breaktool import BreakTool
from .erasetool import EraseTool
from .insertiontool import InsertionTool
from .skiptool import SkipTool
from .painttool import PaintTool
from .addseqtool import AddSeqTool
import uti... |
import sqlite3
import jarvis.db.dal as dal
class DockerhubDal(dal.Dal):
def create_follow(cur, uuid, repository):
try:
cur.execute(""" INSERT INTO dockerhub_repository
(uuid, repository)
VALUES (?, ?)
""", [uuid... |
""" Module that implements various algorithms related to interface construction and analysis """
from pymatgen.analysis.interfaces.zsl import ZSLGenerator, ZSLMatch # noqa
from pymatgen.analysis.interfaces.coherent_interfaces import CoherentInterfaceBuilder # noqa
from pymatgen.analysis.interfaces.substrate_analyzer ... |
import pandas as pd
from pyspark.sql import DataFrame
class DataFrameReport(object):
def __init__(self, report_path):
assert(isinstance(report_path, str) and (report_path.endswith(".xlsx"))), "report path must be of type string" \
... |
import numpy as np
try:
from sentence_transformers.SentenceTransformer import SentenceTransformer # noqa
except ImportError:
ST_AVAILABLE = False
else:
ST_AVAILABLE = True
from asreview.models.feature_extraction.base import BaseFeatureExtraction
def _check_st():
if not ST_AVAILABLE:
raise I... |
def add(fnum, snum):
return fnum + snum
def sub(fnum, snum):
return fnum - snum
def mul(fnum, snum):
return fnum * snum
def div(fnum, snum):
try:
result = fnum/snum
except ZeroDivisionError as e:
result = 'N/A'
print(e)
print('snum cannot be zero for operation "/"')
fi... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Miao Feng
@contact: skaudreymia@gmail.com
@software: PyCharm
@file: util.py
@time: 2020/11/25 19:43
@desc: utilities: path...
'''
import os
import pandas as pd
import numpy as np
def getBasePath():
return os.getcwd()
def saveResult(id,ypred):
ypred = np.sque... |
from flask import Blueprint
blueprint = Blueprint("main", __name__)
from app.main import routes
|
import numpy as np
from distutils.version import LooseVersion
import warnings
import keras
import keras.backend as K
from keras.layers import *
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import ReduceLROnPlateau, TensorBoard
from csbdeep.utils import _raise, axes_check_and_n... |
import os
from glob import glob
def mkdir(path: str) -> None:
if not os.path.exists(path):
os.mkdir(path)
def get_dirs(path: str) -> list:
"""[summary]
Args:
path (str): [path of root directory]
Returns:
list: [all directories]
"""
dirs = [path]
for d in dirs:
... |
#!/usr/bin/env python
import argparse
import re
from pathlib import Path
from rdflib import Graph
def _stripping_square_bracket(s):
s = re.sub(r"\[[^\[\]]+]", "", s)
return s
def _stripping_slashes(s):
s = s.replace('/', ' ').replace('\\', ' ')
return s
def _stripping_comma(s):
s = s.repla... |
import sys
import argparse
from time import time
import random
from se_scraper import query, get_links
from csvsaver import SaveToCSV
def get_parser():
parser = argparse.ArgumentParser(
description='Search engine scraping via the command line')
parser.add_argument('query', metavar='QUERY', type=str... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Steven P. Goldsmith
# See LICENSE.md for details.
"""
Simple blocking event loop reads built in button and turns LED on and off based
on line edge. If you do not pass in --led then only button status is displayed.
-------------
Should work on any board with a button built i... |
# -*- coding: utf-8 -*-
!pip install requests
import requests
import json
import time
from random import randint
import pandas as pd
from pandas import json_normalize
from datetime import date, datetime, timedelta
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
from urllib.error import HTTPE... |
"""Ensure that matrix rotations do their"""
from random import randint
import pytest
from algorithms.src.rotation import out_of_place, in_place
rotators = [out_of_place, in_place]
@pytest.fixture
def small():
return [[1, 2], [3, 4]]
@pytest.fixture
def medium():
return [
[1, 2, 3, 4, 5],
... |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* re... |
from django.urls import path
from rest_framework_simplejwt.views import (
TokenRefreshView,
)
urlpatterns = [
#path('product/', MyTokenObtainPairView.as_view()),
#path('order/', TokenRefreshView.as_view()),
]
|
tamanio = float(input("Ingrese el tamaño del pez \n"))
if tamanio >= 10:
print("Pez contaminado")
elif tamanio >= 7:
print("Pez con síntomas de organismo contaminado")
elif tamanio >= 4:
print("Pez en buenas condiciones")
else:
print("Pez con problemas de nutrición")
input() |
import discord
import datetime
from discord.ext import commands
class Strike:
async def send_log(self, ctx: commands.Context, member: discord.Member, reason: str):
strike_embed = discord.Embed(
title="Strike",
color=discord.Color.red()
)
strike_embed.add_field(
... |
import tensorflow as tf
import numpy as np
from keras import backend as K
# src: https://www.kaggle.com/aglotero/another-iou-metric
def get_iou_vector(A, B):
batch_size = A.shape[0]
metric = []
for batch in range(batch_size):
t, p = A[batch]>0, B[batch]>0
intersection = np... |
# Three number sum program
# We will be using the sliding window algorithm here as well which will give us the complexity of O(nlogn)
def sum_of_three(arr, target) :
result = list()
arr.sort()
for i in range(len(arr)-2) :
left = i+1;right=len(arr)-1
while left < right :
... |
import os.path
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.geos import Point
from django.contrib.gis.geos.error import GEOSException
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from geotrek.authent.models import default_structure
from ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2019-20: Homework 5
Usage:
cnn.py view
cnn.py value
cnn.py -h
"""
from docopt import docopt
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class CNN(nn.Module):
# Remember to delete the above 'pass' after your ... |
## Contributors: Matt Ware
import numpy as np
import sys
sys.path.insert(1, '../../xtc')
###############################################################
### Specify detectors
###############################################################
detectors = {}
# Fast detectors
# detectors['sample']={'pskey':'timing', 'get'... |
from setuptools import setup, find_packages
from aikit import __meta__ as META
DISTNAME = 'aikit'
DESCRIPTION = 'An automated machine learning framework'
with open('README.md') as f:
LONG_DESCRIPTION = f.read()
MAINTAINER = META.__author__
MAINTAINER_EMAIL = ''
URL = META.__website__
DOWNLOAD_URL = 'https://pypi... |
import os
import torch
import numpy as np
from utils_grid import MatReader, UnitGaussianNormalizer
from utils_grid import create_grid
from protein_io import load_list
from protein_gen import PDNetDataset
def load_pde_data(path, sub, train=True):
TRAIN_PATH = os.path.join(path, 'piececonst_r421_N1024_smooth1.mat'... |
# Copyright 2018-2019 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS"... |
import datetime
import pytest
from anyway.models import AccidentMarker # for AccidentMarker.bounding_box_query
# This tests year 2014 accidents as this is the current example git data for testing
# Once this changes to another year or to the current year's accidents (as should be) un-comment lines 11,13,15
# and c... |
import configparser
import logging
import os
from shutil import copyfile
try:
import pymysql
except ImportError:
pymysql = None
import sqlalchemy as sa
from tlbx import rmfile
from glide import *
logging.getLogger("glide").setLevel(logging.DEBUG)
TEST_DATA_NAME = "dma_zip"
assert "GLIDE_CONFIG_FILE" in os.... |
'''
formatando valores com modificadores
:s - texto - string
:d - inteiros - int
:f - numeros ponto flutuante - float
:.(numero)f - quantidade de dasas decimais - float
:(caractere) (> ou < ^) (quantidade) (tipos - s, d ou f)
> - esquerda
< - direita
^ - centro
'''
#:.(numero)f - quantidade de dasas decimais - float... |
import os
import sys
import traceback
import time as time_module
import numpy as np
from qtpy.compat import getopenfilename
#from qtpy.QtWidgets import QFileDialog
from pyNastran.bdf.patran_utils.read_patran_custom_results import load_patran_nod
from pyNastran.utils import print_bad_path
from pyNastran.gui.utils.load... |
from rest_framework import serializers
from ...models.creel import FN025
class FN025Serializer(serializers.ModelSerializer):
"""Class to serialize the exception dates within seasons within each creel."""
class Meta:
model = FN025
fields = ("slug", "season", "date", "dtp1", "description")
c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-11-24 07:29
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
import tinymce.models
class Migration(migrati... |
# Copyright 2021 The Meson development team
# 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 ... |
# Add taintlib to PATH so it can be imported during runtime without any hassle
import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__))))
from taintlib import *
# This has no runtime impact, but allows autocomplete to work
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..taintlib... |
# Reserved keys used to handle ClassMethodNode in Ray DAG building.
PARENT_CLASS_NODE_KEY = "parent_class_node"
PREV_CLASS_METHOD_CALL_KEY = "prev_class_method_call"
# Reserved key to distinguish DAGNode type and avoid collision with user dict.
DAGNODE_TYPE_KEY = "__dag_node_type__"
|
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
#
# TITLE : Test `utilipy.units.decorators`
# PROJECT : `utilipy`
#
# ----------------------------------------------------------------------------
"""Test `utilipy.units.decorators`.
Routine Listings
-----------... |
#
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
#
# Copyright (c) 2016, Juniper Networks, Inc. All rights reserved.
#
#
# The contents of this file are subject to the terms of the BSD 3 clause
# License (the "License"). You may not use this file except in compliance
# with the License.
#
# You can obta... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migratio... |
from voximplant.apiclient import VoximplantAPI, VoximplantException
if __name__ == "__main__":
voxapi = VoximplantAPI("credentials.json")
# Bind the skills with id 1 and 2 to all users.
APPLICATION_ID = 1
USER_ID = "all"
SQ_SKILLS = "[{\"sq_skill_id\":1,\"sq_skill_level\":1},{\"sq_skill_id\":... |
from os.path import join
from boucanpy.core.utils import db_dir
from boucanpy.db.session import session, db_register
from boucanpy.db.utils import make_db_url
from boucanpy.db.migrate.show import show
from boucanpy.cli.base import BaseCommand
class AlembicShow(BaseCommand):
name = "alembic-show"
aliases = ["a... |
from __future__ import annotations
from typing import Iterable
import click
from ckan import model
import ckan.plugins.toolkit as tk
# datagovau spatial-ingestor command group.
@click.group("spatial-ingestor", short_help="Ingest spatial data")
def spatial_ingestor():
pass
def ingest_scope(scope) -> Iterable[tu... |
from django.db import models
class Electricity(models.Model):
class Meta:
unique_together = (("date", "hour"))
ordering = ["date", "hour"]
date = models.DateField()
hour = models.PositiveSmallIntegerField()
usage = models.DecimalField(max_digits=10, decimal_places=2)
def get_ti... |
def test_delete_rowid_table(fresh_db):
table = fresh_db["table"]
table.insert({"foo": 1}).last_pk
rowid = table.insert({"foo": 2}).last_pk
table.delete(rowid)
assert [{"foo": 1}] == list(table.rows)
def test_delete_pk_table(fresh_db):
table = fresh_db["table"]
table.insert({"id": 1}, pk="i... |
import argparse
import simpleamt
if __name__ == '__main__':
parser = argparse.ArgumentParser(parents=[simpleamt.get_parent_parser()],
description="Delete HITs")
parser.add_argument('--hit_id')
args = parser.parse_args()
mtc = simpleamt.get_mturk_connection_from_args(args)
hit_id = args.hit_id
... |
from django.contrib import admin
from related_admin import RelatedFieldAdmin
from . import models
class PaymentAdmin(RelatedFieldAdmin):
list_display = (
'id',
'transaction_id',
'order__user',
'variant',
'status',
'fraud_status',
'currency',
'total... |
#Don't know why this file is needed. VSCode won't load the tests otherwise, even when the package is installed in the pythonpath..
#Seems like an abuse of pytest test discovery.. https://stackoverflow.com/questions/49028611/pytest-cannot-find-module/49033954 |
from django.apps import AppConfig
from django.conf import settings
import os
import pickle
class PredictorConfig(AppConfig):
# create path to models
pass
|
from __future__ import print_function
from deco import *
import time
@concurrent
def work():
time.sleep(0.1)
@synchronized
def run():
for _ in range(100):
work()
if __name__ == "__main__":
start = time.time()
run()
print("Executing in serial should take 10 seconds")
print("Executin... |
"""
Schema Validation
Tests a dictionary against a schema to test for conformity.
Schema definition is similar to - but not the same as - avro schemas
Supported Types:
- string - a character sequence
- numeric - a number
- int - alias for numeric
- date - an iso format date or time
- boolean -... |
# world/africa/zimbabwe.py
print("Shona: Mhoroyi vhanu vese")
print("Ndebele: Sabona mhlaba")
|
from django.db import models
class Series(models.Model):
hash = models.CharField(max_length=64, unique=True)
path = models.TextField()
__str__ = lambda self: "Series [%s]" % self.path
class Tag(models.Model):
tag = models.CharField(max_length=191, unique=True)
__str__ = lambda self: "Tag [%s]" %... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from typing import List, Optional, Tuple
from collections import deque
import copy
class Deck:
def __init__(self, number: int, cards: List[int]) -> None:
self.number = number
self.cards = deque(cards)
def hascards(self) -> bool:
return bool(self.cards)
def draw(self) -> int:
... |
import ila
from gb_arch import GBArch
from gb_wri import WRI
from gb_u1 import U1
from gb_u2 import U2
from gb_u3 import U3
from gb_u4 import U4
def createILA ():
gb = GBArch ()
U1 (gb)
U2 (gb)
U3 (gb)
U4 (gb)
WRI (gb)
gb.setNext ()
verilogFile = 'gb_verilog_wri.v'
gb.exportVerilo... |
import numpy as np
import pandas as pd
class FeatureImport:
def __init__(self, filename=None):
self.filename = filename
self.skyline_export = None
self.sample_df = None
self.precursor_df = None
self.transition_df = None
self.features = None
self.ion_type_m... |
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=255)
text = models.TextField()
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
text = models.TextField()
created_at = models.DateTimeField(aut... |
# coding=utf-8
import random
def permutation(n):
ret = list(range(1, n+1))
for _ in range(2 * n):
i = random.randint(0, n-1)
j = random.randint(0, n-1)
ret[i], ret[j] = ret[j], ret[i]
return ret
def flat_block(i, j, m, size):
a, b = (i // size) * size, (j // size) * size
... |
# -*- coding: utf-8 -*-
"""
@author: Manasseh Madu
A simple Image Manipulation application
"""
import os
import sys
import time
import platform
from PyQt5.QtGui import (QBrush, QPixmap, QPainter)
from PyQt5.QtWidgets import (QColorDialog, QDialog, QLabel, QSpinBox, QComboBox, QPushButton, QDialogButtonBox, QGridLayout... |
from decimal import Decimal
from django.db import models
from django.contrib import admin
class Food(models.Model):
"""
Model that represents a food item on the restaurant menu.
Attributes:
:name: The name of the food.
:type: The type of the food limited to: "sta... |
from dagster import job
@job(tags={"dagster/max_retries": 3})
def sample_job():
pass
@job(tags={"dagster/max_retries": 3, "dagster/retry_strategy": "ALL_STEPS"})
def other_sample_sample_job():
pass
|
from evawiz_basic import *
def request(handler,*args):
#def request_download_module_to_user(self,module_name='',options={}):
module_name = args_get(0,args)
options = args_get(1,args)
#step 1 check module information
if not module_name: return None
handler.contact_server('mod_download_module')
h... |
import os, time, glob, shutil
from selenium import webdriver
from math import ceil
import re
def load_book(driver, page, keyword):
url = 'http://www.riss.kr/search/Search.do?detailSearch=false&viewYn=OP&queryText=&iGroupView=5&icate=all&colName=bib_m&pageScale=1000&strSort=RANK&order=%2FDESC&query='
url2 = '&... |
from tulip import *
from graphfuncs import *
import networkx as nx
import citation_graph as cg
import datetime
import abc
import random
#############################CLASS DECLARATIONS
#initialize the global variable base_graph
#The abstract class for the graphclass.
#The goal of this is the abstract method build_... |
def permutationWCaseChangeUtil(input_string, output_string):
if len(input_string) == 0:
print(output_string, end=', ')
return
modified_output_string1 = output_string + input_string[0].upper()
modified_output_string2 = output_string + input_string[0]
modified_input_string = input... |
"""
This script converts the genome fasta file to a memory map
file of genome one-hot encodings. This is used to accelerate
genome sequence retrieval (Orca automatically detects the memmap
file and use it) and is required if you use the training scripts.
Example usage: python make_genome_memmap.py
"""
import... |
# Bazsalya András Vizsgaremek Feladat: (register), Login, logout
# -Regisztráció (sign_up_func(usern, email, pwd, result1)
# Érvényes: TC1-1-001-5
# Érvénytelen: TC1-0-001-5
# -Bejelentkezés (login_func(email, pwd, logged_in, e_result))
# Érvényes: TC2-1-001-5
# Érvénytelen: TC2-0-001-5
# -Adatkezelési nyila... |
db.parte_ti.cumplimiento_fact.represent = db.parte_ti.indicadores_acum.represent = db.parte_ti.indicadores_mes.represent = db.parte_ti.cumplimiento_cronogramas.represent = lambda dato, row: MARKMIN(dato)
def index():
titulo = "Partes del Dpto. TI"
p = P(XML('<a href="/ti/plugin_wiki/ayuda-wiki" target="_bl... |
import asyncio
import sqlalchemy as sa
from sqlalchemy.schema import CreateTable
from aiopg.sa import create_engine
metadata = sa.MetaData()
users = sa.Table(
'users_sa_transaction', metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('name', sa.String(255))
)
async def create_sa_transa... |
import numpy as np
import pytest
from npe2 import DynamicPlugin
from qtpy.QtWidgets import QLabel, QRadioButton
from napari._qt.dialogs.qt_reader_dialog import (
QtReaderDialog,
open_with_dialog_choices,
prepare_remaining_readers,
)
from napari.errors.reader_errors import ReaderPluginError
from napari.sett... |
def insort_any_type_left(sorted_list, list_item, less_than=lambda lhs, rhs: lhs < rhs):
"""Insert a list item into a sorted list, keeping the list sorted."""
low = 0
high = len(sorted_list)
while low < high:
mid = (low + high) // 2
if less_than(sorted_list[mid], list_item):
... |
import numpy as np
import sys
def main():
input = sys.stdin.readline
N = int(input())
A = np.array([tuple(map(int, input().split())) for _ in range(N)], dtype=np.float)
B = np.array([tuple(map(int, input().split())) for _ in range(N)], dtype=np.float)
A_weighted_center = np.sum(A, axis=0) / N
... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Hang Zhang
## ECE Department, Rutgers University
## Email: zhang.hang@rutgers.edu
## Copyright (c) 2017
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this sou... |
app_name = "accounts"
urlpatterns = []
|
# coding: utf-8
"""
Xero Projects API
This is the Xero Projects API # noqa: E501
OpenAPI spec version: 2.3.4
Contact: api@xero.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
from xero_python.models import BaseModel
class Error(BaseModel):
"""NOTE: This clas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.