content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.27 on 2020-02-19 01:58
from __future__ import unicode_literals
from corehq.sql_db.operations import RawSQLMigration
from django.db import migrations, models
from custom.icds_reports.const import SQL_TEMPLATES_ROOT
migrator = RawSQLMigration((SQL_TEMPLATES_ROOT, 'dat... |
# ----------------
# User Instructions
#
# Implement twiddle as shown in the previous two videos.
# Your accumulated error should be very small!
#
# You don't have to use the exact values as shown in the video
# play around with different values! This quiz isn't graded just see
# how low of an error you can get.
#
# Tr... |
#!/usr/bin/env python3
'''
This script will set up the current folder with its dependencies
'''
import os
import argparse
import subprocess
from _load_vars import load_vars
GN_ARGS = 'target_os = "android"\ntarget_cpu = "arm64"\n'.encode('utf-8')
parser = argparse.ArgumentParser(
description='Initialize the cur... |
VERSION = (1, 3, 5)
__version__ = '.'.join(str(i) for i in VERSION)
|
from pathlib import Path
from unittest import mock
from typing import Callable
import json
import pytest
from my_utils.decorators import cache
def test_cache_decorator_factory(tmpdir):
m = mock.Mock()
hash_f = lambda f, args, _: hash(f"{f.__name__}-{json.dumps(args)}")
@cache.cache_decorator_factory(Pa... |
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.flood import stations_highest_rel_level, stations_level_over_threshold
stations = build_station_list()
update_water_levels(stations)
def test_stations_level_over_thresh... |
import os
from flask import Flask, render_template, request
from MovieClass import MovieClass
#initialize the movie class and randomize the internal list
movie = MovieClass()
movie.import_top250()
movie.randomize()
app = Flask(__name__)
pictures = os.path.join('static','pics') #load pictures folder to flask
app.confi... |
from ..item import Item
from ..writer import Writer
import yaml
content_type = "application/yaml"
def load(self, text):
"""Item from YAML representation."""
self.__dict__ = yaml.safe_load(text)
def dump(self):
"""Item in YAML representation."""
return yaml.dump(self.primitive, default_flow_style=F... |
#!/usr/bin/env python
#encoding=utf-8
# setup.py
# This file is part of PSR Registration Shuffler
#
# Copyright (C) 2008 - Dennis Schulmeister <dennis -at- ncc-1701a.homelinux.net>
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
#... |
import os
import boto3
media_url = './media/unknown'
target = ''
bucket_name = 'korestate'
s3 = boto3.resource('s3')
abs_curdir = os.path.abspath('.')
dir_cointents = os.path.join(abs)
def write_all(target = media_url, to_bucket = bucket_name, usr = 'images'):
dir_contents = os.listdir(target)
print ... |
# import the necessary packages
import numpy as np
# Felzenszwalb et al.
def non_max_suppression_slow(boxes, overlapThresh):
# if there are no boxes, return an empty list
if len(boxes) == 0:
return []
# initialize the list of picked indexes
pick = []
# grab the coordinates of the bounding boxes
x1 = boxes[:... |
import numbers
from scipy.stats import mode
import pandas as pd
import numpy as np
import datetime
from mlapp.utils.exceptions.framework_exceptions import UnsupportedFileType
class ClassificationFeatureEngineering(object):
def drop_features(self, data_df, features_to_drop=None):
"""
Dropping requ... |
from typing import Optional, Union
from urllib.parse import urljoin
import aiohttp
from starlette.datastructures import Headers
from starlette.requests import Request
from starlette.types import Scope
from starlette.websockets import WebSocket
Headerlike = Union[dict, Headers]
class ProxyConfig:
def get_upstrea... |
import logging
import sys
import os
import requests as req
from collections import OrderedDict
import cartosql
import lxml
from xmljson import parker as xml2json
from dateutil import parser
import requests
import datetime
### Constants
SOURCE_URL = "http://volcano.si.edu/news/WeeklyVolcanoRSS.xml"
DATETIME_FORMAT = '... |
# -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
from swf.models.event.base import Event
from swf.models.event.compiler import CompiledEvent
class MarkerEvent(Event):
_type = "Marker"
class CompiledMarkerEvent(Compile... |
# Copyright (C) 2019 NTT DATA
# 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 ... |
from AudioData import AudioData
import numpy as np
def test_it_handles_already_normalized_data():
audioData = AudioData()
arr = np.array([0, 1])
assert (audioData.normalize(arr) == arr).all()
def test_that_it_normalizes_data():
audioData = AudioData()
arr = np.array([0, 2])
assert (audioData.n... |
from app.models import db
class LibraryBook(db.Model):
__tablename__ = "library_book"
# table columns
id = db.Column(db.Integer, primary_key=True)
book_id = db.Column(db.Integer, db.ForeignKey("book.id"), nullable=False)
library_id = db.Column(db.Integer, db.ForeignKey("library.id"), nullable=Fal... |
import pygame
from pygame.locals import *
import obstacle
from utils import *
class Environnement(pygame.sprite.Group):
def __init__(self):
super().__init__()
self.new_obs = None
def process_event(self, event):
if event.type == MOUSEBUTTONDOWN:
# Check f... |
# -*- coding: utf-8 -*-
# <standard imports>
from __future__ import division
import random
import otree.models
import otree.constants
from otree.db import models
from otree import widgets
from otree.common import Currency as c, currency_range, safe_json
from otree.constants import BaseConstants
from otree.models impo... |
from keras import backend as K
from keras.models import Model
from keras.layers import (BatchNormalization, Conv1D, Dense, Input,
TimeDistributed, Activation, Bidirectional, SimpleRNN, GRU, LSTM, CuDNNGRU, CuDNNLSTM, Dropout)
def simple_rnn_model(input_dim, output_dim=29):
""" Build a recurrent network for sp... |
#!/usr/bin/env python3
"""
MIT License
Copyright (c) 2021 Ygor Simões
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, m... |
"""Template tags for working with lists of items."""
from django import template
from soclone.utils.lists import batch_size, batches
register = template.Library()
@register.filter
def in_batches_of_size(items, size):
"""
Retrieves items in batches of the given size.
"""
return batch_size(items, int(s... |
"""
Pipelines that perform many operations at once (eg. tracking all particles from a directory of images), and help scripts.
"""
from .ForceSolve import *
from .TrialObject import *
|
import os
import pytest
from voluptuous import Schema as _Schema
from dvc import output
from dvc.dvcfile import PIPELINE_FILE
from dvc.schema import SINGLE_PIPELINE_STAGE_SCHEMA
from dvc.stage import PipelineStage, create_stage
from dvc.stage.serialize import to_pipeline_file as _to_pipeline_file
kwargs = {"name": "... |
from datetime import datetime
import sqlalchemy
from loguru import logger
from app.models.user import User
from app.schemas.user import (
UserCreate,
UserIncreaseFileCount,
UpdateUserDownloadStats,
)
from app.services.main import AppService, AppCRUD
from app.utils.app_exceptions import AppException
from a... |
"""This contains all of the forms used by the API application."""
# Django Imports
from django import forms
# 3rd Party Libraries
from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, ButtonHolder, Column, Layout, Row, Submit
class ApiKeyForm(forms.Form):
"""
Save an individual :... |
# Define a procedure, biggest, that takes three
# numbers as inputs and returns the largest of
# those three numbers.
def biggest (n1, n2, n3):
if n1 > n2:
if n1 > n3:
return n1
else:
return n3
if n2 > n3:
return n2
return n3
print biggest(3, 6, 9)
#>>> 9
p... |
'''
The Sphere manifold can be paramterized using theta and phi
The sphere manifold is isometric to R2 using the conical projection map
The Sphere manifold's laplacian hence must be similar to the laplacian of R2
This experiment would seek to infer the laplacian from given samples, with the manifold being endowed with ... |
import io
import json
import os
import shutil
import sys
pjoin = os.path.join
from IPython.utils.path import get_ipython_dir
from IPython.utils.py3compat import PY3
from IPython.utils.traitlets import HasTraits, List, Unicode, Dict, Any, Set
from IPython.config import Configurable
from .launcher import make_ipkernel_... |
# Copyright 2016 Twitter. 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 applicable law or agree... |
class Node(object):
"""
Represents a node in a contingent plan.
Only the stated fields are mandatory.
Other optional info can be added by ConfigurationProvider implementations
"""
def __init__(self, id, partial_state, is_initial, is_goal):
self._is_initial = is_initial
self._is... |
from groups import Group
from operator import itemgetter
class Subgroup(Group):
"""
Define subgroup by generators or by set of elements
"""
def __init__(self, G, gens = None, H = None):
if isinstance(G,Subgroup):
H = list(itemgetter(*H)(G._H)) if len(H)>1 else [G._H[list(H)[0]]]... |
from django.conf.urls import patterns, include, url
from rest_framework import routers
import views
router = routers.DefaultRouter()
router.register(r'attempt', views.AttemptViewSet, base_name='attempt')
router.register(r'repository', views.RepositoryViewSet, base_name='repository')
urlpatterns = patterns('',
url... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016, 2017 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Li... |
from babelsubs.generators.base import BaseGenerator, register
from babelsubs.utils import UNSYNCED_TIME_ONE_HOUR_DIGIT
class SBVGenerator(BaseGenerator):
file_type = 'sbv'
MAPPINGS = dict(linebreaks="[br]")
def __init__(self, subtitles_set, line_delimiter=u'\r\n', language=None):
super(SBVGenerat... |
# lend admin
from django.contrib import admin
from django_admin_listfilter_dropdown.filters import RelatedDropdownFilter, DropdownFilter
from lend_models.class_models.lend_client import LendClientSet, LendClient
class LendClientSetAdmin(admin.ModelAdmin):
list_display = ['name', ]
list_per_page = 25
sear... |
import genkey
import db
import re
def genURL(data):
url = data
key = genkey.generateKey()
db.insert(key, url)
return ("localhost:8000/"+key)
def retURL(path):
rankey = re.findall('\/(.*)', path)
for i in rankey:
rankey = i
stourl = db.retrieve(rankey)
return stourl
# print("... |
# 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 the "license" file acc... |
import os
from typing import List, Dict, Any, Callable
from argparse import Namespace as Arguments
from platform import node as get_hostname
from . import EXECUTION_CONTEXT, MOUNT_CONTEXT
from .utils import (
find_variable_names_in_questions,
ask_yes_no, get_input,
distribution_of_users_per_scenario,
... |
"""
Test Generate RDF from Assocs
"""
import rdflib
from rdflib.namespace import RDFS
from rdflib import compare
from ontobio.io.gafparser import GafParser
from ontobio.rdfgen.assoc_rdfgen import TurtleRdfWriter, CamRdfTransform
from ontobio.assoc_factory import AssociationSetFactory
from ontobio.ontol_factory import ... |
import datetime
import unittest
from sqlalchemy.orm import sessionmaker
from bot.conversations.statistics.utils import get_consumptions_for_graph_user, get_earnings_for_graph_user
from bot.models import Base, Consumption, User, Earning
from tests.test_models import engine
from tests.utils_models import add_example_us... |
# -*- coding: utf-8 -*-
from ..errors import XmppError
from ..stanzas import Stanza
NS_URI = "urn:ietf:params:xml:ns:xmpp-tls"
async def handle(stream, feature_elem, timeout=None):
nsmap = {"tls": NS_URI}
stream.send(Stanza("starttls", nsmap={None: NS_URI}))
resp = await stream.wait([("/tls:proceed", n... |
import torch
import torch.nn as nn
from glasses.models.classification.fishnet import FishNet, FishNetBottleNeck
from glasses.nn.att import SpatialSE
from torchinfo import summary
def test_fishnet():
device = torch.device('cpu')
x = torch.rand(1, 3,224,224)
model = FishNet().eval()
pred = model(x)
... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import logging
from typing import Any, List, Mapping, Tuple, Type
import pendulum
from airbyte_cdk.models import AuthSpecification, ConnectorSpecification, DestinationSyncMode, OAuth2Specification
from airbyte_cdk.sources import AbstractSource
from airbyte_... |
"""
Copyright (C) 2020 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 wri... |
# Copyright (c) 2015 Red Hat, 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 writ... |
# The process in which a function calls itself directly or indirectly is called recursion.
# Here is a Good example for Recursion in Python..
# This Recursion makes factorial-finding efficient compared to other methods using loops.
def factorial(n):
if n < 0 :
return 'try non-negative integer'
elif n =... |
"""
The test suite has some dependencies that aren't necessarily required for the
blingalytics package itself:
* You should have postgresql installed, with a "bling" user whose password is
set to "bling", and a database named "bling" owned by "bling".
* You need the following Python packages installed: mock, django ... |
from dotenv import load_dotenv
load_dotenv()
from src.dao.firebase import firebase_instance
id_token = "id_token"
if __name__ == '__main__':
firebase = firebase_instance()
auth = firebase.auth()
account_info = auth.get_account_info(id_token)
print(account_info)
|
print(1 + 2) # 加法
print(1 - 2) # 减法
print(1 * 2) # 乘法
print(1 / 2) # 浮点数除法
print(3 ** 2) # 指数计算
print(3 % 2) # 取模计算
print(3 // 2) # 整数除法
# 查看数据类型
print(type(1))
print(type(1.11))
print(type(1 + 2j))
print(type("Python"))
print(type([1, 2, 3]))
print(type({'name': '张三'}))
print(type({1.1, 2.2, 3.3}))
|
import zengin
if __name__ == '__main__':
print(zengin.Bank.get('0001'))
for bank in zengin.Bank.search('み'):
print(bank)
for branch in zengin.Branch.get('0001', '001'):
print(branch)
for branch in zengin.Branch.search('0005', 'キチジョウジ'):
print(branch)
for bank in zengin.B... |
"""django-changerequest views"""
from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
from django.http import HttpResponseRedirect, QueryDict
from django.urls import reverse
from django.views.generic import DetailView, ListView
from django.contrib.auth.mixins import PermissionRequ... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from lxml import etree
class LinkscrapyPipeline:
def open_spider(self, spider):
self.root = etree.Element('data')... |
from rest_framework.generics import (
ListAPIView,
RetrieveAPIView,
DestroyAPIView,
UpdateAPIView
)
from debate.models import DebateTopic
from debate.api.serializers import DebateTopicSerializer
class DebateTopicListAPIView(ListAPIView):
queryset = DebateTopic.objects.all()
serializer_class... |
"""
Module to contain the Bot class, which acts as 'glue' to combine the rhythm, row generation and
SocketIO communication provided by the Rhythm, RowGenerator and Tower objects into a useful program.
"""
import time
import logging
import threading
from typing import Optional, Any, List
from wheatley import calls
fro... |
#HARDWARE_AQUISITION = BudgetLine.objects.get(id=3)
from django.contrib.auth.models import User
from django.db import models
from django.forms import fields
from django.utils.translation import ugettext_lazy as _
from what_apps.commerce.models import RealThing
from what_apps.products.models import Product, ProductBran... |
# Paybag
# Author - D3adpool2K
# github - https://github.com/Deadpool2000
import os
import random
import sys
from prettytable import PrettyTable
import distro
try:
os.system('clear')
R='\033[91m'
Y='\033[93m'
G='\033[92m'
CY='\033[96m'
W='\033[97m'
B='\033[95m'
global osname
... |
# Taken from https://github.com/CCGSRobotics/CCGSRobotics-battlebots
from pyax12.connection import Connection
servo_connection = Connection(port="/dev/ttyACM0", baudrate=1000000)
servo_connection.flush()
# Consult the robotics emanual for more infomation on how
# the dynamixel servos interpret communications.
# ==... |
import pytest
import torch
import torch.nn as nn
from gyomei_trainer.modules.lr_scheduler import Scheduler
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28... |
# Generated by Django 2.2.10 on 2020-04-29 22:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('youtube_saver', '0006_auto_20200430_0113'),
]
operations = [
migrations.DeleteModel(
name='YoutubeFormats',
),
]
|
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from article import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name="index"),
path('about/', views.about, name="about"),
... |
# -*- coding: UTF-8 -*-
from . import config
from . import log
log = log.Log(__name__)
def set(filename, content):
try:
file = open(config.cache_root_path + filename, 'w+', encoding='utf8')
file.write(content)
file.close()
except Exception as e:
log.error(str(e))
def get(file... |
from config import *
from scipy.io import loadmat
from keras.utils import np_utils
import pickle
def load(file_path=dataset_path):
"""
load dataset from a .mat file and save mapping to ASCII into a file
:param
file_path: path to the .mat file (default value specified in config)
:return:
... |
import torch
from torch import nn
from tqdm.notebook import tqdm
from criterion import WassersteinLoss, GradientPenalty
class Trainer():
def __init__(self, generator, critic, g_optimizer, c_optimizer, device='cuda:0'):
self.generator = generator.to(device)
self.critic = critic.to(device)
s... |
"""
Contains fields used to select database models
"""
import logging
from . import basicfields
__author__ = 'Yu Lee Paul (Little Fish Solutions LTD)'
log = logging.getLogger(__name__)
class DbCodeSelectField(basicfields.SelectField):
"""
A select field that loads the database model by code
"""
de... |
from __future__ import absolute_import, division, print_function
import warnings
from collections import namedtuple
import networkx
import numpy as np
import torch
import pyro
import pyro.poutine as poutine
from pyro.infer.util import torch_backward, torch_data_sum
from pyro.poutine.util import prune_subsample_sites... |
__version__ = "20.02.3"
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 04:37:02 2017
@author: gurjot
"""
### START BOILERPLATE CODE
# Sample Python code for user authorization
#import httplib2
from apiclient.discovery import build
#from oauth2client.client import flow_from_clientsecrets
#from oauth2client.file import Storage
from oaut... |
################################################################################
#
# Copyright (c) 2019, the Perspective Authors.
#
# This file is part of the Perspective library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
import tornado
from random i... |
import unittest
from pathlib import Path
import volatile
from ..flit import FlitReader
from ..pep517 import get_backend
from ..setuptools import SetuptoolsReader
class Pep517Test(unittest.TestCase):
def test_no_backend(self) -> None:
with volatile.dir() as d:
dp = Path(d)
require... |
"""Web frontend functions for stand-alone running."""
import typing
import aiohttp.web
from cryptography.fernet import InvalidToken
from swift_browser_ui.ui.settings import setd
from swift_browser_ui.ui._convenience import session_check
async def browse(request: aiohttp.web.Request) -> aiohttp.web.FileResponse:
... |
#!/usr/bin/python
##################################################
## Author: Joshua Franklin
## whoarethey.py
## Example input to start:
## sudo ./whoarethey.py -f someFileNmae
## The file name should contain an electionBuster results file
## This code relies on a library from Google: https://code.google.com/p/pywh... |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
hashmap = {}
hashset = set()
for i in range(len(s)):
if s[i] not in hashmap:
if t[i] in hashset:
return False
elif hashmap[s[i]] != t[i]:
return False
... |
#!/usr/bin/env python3
# coding: utf-8
__author__ = 'mkanai'
import argparse
import atexit
import numpy as np
import hail as hl
import uuid
from hail.linalg import BlockMatrix
from hail.utils import new_temp_file, hadoop_open, timestamp_path
from ukbb_pan_ancestry.resources import get_filtered_mt, get_variant_results... |
from rest_framework import serializers
from rest_framework.reverse import reverse
from unifier.apps.core.models import Manga, Novel, Platform
class MangaPlatformSerializer(serializers.ModelSerializer):
class Meta:
model = Manga
fields = ["id", "title", "year", "chapters_count"]
class NovelPlatfo... |
from abc import abstractmethod, ABCMeta
import numpy as np
from palmnet.layers.multi_conv2D import MultiConv2D
from palmnet.layers.multi_dense import MultiDense
from skluc.utils import logger
from tensorly.decomposition import matrix_product_state
from palmnet.core.layer_replacer import LayerReplacer
from palmnet.dat... |
import numpy as np
import statistics as st
"""
Enunciado
Crie uma função que recebe uma lista de números e devolve, nesta ordem, o mínimo, a média, o desvio padrão e o máximo.
Dica: Use a biblioteca statistics (import statistics) para calcular o desvio padrão: desvio = statistics.stdev(lista)
"""
lista = [6, 4, 3, 7,... |
n = int(input())
answer = 0
for _ in range(n) :
exp = input()
answer = max(answer, eval(exp))
print(answer) |
# -*- coding: utf-8 -*-
# @Time : 2021/3/19 12:18 PM
import traceback
from flask import request, current_app
from werkzeug.exceptions import HTTPException
from app.api import route_api
from common.libs.customException import CustomException
from common.libs.api_result import api_result
@route_api.app_errorhand... |
from jsut.corpus import Subtype
from typing import Callable, List, Optional, Union
import pytorch_lightning as pl
from torch.tensor import Tensor
from torch.utils.data import random_split, DataLoader
from ...dataset.spectrogram import JSUT_spec
class JSUT_spec_DataModule(pl.LightningDataModule):
"""
JSUT_sp... |
from octis.models.DETM_model import detm
from octis.models.base_etm import BaseETM
from octis.models.DETM_model import data
import torch
import warnings
class DETM(BaseETM):
def __init__(self, num_topics=50, rho_size=300, embedding_size=300, t_hidden_size=800,
activation='relu', train_embeddings=1... |
#!/usr/bin/env python3
def read_fastq(infile):
# reading one fastq-record at a time using a generator
name, seq, qual = None, None, None
while True:
line = infile.readline()
if not line:
break
name = line.rstrip()
line = infile.readline()
if not line:
... |
# Generated by Django 3.1.7 on 2021-04-29 05:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('patient', '0003_auto_20210429_1259'),
]
operations = [
migrations.RenameField(
model_name='patientuser',
old_n... |
# Copyright (c) 2013, August Infotech and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import msgprint, _, throw
def execute(filters=None):
if not filters: filters = {}
columns = get_columns(filters)
data = []
entries = get_income... |
"""
This module contains all functions and classes for reading a response file and pushing it into the database
Functions and Classes
---------------------
"""
from nordb.database import sitechan2sql
from nordb.core import usernameUtilities
from nordb.database import creationInfo
RESPONSE_INSERT = (
... |
#!/usr/bin/python
# Copyright 2015 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.
"""This is a small script designed to issue REINDEX TABLE commands to psql."""
import argparse
import os
import sys
# Import 'common.env'... |
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from django.urls import reverse
from wagtail.admin.admin_url_finder import AdminURLFinder
from wagtail.documents.models import Document
from wagtail.models import Collect... |
# Copyright (C) 2007-2017, Raffaele Salmaso <raffaele@salmaso.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, cop... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 2 08:22:48 2022
@author: xavier.mouy
"""
from ecosound.core.annotation import Annotation
from ecosound.core.metadata import DeploymentInfo
from ecosound.core.audiotools import Sound
import pandas as pd
from datetime import datetime
import os
import librosa
import libros... |
"""A very simple MNIST classifier.
See extensive documentation at
http://tensorflow.org/tutorials/mnist/beginners/index.md
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
# assert tf.__version__ == "1.8.0"
tf.set... |
"""
This is the main, runnable .py script for the xor-problem
"""
from nn import NN
from optimizer import ADAM
from loss import cross_entropy_loss
from batching import MiniBatcher
import numpy as np
import matplotlib.pyplot as plt
import os
savefig_location = os.path.join(os.path.dirname(__file__), 'media')
train_sa... |
import pytest
from sklearn.datasets import load_iris, make_regression
from Amplo.AutoML import DataExplorer
from tests import rmtree
@pytest.fixture(scope='class', params=['classification', 'regression'])
def make_mode(request):
mode = request.param
if mode == 'classification':
x, y = load_iris(retu... |
from kittens.tui.handler import result_handler
import os
def main(args):
pass
@result_handler(no_ui=True)
def handle_result(args, result, target_window_id, boss):
window_title = "vimjupyter"
jupyter_cmd = "jupyter"
cwd = args[1].replace(" ","\\ ")
cmd = f"cd {cwd}; {jupyter_cmd} console"
# Runs a command... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-29 12:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djangovirtualpos', '0009_vpsrefundoperation'),
]
operations = [
migrations.... |
from django.conf.urls import url
from django.conf.urls import include
from django.urls import path
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, 'hello-viewset')
router.register('signup', views.UserProfileViewSet)
rou... |
"""
## iam_detach_policy
What it does: detach all entities that attached to policy
Usage: iam_detach_policy
Limitations: none
"""
import boto3
from botocore.exceptions import ClientError
def detach_policy_from_entity(iterator, policy_arn):
"""
iterates throw list of entities and detach the policy
"""
t... |
import unittest
from getnet.services.customers import Customer, Address
sample = {
"seller_id": "6eb2412c-165a-41cd-b1d9-76c575d70a28",
"customer_id": "customer_21081826",
"first_name": "João",
"last_name": "da Silva",
"document_type": "CPF",
"document_number": "78075751159",
"birth_date":... |
"""
zadeklaruj funkcje która zwraca błąd
"""
def blad():
return ValueError
print(blad())
|
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.