content
stringlengths
5
1.05M
import os import numpy as np import argparse from sklearn.model_selection import StratifiedKFold #from data.image_folder import make_dataset #from tensorflow.keras.preprocessing.image import ImageDataGenerator import tensorflow as tf import json import pandas as pd import numpy as np import os, sys import glob import...
# Return some system information # Because the universe will never have enough scripts that do this # It's only going to work on fairly recent *NIX platforms import os, socket uname_ = os.uname() system = uname_[0] host = socket.gethostname() kernel = uname_[2] release = uname_[3] processor = uname_[4]
## Copyright 2004-2007 Virtutech AB ## ## The contents herein are Source Code which are a subset of Licensed ## Software pursuant to the terms of the Virtutech Simics Software ## License Agreement (the "Agreement"), and are being distributed under ## the Agreement. You should have received a copy of the Agreem...
import numpy as np from sklearn.ensemble import RandomForestRegressor from sklearn.externals import joblib sgids = joblib.load('sgids.pkl') sgdiv = joblib.load('data/sg_div_tr_ns.pkl') params = joblib.load('params.pkl') dt = dict.fromkeys(sgids) sgid = sgids[0] for i, sgid in enumerate(sgids): print(f'{sgid} ({i...
#-*-coding utf-8 -*- #Affine Transformation import numpy as np import cv2 from matplotlib import pyplot as plt img=cv2.imread('resimler/sudoku.png') rows,cols,ch=img.shape pts1 = np.float32([[50,50],[200,50],[50,200]]) pts2=np.float32([[10,100],[200,50],[100,250]]) M = cv2.getAffineTransform(pts1,pts2) ...
# /usr/bin/env python3 # -*- coding: utf-8 -*- """ This file contains the implementation to the HTTP server that serves the web API for the Serial port. """ import logging import threading import typing as t import flask import flask_restful import waitress from flask_cors import CORS from . import connection # fo...
""" Version information for PyBioMed, created during installation. Do not add this file to the repository. """ import datetime version = '1.0' date = 'Nov 7 9:17:16 2016' dev = False # Format: (name, major, min, revision) version_info = ('PyBioMed', '1', '0', None) # Format: a 'datetime.datetime' instance date_i...
#!/usr/bin/python # -*- coding: UTF-8 -*- import requests import os import zipfile import urllib import dirconfig import logging from autobuild import autobuild,git_pull import commands import os from githubdownload import GithubDownload from repositories import repositories from ziptool import ZipTool logging.basi...
""" Unit test for LocalProcessMemoryConsumption measurement. """ import os import time import pytest import threading import subprocess from mlte._private.platform import is_windows, is_nix from mlte.measurement.memory import LocalProcessMemoryConsumption from mlte.measurement.memory.local_process_memory_consumption ...
from .emonet import EmoNetPredictor __version__ = '0.1.0'
"""Utilities for building command-line interfaces for your daemons""" import inspect from functools import wraps import click from .core import Daemon from .helpers import MultiDaemon def _parse_cli_options(func): """Parse click options from a function signature""" options = [] for param in inspect.sig...
"""This module provide multiple test of ingestion services""" import logging from conftest import ValueStorage import time from server_automation.configuration import config from server_automation.functions import executors from server_automation.postgress import postgress_adapter _log = logging.getLogger("server_auto...
import jax from absl import app from absl import flags flags.DEFINE_string('server_addr', '', help='server ip addr') flags.DEFINE_integer('num_hosts', 1, help='num of hosts' ) flags.DEFINE_integer('host_idx', 0, help='index of current host' ) FLAGS = flags.FLAGS def main(argv): jax.distributed.initialize(FLAGS.ser...
""" This script prepares the files that populate the databases, such as adding headers to them and removing a couple of noun phrases that do not belong there. """ def prepare_data(file): """ Prepares the argument file for SQL insertion """ with open(file, 'r', encoding='utf-8') as infile: inf...
# # This file is part of Brazil Data Cube Validation Tools. # Copyright (C) 2020 INPE. # # Python Native import os import time import sys # 3rdparty import gdal import numpy as np def diff_sum_abs(image_path1,image_path2, output_folder): ''' documentar para sair automaticamente ''' # get o stk de banda...
from django import forms class LoginForm(forms.Form): email = forms.EmailField(required = True, error_messages = {"required": "邮箱不能为空"}) password = forms.CharField(required = True, min_length = 6, max_length = 20, error_messages={ "min_length": "密码应该大于等于6个字符", "max_length": "密码应该小于等于20个字符", }) class Registe...
''' This code is for head detection for PAN. ''' import torch import torch.nn as nn import math __all__ = ['PA_Head'] class PA_Head(nn.Module): def __init__(self, in_channels, hidden_dim, num_classes): super(PA_Head, self).__init__() self.conv1 = nn.Conv2d(in_channels, hidden_dim, kernel_size=3, s...
#!/usr/bin/python # -*- coding: UTF-8 -*- # # Copyright 2011 Google Inc. 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...
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = "0xdeadbeefdeadbeef" DEBUG = True INSTALLED_APPS = [ "django_jsonfield_backport", "tests", ] DATABASES = { "default": { "ENGINE": "django.db.backends.%s" % os.getenv("DB_BACKEND"), "NAME": os.get...
# Given a linked list which might contain a loop, implement an algorithm that returns the node at the beginning of the loop (if one exists) from utils import Node first_node = Node(1) second_node = Node(2) third_node = Node(3) fourth_node = Node(4) fifth_node = Node(5) sixth_node = Node(6) # Visual [1, 2, 3, 4, 5, ...
#!/usr/bin/env python # Plots Sigmoid vs. Probit. import matplotlib.pyplot as pl import numpy as np from scipy.special import expit from scipy.stats import norm x = np.arange(-6, 6, 0.1) l = np.sqrt(np.pi/8); pl.plot(x, expit(x), 'r-', label='sigmoid') pl.plot(x, norm.cdf(l*x), 'b--', label='probit') pl.axis([-6, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from PySide6 import QtCore, QtWidgets class MyWidget(QtWidgets.QWidget): def __init__(self): super().__init__() self.text = QtWidgets.QLabel("Hello World", alignment=QtCore.Qt.AlignCenter) self.layout = QtWidgets.QVBoxLayout(self)...
# Author: Bohua Zhan import unittest from kernel.type import boolT, TVar, TFun from kernel.term import Term, Var from kernel.thm import Thm from kernel.proof import ProofItem from logic.proofterm import ProofTerm, ProofTermAtom from logic import basic from logic.logic import conj, disj, mk_if from logic.nat import na...
# -*- coding: utf-8 -*- # # Copyright 2021 Google Inc. 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 requir...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 27 18:11:58 2021 @author: TSAI, TUNG-CHEN @update: 2021/10/05 """ import numpy as np from .nn import get_network from .utils import get_inputs, print_prediction # ============================================================================= # # =...
"""Mock callback module to support device and state testing.""" import logging _LOGGER = logging.getLogger(__name__) # pylint: disable=unused-argument # pylint: disable=too-many-instance-attributes class MockCallbacks(): """Mock callback class to support device and state testing.""" def __init__(self): ...
# This file will grab the hashes from the file generation and compare them to # hashes gotten from user-given files. Can return positive (files that do match) # or negative (files that don't match) hash results import argparse import os import sys from file_object import FileObject def log_and_print(log_file...
''' Get the hottest news title on baidu page, then save these data into mysql ''' import datetime import pymysql from pyquery import PyQuery as pq import requests from requests.exceptions import ConnectionError URL = 'https://www.baidu.com/s?wd=%E7%83%AD%E7%82%B9' headers = { 'User-Agent':'Mozilla/5.0 (Windows NT...
'''1. 游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏。 (初学者不一定可以完整实现,但请务必先自己动手,你会从中学习到很多知识的^_^) 假设游戏场景为范围(x, y)为0<=x<=10,0<=y<=10 游戏生成1只乌龟和10条鱼 它们的移动方向均随机 乌龟的最大移动能力是2(Ta可以随机选择1还是2移动),鱼儿的最大移动能力是1 当移动到场景边缘,自动向反方向移动 乌龟初始化体力为100(上限) 乌龟每移动一次,体力消耗1 当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20 鱼暂不计算体力 当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束 ''' import random...
salario = float(input('Qual é o salário do Funcionário? R$')) aumentoSalario = salario + (salario * (5 / 100)) print(f'Um funcionário que ganhava R${salario:.2f}, com 15% de aumento, passa a receber R${aumentoSalario:.2f}')
import bs4 # type: ignore[import] from .activity import _parse_subtitles, _parse_caption, _is_location_api_link # bring into scope from .comment import test_parse_html_comment_file # noqa: F401 from .html_time_utils import test_parse_dt # noqa: F401 def bs4_div(html: str) -> bs4.element.Tag: tag = bs4.Beauti...
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import unittest import pytest from builtins import open from future import standard_library #standard_library.install_aliases() from builtins import * from freezegun imp...
from PIL import ImageGrab from PIL import BmpImagePlugin from aip import AipOcr from win10toast import ToastNotifier import sys, os import keyboard import time, datetime import random from os import path from multiprocessing.dummy import Pool as ThreadPool PIC_DIR = r"C:\Users\hytian3019\Pictures\ocr" #百度云账号设置 APP_...
""" targetstateinfidelity.py - This module defines a cost function that penalizes the infidelity of an evolved state and a target state. """ import autograd.numpy as anp import numpy as np from qoc.models import Cost from qoc.standard.functions import conjugate_transpose class TargetStateInfidelity(Cost): """ ...
#Micro codes for checking the Pandas # Read CSV in chunks data_read = pd.read_csv('Filename.csv',chunksize=x,encoding = "any encoding format for eg :ISO-8859-1") data = pd.concat(data_read,ignore_index=True) # Split the dataframe based on the numeric and categorical values # Numeric Split clean...
import numpy as np import tensorflow as tf class Weights: def __init__(self, initializer, depth): self.initializer = initializer self.depth = depth def __call__(self, num_inputs, num_outputs): x = tf.Variable(self.initializer(shape=(num_inputs, self.depth))) y = tf.Variable(...
#!/usr/bin/env python3 # ============================================================================================= # # Distributed dynamic map fusion via federated learning for intelligent networked vehicles, # # 2021 International Conference on Robotics and Automation (ICRA) # # ...
import argparse import csv import torch import torch.nn as nn import torch.nn.functional as F #from models.gatedconv import InpaintGCNet, InpaintDirciminator from models.sa_gan import InpaintSANet, InpaintSADirciminator from models.loss import SNDisLoss, SNGenLoss, ReconLoss from data.inpaint_dataset import InpaintData...
from flask import Flask,jsonify,request from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column,Integer,Float,String import os from flask_marshmallow import Marshmallow from flask_jwt_extended import JWTManager,jwt_required,create_access_token from flask_mail import Mail,Message app=Flask(__name__) based...
# -*- coding: utf-8 -*- import numpy as np from math import factorial, exp, trunc from linear_congruential_generator import LinearCongruentialGenerator lcg = LinearCongruentialGenerator() def poisson(lambda_value, random_number): return round(((lambda_value ** random_number) * (np.e ** (-lambda_value))) / factor...
import rclpy from rclpy.node import Node import numpy as np from .handeye_4dof import Calibrator4DOF, robot_pose_selector from .handeye_4dof import transformations as tf from geometry_msgs.msg import PoseArray from geometry_msgs.msg import Pose from std_srvs.srv import Empty from ament_index_python.packages import g...
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in ...
from __future__ import unicode_literals import os import json from functools import wraps from datetime import datetime, date from contextlib import contextmanager from threading import RLock, Condition, current_thread from collections import Sized, Iterable, Mapping, defaultdict def is_listy(x): """ returns ...
""" Copyright (c) 2020 COTOBA DESIGN, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
from dataclasses import dataclass, field import backtrader as bt from models.Analyzers.CustomReturns import CustomReturns_analyzer from models.Analyzers.ReturnsVolatility import ReturnsVolatility_analyzer from models.Analyzers.TradesInfo import TradesInfo_analyzer from models.Analyzers.CalmarRatio import CalmarRatio_a...
def unorder_search(item, items: list): if not isinstance(items, list): print(f'The items {items} MUST be of type list') return for i in range(0, len(items)): if item == items[i]: return i return None data = [87, 47, 23, 53, 20, 56, 6, 19, 8, 41] print(unorder_search...
# -*- coding: utf-8 -*- import re from xkeysnail.transform import * define_keymap(lambda wm_class: wm_class != 'Gnome-terminal', { K('LSuper-V'): K('C-V'), K('LSuper-X'): K('C-X'), K('LSuper-C'): K('C-C'), K('LSuper-A'): K('C-A') }, 'non-terminal') define_keymap(re.compile('Gnome-terminal'), { K(...
# -*- coding: utf-8 -*- """ Created on Thu Apr 2 14:24:56 2020 @author: rucha """ import pandas as pd import numpy as np from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import confusion_matrix, accuracy_score, classification_rep...
from django.contrib import admin from django import forms from django.db import models from django.utils.translation import ugettext as _ from medicament.models import * class GroupAdmin(admin.ModelAdmin): fieldsets = [(None, {'fields': ['name', 'adverse_reaction']})] list_display = ('name', 'adverse_reactio...
from setuptools import setup from distutils.util import convert_path from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() main_ns = {} ver_path = convert_path('betacal/version.py') with open(...
# Accept three subject marks and display % marks. m1 = float(input("Enter marks 1.: ")) m2 = float(input("Enter marks 2: ")) m3 = float(input("Enter marks 3: ")) percent = (m1+m2+m3)/3 print("% marks", percent)
class ReturnValue(object): """\brief Container for a return value for a daemon task or command. If the the code is set to 0 the operation succeeded and the return value is available. Any other code indicates an error. [NOTE: we need to define other values, ala HTTP] """...
# This example shows how to train a built in DQN model to play CartPole-v0. # Example usage: # python -m example.cartpole.train_dqn # --- built in --- import time import json # --- 3rd party --- import gym import tensorflow as tf # run on cpu tf.config.set_visible_devices([], 'GPU') # --- my module --- import unst...
# # General Electricity sector Decarbonization Model (GEDM) # Copyright (C) 2020 Cheng-Ta Chu. # Licensed under the MIT License (see LICENSE file). # # Module note: # Functions to initialize instance settings # #---------------------------------------------------- # sets #---------------------------------------------...
from email import header from multimethod import distance import scipy from scipy.signal import find_peaks as scipy_find from core.preprocessing import read_data from scipy.signal._peak_finding_utils import _local_maxima_1d from scipy.signal._peak_finding import _arg_x_as_expected from utils.visualize import see_spec...
# <auto-generated> # This code was generated by the UnitCodeGenerator tool # # Changes to this file will be lost if the code is regenerated # </auto-generated> import unittest import units.pressure.pascals class TestPascalsMethods(unittest.TestCase): def test_convert_known_pascals_to_atmospheres(self): self.asser...
from binaryninja import * from pathlib import Path import hashlib import os import subprocess class Decompiler(BackgroundTaskThread): def __init__(self,file_name,current_path): self.progress_banner = f"[Ghinja] Running the decompiler job ... Ghinja decompiler output not available until finished." B...
# coding: utf8 from __future__ import unicode_literals from ..norm_exceptions import BASE_NORMS from ...attrs import NORM from ...attrs import LIKE_NUM from ...util import add_lookups _stem_suffixes = [ ["ो","े","ू","ु","ी","ि","ा"], ["कर","ाओ","िए","ाई","ाए","ने","नी","ना","ते","ीं","ती","ता","ाँ",...
from rpasdt.common.enums import StringChoiceEnum class NodeAttributeEnum(StringChoiceEnum): """Available node attributes.""" COLOR = "COLOR" SIZE = "SIZE" EXTRA_LABEL = "EXTRA_LABEL" LABEL = "LABEL" SOURCE = "SOURCE" class DistanceMeasureOptionEnum(StringChoiceEnum): pass NETWORK_OPTI...
"""ProtocolEngine tests module."""
# -*- coding: utf-8 -*- import logging import requests from bs4 import BeautifulSoup logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('wb') class Client: def __init__(self): self.session = requests.Session() self.session.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Wi...
import json import os from pathlib import Path from time import sleep from tqdm import tqdm from ..graph.models import Concept, Work from ..utils import get_logger from . import get_concepts_es_client from .format import ( format_concept_for_elasticsearch, format_story_for_elasticsearch, format_work_for_e...
# ex_sin.py # author: C.F.Kwok # date: 2018-1-5 from simp_py import tft from math import sin, radians import time class SIN: global tft def __init__(self): self.init_plot() tft.tft.clear() def run(self): global sin, radians ang=0 for x in range(320): ...
from django import forms class ModelMultiValueWidget(forms.MultiWidget): def __init__(self, *args, **kwargs): self.model = kwargs.pop('model') self.labels = kwargs.pop('labels', [None]) self.field_names = kwargs.pop('field_names', [None]) super(ModelMultiValueWidget, self).__init__...
import atexit import subprocess from multimedia.constants import AUDIO_OUTPUT_ANALOG, KEY_DOWN_ARROW, KEY_LEFT_ARROW, KEY_RIGHT_ARROW, KEY_UP_ARROW from multimedia.functions import exit_process_send_keystroke, popen_and_wait_for_exit, send_keytroke_to_process from multimedia.playerhandler import PlayerHandler class O...
# -*- coding: utf-8 - # # This file is part of tproxy released under the MIT license. # See the NOTICE for more information. version_info = (0, 5, 4) __version__ = ".".join(map(str, version_info))
''' Calculates the Frechet Inception Distance (FID) to evalulate GANs or other image generating functions. The FID metric calculates the distance between two distributions of images. Typically, we have summary statistics (mean & covariance matrix) of one of these distributions, while the 2nd distribution is given by a...
# Copyright (c) 2014 Scality # # 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 writing, s...
from .convunet import unet from .dilatedunet import dilated_unet from .dilateddensenet import dilated_densenet, dilated_densenet2, dilated_densenet3
import mlflow.pyfunc class Model(mlflow.pyfunc.PythonModel): """ Abstract class representing an MLFlow model. Methods: fit predict validate register download Attrs: """ def __init__(): self.base_model = init_BaseModel() def fit(...
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor class TeleBruxellesIE(InfoExtractor): _VALID_URL = ( r"https?://(?:www\.)?(?:telebruxelles|bx1)\.be/(?:[^/]+/)*(?P<id>[^/#?]+)" ) _TESTS = [ { "url": "http://bx1.be/news/que-ri...
from setuptools import setup, find_packages import sys import os.path import numpy as np # Must be one line or PyPI will cut it off DESC = ("A colormap tool") LONG_DESC = open("README.rst").read() setup( name="viscm", version="0.9", description=DESC, long_description=LONG_DESC, author="Nathaniel...
# -*- coding: utf-8 -*- import llbc class pyllbcProperty(object): """ pyllbc property class encapsulation. property can read & write .cfg format file. file format: path.to.name = value # The comments path.to.anotherName = \#\#\# anotherValue \#\#\# # The comments too Property clas...
# -*- coding: utf-8 -*- """ @author: Fredrik Wahlberg <fredrik.wahlberg@it.uu.se> """ import numpy as np import random from sklearn.base import BaseEstimator, ClassifierMixin from scipy.optimize import fmin_l_bfgs_b from sklearn.gaussian_process.gpc import _BinaryGaussianProcessClassifierLaplace as BinaryGPC from skle...
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from typing import Optional, List from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject from UM.Logger import Logger from UM.Preferences import Preferences from UM.Resources import Resources from UM.i18n i...
import numpy as np from utils import resize, opt from skimage import morphology def find_focal_points(image, scope='local', maxima_areas='large', local_maxima_threshold=None, num_points=None): """ Finds the 'focal_points' of a model, given a low resolution CAM. Has two modes: a 'local' scope and a 'global' on...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may...
from core import views from django.urls import path urlpatterns = [ path('user/', views.UserListView.as_view()), path('user/<username>/', views.UserDetailView.as_view()), path('wallet/', views.WalletListView.as_view()), path('subacc/', views.SubAccountListView.as_view()), path('subacc/<sub_address...
from math import gcd from functools import reduce def fun(a): return reduce(gcd,a) for i in range(int(input())): n = int(input()) a = list(set([int(j) for j in input().split()])) if(len(a)==1): print(a[0]+a[0]) else: b = max(a) a.remove(b) m = b+fun(a) c = m...
OTHER_METAl_TYPE = { 'chromium':True, 'kanthal':False, 'solder':False, 'aluminium_steel':True, 'weak_aluminium_steel':False, 'bismuth_steel':True, 'weak_bismuth_steel':False, 'damascus_steel':True, 'weak_damascus_steel':False, 'stainless_steel':False, 'weak_stainless_steel':False, 'rose_alloy':F...
# coding:utf-8 from .util import * from .abstract_predictor import AbstractPredictor from .average_predictor import AveragePredictor from .average_predictor_without_outliers import AveragePredictorWithoutOutliers from .average_predictor_without_outliers2 import AveragePredictorWithoutOutliers2 from .average_predictor_...
import os import uuid class CommitTreeToScriptConverter: def __init__(self, skip_single_child_nodes, post_conversion_commands, script_file): self.skip_single_child_nodes = skip_single_child_nodes self.post_conversion_commands = post_conversion_commands self.print_debug = False self...
class Queue(object): def __init__(self): self.q = [] def push(self, value): self.q.insert(0, value) def pop(self): return self.q.pop() def is_empty(self): return self.q == [] def size(self): return len(self.q) # Example q = Queue() q.push(1...
import os from datetime import datetime, timedelta import pytz import requests from google.transit import gtfs_realtime_pb2 GTFS_API_KEY = os.environ.get('TRANSPORT_NSW_API_KEY') GTFS_REALTIME_URL = 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/buses/' GTFS_VEHICLE_URL = 'https://api.transport.nsw.gov.au/v1/gtf...
# Generated by Django 3.0.6 on 2020-05-25 01:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sme_management', '0008_auto_20200525_0113'), ] operations = [ migrations.AlterField( model_name='smeproject', name='...
"""Build an online book using Jupyter Notebooks and Jekyll.""" from pathlib import Path import os # Load the version from the template Jupyter Book repository config path_file = Path(__file__) path_yml = path_file.parent.joinpath('book_template', '_config.yml') # Read in the version *without* pyyaml because we can't ...
# importing forms from django import forms from messenger.models import Message from newsletter.models import * class MessageForm(forms.ModelForm): OPTIONS = (('Y', 'Yes'), ('N', 'No'),) is_encrypted = forms.ChoiceField(required=True, choices=OPTIONS, help_text="Encrypt this message?") mess...
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2017-08-16 09:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('program_manage', '0001_initial'), ] operations = [ migrations.AlterField( ...
class Shark: animal_type = "fish" location = "ocean" followers = 5 def __init__(self, name, age): self.name = name self.age = age s1 = Shark("Frederick", 12) s2 = Shark("Nicholas", "10") print("\n>>> Shark 1 <<<") print("Name:", s1.name) print("Age:", s1.age) print("Type:", s1.ani...
import requests import os from core.client import TweepyClient, OpenaiClient BEARER_TOKEN = "" API_SECRET_KEY = "" CLIENT_SECRET = "" API_KEY = "" CLIENT_KEY = "" OPENAI_KEY = "" def bearer_oauth(r): # To set your environment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bea...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Category, Choice, BallotPaper class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class CategoryAdmin(admin.ModelAdmin): readonly_fields = ('ballot_paper', 'category_name', 'created...
import torch import torch.nn as nn import torch.nn.functional as F class CTLSTMCell(nn.Module): def __init__(self, hidden_dim, beta=1.0, device=None): super(CTLSTMCell, self).__init__() device = device or 'cpu' self.device = torch.device(device) self.hidden_dim = hidden_dim ...
"""tools.""" from collections import OrderedDict import yaml def ordered_yaml_load(filepath, loader=yaml.Loader, object_pairs_hook=OrderedDict): """ordered_yaml_load.""" class OrderedLoader(loader): """OrderedLoader.""" def construct_mapping(loader, node): """cons...
from .hankify_pw import hanky_pass # noqa
from django import template from ..forms.widgets import LikertSelect, RatingSelect register = template.Library() @register.filter def is_likert(field): return isinstance(field.field.widget, LikertSelect) @register.filter def is_rating(field): return isinstance(field.field.widget, RatingSelect)
picture = [ [0,0,0,1,0,0,0], [0,0,1,1,1,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,0,0,1,0,0,0], [0,0,0,1,0,0,0] ] for row in range(len(picture)): for col in range(len(picture[row])): if picture[row][col] == 1: print('*', end = '') else: print(' ', end = ''...
import socket from threading import Thread, Lock import sys def receiver(sock): while flag: data = sock.recv(1024) if data == 'quit': sys.exit(0) print "\t\t"+data host = '192.168.122.1' port = 50020 size = 1024 flag = True sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) hop ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pass1objects.py # # Part of MARK II project. For informations about license, please # see file /LICENSE . # # author: Vladislav Mlejnecký # email: v.mlejnecky@seznam.cz from common import * class item(): def __init__(self, parrent, address): self.address...
from __future__ import unicode_literals SEQUENCE = [ 'bugzilla_url_charfield', 'repository_raw_file_url', 'repository_visible', 'repository_path_length_255', 'localsite', 'repository_access_control', 'group_site', 'repository_hosting_accounts', 'repository_extra_data_null', 'un...
_version='2022.0.1.dev8'