content
stringlengths
0
894k
type
stringclasses
2 values
"""Auth namespace contains the class to manage authentication: Credentials. It also includes the utility functions :func:`cartoframes.auth.set_default_credentials` and :func:`cartoframes.auth.get_default_credentials`.""" from __future__ import absolute_import from .credentials import Credentials from .defaults import ...
python
from telnetlib import Telnet import os import sys import time #1; E e geo eclip 2018-jan-01 00:00 2018-jan-02 00:00 1d #ASTNAM=1 TABLE_TYPE= 'ELEMENTS e geo eclip START_TIME='2018-jan-01' STOP_TIME='2018-jan-02' STEP_SIZE='1 d' tn=Telnet('horizons.jpl.nasa.gov', 6775) #tn.set_debuglevel(10) for i in range(30)...
python
# Copyright 2021 Google LLC. 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 a...
python
from __future__ import division import torch import pytorch_warpctc from ._warp_ctc import * from .validators import validate_inputs class CTCAutogradFunction(torch.autograd.Function): @staticmethod def forward(ctx, activations, labels, lengths, label_lengths, take_average=True, blank=None): use_cuda...
python
a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 10 a = 1...
python
def fill_matrix(matrix, input_var, option=0): for row in range(input_var[0]): if option == 1: row_input = [int(x) for x in input().split(" ")] else: row_input = [float(x) for x in input().split(" ")] matrix.append(row_input) return def add_matrix(m...
python
from django.contrib.auth.models import User from rest_framework import serializers from ..models import Game class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'is_staff') class GameSerializer(serializers.ModelSerializer): creato...
python
extensions = ['sphinx.ext.autosectionlabel'] autosectionlabel_prefix_document = True
python
from fastapi.testclient import TestClient from main import app from unittest import TestCase, mock from persistence.repositories.question_template_repository_postgres import QuestionTemplateRepositoryPostgres from infrastructure.db.question_template_schema import QuestionTemplate, QuestionTypeEnum import json import os...
python
# coding=utf-8 import time import re import zlib import random from gzip import GzipFile from PIL import Image # 兼容2.7和3.x try: from io import BytesIO as StringIO except ImportError: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO ''' 百度云引擎工具模块 ''' d...
python
#!/usr/bin/env python """ Application: COMPOSE Framework - K-Nearest Neighbors Algorithm File name: knn.py Author: Martin Manuel Lopez Creation: 10/20/2021 The University of Arizona Department of Electrical and Computer Engineering College of Engineering """ # MIT License # # ...
python
import csv import logging import os import string import numpy as np import tensorflow as tf from gensim.models import KeyedVectors from sklearn.metrics.pairwise import cosine_similarity from keyed_vectors_prediction_config import KeyedVectorsPredictionConfig class KeyedVectorsFormatPredictor: def __init__(sel...
python
import numpy as np import matplotlib.pyplot as plt import banners from constants import * from scipy import stats #%% Model parameters n=1 # Number successes p_cons = banners.DEFAULT_EVENT_RATES.fiveStarCons #* banners.DEFAULT_EVENT_RATES.fiveStarPriorityRate# Probability of success primo_spend = 181 usd_spend = ...
python
"""Routing manager classes for tracking and inspecting routing records.""" import json from typing import Sequence from ...config.injection_context import InjectionContext from ...error import BaseError from ...messaging.util import time_now from ...storage.base import BaseStorage, StorageRecord from ...storage.error...
python
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, DateField, SelectField from wtforms.validators import DataRequired, Optional from wotd.models import PartOfSpeech class WordForm(FlaskForm): word = StringField('Word', validators=[DataRequired()]) part_o_speech = Sele...
python
import re import os import argparse import matplotlib.pyplot as plt import pandas as pd import numpy as np from dataloader import LOSO_sequence_generate # Selected action units AU_CODE = [1, 2, 4, 10, 12, 14, 15, 17, 25] AU_DICT = { number: idx for idx, number in enumerate(AU_CODE) } def evaluate_adj(df, arg...
python
# Unit test _bayesian_search_skopt # ============================================================================== import pytest import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import Ridge from skopt.space import Categorical, Real, Integer from skopt...
python
import os import sys import logging import csv from py.hookandline.HookandlineFpcDB_model import database, TideStations, Sites class SiteManager: def __init__(self, app=None, db=None): super().__init__() self._logger = logging.getLogger(__name__) self._app = app self._db = db ...
python
# # utilities.py # # (c) 2017 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # This module defines various internal utility functions for the library. # from lxml import etree as ET import onem2mlib.constants as CON import onem2mlib.utilities as UT import onem2mlib.mcare...
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: networking/v1alpha3/workload_entry.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _messa...
python
from ..query.grammars import SQLiteGrammar from .BaseConnection import BaseConnection from ..schema.platforms import SQLitePlatform from ..query.processors import SQLitePostProcessor from ..exceptions import DriverNotFound, QueryException class SQLiteConnection(BaseConnection): """SQLite Connection class.""" ...
python
########## Script 1 ################### import sys from RK_IO_model import RK_IO_methods from Generalized_RK_Framework import generalized_RK_framework import pdb #for debugging import numpy as np import pyomo.environ as pyo from pyomo.opt import SolverFactory from pyomo.opt import SolverStatus,...
python
str2slice = "Just do it!" print(str2slice[10]) # prints "!" print(str2slice[5:7]) # prints "do" print(str2slice[8:]) # prints "it!" print(str2slice[:4]) # prints "Just" print("Don't " + str2slice[5:]) # prints "Don't do it!"
python
import abc from typing import Any from typing import Dict from typing import Optional from typing import Sequence from optuna.distributions import BaseDistribution from optuna.study import Study from optuna.trial import FrozenTrial from optuna.trial import TrialState class BaseSampler(object, metaclass=abc.ABCMeta):...
python
from ledfx.effects.temporal import TemporalEffect from ledfx.effects.gradient import GradientEffect #from ledfx.color import COLORS, GRADIENTS #from ledfx.effects import Effect import voluptuous as vol import numpy as np import logging class FadeEffect(TemporalEffect, GradientEffect): """ Fades through the col...
python
import numpy as np from hand import Hand from mulliganTester import MulliganTester class BurnMullTester(MulliganTester): hand_types = ["twolandCreature","goodhand","keepable"] hand = Hand("decklists/burn.txt") output_file_header = "burn" land_value_list = ["Mountain", "Bloodstained Mire", "Inspiring V...
python
""" Script to download the examples from the stac-spec repository. This is used when upgrading to a new version of STAC. """ import os import argparse import json from subprocess import call import tempfile from typing import Any, Dict, List, Optional from urllib.error import HTTPError import pystac from pystac.serial...
python
import numpy as np import cv2 import os basepath = os.path.dirname(os.path.abspath(__file__))+"/Sample-Videos/" def background_subtractor(video_link,method="MOG"): cap = cv2.VideoCapture(video_link) if method == "MOG": fgbg = cv2.createBackgroundSubtractorMOG() elif method == "MOG2": fgbg = cv2.createBackgroun...
python
#!/usr/bin/env python2 # # Copyright (c) 2016,2018 Cisco and/or its affiliates. # 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 re...
python
# Copyright 2017, 2019-2020 National Research Foundation (Square Kilometre Array) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list...
python
import pytest from tgbotscenario.asynchronous import Machine, BaseScene, MemorySceneStorage from tests.generators import generate_direction @pytest.mark.parametrize( ("direction",), ( (None,), (generate_direction(),) ) ) def test_transition_not_exists(direction, handler): class Initi...
python
#!/usr/bin/env python3 import datetime import logging import os import sys import time import urllib.request import argparse from imageai.Detection import ObjectDetection from imageai.Classification import ImageClassification import simplejson as json import tweepy from tweepy import API, Cursor, Stream, OAuthHandler...
python
import math import pytz import singer import singer.utils import singer.metrics import time from datetime import timedelta, datetime import tap_ringcentral.cache from tap_ringcentral.config import get_config_start_date from tap_ringcentral.state import incorporate, save_state, \ get_last_record_value_for_table f...
python
from copy import deepcopy from datetime import date, timedelta from hashlib import sha256 import starkbank from starkbank import BoletoPayment from .boleto import generateExampleBoletosJson example_payment = BoletoPayment( line="34191.09008 61713.957308 71444.640008 2 83430000984732", scheduled="2020-02-29", ...
python
import numpy as np import pandas as pd import time from collections import OrderedDict import argparse import os import re import pickle import subprocess def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False ...
python
question1 = input("random number ") question2 = input("another random number ") if (question1 > question2): print(question1, ">", question2) elif (question1 < question2): print(question1, "<", question2) else: print(question1, "=", question2)
python
import requests data = {'stuff': 'things'} r = requests.post('http://127.0.0.1:5042/incoming', data=data) print(r.text)
python
import json import requests from fisherman import exceptions from fisherman.utils import colors # Documentation: https://apility.io/apidocs/#email-check BASE_URL = "https://api.apility.net/bademail/" def check_email_rep(email, verbose_flag): try: colors.print_gray('Casting line - sending email...
python
import numpy as np import torch import torch.nn.functional as F import torch.nn as nn from . import dataloader def default_eval(loader,model,class_acc=False): data_source = loader.dataset way = len(data_source.classes) correct_count = torch.zeros(way).cuda() counts = torch.zeros(way).cuda() ...
python
from abc import ABC, abstractmethod from collections import defaultdict from enum import Enum from io import StringIO from itertools import chain from os import linesep from typing import List, Dict, Any, Union, Type, Set, Tuple class GenericSchemaError(Exception): pass class BaseSchemaError(Exception, ABC): ...
python
""" What does this module do? Does it do things? """ import logging from taxii_client import TaxiiClient __all__ = [] __version__ = '0.1' __author__ = 'Chris Fauerbach' __email__ = 'chrisfauerbach@gmail.com' class EdgeClient(TaxiiClient): def __init__(self, config): super(EdgeClient, self).__init__(co...
python
import torch import pickle import torch.utils.data import time import os import numpy as np from torch_geometric.utils import get_laplacian import csv from scipy import sparse as sp import dgl from dgl.data import TUDataset from dgl.data import LegacyTUDataset import torch_geometric as pyg from scipy.sparse import csr_...
python
# 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 agreed to in...
python
# -*- coding: utf-8 -*- """ Created on Tue May 14 08:26:52 2019 @author: mritch3 """ from __future__ import print_function from keras.preprocessing.image import ImageDataGenerator import numpy as np import os, glob import skimage.io as io import skimage.transform as trans import matplotlib as mp from PIL import Image...
python
from pinger import pinger import responses from requests.exceptions import ConnectTimeout def test_check_site_not_found(): url = 'https://fake.url/' site = { 'url': url, 'timeout': 1, } with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(res...
python
class Attributes: # Attributes of HTML elements accept = 'accept' # Specifies the types of files that the server accepts (only for type="file") accept_charset = 'accept-charset' # Specifies the character encodings that are to be used for the form submission accesskey = 'accesskey' # Specifies a shor...
python
from .api import Stage, concat, each, filter, flat_map, from_iterable, map, run, ordered, to_iterable from .utils import get_namespace
python
import numpy as np import pandas as pd import geopandas as gpd from _utils import clean_segments, filter_segments, split_by_dir, pd2gpd, edit_asfinag_file from _variable_definitions import * import pickle # ----------------------------------------------------------------------------------------------------------------...
python
import enum import pandas as pd from data import dataset class ColumnType(enum.Enum): sentence1 = 0, sentence2 = 1, labels = 2, columns = [ ColumnType.sentence1.name, ColumnType.sentence2.name, ColumnType.labels.name, ] class SNLIDataset(dataset.DatasetExperiment): def __init__(...
python
from pathlib import Path import yaml from charms import layer from charms.reactive import clear_flag, set_flag, when, when_any, when_not @when('charm.started') def charm_ready(): layer.status.active('') @when_any('layer.docker-resource.oci-image.changed', 'config.changed') def update_image(): clear_flag('c...
python
import numpy as np def read_log(log_file=None): '''This function reads Nalu log files Currently, the function only reads timing info output by nalu-wind It would be good to add more functionality to this function ''' if log_file is None: raise Exception('Please enter a log file name...
python
from avalon import api, houdini def main(): print("Installing OpenPype ...") api.install(houdini) main()
python
from distutils.version import LooseVersion import os import re import shutil import typing import pandas as pd import audbackend import audeer import audformat from audb.core import define from audb.core.api import ( cached, default_cache_root, dependencies, latest_version, ) from audb.core.backward ...
python
__author__ = 'schelle' import unittest import wflow.wflow_sceleton as wf import os """ Run sceleton for 10 steps and checks if the outcome is approx that of the reference run """ class MyTest(unittest.TestCase): def testapirun(self): startTime = 1 stopTime = 20 currentTime =...
python
from sqlalchemy import * from config.base import getBase, getMetaData, getEngine from utils.checkers import Checkers from utils.table_names import LstTableNames if Checkers.check_table_exists(getEngine(), LstTableNames.LST_R1_DATA_CHECK_GENERIC): class LstR1DataCheckGeneric(getBase()): __tablename__ = Tab...
python
# Generated by Django 3.2.7 on 2021-10-13 15:08 from django.db import migrations, models import django_countries.fields class Migration(migrations.Migration): dependencies = [ ('profiles', '0001_initial'), ] operations = [ migrations.AlterField( model_name='userprofile', ...
python
import os.path, logging from re import compile as re_compile from handlers.upstream import Upstream from handlers.dummy import DummyResponse, ExceptionResponse from handlers import is_uuid, CDE, CDE_PATH from content import copy_streams import annotations import config, features import calibre _BUFFER_SIZE = 64 * 10...
python
import os from curtsies.fmtfuncs import cyan, bold, green, red, yellow MAX_CHAR_LENGTH = 512 MIN_CHAR_LENGTH = 20 NEWLINECHAR = '<N>' d = 'repos' paths = [] for dirpath, dirnames, filenames in os.walk(d): for f in filenames: path = os.path.join(dirpath, f) paths.append(path) print(len(paths)) wit...
python
#!/usr/bin/env python import os from os.path import abspath, dirname, sep from idagrap.modules.Module import ModuleTestMisc from idagrap.modules.Pattern import Pattern, Patterns from idagrap.config.General import config def get_test_misc(): # Definition-----------------------------------------------------------...
python
"""Tests the functionality in the dinao.binding module.""" from typing import Generator, Mapping, Tuple from dinao.binding.binders import FunctionBinder from dinao.binding.errors import TooManyRowsError import pytest from tests.binding.mocks import MockConnection, MockConnectionPool, MockDMLCursor, MockDQLCursor ...
python
from alento_bot.storage_module.managers.config_manager import ConfigManager from alento_bot.storage_module.managers.guild_manager import GuildManager, GuildNameNotRegistered, AlreadyRegisteredGuildName from alento_bot.storage_module.managers.user_manager import UserManager, UserNameNotRegistered, AlreadyRegisteredUserN...
python
from flask import Blueprint, render_template, session from app.models import Post from app.db import get_db from app.utils.auth import login_required bp = Blueprint('dashboard', __name__, url_prefix='/dashboard') @bp.route('/') @login_required def dash(): db = get_db() posts = ( db.query(Post) .filter(Pos...
python
from getpass import getpass def login(): user = input("Enter your username: ") password = getpass() return user, password if __name__ == '__main__': print(login())
python
import logging from typing import Optional, List from django.db import models from django.db.models import Q from django.db.models.deletion import SET_NULL, CASCADE from django.db.models.signals import post_delete from django.dispatch.dispatcher import receiver from analysis.models.nodes.analysis_node import Analysis...
python
class Inputs(object): """ split-and: inputs.step_a.x inputs.step_b.x foreach: inputs[0].x both: (inp.x for inp in inputs) """ def __init__(self, flows): # TODO sort by foreach index self.flows = list(flows) for flow in self.flows: setattr(self, flow._current_s...
python
from prescription_data import * trial_patients = ['Denise', 'Eddie', 'Frank', 'Georgia', 'Kenny'] # Remove Earfarin and add Edoxaban for patient in trial_patients: prescription = patients[patient] try: prescription.remove(warfarin) prescription.add(edoxaban) except KeyError: print(...
python
# Copyright (c) 2020 Branislav Holländer. All rights reserved. # See the file LICENSE for copying permission. import jax import jax.numpy as jnp import jax.scipy.stats.norm as jax_norm from piper.distributions.distribution import Distribution from piper import core from piper import utils class Normal(Distribution)...
python
import os import pystache import re import sys sys.path.append("..") from ansible import build_ansible_yaml from api import build_resource_api_config from common.utils import (fetch_api, normal_dir, read_yaml, write_file) from design.resource_params_tree import generate_resource_properties from resource import build_r...
python
import os basedir = os.path.abspath(os.path.dirname(__file__)) APP_NAME = 'Glocal' CHOSEN_MEDIA = ['Twitter', 'Instagram', 'Four Square', 'LastFM', 'Eventful', 'Eventbrite']
python
import os import sys coverage = None try: from coverage import coverage except ImportError: coverage = None os.environ['DJANGO_SETTINGS_MODULE'] = 'example_project.settings' current_dirname = os.path.dirname(__file__) sys.path.insert(0, current_dirname) sys.path.insert(0, os.path.join(current_dirname, '..')) ...
python
#!/usr/bin/env python3.6 # coding=utf-8 import argparse import asyncio import datetime import logging import pprint import configparser import sys import traceback import book_utils import utils from db_model import get_db_session from utils import fix_symbol from ws_exception import WsError FORMAT = "[%(asctime)s, ...
python
# -*- coding: utf-8 -*- from azure.storage.blob import BlockBlobService import UtilityHelper import asyncio import requests, datetime import os, json, threading import multiprocessing from azure.eventprocessorhost import ( AbstractEventProcessor, AzureStorageCheckpointLeaseManager, EventHubConfig, E...
python
Gem_Qty = {"ruby": 25, "diamond": 30, "emrald": 15, "topaz": 18, "sapphire": 20} Gem_Price = {"ruby": 2000, "diamond": 4000, "emrald": 1900, "topaz": 500, "sapphire": 2500} Gem_Name = input("Enter Gem Names: ").split(",") Gem_Num = input("Enter Gem Quantities: ").split(",") Total_Cost = 0 ...
python
# 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 2.3.3...
python
import torch from torch import nn from transformers import AutoModel, AutoConfig from pdb import set_trace def init_weights(module, init_type='xavier'): """Initialize the weights""" if init_type =='default': return elif init_type == 'huggingface': if isinstance(module, nn.Linear): ...
python
#!/usr/bin/env python3 import sys class FuelDepotCracker: def __init__(self): self.minimum = 271973 self.maximum = 785961 self.position = self.minimum def is_valid(self, value): """Returns boolean is valid fuel depot password?""" has_duplicate = False numbers ...
python
'''def print_args(farg, *args): print("formal arg: %s" % farg) for arg in args: print("another positional arg: %s" % arg) print_args(1, "two", 3) ''' def example(a, **kw): print (kw) example(3, c=4) # => {'b': 3, 'c': 4}
python
from .light import light from .eos import calc_density as density, viscosity from .rasterize import ladim_raster
python
import logging import unittest from unittest import TestCase from facebookproducer.posts.posts_provider import PostsProvider class PostsProviderTests(TestCase): def __init__(self, *args, **kwargs): super(PostsProviderTests, self).__init__(*args, **kwargs) logging.basicConfig( format=...
python
#!/usr/bin/env python """ Field """ """ Copyright 2001 Pearu Peterson all rights reserved, Pearu Peterson <pearu@ioc.ee> Permission to use, modify, and distribute this software is given under the terms of the LGPL. See http://www.fsf.org NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Revision...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Conversation module.""" import rospy from .state_machine import StateMachine from .rospy_helper import * import nltk from nltk.corpus import stopwords def preprocess_txt(txt): list_words = ['oh', 'ah', 'okay', 'ok', 'well', 'please', 'first', 'then', 'finally',...
python
"""Provision hosts for running tests.""" from __future__ import annotations import atexit import dataclasses import functools import itertools import os import pickle import sys import time import traceback import typing as t from .config import ( EnvironmentConfig, ) from .util import ( ApplicationError, ...
python
from abc import ABC from .private_torrent import PrivateTorrent from ..base.sign_in import SignState, check_final_state from ..base.work import Work from ..utils.value_hanlder import handle_join_date class AvistaZ(PrivateTorrent, ABC): SUCCEED_REGEX = None def sign_in_build_workflow(self, entry, config): ...
python
class Audit: # Class for the different sub classes def __init__(self, json): self.id = json["id"] self.action = json["action"] self.timestamp = json["timestamp"] self.tenantId = json["tenantId"] self.customerId = json["customerId"] self.changedBy = json["changedBy"] ...
python
from flask import Blueprint from flask_restful import Api, Resource root_blueprint = Blueprint("root", __name__) api = Api(root_blueprint) class Root(Resource): def get(self): return {"status": "success", "message": "TODO react app"} api.add_resource(Root, "/")
python
import os import numbers import datetime from celery import schedules from celery.beat import Scheduler from celery.utils.log import get_logger from sqlalchemy import create_engine, inspect from sqlalchemy.orm import sessionmaker from typing import Any, Dict from .models import Base, TaskEntry logger = get_logger...
python
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2017 Damian Ziobro <damian@xmementoit.com> # # Distributed under terms of the MIT license. """ This is hello world application to use Redis NoSQL databas """ import redis REDIS = redis.Redis(host='localhost', port=5000, password='passwor...
python
from initialize import initialize import matplotlib.pyplot as plt x, y = initialize() x.sort() y.sort() plt.plot(x,y) plt.show()
python
"""A core utility function for downloading efficiently and robustly""" def download_file(url, path, progress=False, if_newer=True): """Download large file efficiently from url into path Parameters ---------- url : str The URL to download from. Redirects are followed. path : {str, pathlib....
python
[print] [1,3] [b,]
python
from concurrent.futures import ThreadPoolExecutor import socket import os def __handle_message(args_tuple): conn, addr, data_sum = args_tuple while True: data = conn.recv(1024) data_sum = data_sum + data.decode('utf-8') if not data: break if data_sum != '': p...
python
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2020, Caleb Bell <Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal...
python
import json import os from os import listdir from os.path import isfile, join from pprint import pprint from database.user import SessionUser from util.login_spotify import login_spotify def json_to_database(): """ Loads the json files from the first experiment into a database, the folder can be specified by...
python
#!/usr/bin/env python # coding: utf-8 __author__ = 'ChenyangGao <https://chenyanggao.github.io/>' __version__ = (0, 0, 2) __all__ = ['watch'] # TODO: 移动文件到其他文件夹,那么这个文件所引用的那些文件,相对位置也会改变 # TODO: created 事件时,文件不存在,则文件可能是被移动或删除,则应该注册一个回调,因为事件没有被正确处理 plugin.ensure_import('watchdog') import logging import posixpath impo...
python
import math LambdaM = {0: None} L = [2, 1] Ll = 2 def compute_Lucas(n): global L global Ll while Ll <= n: L.append(L[-1] + L[-2]) Ll += 1 return L[n] def struct_thm(n, i=0): # TODO: make this loop more efficient # it loops up to log n ^2 times # get it down to log n by s...
python
import pandas as pd ## Getting the data ## # save filepath to variable for easier access melbourne_file_path = 'melb_data.csv' # read the data and store data in DataFrame titled melbourne_data melbourne_data = pd.read_csv(melbourne_file_path) # print a summary of the data in Melbourne data print(melbourne_data.descri...
python
"""Unit test package for publiquese."""
python
import pandas as pd import numpy as np import pandas2latex_CELEX as p2l import sys def formatter_counts(x): return ('%.2f' % x) def formatter_percent(x): return (r'%.2f\%%' % x) def format_sublex_name(sublex_name): return (r'\textsc{Sublex}\textsubscript{$\approx$%s}' % sublex_name) # return (r'\textsc{Sublex}\...
python
"""Test dynamic width position amplitude routines.""" import jax.numpy as jnp import numpy as np import vmcnet.mcmc.dynamic_width_position_amplitude as dwpa def test_threshold_adjust_std_move_no_adjustment(): """Test that when mean acceptance is close to target, no adjustment is made.""" target = 0.5 thr...
python
import sys input = sys.stdin.readline n = int(input()) cnt = 0 for i in range(1, n + 1): if i % 2 == 1: cnt += 1 print(cnt / n)
python