content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
import argparse
import yaml
from firewall import FirewallRule
from gcloud_firewall import get_creds_project, init_gcloud_client, apply_gcloud_firewall
from aws_firewall import init_aws_client, apply_aws_rule_group, apply_aws_firewall_resources
def apply_gcloud_rule(client, firewall_rule, pro... |
# Copyright 2015 NEC Corporation. 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 b... |
"""Neocities client."""
import requests
from .filetree import FileTree
from .log import debug
class BearerAuth(requests.auth.AuthBase):
"""Bearer token authentication functor for requests."""
__token: str
def __init__(self, token: str):
"""
Initialize object.
Parameters
... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ads', '0002_site_m2m'),
]
operations = [
migrations.AlterField(
model_name='banner',
name='active',
field=models.BooleanField(default=True, help_text=b'V... |
#!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... |
# job = Job(uuid1(), td(seconds=5))
# job_dict_coerce = dict(job)
# job_dict_compre = {**job}
# job_dict_cast = {job}
# assert job_dict_coerce == job_dict_cast == job_dict_compre
|
narrators = [
"Simon Jäger",
"David Nathan",
]
authors = [
"Sebastian Fitzek",
"Michael Tsokos",
"Volker Kutscher",
"Horst Evers",
]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) 2020, Bodo Schulz <bodo@boone-schulz.de>
# BSD 2-clause (see LICENSE or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
# import json
import os
from ansible.module_utils.basic import AnsibleModule
# i... |
!/bin/python
# structure.py
class Tag:
id_num
title_str
class Structure_Archetype
id_num
name_str
description_str
// what can this structure type do?
process_list
class Structure:
structure_type
name_str
desc_str
hitpoints_u
... |
def check_congruence(oe):
assert (oe.FHIT_C == 1)
assert (oe.FSHAPE == 1)
assert (oe.F_REFLEC == 0)
assert (oe.FMIRR == 5)
assert (oe.F_GRATING == 0)
assert (oe.F_CRYSTAL == 0)
if __name__ == "__main__":
import numpy
from srxraylib.plot.gol import set_qt
set_qt()
from shadow... |
import os
__DIR__ = os.path.dirname(__file__)
if os.getenv('COFFEEBOT_DATABASE_URI'):
DATABASE_URI = os.getenv('COFFEEBOT_DATABASE_URI')
else:
DATABASE_URI = 'sqlite:////' + __DIR__ + '/../' + \
os.getenv('COFFEEBOT_DATABASE_FILENAME')
DEBUG = int(os.getenv('COFFEEBOT_DEBUG', 0))
URL = os.getenv('C... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import datetime as DT
import json
import re
import shutil
import traceback
from os import makedirs
from os.path import abspath, normpath
from urllib.request import urlretrieve
from typing import List, Union, NamedTuple
import requests
class C... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack.package import *
class Lhapdfsets(BundlePackage):
"""A set of disretised data files of parton ... |
from masonite.routes import Route
from masonite.configuration import config
from src.masonite_commerce.controllers.api.category_controller import CategoryController
from src.masonite_commerce.controllers.api.product_controller import ProductController
ROUTES = Route.group(
[
# Product Routes
Rout... |
"""
Validation information for an xblock instance.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import six
class ValidationMessage:
"""
A message containing validation information about an xblock.
"""
WARNING = "warning"
ERROR = "error"
TYPES = [WA... |
import numpy as np
GENERATIONS = 20
def input_parser(filename):
f = open(filename)
init_state = f.readline().split()[2]
rules = {}
f.readline() # skip the empty line
for line in f.readlines():
pattern, _, output = line.strip().split()
rules[pattern] = output
f.close()
... |
from Bio import SeqIO
# https://www.biostars.org/p/10162/
def get_ids(source):
ids = map(lambda x: x.id, source)
return set(ids)
def subset_records(source, ids):
for record in source:
if record.id in ids:
yield record
# Parse fasta
fasta = SeqIO.parse(snakemake.input[0], "fasta")
#... |
"""
This file contains the generic, assorted views that don't fall under one of
the other applications. Views are django's way of processing e.g. html
templates on the fly.
"""
from django.contrib.admin.sites import site
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_r... |
import os
#Disabling warnings
import logging
logging.getLogger('tensorflow').setLevel(logging.ERROR)
os.environ["KMP_AFFINITY"] = "noverbose"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
tf.autograph.set_verbosity(3)
from models.models import *
from lstm_utils import *
from tensorflow.keras.model... |
"""
Python 'utf-32-le' Codec
"""
import codecs
# ## Codec APIs
encode = codecs.utf_32_le_encode
def decode(input, errors='strict'):
return codecs.utf_32_le_decode(input, errors, True)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.utf_32_le... |
from benwaonline.schemas import TagSchema
from benwaonline.entities import Entity
class Tag(Entity):
'''Represents a Tag resource object, related to the Tag model in the database
Attributes:
type_: 'Tag'
'''
_schema = 'TagSchema'
type_ = 'tag'
attrs = {
'post': 'posts'
}
... |
from gocam_loader.io.parser import Parser
import gocam_loader.util.utils as Utils
import rdflib
class TtlParser(Parser):
def __init__(self, **args: dict):
super().__init__()
def parse_graph(self, graph: rdflib.Graph):
for subject, pred, object in graph:
pass |
import tensorflow as tf; import numpy as np
"""
A collection of method for the generation of the dual networks for Complete Prove.
dual_network: tf.keras.Model
the dual netowrk is built to deny the properties, is the negation of the main netowrk, a property is violated when "at least
ONE output of the dual netow... |
class BadTxnSenderError(Exception):
def __init__(self):
Exception.__init__(self, "transaction sender does not " +
"match multisig parameters")
class InvalidThresholdError(Exception):
def __init__(self):
Exception.__init__(self, "invalid multisig threshold")
c... |
# Copyright 2022 Martin Lueker-Boden
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
class Config:
default_rel_curv_thresh = 0.1
|
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... |
class GeometryTree(object):
""" GeometryTree(node: IGeometryNode) """
def AddBranch(self,branchSource,branchRoot):
""" AddBranch(self: GeometryTree,branchSource: GeometryTree,branchRoot: IGeometryNode) """
pass
def AddEdge(self,*__args):
""" AddEdge(self: GeometryTree,fromIndex: int,toIndex: int)AddEdge(... |
from typing import Tuple
import cv2
import gym
import numpy as np
from gym_gathering.observations.base_observation_generator import ObservationGenerator
class SingleChannelRealWorldObservationGenerator(ObservationGenerator):
def __init__(
self,
maze: np.ndarray,
random_goal: bool,
... |
#!/usr/bin/python3
# -*- codign: utf-8 -*-
import wx
import wx.aui
from DBManager import DBManager
from UserSetting import UserSetting
class Katomo(wx.Frame):
ifOpenConnection = False
def __init__(self,parent):
wx.Frame.__init__(self,parent,-1)
self.SetSize((500,300))
self.SetTitle("titulo")
self.Centre(... |
import json
from jsonschema import Draft4Validator as Validator
import pytest
from jupyterlab_sql.request_decoder import decode, RequestDecodeError
test_schema = {
"type": "object",
"properties": {"prop": {"type": "string"}},
"required": ["prop"],
}
test_body = {"prop": "value"}
def test_decode_not_... |
import cv2
import numpy as np
import pandas as pd
import argparse
import os
import sys
sys.path.append('../../')
from common.utility import prepareCams
from modules.reconstruction.Triangulate import Triangulate
clickEvent_top = False
mouseX_top, mouseY_top = None, None
clickEvent_front = False
mouseX_front, mouseY_f... |
import numpy as np
import scipy as sp
from scipy.sparse import linalg
from . import Reversible
import moments.Spectrum_mod
from . import Numerics
import Jackknife as jk
import LinearSystem_1D as ls1
import LinearSystem_2D as ls2
import Tridiag_solve as ts
from . import Integration
import copy
#-------------------------... |
from typing import Optional
from mongoengine.errors import ValidationError
from mini_gplus.models import LinkPreview, LinkPreviewState
from mini_gplus.tasks.tasks import generate_link_preview
def get_link_preview(url: str) -> Optional[LinkPreview]:
try:
link_preview = LinkPreview.objects(url=url)
... |
# Generated by Django 3.1.7 on 2021-04-13 22:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tgbot', '0002_message'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='external_id',
... |
'''
this program will ask user for artist/band name and return the lyrics
webaddress for the desired artist/musician while also retrieving the
htlm soup from the artist landing page
'''
import requests
import time
import numpy as np
from bs4 import BeautifulSoup
def search_lyricsdotcom(artist):
'''
creates li... |
import os, subprocess, json, shutil
from microapp import App, appdict
from ckgen.utils import xmlquery
here = os.path.dirname(os.path.abspath(__file__))
class MPASOcnKernel(App):
_name_ = "mpasocn"
_version_ = "0.1.0"
def __init__(self, mgr):
self.add_argument("casedir", metavar="casedir", help=... |
import argparse
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from sympy.parsing.sympy_parser import (parse_expr, standard_transformations, implicit_multiplication_application)
parser = argparse.ArgumentParser('Continuously train SCMs on functions')
parser.add_argument('-f', '-... |
import pandas as pd
from fibber.benchmark.benchmark_utils import load_detailed_result, update_overview_result
from fibber.metrics.metric_utils import DIRECTION_HIGHER_BETTER, DIRECTION_LOWER_BETTER
DATASET_NAME_COL = "dataset_name"
STRATEGY_NAME_COL = "paraphrase_strategy_name"
def make_overview():
"""Generate ... |
from fzfaws.cloudformation.helper.cloudformationargs import CloudformationArgs
from fzfaws.s3.s3 import S3
import io
import os
import sys
import unittest
from unittest.mock import ANY, patch
from pathlib import Path
from fzfaws.cloudformation.cloudformation import Cloudformation
from fzfaws.cloudformation.create_stack... |
#!/usr/bin/env python
#
# Copyright (c) 2014 Shadow Robot Company Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 2 of the License, or (at your option)
# any later version... |
import boto3
dynamodb = boto3.resource('dynamodb', region_name='eu-west-2')
table = dynamodb.Table('Books')
# The UpdateItem API allows you to update a particular item as identified by its key.
resp = table.update_item(
Key={"Author": "John Grisham", "Title": "The Rainmaker"},
# Expression attribute names spec... |
from collections import defaultdict, deque
class Solution:
def findOrder(self, numCourses: int, prerequisites):
preReqs, postReqs = defaultdict(set), defaultdict(set)
for p in prerequisites:
preReqs[p[0]].add(p[1])
postReqs[p[1]].add(p[0])
sources = deque([])
... |
import configparser
import os
from pathlib import Path
APP_DIR = Path(__file__).parent
APP_NAME = 'encrypted_config'
config = configparser.ConfigParser()
config.read(f'{APP_DIR}/encrypted-config.ini')
home_folder = os.path.expanduser('~')
CONFIG_FOLDER = os.path.join(home_folder, config['DEFAULT']['config_folder'])
... |
import urllib.request as url
import json
import datetime
import requests
VERSION = "1.3.3"
CAS_QUERY_URL = "https://api.cas.chat/check?user_id="
DL_DIR = "./csvExports"
def get_user_data(user_id):
with requests.request('GET', CAS_QUERY_URL + str(user_id)) as userdata_raw:
userdata = json.loads(userdata_ra... |
import os
from celery import Celery
# set the default Django settings module for the 'celery' program
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "configs.settings.core")
# initailize Celery
app = Celery("src")
# Using a string here means the worker don't have to serialize
# the configuration object to child pr... |
import random
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_path, "open_your_notebook.txt")) as f:
journal_practices = [care.rstrip('\r\n ') for care in f.readlines() if care != ""]
with open(os.path.join(dir_path, "put_your_phone_down.txt")) as f:
unplu... |
#! /usr/bin/env python
# Copyright (c) 2000 Roman Milner
# See the file COPYING for more information
import sys
from time import localtime, time, mktime
import weakref
from SQLRelay import CSQLRelay
apilevel='2.0'
threadsafety=1
paramstyle='named'
class Error(Exception):
pass
class Warning(Exception):
pa... |
import pickle,random,time,os,winsound
def title():
print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
print " H====== @ [] "
print " H W __ [] // "
print " H=== W I [] ... |
#!/usr/bin/env python
import subprocess
import sys
import os
import time
from pymavlink import mavutil
import glob
import ConfigParser
import shutil
from datetime import datetime
import re
import json
import argparse
SELECT_GPIO = "21"
ENABLE_GPIO = "19"
#GPIO direction set
def setGPIODir(gpio, direction):
dir_... |
from functools import partial
import os
from decouple import Config, RepositoryShell
from huskar_api.bootstrap import Bootstrap
class RepositoryHuskar(object):
"""The python-decouple integration of zookeeper and huskar."""
def __init__(self, manager, fallback, fallback_key_prefix=''):
self._manager... |
"""
This module should handle all of the command-line parsing and
invoke the correct command from commands.py
"""
import argparse
from led.__version__ import __version__
# create the top-level parser
parser = argparse.ArgumentParser(
prog='led',
usage='led [OPTIONS] COMMAND',
description=('Use led to man... |
from django.conf.urls import url
from django.contrib import admin
from . import views
app_name='main'
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
|
import pytest
from great_expectations.data_context.util import (
instantiate_class_from_config
)
def test_instantiate_class_from_config():
# This config structure feels very tidy to me.
instantiate_class_from_config(
config = {
"module_name" : "tests.test_plugins.fake_configs",
... |
"""Looks good to me command."""
import traceback
import sys
async def run(event, gh, config):
"""Run the task."""
disabled = 'lgtm' in config.get('disabled_actions', [])
print(f'LGTM: {event.full_name} ({"disabled" if disabled else "enabled"})')
if disabled:
return
try:
if config... |
import os
import shutil
from unittest import TestCase
from micro.core.params import Params
from micro.core.celeryapp import CeleryApp
class TestCeleryApp(TestCase):
@classmethod
def setUpClass(cls):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
... |
import math
an = float(input("Enter the angle: "))
seno = math.sin(math.radians(an))
print("The angle is {} and sen is {:.2f}".format(an, seno))
cos = math.cos(math.radians(an))
print("The angle is {} and sen is {:.2f}".format(an, cos))
tang = math.tan(math.radians(an))
print("The angle is {} and sen is {:.2f}".format(... |
#!/usr/bin/env python3
# The concierge utility is a basic package manager for cm3.
#
# The concierge has partial knowledge of package dependencies, as
# encoded in the file `scripts/pkginfo.txt` which topologically sorts
# all known packages in dependency order. Given a request to operate
# on (build, clean, or insta... |
from ctypes import *
import time
from Xlib.display import Display
import Xlib
from Xlib import X
import Xlib.XK
# custom types
t_Atom = c_ulong
t_Bool = c_int
t_Display = c_void_p
t_Window = c_ulong
t_Colormap = c_ulong
class X11Util(object):
def __init__(self):
self.__xlib = cdll.LoadLibrary('libX11.so... |
import numpy as np
import pandas as pd
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, pyqtSlot
from pathlib import Path
from PyQt5.QtQuick import QQuickView
from PyQt5.QtWidgets import QMainWindow
from vispy import scene
from canvas import MyCanvas
TOP_PANEL_OBJ_NAME = "TOP_PANEL_OBJ"
class Visualizer... |
from pathlib import Path
from shutil import which
from geopandas.geodataframe import GeoDataFrame
from ipywidgets.widgets import widget
from keplergl import KeplerGl
import pandas as pd
import geopandas as gpd
from typing import Union
from .config import load_config
import contextily as ctx
import matplotlib.pyplot as ... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('transaction',views.TransactionView, name="transaction"),
path('block',views.BlockView, name ="block")
]
|
#
# Copyright 2016 The BigDL Authors.
#
# 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 ... |
# (https://github.com/sandorex/extract-browser-data.py)
# extract-browser-data
#
# Copyright 2020 Aleksandar Radivojevic
#
# 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.apach... |
load("@bazel_skylib//lib:partial.bzl", "partial")
load("@fbcode_macros//build_defs:build_mode.bzl", _build_mode = "build_mode")
load("@fbcode_macros//build_defs:config.bzl", "config")
load("@fbcode_macros//build_defs/config:read_configs.bzl", "read_flags", "read_int")
load("@fbcode_macros//build_defs:coverage.bzl", "co... |
#!/usr/bin/env python3
# coding=utf-8
def main(): # основная функция
a = int(input('введите A: '))
b = int(input('введите B: '))
x = int(input('введите X: '))
if x >= 4:
y =(a ** 2 + 5 * x + b ** 2)/ (a * b)
else:
y = x * (a - b)
print("y = %.1f" % y)
|
#!/opt/bin/python3
# This script is for exporting FritzBox metrics into Telegraf in InfluxDB format.
# https://github.com/Schmidsfeld/TelegrafFritzBox
# License: MIT (https://opensource.org/licenses/MIT)
# Author: Alexander von Schmidsfeld
# This script requires the FritzConnection package
# Install with:
# pip3 inst... |
import torch
from torch.utils.data import DataLoader, Dataset
from torch.distributions import MultivariateNormal
import numpy as np
from sklearn.decomposition import PCA
class SyntheticDataset(Dataset):
def __init__(
self,
num_batches,
BATCH_SIZE,
mo... |
import helixtiltrot as htr
from matplotlib.pyplot import subplots
import numpy as np
# input coordinate files
pdb = 'transmembrane-alpha-helix.pdb'
xtc = 'transmembrane-alpha-helix.xtc'
ca, dssp = htr.load_ca_dssp(xtc, top=pdb)
# create numpy mask called sse_mask, such that
# sse_mask[n,i] == True if the residue ... |
from flask import (
blueprints,
current_app,
flash,
jsonify,
redirect,
request,
url_for
)
from sqlalchemy.exc import IntegrityError
from patchserver.exc import (
InvalidPatchDefinitionError,
InvalidWebhook,
PatchArchiveRestoreFailure,
SoftwareTitleNotFound,
Unauthorized
... |
# coding:utf8
import logging
logging.basicConfig(level=logging.INFO)
import sys
import glob
sys.path.append('gen-py.tornado')
from HelloService import HelloService
from HelloService.ttypes import *
from thrift import TTornado
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from th... |
# -*- coding: utf-8 -*-
import logging
import json
from os.path import join
from django.views.generic import TemplateView
from django.http import JsonResponse
from eops.settings import DATADIR
LOG = logging.getLogger(__name__)
def get_data(i):
choices = [
'elavaOPSv5.json',
'elavaOPSv6.json',
'elavaO... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data.sampler import Sampler
from torch.nn.utils.rnn import pad_sequence
from torch.nn import CrossEntropyLoss, MSELoss
from torch.autograd import Variable
from slp.modules.regularization import GaussianNoise
from slp.util import mktenso... |
# Ensures we can import from the 'examples' directory
import json
import sys
from pathlib import Path
examples_dir = Path(__file__).absolute().parent
sys.path.append(str(examples_dir))
from example_1_making_requests import app_search
from example_2_first_engine_and_documents import APP_SEARCH_ENGINE_NAME
print(">>> ... |
#!/usr/bin/env python
import tarfile
from simdb.utils import lammps_logfile_parser as llp
from pprint import pformat
with tarfile.open('logfiles.tar.gz', mode='r:gz') as tar:
storage = dict()
for fname in tar.getnames():
fileobj = tar.extractfile(tar.getmember(fname))
L = llp.LogFileReader(fil... |
import time
from datetime import datetime, timezone, tzinfo
from typing import NewType, Optional
AwareDateTime = NewType('AwareDateTime', datetime)
def make_aware(
dt: datetime,
tz: tzinfo,
*,
is_dst: Optional[bool] = None,
) -> AwareDateTime:
return tz.localize(dt, is_dst) # typ... |
from unittest import TestCase
import numpy as np
from Implementations.FastIntegersPersonal import FastIntegersPersonal
from benchmarks.test_distributions import Distributions
class Test(TestCase):
@classmethod
def setUp(self):
self.fastIntegers = FastIntegersPersonal('does not matter')
def test... |
import sys
A, B = map(int, sys.stdin.readline().split())
print(A + B) |
import tensorflow as tf
gpu_devices = tf.config.experimental.list_physical_devices('GPU')
for device in gpu_devices:
tf.config.experimental.set_memory_growth(device, True)
from crop_gan_losses import generator_loss_with_features
from crop_gan_losses import discriminator_wasshinge_loss as discriminator_loss
impor... |
#
# Licensed to Dagda under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Dagda licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance... |
#! /usr/bin/env python
# coding=utf-8
# GUI module generated by PAGE version 4.5
# In conjunction with Tcl version 8.6
# Apr 23, 2015 04:15:22 PM
import sys
import sqlite3
import io
import tkMessageBox
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
exce... |
from ecdsa import SigningKey
from ecdsa.keys import VerifyingKey
class Card:
def __init__(self, poke_id, name, poke_type, hp, attack, defense, speed, total, legendary):
self.poke_id = poke_id
self.name = name
self.poke_type = poke_type
self.hp = hp
self.attack = attack
... |
from simple_api.adapters.graphql.graphql import GraphQLAdapter
from simple_api.adapters.utils import generate_w
from simple_api.django_object.django_object import DjangoObject
from simple_api.object.actions import Action
from simple_api.object.datatypes import StringType
from simple_api.adapters.graphql.utils import b... |
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import pyparsing as pp
from cwr.grammar.factory.config import rule_at_least
"""
Rules factories.
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status__ = 'Development'
class RuleFactory(object, metaclass=ABCMeta):
def __init... |
import cv2
import sqlite3
from .database import getProfileDataById
import time
import smtplib
import mimetypes
import way2sms
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
import sys
import os
def send_msg():
q = way... |
# Generated by Django 2.2.2 on 2019-07-29 06:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webapp', '0046_systemmessage_reply_status'),
]
operations = [
migrations.AlterField(
model_name='studentinfo',
name=... |
from numpy import where, sqrt
from numpy.random import rand, randn
def IG(l,m,j_):
n=randn(j_,1)
y=n**2
x = m + (.5*m*m/l)*y - (.5*m/l)*sqrt(4*m*l*y+m*m*(y**2))
u=rand(j_,1)
index=where(u>m/(x+m))
x[index]=m*m/x[index]
return x
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 6 00:25:34 2019
@author: Warmachine
"""
import scipy.io as sio
import os
import torch
from torch import nn
from torch.nn import functional as F
import pandas as pd
from PIL import Image
from skimage import io, transform
import numpy as np
from collection... |
import random
from random import randint
oldf =open('./List/dygz_train_20c_list_10_percent.csv' ,'r' ,encoding='UTF-8')
newf =open('./List/dygz_train_20c_list_128.csv' ,'w' ,encoding='UTF-8')
n = 0
# sample(x,y)函数的作用是从序列x中,随机选择y个不重复的元素
resultList = random.sample(range(0 ,2155) ,128)
lines =oldf.readlines()
for i in ... |
"""
Description:
-----------
This script will help users download THE ENTIRE SEVIR dataset.
!NOTE NOTE NOTE!
This data is about 1 TB in size so please do not run this on your machine unless you have that storage space and
or you can even download that much data on your internet plan (my internet plan has a CAP of 1... |
"""syc URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... |
def buy_condition_trix(row, stoch_top, stoch_bottom, stoch_over_sold):
if row['TRIX_HISTO'] > 0 and row['STOCH_RSI'] < stoch_top:
return True
else:
return False
def sell_condition_trix(row, stoch_top, stoch_bottom, stoch_over_sold):
if row['TRIX_HISTO'] < 0 and row['STOCH_RSI'] > stoch_bottom:
return... |
"""census data upload
Revision ID: 3fd25ba9c477
Revises: 131709af5cc
Create Date: 2016-03-24 14:20:25.488054
"""
# revision identifiers, used by Alembic.
revision = '3fd25ba9c477'
down_revision = '131709af5cc'
branch_labels = None
depends_on = None
from alembic import op
import pandas as pd
from sutter.lib.path imp... |
import boto3
exceptions = boto3.client('efs').exceptions
BadRequest = exceptions.BadRequest
DependencyTimeout = exceptions.DependencyTimeout
FileSystemAlreadyExists = exceptions.FileSystemAlreadyExists
FileSystemInUse = exceptions.FileSystemInUse
FileSystemLimitExceeded = exceptions.FileSystemLimitExceeded
FileSystem... |
__version__ = '0.12.0.dev'
|
import re
from django.contrib.contenttypes.models import ContentType
from apis_core.apis_metainfo.models import Text
from apis_highlighter.models import Annotation
def highlight_text_new(*args, **kwargs):
ann_proj_pk = kwargs.pop("set_ann_proj", False)
types = kwargs.pop("types", False)
users_show = kwa... |
import logging
from example import app, muffin
@app.ps.debugtoolbar.authorization
def authorize(request):
return True
@app.register('/')
def index(request):
""" Just sample. """
logging.warn('logging message')
yield from request.read()
return (
"<body>"
"Hello, World!"
"... |
from django import forms
from django.contrib import admin, messages
from django.contrib.admin import helpers
from django.contrib.admin.widgets import AutocompleteSelectMultiple
from django.db.models import Max
from django.forms import TextInput
from rangefilter.filter import DateRangeFilter
from business_register.mode... |
import requests, os, re, shutil
from PIL import Image
def save(book_url: str, correction_url: str, cookies: dict, path="pages"):
if not os.path.exists(path):
os.mkdir(path)
with requests.Session() as s:
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 6.3; WOW64) ... |
def moveZeros(arr):
j = 0
for a in arr:
if a != 0:
arr[j] = a
j += 1
for i in range(j, len(arr)):
arr[i] = 0
return arr
print(moveZeros([1, 0, 8, 0, 0, 5, -9, 0, 0, 2, 0, 0])) |
import argparse
import os
import sys
import copy
from . import yacc
from . import bootbakyi
def run_code(code, file_name = None):
code = yacc.compile_code(code, file_name=file_name)
locals_dict = {}
g = copy.deepcopy(yaksok_globals)
locals_dict['____functions'] = g['____functions']
if file_name i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.