content stringlengths 5 1.05M |
|---|
# Quick Script to execute spark-submit commands
|
#!/usr/bin/env python
import requests
from HTMLParser import HTMLParser
from config import HTTP_HEADERS
def new_or_revised(pub_id):
resp = requests.get(
'http://eprint.iacr.org/eprint-bin/versions.pl?entry=' + pub_id,
headers=HTTP_HEADERS
)
if resp.status_code != 200:
# try aga... |
"""Tests for Kamereon models."""
from typing import cast
from tests import get_response_content
from renault_api.kamereon import models
from renault_api.kamereon import schemas
FIXTURE_PATH = "tests/fixtures/kamereon/vehicle_data"
TEST_UPDATE = {
"id": 1,
"tuesday": {"startTime": "T12:00Z", "duration": 15}... |
'''
Copyright (c) Project TemperStat. All rights reserved.
by Aditya Borgaonkar & Sahil Gothoskar, 2020.
https://github.com/adityaborgaonkar
https://github.com/SahilGothoskar
'''
import csv
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import ... |
import torch.cuda as cuda
import torch.optim as optim
import torch.utils.trainer as trainer
import torch.utils.trainer.plugins
import torch.utils.data as tudata
import torch.nn as nn
from torch.autograd import Variable
import torchvision as tv
import torchvision.transforms as tforms
import torchvision.datasets as dsets... |
INT = 0
BYTES = 1
STRING = 2
BOOL = 3
ARRAY = 4
DICT = 5
B_INT = b'\x00'
B_BYTES = b'\x01'
B_STRING = b'\x02'
B_BOOL = b'\x03'
B_ARRAY = b'\x04'
B_DICT = b'\x05'
def encode_int(n):
if n == 0:
return b'\x00'
else:
return bytes([n % 256]) + encode_int(n // 256)
def consume_int(index, bstring):
... |
# -*- coding: utf-8 -*-
from fixture.orm import ORMFixture
from model.group import Contact, Group
import random
db = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="")
def test_add_contact_in_group(app):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="NewGroup"))
... |
import sys
sys.stderr = open(snakemake.log[0], "w")
import pandas as pd
def aggregate(sm_input, sm_output, samples):
single_outputs = []
for file_path, sample in zip(sm_input, samples):
single_deep_arg_output = pd.read_csv(file_path, sep="\t")
single_deep_arg_output["sample"] = sample
... |
"""
The splash screen of the game. The first thing the user sees.
"""
import pygame as pg
from .. import prepare, state_machine
class Splash(state_machine._State):
"""This State is updated while our game shows the splash screen."""
def __init__(self):
state_machine._State.__init__(self)
self... |
from mongoengine import Document
from mongoengine import ListField
from mongoengine import StringField
from mongoengine import IntField
import numpy as np
import cPickle as pickle
from sklearn import svm
class User(Document):
email = StringField(required=True, max_length=50)
first_name = StringField(max_len... |
from django.contrib import admin
from .models import User, Income, Transaction, Budget
# Register your models here.
admin.site.register(User)
admin.site.register(Income)
admin.site.register(Transaction)
# admin.site.register(Budget)
|
def acceleration():
initial_velocity = float(input("What is the initial velocity?: "))
final_velocity = float(input("What is the final velocity?: "))
starting_time = float(input("What is the starting time?: "))
ending_time = float(input("What is the ending time?: "))
delta_t = ending_time - starting... |
from unittest import TestCase
from tests.integration.it_utils import submit_transaction
from tests.integration.reusable_values import FEE, WALLET
from xrpl.models.transactions import SignerEntry, SignerListSet
from xrpl.wallet import Wallet
class TestSignerListSet(TestCase):
def test_add_signer(self):
# ... |
#Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
usuario = input("Digite o nome do usuário: ")
senha = input("Digite a senha: ")
while usuario == senha:
print("Valor inválido - usuário e sen... |
import theano
import theano.tensor as T
import lasagne
from lasagne.layers import *
class NLLELayer(lasagne.layers.Layer):
#Negative Log Likelihood Estimator Layer
def get_output_for(self, input, **kwargs):
return -T.mean(T.log(input))
def get_output_shape_for(self, shape, **kwargs):
r... |
import lzma
def compress(path: str, content):
f = lzma.open(path, 'w')
f.write(bytes(content, encoding='utf-8'))
f.close()
def decompress(path):
f = lzma.open(path, 'r')
result = f.read()
f.close()
return result
|
import frappe
from awesome_cart.compat.customer import get_current_customer
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
from frappe import _
from frappe.contacts.doctype.contact.contact import get_default_contact
from frappe.core.doctype.role.role import get_emails_from_role
from fr... |
"""Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is included. Write a program to find Nth Ugly Number.
Example 1:
Input:
N = 10
Output: 12
Explanation: 10th ugly number is 12.
Example 2:
Input:
N =... |
"""
API file for discussion app
consists of the viewsets for the apis in the discussion app
"""
from django.utils import timezone
from rest_framework import status
from rest_framework.authentication import TokenAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_frame... |
from pathlib import Path
from fhir.resources.codesystem import CodeSystem
from oops_fhir.utils import CodeSystemConcept
__all__ = ["AdditionalMaterialCodes"]
_resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json"))
class AdditionalMaterialCodes:
"""
Additional Material Codes
This value... |
import os
import time
import zc.lockfile
from dvc.exceptions import DvcException
class LockError(DvcException):
pass
class Lock(object):
LOCK_FILE = 'lock'
TIMEOUT = 5
def __init__(self, dvc_dir, name=LOCK_FILE):
self.lock_file = os.path.join(dvc_dir, name)
self._lock = None
@... |
##############################################################################
# Copyright (c) 2021, Oak Ridge National Laboratory #
# All rights reserved. #
# #
# Th... |
# from bw_processing import (
# as_unique_attributes,
# chunked,
# COMMON_DTYPE,
# create_package,
# create_datapackage_metadata,
# create_structured_array,
# create_processed_datapackage,
# format_calculation_resource,
# greedy_set_cover,
# NAME_RE,
# )
# from copy import deepco... |
# -*- coding: utf-8 -*-
from .api import Api
from .exceptions import PushException, GetException
|
"""Add git parameters to model
Revision ID: ebbfb7d55f62
Revises: 75933cf6bdb9
Create Date: 2019-04-01 14:50:29.492904
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "ebbfb7d55f62"
down_revision = "75933cf6bdb9"
branch_labels = None
depends_on = None
def upg... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import os
f... |
from scipy.spatial.distance import cosine
import numpy as np
import cv2
import mtcnn
from keras.models import load_model
from utils import get_face, plt_show, get_encode, load_pickle, l2_normalizer
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder
from... |
from functools import partial
from typing import Any, Callable, Tuple
import numpy as np
import jax
from jax import numpy as jnp
from jax import tree_map
from netket import jax as nkjax
from netket import config
from netket.stats import Stats, statistics, mean
from netket.utils import mpi
from netket.utils.types imp... |
from .models import *
from .backends import *
from .reporters import *
from .constants import *
from .cover import *
from .persister import *
from .scheduler import *
from .celery import *
|
from datetime import timedelta, datetime
import pytest
from crawler.api_client import RestClient, Token
from crawler import api_client
from crawler.exceptions import APIException
class MockResponse:
"""Class to mock server responses"""
def __init__(self, json_date, status_code):
self.json_data = js... |
# Copyright 2022 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
# based on https://github.com/sfotiadis/yenlp/blob/master/extract_reviews.py
import json
import os
import sys
from string import Template
from lingofunk_classify_sentiment.config import config, fetch
business_data_filename = fetch(config["datasets"]["yelp"]["ids"])
reviews_data_filename = fetch(config["datasets"]["... |
import requests
from zvgportal.zvgclient.formdata import FormData
SEARCH_URL = "https://www.zvg-portal.de/index.php"
class ZvgClient:
def __init__(self, query):
self.query = query
def search(self):
params = {"button": "Suchen", "all": 1}
data = FormData(
land_abk=self.q... |
"""
This module is used to discover the serial address of any ML600 connected to the PC.
"""
import asyncio
import aioserial
import serial.tools.list_ports
from loguru import logger
from flowchem.components.devices.Hamilton.ML600 import (
HamiltonPumpIO,
InvalidConfiguration,
)
def ml600_finder():
"""Tr... |
### Main Functionality - Export CSV file names py jobs with 25 jobs
from files import converter as con
from search import cb_job_search as cb
from util import states
def main(job, location, filename):
for state in states.get_us_states():
job_data = cb.start_search(job, location)
for item in jo... |
"""
Exercise django-registration's built-in form classes.
"""
import uuid
from django.core.exceptions import ValidationError
from django.test import modify_settings
from django.utils.six import text_type
from django_registration import forms, validators
from .base import RegistrationTestCase
@modify_settings(INST... |
liste = [12, -3, 3, 1, 34, 100]
liste.sort(reverse = True)
print(liste)
|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Simphony Photonic Simulator
This module implements a free and open source
photonic integrated circuit (PIC) simulation engine.
It is speedy and easily extensible... |
import statistics
# Assign problem data to variables with representative names
# well height, daily advance, night retreat, accumulated distance
advance_cm, well_height_cm, night_retreat_cm, accumulated_distance_cm= [30, 21, 33, 77, 44, 45, 23, 45, 12, 34, 55], 125, 20, 0
# Assign 0 to the variable that represents ... |
from django.conf import settings
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.core.cache import cache
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required, user_passes_test, permission_required
... |
from app.objects.secondclass.c_parserconfig import ParserConfig
from app.utility.base_object import BaseObject
class Parser(BaseObject):
@property
def unique(self):
return self.module
@classmethod
def from_json(cls, json):
parserconfigs = [ParserConfig.from_json(r) for r in json['rel... |
import json
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
import cattr
import pytest
from pytest_mock import MockerFixture
from ambramelin.util import config as util_config
from ambramelin.util.config import Config, Environment, User
class TestLoadConfig:
def test_with_fil... |
import warnings
import pandas as pd
import time
from autox.autox_server.util import log
from tqdm import tqdm
warnings.filterwarnings('ignore')
import re
def fe_stat_for_same_prefix(G_df_dict, G_data_info, G_hist, is_train, remain_time, AMPERE):
# 对G_df_dict['BIG']表做扩展特征
start = time.time()
log('[+] featur... |
from flask import make_response, jsonify
from fusillade.directory.resource import ResourceType, ResourceId
from fusillade.utils.authorize import authorize
@authorize(["fus:GetResources"],
["arn:hca:fus:*:*:resource/{resource_type_name}/{resource_id}"],
resource_params=['resource_type_name', 're... |
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# TH... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from headstock.lib.utils import extract_from_stanza
__all__ = ['ProxyRegistry']
class ProxyRegistry(object):
def __init__(self, stream):
self.stream = stream
self._dispatchers = {}
self.logger = None
def set_logger(self, logger):
... |
import six
import py
import pytest
import execnet
pytest_plugins = "pytester"
if six.PY2:
@pytest.fixture(scope="session", autouse=True)
def _ensure_imports():
# we import some modules because pytest-2.8's testdir fixture
# will unload all modules after each test and this cause
# (unk... |
SECOND_REMIND_TIME = 5
THIRD_REMIND_TIME = 15
LAST_REMIND_TIME = 30
EXPIRED_REMIND_TIME = LAST_REMIND_TIME + 1
DATETIME_FORMAT = '%Y-%m-%d %H:%M:00'
# Date/time format for week
START_WEEK_FORMAT = '%Y-%m-%d 00:01:00'
END_WEEK_FORMAT = '%Y-%m-%d 23:59:00'
# List flags
LIST_ALL_FLAG = 'all'
LIST_WEEK_FLAG = 'week'
HOU... |
# Generated by Django 3.2.7 on 2021-11-03 14:40
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('app', '0002_profile'),
... |
# -*- coding: utf-8 -*-
"""
Copyright 2018 Alexey Melnikov and Katja Ried.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
Please acknowledge the authors when re-using this code and maintain this notice intact.
Code written by Katja Ried... |
from flask import current_app as app
from flask import Flask, request
from passlib.hash import pbkdf2_sha256
from jose import jwt
from ..tools import tools
from ..auth import auth
import json
class User:
def __init__(self):
self.defaults = {
"id": tools.randID(),
"ip_addresses": [... |
from kgx import PandasTransformer
from kgx import ObanRdfTransformer
from kgx import PrefixManager
import networkx as nx
import logging
HAS_EVIDENCE_CURIE = 'RO:0002558'
HAS_EVIDENCE_IRI = 'http://purl.obolibrary.org/obo/RO_0002558'
# TODO: sync with context when we switch to identifiers.org
PUB = 'http://www.ncbi.nl... |
import sympy.physics.mechanics as me
import sympy as sm
import math as m
import numpy as np
x, y = me.dynamicsymbols('x y')
xd, yd = me.dynamicsymbols('x y', 1)
e1 = (x+y)**2+(x-y)**3
e2 = (x-y)**2
e3 = x**2+y**2+2*x*y
m1 = sm.Matrix([e1,e2]).reshape(2, 1)
m2 = sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)
m3 = m1+sm.M... |
import os
import tarfile
from argparse import ArgumentParser, Namespace
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import mlflow.pytorch
import pandas as pd
import pytorch_lightning as pl
import requests
import torch
from pytorch... |
import copy
import heapq
import math
import matplotlib.pyplot as plt
import numpy as np
import time
import utils
from occupancy_grid import OccupancyCell, OccupancyGrid
from robot import Robot
from shapely import affinity, geometry
from typing import List, Tuple
class FrontierPlanner():
def __init__(self, grid: Oc... |
from math import gcd
from functools import reduce
class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
return reduce(gcd, nums) == 1 |
# -*- coding: utf-8 -*-
"""
File multi_label_loss.py
@author:ZhengYuwei
"""
import numpy as np
import tensorflow as tf
from tensorflow import keras
class MyLoss(object):
""" 损失函数 """
def __init__(self, model, **options):
self.model = model
self.is_label_smoothing = options.setdefault('is_label... |
for i in range(1, 21):
print(i) |
from setuptools import setup, find_packages
# name is the package name in pip, should be lower case and not conflict with existing packages
# packages are code source
setup(
name="astrosimon",
version="0.8.5",
description="Simulation Monitor for computational astrophysics",
url="https://github.com/max... |
from .runner import Runner # noqa
|
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def caesar(directionn,cypher_text, shift_amount... |
import pytest
from stock_indicators import indicators
class TestSTC:
def test_standard(self, quotes):
cycle_periods = 9
fast_periods = 12
slow_periods = 26
results = indicators.get_stc(quotes, cycle_periods, fast_periods, slow_periods)
r = results[34]
... |
import io
import logging
import os
import pathlib
from datetime import datetime
from typing import List
from musiquepy.data.errors import MusiquepyExistingUserError
from musiquepy.data.media import get_profile_pictures_dir
from musiquepy.data.model import (
Album, AlbumPhoto, Artist, MusicGenre, MusicTrack, User)
... |
"""
#def swap(x,y):
T=((10,'Q1'), (20,'Q2'), (50,'Q3'))
for i in T:
print(i[1])
def get_data(aTuple):
nums = ()
words = ()
for t in aTuple:
nums = nums + (t[0],)
if t[1] not in words:
words = words + (t[1],)
min_n = min(nums)
max_n = max(nums)
uniq... |
from base64 import b64encode, b64decode
import binascii
from itertools import islice
import logging
LOG = logging.getLogger(__name__)
gen_raw_nec_protocols_standard = ['nec1',
'nec2',
'necx1',
'necx2']
gen_raw_nec_p... |
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.kernel_ridge import KernelRidge
from sklearn.datasets import make_regression, make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, log_loss
from sklearn.base import clone
c... |
# Python library import
import asyncio, netscud
async def task():
"""
Async function
"""
my_device = {
"ip": "192.168.0.16",
"username": "cisco",
"password": "cisco",
"device_type": "cisco_ios",
}
# Creation of a device
sw1 = netscud.ConnectDevice(**my_dev... |
from setuptools import setup
from setuptools import find_packages
VERSION = "1.0.0"
DESCRIPTION = "DWIO NYU Helpers"
setup(
name="dwio-nyu",
version=VERSION,
author="Daniel Walt",
description=DESCRIPTION,
packages=find_packages(),
intsall_requires=[
]
)
|
#!/usr/bin/env python3
from utils import add_to_dict_num
from math import log10
from jellyfish import levenshtein_distance
from operator import itemgetter
class comparator:
def __init__(self):
None
def compare(self, A, B):
return A == B
class probabilityTree:
def __init__(self, funct... |
from IPython.core.display import HTML, SVG
import pandas as pd
import numpy as np
import xport
import IPython
from ipywidgets import Layout
from ipywidgets import widgets
from IPython.display import display
import matplotlib.ticker as ticker
import matplotlib.cm as cm
import matplotlib as mpl
from matplotlib.gridspec ... |
from .train_wandb_fpc import train_wandb_cae, train_wandb_aae, \
train_wandb_svdae # noqa: F401
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils.translation import ugettext_lazy
from .models import Client, ProxyResource, HTTPMethod, Api
@admin.register(Client)
class ClientAdmin(admin.ModelAdmin):
list_display = ('name', 'api_key', )
readonly_fields = ('api_key', )
def sav... |
# Generated with LoadAndMassFormulation
#
from enum import Enum
from enum import auto
class LoadAndMassFormulation(Enum):
""""""
LUMPED = auto()
CONSISTENT = auto()
def label(self):
if self == LoadAndMassFormulation.LUMPED:
return "Lumped load and mass formulation"
if self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Trace splay tree."""
import inspect
import logging
import os
import pygraphviz as pgv
from splay_tree_orig import SplayTree
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
os.makedirs("graph", exist_ok=True)
def for_all_methods(decora... |
import numpy as np
from rpy2.robjects import FloatVector
from rpy2.robjects.packages import importr
import matplotlib.pyplot as plt
from itertools import combinations_with_replacement as comb_rep
from src.tools import get_params
def scale_omega(Omega, omega_scale, pos, C):
Omega_tmp = np.copy(Omega)
idxC = get... |
import unittest
from think import Agent, Memory, Speech
class AgentTest(unittest.TestCase):
def test_agent(self, output=False):
agent = Agent(output=output)
agent.wait(10.0)
self.assertAlmostEqual(10.0, agent.time(), 2)
agent.run_thread(lambda: agent.wait(5.0))
agent.wait... |
"""
Generic training script that trains a model using a given dataset.
This code modifies the "TensorFlow-Slim image classification model library",
Please visit https://github.com/tensorflow/models/tree/master/research/slim
for more detailed usage.
"""
from __future__ import absolute_import
from __futu... |
import os
import sys
def count_tabs(text):
counter = 0
for i in range(len(text)):
if i+1 < len(text)-1:
#print(text[i], text[i+1])
if text[i] == "\\" and text[i+1] == "t":
counter += 1
return counter
def parser(file='default_file.cc', substitute_lines=[""], ... |
# Generated by Django 2.1.7 on 2019-03-25 10:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ingenieria', '0002_auto_20190322_0931'),
]
operations = [
migrations.AlterField(
model_name='recurrente',
name='nomb... |
import unittest
from parameterized import parameterized_class
from src.calculus_of_variations import HigherDerivativesSolver
from src.calculus_of_variations.utils import t, var
Cs = {}
for i in range(1, 9):
Cs[i] = var("C{}".format(i))
def make_solution(
n: str, L: str, t0: str, t1: str, x0: str, x1: str, ... |
"""
Functions for plotting datasets nicely.
"""
# TODO: custom xtick labels #
# TODO: annotations, arbitrary text #
# TODO: docs #
import functools
import numpy ... |
from telegram.ext.updater import Updater
from telegram.update import Update
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.commandhandler import CommandHandler
from telegram.ext.messagehandler import MessageHandler
from telegram.ext.filters import Filters
from telegram import KeyboardButton,... |
# TULISAN nya digituin pokoknya gk tau istilah nya ngasal aja
def rev(txt):
g=int(len(txt)/2)
print(txt[g:]+txt[:g])
# if len(txt)%2==0:
# print(txt[g:]+txt[:g])
# else:
# print('eror pie iki')
tulisan='sabi lika taki jarbela honpyt engbar'
les =tulisan.split()
for i in range(len(les)):
rev(les[i])
... |
#!/usr/bin/python
import ConfigParser
class Configuration:
def __init__(self, size, count, page):
self.config = ConfigParser.ConfigParser()
self.config.read('/opt/esm/etc/http.ini')
def user(self):
return self.config.get('access', 'admin')
def passwd(self):
return self... |
import numpy as np
import pandas as pd
import sys
import json
import os
import igraph as ig
import pprint
import copy
def getopts(argv):
opts = {}
while argv:
if argv[0][0] == '-':
opts[argv[0]] = argv[1]
argv = argv[1:]
return opts
if __name__ == '__main__':
args = getopt... |
import os
from pathlib import Path
from urllib.parse import quote
from django.http import JsonResponse
from django.shortcuts import redirect, render
from Tagger import params, settings
from . import db_operations as db
def _is_allowed_path(path: Path) -> bool:
return (
not params.BASE_PATH
or p... |
from datetime import date, timedelta
from django.conf import settings
from django.core.management.base import BaseCommand
from kitsune.kpi.management import utils
from kitsune.kpi.models import L10N_METRIC_CODE, Metric, MetricKind
from kitsune.sumo import googleanalytics
class Command(BaseCommand):
help = "Calc... |
number_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
for number in number_list:
if number == '1':
print(number + "st")
elif number == '2':
print(number + "nd")
elif number == '3':
print(number + "rd")
elif number == '4':
print(number + "th")
elif number == '5'... |
from music21 import note, instrument, stream
import numpy as np
import matplotlib.pyplot as plt
import os
import os.path
from helper import createPitchVocabularies, loadChorales
from config import note_embedding_dim, note_embedding_dir
from keras.models import Model
from keras.layers import Input, Dense
# create th... |
from typing import Dict
from .abstract_template import AbstractXDLElementTemplate
from ..base_steps import AbstractStep
from ...constants import VESSEL_PROP_TYPE
from ...utils.prop_limits import TIME_PROP_LIMIT, PRESSURE_PROP_LIMIT
from ...utils.vessels import VesselSpec
class AbstractEvacuateAndRefillStep(AbstractXDL... |
def main():
# get
sales = get_sales()
advanced_pay = get_advanced_pay()
rate = determined_comm_rate(sales)
# calc
pay = sales * rate - advanced_pay
# print
print("The pay is $", format(pay, ",.2f"), sep='')
return
def get_sales():
return float(input("Sales: $"))
def determined_... |
class Angel:
color = "white"
feature = "wings"
home = "Heaven"
class Demon:
color = "red"
feature = "horns"
home = "Hell"
goodie = Angel()
baddie = Demon()
print(f'{goodie.color}\n{goodie.feature}\n{goodie.home}')
print(f'{baddie.color}\n{baddie.feature}\n{baddie.home}')
|
import os
from shutil import copyfile
class FileCheck:
@staticmethod
def check_folder(path):
if os.path.exists(path):
return True
return False
def check_create_folder(self, path):
if not self.check_folder(path):
print(f"[Action] Creating a folder for you...... |
__all__ = [
"Extensible"
]
from .pygen import (
pythonizable
)
class Extensible(object):
"Remembers attributes added to it and support serialization to Python."
def __init__(self, **kw):
self.__added = set(kw)
self.__dict__.update(kw)
def __setattr__(self, n, v):
if n[0]... |
from optparse import OptionParser
from sys import maxint
import string
import time
import random
import socket
import logging
import logging.handlers
fixed_line = ""
hostname = socket.gethostname()
# Possible run times are:
# - fixed number of seconds
# - set number of messages
# - run until stopped
def determine... |
#IMPORTS
import praw #Reddit API Package (https://praw.readthedocs.io/en/latest/index.html)
import datetime as dt
from datetime import date
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy.util as util
from spotipy.oauth2 import SpotifyOAuth
import random
import json
import re... |
import math
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler, SequentialSampler
from sklearn.model_selection import StratifiedKFold
import dgl
def collate(samples):
# 'samples (graph, label)'
graphs, labels = map(list, zi... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from enum import IntEnum
from typing import Tuple, Optional, List, Union
from typing import Any
from nassl import _nassl
from typing import Dict
from typing import Text
class OcspResponseNotTrustedError... |
import cocos
from cocos.text import Label
from cocos import scene
from cocos.layer import Layer
from cocos.director import director
from cocos.sprite import Sprite
# Except for this import. This import, from Pyglet (one of the dependencies of cocos), is to recognize keyboard codes
from pyglet.window.key import symbol_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-07 00:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.