text stringlengths 1 927k |
|---|
import sklearn.datasets as data
from classix import CLASSIX
import matplotlib.pyplot as plt
def rn_scale_explore():
plt.style.use('bmh')
TOL = 0.1
random_state = 1
moons, _ = data.make_moons(n_samples=1000, noise=0.05, random_state=random_state)
blobs, _ = data.make_blobs(n_samples=1500, centers=... |
# qubit number=3
# total number=73
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from... |
##python27
from pprint import pprint
import pandas as pd
##..............open manually merged geoparsed results
geo = pd.read_csv('./data/merger_xml_extracted_geoparsed_collocates.csv')
geo = [tuple(x) for x in geo.values] # df to list
print(geo[1])
##..........open collocate results....
collocate = pd.read_csv('.... |
#!/home/khadija/pro-awwwards/venv/bin/python3.6
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line() |
#!/usr/bin/env python
"""
Author: Robin Ankele <robin.ankele@cs.ox.ac.uk>
http://users.ox.ac.uk/~kell4062
Copyright (c) 2017, University of Oxford
All rights reserved.
"""
from gameBasic import G
class G_PS(G):
def __init__(self):
G.__init__(self)
def __finialize__(self):
G.__finia... |
#!/usr/bin/env python
"""This modules contains regression tests for hunts API handlers."""
import pdb
from grr.gui import api_regression_test_lib
from grr.gui.api_plugins import hunt as hunt_plugin
from grr.lib import aff4
from grr.lib import flags
from grr.lib import output_plugin
from grr.lib import rdfvalue
fr... |
"""
This module exports all latin and greek letters as Symbols, so you can
conveniently do
>>> from sympy.abc import x, y
instead of the slightly more clunky-looking
>>> from sympy import symbols
>>> x, y = symbols('x y')
Caveats
=======
1. As of the time of writing this, the names ``C``, ``O``, ``S``,... |
from requests import session
from threading import Thread
from re import findall
SERVER = "http://mustard.stt.rnl.tecnico.ulisboa.pt:12202"
s = session()
f = None
def doLogin():
data = {
"username": "admin",
"password": "admin"
}
s.post(SERVER + "/login", data=data)
def doJackpot():
... |
import os
import numpy as np
import logging
import argparse
import sys
logger = logging.getLogger('s-norm score.')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s [%(pathname)s:%(lineno)s - "
... |
string = input()
string = string.lower()
for sdv in range(1, 32):
s = ''
for c in string:
if 'а' <= c <= 'я':
ot_sm = ord(c) - ord('а')
new_ot_sm = (ot_sm - sdv) % 32
abs_sm = ord('а') + new_ot_sm
c = chr(abs_sm)
s += c
print(s) |
""" PhotoCompare class to compare date/time/timezone in Photos to the exif data """
from collections import namedtuple
from typing import Callable, List, Optional, Tuple
from osxphotos import PhotosDB
from osxphotos.exiftool import ExifTool
from photoscript import Photo
from .datetime_utils import datetime_naive_to_... |
#!/usr/bin/python3
# this script eliminates randomly a percentage of citations from the citation data
from random import randrange
input_file = "pmid_citations.txt"
# percentage of citation that will be left after the process
percentage_left = 80
output_file = "pmid_citations_" + str(percentage_left) + ".txt"
f_in ... |
#!/usr/bin/env python3
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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 withou... |
import numpy as np
from scipy.sparse import issparse
from sparse_ho.forward import get_beta_jac_iterdiff
class ImplicitForward():
def __init__(
self, criterion, tol_jac=1e-3, n_iter=100, n_iter_jac=100,
use_sk=False, verbose=False):
self.criterion = criterion
self.n_iter = ... |
# ----------------------------------------------------------------------------
# Copyright (c) 2017-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
"""
Octree geometry handler
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------... |
# Copyright 2017 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 applica... |
from aalpy.automata import Onfsm, Mdp, StochasticMealyMachine
from aalpy.base import Oracle, SUL
from random import randint, choice
automaton_dict = {Onfsm: 'onfsm', Mdp: 'mdp', StochasticMealyMachine: 'smm'}
class RandomWordEqOracle(Oracle):
"""
Equivalence oracle where queries are of random length in a pre... |
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'noticeboard' |
from .ebook_renderer import EbookRenderer
from .epub_renderer import EpubRenderer |
# -*- coding: utf-8 -*-
"""
These checks ensure that you follow the best practices.
The source for these best practices is hidden inside countless hours
we have spent debugging software or reviewing it.
How do we find inspiration for new rules?
We find some ugly code during code reviews and audits.
Then we forbid to... |
import os
import os.path
import sys
import subprocess
from SCons.Script import Dir, Environment
if os.name == 'nt':
from . import mono_reg_utils as monoreg
android_arch_dirs = {
'armv7': 'armeabi-v7a',
'arm64v8': 'arm64-v8a',
'x86': 'x86',
'x86_64': 'x86_64'
}
def get_android_out_dir(env):
... |
# Copyright 2019 The Forte 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 applicable ... |
from __future__ import print_function
import sys
import os
import re
import copy
import rdkit.Chem as Chem
import rdkit.Chem.AllChem as AllChem
from rdkit.Chem.rdchem import ChiralType, BondType, BondDir
from retrobiocat_web.retro.rdchiral.utils import vprint, PLEVEL, atoms_are_different
from retrobiocat_web.retro.r... |
# Resize image
import os
import cv2
import numpy as np
from plantcv.plantcv._debug import _debug
from plantcv.plantcv import params
from plantcv.plantcv import fatal_error
def auto_crop(img, obj, padding_x=0, padding_y=0, color='black'):
"""
Resize image.
Inputs:
img = RGB or grayscale image d... |
#---------------------------------------------------------------------------
# This python module is used to customize a supported toolchain for your
# project specific settings.
#
# Notes:
# - ONLY edit/add statements in the sections marked by BEGIN/END EDITS
# markers.
# - Maintain indentation level and u... |
import datetime as dt
from abc import abstractmethod
from django.db import models
from tacticalrmm.middleware import get_debug_info, get_username
ACTION_TYPE_CHOICES = [
("schedreboot", "Scheduled Reboot"),
("taskaction", "Scheduled Task Action"),
("agentupdate", "Agent Update"),
("chocoinstall", "Ch... |
import pathlib
from setuptools import find_packages, setup
about = {}
with open(pathlib.Path("rikai") / "__version__.py", "r") as fh:
exec(fh.read(), about)
with open(
pathlib.Path(__file__).absolute().parent.parent / "README.md", "r"
) as fh:
long_description = fh.read()
# extras
dev = [
"black",
... |
"""Sample command line parser."""
from argparse import ArgumentParser, Action
class AuthOptionsAction(Action): # pylint: disable=too-few-public-methods
"""Parse authorization args from user input."""
def __call__(self, parser, args, values, option_string=None):
value = values
vals = value.s... |
#!/usr/bin/env python2
# Author: Jonah Miller (jonah.maxwell.miller@gmail.com)
# Time-stamp: <2013-12-14 16:50:20 (jonah)>
# This is a companion program to my FLRW simulator. It takes a data
# file and generates a plot of the scale factor, its derivative, the
# density, and the pressure of the matter.
# Call the prog... |
'''
An example of fitting a function with ZexGP.
'''
from zexgp.kernel import Kernel
from os import path
from sys import float_info as fi
from matplotlib import pyplot as plt
# some necessary global variables
func_val = []
domain = []
def init_func_val():
'''
Initialize function value.
'''
def func(x): ret... |
import yaml
import io
import abc
from warnings import warn
class Parameters:
""" Defines basic functionality for loading/saving configuration files.
Handles loading, and saving of YAML configuration files. Also, generically,
initializes classes based on the loaded configuration.
Attributes:
... |
#!/usr/bin/env python
'''
Copyright 2021 Joāo Ferreira Nunes
This script 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... |
# -*- coding: utf-8 -*-
import cherrypy
__all__ = ['Jinja2Tool']
class Jinja2Tool(cherrypy.Tool):
def __init__(self):
cherrypy.Tool.__init__(self, 'before_finalize',
self._render,
priority=10)
def _render(self, template=None, debug... |
# -*- coding: utf-8 -*-
# Author: Christoph Berger
# Script for evaluation and bulk segmentation of Brain Tumor Scans
# using the MICCAI BRATS algorithmic repository
#
# Please refer to README.md and LICENSE.md for further documentation
# This software is not certified for clinical use.
import sys
import subprocess
im... |
import FWCore.ParameterSet.Config as cms
import sys
from Configuration.Eras.Era_Run2_2018_cff import Run2_2018
process = cms.Process("L1TStage2DQM", Run2_2018)
unitTest = False
if 'unitTest=True' in sys.argv:
unitTest=True
#--------------------------------------------------
# Event Source and Condition
if unitT... |
#!/usr/bin/env python3
import numpy as np
import lightgbm as lgb
from sklearn import linear_model
from sklearn import kernel_ridge
from sklearn import ensemble
from sklearn import preprocessing
from sklearn import neural_network
from sklearn import multioutput
# import warnings filter
from warnings import simplefil... |
import json
from pathlib import Path
from .translate import Translate
with open(Path(__file__).parent / "info.json") as fp:
__red_end_user_data_statement__ = json.load(fp)["end_user_data_statement"]
async def setup(bot):
bot.add_cog(Translate(bot)) |
# I'm going to test through an actual web call, so there is no actuall
# importation of the morris_api file. Instead, we will rely on Requests.
# You need to have Bottle already running on Port 8080 and answering on
# localhost for these tests to run.
# The set up fixture below starts up the Bottle server on port 80... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import pytest
import platform
import functools
import json
from azure.core.exceptions import HttpResponseError, ClientAuthenticationError
from azure.core.crede... |
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core as _c... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torch.autograd.variable import Variable
class QNetwork(nn.Module):
def __init__(self, state_size, action_size, nb_hidden, seed=1412):
super(QNetwork, self).__init__()
self.seed = torch.manual_seed(seed)
... |
# Copyright 2013-2020 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)
from spack import *
class PyCounter(PythonPackage):
"""Counter package defines the "counter.Counter" class similar t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pytests for :class:`dead_sfs.keygen`"""
import argparse
import os
from tempfile import TemporaryDirectory
import nacl.secret
import pytest
from dead_sfs.keygen import get_parser, main
def test_get_argparser():
parser = get_parser()
assert parser
assert ... |
import os
import numpy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import argparse
from PIL import Image
parser = argparse.ArgumentParser()
parser.add_argument('-input', default = '', help = 'input file folder')
parser.add_argument('-label', default = '', help = 'label file')
parser.add_ar... |
import os
from keras.models import Model
from keras.layers import Dense, Dropout
from keras.applications.inception_resnet_v2 import InceptionResNetV2
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.optimizers import Adam
from keras import backend as K
from utils.data_loader import train_generator,... |
import numpy as np
from keras.models import model_from_json
try:
import cPickle as pickle
except ImportError:
import pickle
class KerasSimilarityShim(object):
entailment_types = ["entailment", "contradiction", "neutral"]
@classmethod
def load(cls, path, nlp, max_length=100, get_features=None):
... |
"""Fixer for 'raise E, V'
From Armin Ronacher's ``python-modernize``.
raise -> raise
raise E -> raise E
raise E, 5 -> raise E(5)
raise E, 5, T -> raise E(5).with_traceback(T)
raise E, None, T -> raise E.with_traceback(T)
raise (((E, E'), E''), E'''), 5 -> raise E(5)
raise "foo", V, T -... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def get_factorials(n):
f = lambda x: x * f(x - 1) if x else 1
return [f(i) for i in range(n)]
def sum_factorial_digits(limit):
factorial = get_factorials(10)
total = 0
digit_sum = 0
order = int(math.log10(limit))
for n in range(3, int(limit)):
digi... |
def binarySearch(array, target):
return binary_search_helper(array, target, 0, len(array) - 1)
def binary_search_helper(array, target, start, end):
while start <= end:
mid = (start + end) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
end = mi... |
import os
import sys
import pytest
from bs4 import BeautifulSoup
sys.path.insert(0, os.path.abspath('.'))
sys.path.append(os.path.join(os.path.abspath('.'), 'habrpars'))
@pytest.fixture
def page():
path = os.path.abspath('.')
filename = os.path.join(path, 'habrpars', 'fixtures', 'page.html')
return fil... |
import configparser
import json
import os
import pathlib
import shutil
import subprocess
import tempfile
from docker import DockerClient
from .compat import constant
class Podman(object):
"""
Instances hold the configuration and setup for running podman commands
"""
def __init__(self):
"""I... |
import argparse
from stevedore import extension
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--width',
default=60,
type=int,
help='maximum output width for text',
)
parsed_args = parser.parse_args()
data = {
'a': 'A',... |
import logging
def setup():
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger('root')
logger.setLevel(logging.INFO)
logger.addHandler(handler) |
'''
Created on Mar 23, 2016
@author: Husen M. Umer
'''
import os, sys
import urllib2
import gzip
import pybedtools
from pybedtools import BedTool
import shutil
def generate_list_of_accession_info(encode_metadata_inputfile, biosample_name_to_extract, assay_type, accepted_file_formats=[], default_target_name="Unknown"... |
"""
WSGI config for template_test project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 13:39:13 2018
@author: Hassan Yousuf & Nabeel Hussain
"""
from __future__ import print_function
import sklearn.ensemble
from sklearn import metrics
from myo import init, Hub, DeviceListener, StreamEmg
from time import sleep
import numpy as np
import threading
import co... |
#!/usr/bin/python
""" Authors - Akshay Sonawane and Viraj Shetty """
import smtplib
from Corona_Updates import update
sender = 'corona.updates.av.2020@gmail.com'
receivers = ['akshaysonawane10526@gmail.com', 'virajshetty1@hotmail.com']
pwd = 'sakecboys-akvi'
if __name__ == "__main__":
india_list, india_percent... |
from django.conf import settings
def debug(context):
return {'DEBUG': settings.DEBUG} |
#! /usr/bin/env python3
"""
Sherlock: Find Usernames Across Social Networks Module
This module contains the main logic to search for usernames at social
networks.
"""
import csv
import json
import os
import platform
import re
import sys
import random
from argparse import ArgumentParser, RawDescriptionHelpFormatter
f... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
if "WPROBOT_DIR" not in os.environ:
import sys
sys.path.append(os.path.abspath(
os.path.join(os.path.dirname(__file__), "..")))
import wprobot |
#!/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
# "L... |
n, k = map(int, input().split())
ans = 0
while n:
n //= k
ans += 1
print(ans) |
import scipy.interpolate
import numpy as np
import pytest
import naturalneighbor
@pytest.mark.parametrize("grid_ranges", [
[[0, 4, 0.6], [-3, 3, 1.0], [0, 1, 3]],
[[0, 2, 1], [0, 2, 1j], [0, 2, 2j]],
[[0, 2, 1 + 1j], [0, 2, -10j], [0, 2, 2j]],
[[0, 2, 1 + 1j], [0, 2, -0.9j], [0, 2, 2.1j]],
])
def tes... |
import setuptools
with open('README.md','r',encoding='utf-8') as fh:
long_description = fh.read()
setuptools.setup(
name = 'HeadersFormatter',
version = '0.0.2',
author = 'pangbo',
author_email = '373108669@qq.com',
description = 'Format headers in clipboard to <dict>.',
long_description =... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from tastypie.api import Api
from manager.apps.brand.api import BrandResource # [#58] , BrandOwnerResource
from django.conf import settings
admin.autodiscover()
v1_api = Api(api_name='v1')
v1_api.register(BrandResource())
# Postpone... |
import numpy as np
import pandas as pd
import psycopg2, sys
hostname, user, dbname, passward = sys.argv[1:5]
def load_data():
lon0, lat0 = 115.8, 29.4
x = pd.read_excel('../data/x.xlsx', header=0, index_col=0).values
y = pd.read_excel('../data/y.xlsx', header=0, index_col=0).values
lon = lon0 + ... |
'''
style text background(fundo)
0 = sem estilo 30 =branco 40 =branco
1 = negrito 31 =vermelho 41 =vermelho
4 = sublinhado 32 =verde 42 =verde
7 = iverte cores 33 =amarelo 43 =amarelo
... |
from django_messages_framework.storage.base import BaseStorage
class SessionStorage(BaseStorage):
"""
Stores messages in the session (that is, django.contrib.sessions).
"""
session_key = '_messages'
def __init__(self, request, *args, **kwargs):
assert hasattr(request, 'session'), "The ses... |
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# importing the Kratos Library
from KratosMultiphysics import *
from KratosMultiphysics.IncompressibleFluidApplication import *
from KratosMultiphysics.MeshingApplication import *
def ... |
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
import argparse
import boto3
"""Helper module to assist in AWS deployments"""
def get_lambda_client(
aws_access_key_id: str, aws_secret_access_key: str, aws_region: str
) -> boto3.client:
return boto3.client(
"lambda",
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_se... |
# Electrum - Lightweight Bitcoin Client
# Copyright (c) 2011-2016 Thomas Voegtlin
#
# 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 rig... |
from flask import Flask, url_for, redirect, render_template, request, make_response, session, jsonify
from flask_session import Session
from flask_caching import Cache
from dotenv import load_dotenv
import os
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from spotipy.cache_handler import CacheFileHandler
impor... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run PBJelly on reference FASTA and a set of patching reads. Sometimes patching
'reads' can also be contigs, which require setting the blasr criteria to be
higher in `Protocol.xml`.
"""
from __future__ import print_function
import os
import os.path as op
import sys
imp... |
from . import util
from engine import metroverse as mv
def render_boosts(blocks=None, highlight=False, render_stacked=False):
active_boosts = mv.active_boosts(blocks)
names = set()
if blocks is not None:
for block in blocks:
names.update(block['buildings']['all'].keys())
large_ho... |
from __future__ import print_function
# a
# / \
# b c
# / \
# d e
edges = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []}
vertices = ["a", "b", "c", "d", "e"]
def topological_sort(start, visited, sort):
"""Perform topolical sort on a directed acyclic graph."""
current = start
# ... |
# model settings
model = dict(
type='TTFNet',
pretrained='modelzoo://resnet18',
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_eval=False,
style='pytorch'),
neck=None,
bbox_head=dict(
... |
""" Splice together a planet from a cache of feed entries """
import glob, os, time, shutil
from xml.dom import minidom
import planet, config, feedparser, reconstitute, shell
from reconstitute import createTextElement, date
from spider import filename
from planet import idindex
def splice():
""" Splice together a ... |
#!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open("README.adoc") as fh_readme:
readme = fh_readme.read()
install_reqs = []
setup(
author="Sven Wilhelm",
author_email='refnode@gmail.com',
python_requires='>=3.8',
classifiers=[
'Developmen... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
def create_user(**params):
return get_user_model()... |
"""
pygments.filter
~~~~~~~~~~~~~~~
Module that implements the default filter.
:copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
def apply_filters(stream, filters, lexer=None):
"""
Use this method to apply an iterable of filter... |
import spacy
nlp = spacy.load("es_core_news_sm")
text = (
"De acuerdo con la revista Fortune, Apple fue la empresa "
"más admirada en el mundo entre 2008 y 2012."
)
# Procesa el texto
doc = nlp(text)
for token in doc:
# Obtén el texto del token, el part-of-speech tag y el dependency label
token_text... |
#! /usr/local/bin/python
# NOTE: the above "/usr/local/bin/python" is NOT a mistake. It is
# intentionally NOT "/usr/bin/env python". On many systems
# (e.g. Solaris), /usr/local/bin is not in $PATH as passed to CGI
# scripts, and /usr/local/bin is the default directory where Python is
# installed, so /usr/bin/env w... |
import datetime
import decimal
from json import dumps
from aiohttp import web
from sqlalchemy import select, delete, update, insert
from sqlalchemy import desc
def alchemyencoder(obj):
"""JSON encoder function for SQLAlchemy special classes."""
if isinstance(obj, datetime.date):
return obj.isoformat(... |
from collections import defaultdict
from ..storage import InMemoryStorage
from .client import ShardClient
from ..utils import get_size
class Shard:
def __init__(self, start, end, storage_class=InMemoryStorage, max_size=1024, bins_num=5,
buffer_size=1024,
**storage_kwargs):
... |
"""
**************
Pickled Graphs
**************
Read and write NetworkX graphs as Python pickles.
"The pickle module implements a fundamental, but powerful algorithm
for serializing and de-serializing a Python object
structure. "Pickling" is the process whereby a Python object hierarchy
is converted into a byte strea... |
# DFS로 특정 노드를 방문하고 연결된 모든 노드들도 방문
def dfs(x, y):
# 주어진 범위를 벗어나는 경우에는 즉시 종료
if x <= -1 or x >= n or y <= -1 or y >= m:
return False
# 현재 노드를 아직 방문하지 않았다면
if graph[x][y] == 0:
# 해당 노드 방문 처리
graph[x][y] = 1
# 상, 하, 좌, 우의 위치들도 모두 재귀적으로 호출
dfs(x - 1, y)
dfs(x, ... |
#!/usr/bin/env python3
# JM: 30 Aug 2018
# process the *scalar.nc files (because I couldn't get XIOS to spit out just
# a number for whatever reason...)
import netCDF4
import glob, sys
#--------------------------------------------------------
# define the argument parser
import argparse
parser = argparse.ArgumentPa... |
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# -*- coding: utf-8 -*-
"""keras_tuner.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1FbSUg_-KxlihGbwBPBEBLFzCw-YtVLhE
# Keras Tuner
- A package to tune Keras hyperparameters
"""
# Commented out IPython magic to ensure Python compatibility.
#... |
"""create and manipulate sqlite databese"""
import sqlite3
import time
import datetime
from Files import scrap_web
def create_tables():
"""create db if don't exists and fill it with tables"""
connect = sqlite3.connect("db.db")
conn = connect.cursor()
conn.execute("""CREATE TABLE IF NOT EXISTS assets... |
import fnmatch
import json
import os
import shutil
import tempfile
import xml.etree.ElementTree as ET
from argparse import ArgumentParser
from pathlib import Path
from typing import Optional
from datasets.commands import BaseTransformersCLICommand
from datasets.load import import_main_class, prepare_module
from datase... |
from rest_framework import serializers
class BPMSerializer(serializers.Serializer):
datetime_from = serializers.DateTimeField()
datetime_to = serializers.DateTimeField()
bpm = serializers.IntegerField(read_only=True) |
import networkx as nx
import math
import matplotlib.pyplot as plt
import numpy as np
def create_prox_graphs(kps, descs, k=5):
"""
Function which creates a proximity graph given a set of points.
:param kps: list containing sets of keypoints
:param descs: list containing sets of descriptors
:param ... |
# !}============================================================================{!
# !} Author: Yezz123 {!
# !} Instagram : https://www.instagram.com/sadnessvibewithbadeffect {!
# !} write with : Python. ... |
from .static.Qua_config import *
from random import sample
from jieba import cut_for_search, cut
from nltk import bigrams, word_tokenize
import nltk
# assistant func
def countBedNum(DormList):
BedNum = {'男性':0,'女性':0}
for index, row in DormList.iterrows():
if('男' in row['dormName'] and row['is_disabi... |
#!/usr/bin/python
from optparse import OptionParser
import Image
import numpy as np
import matplotlib.pyplot as plt
def load_image(fname):
"""Load an image file"""
return np.array(Image.open(fname))
def load_points(fname):
"""Load a text file with 2D points.
The file should contain X and Y locatio... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# Generated by Django 3.2.6 on 2021-08-08 11:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ecommerce', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.