content
stringlengths
0
894k
type
stringclasses
2 values
# # wcsmod -- module wrapper for WCS calculations. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ We are fortunate to have several possible choices for a python WCS package compatible with Ginga: astlib, kapteyn, starlink and astropy. kapteyn and astr...
python
#!/usr/bin/env python3 # # Configure logging # import logging import argparse parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true", help="Show debugging output.") args = parser.parse_args() log_level = logging.DEBUG if args.debug else logging.INFO logging.basicConfig(level=log_level, ...
python
from multiprocessing import Manager, Process def to_add(d, k, v): d[k] = v if __name__ == "__main__": process_dict = Manager().dict() p1 = Process(target=to_add, args=(process_dict, 'name', 'li')) p2 = Process(target=to_add, args=(process_dict, 'age', 13)) p1.start() p2.start() p1.join(...
python
''' Create words from an existing wordlist ''' import random import re class WordBuilder(object): ''' uses an existing corpus to create new phonemically consistent words ''' def __init__(self, initial='>', terminal='<', chunk_size=2): #indicators for start and ends of words - set if necessary to avoid...
python
# -*- coding: utf-8 -*- """ Created on Sun May 01 20:28:46 2016 @author: Anna Directory structure: assumes galaxy directory is the working directory, input_data/ should contain pars, phot and fake files This code generates a CMD plot in the same directory where the program, CMDscript.py, is Use optional -phot, -f...
python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013,2014 Contributor # # 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...
python
"""Request handler base classes """ from decorator import decorator from pyramid.httpexceptions import HTTPForbidden from dd_app.django_codec import DjangoSessionCodec from dd_app.messaging.mixins import MsgMixin class DDHandler(object): """Base view handler object """ def __init__(self, request, *args,...
python
"""Module with view functions that serve each uri.""" from datetime import datetime from learning_journal.models.mymodel import Journal from learning_journal.security import is_authenticated from pyramid.httpexceptions import HTTPFound, HTTPNotFound from pyramid.security import NO_PERMISSION_REQUIRED, forget, remem...
python
import os import torch import pickle import numpy as np from transformers import RobertaConfig, RobertaModel, RobertaTokenizer tokenizer = RobertaTokenizer.from_pretrained('roberta-base') roberta = RobertaModel.from_pretrained('roberta-base') path = '../wikidata5m_alias' if not os.path.exists('../wikidata5m_alias_emb...
python
from array import array import numpy as np import os import cv2 import argparse from tensorflow import lite as tflite from matplotlib import pyplot as plt import time import torch from torchvision import transforms from omegaconf import OmegaConf import torch.nn.functional as F import tensorflow as tf from torch.opti...
python
import os # Bot Setup os.environ["prefix"] = "g!" os.environ["token"] = "NzM5Mjc0NjkxMDg4MjIwMzEw.XyYFNQ.Mb6wJSHhpj9LP5bqO2Hb0w8NBQM" os.environ["botlog"] = "603894328212848651" os.environ["debugEnabled"] = "False" # Database Setup os.environ["db_type"] = "MySQL" # Either MySQL or Flat (or just leave empty for Flat ...
python
### # Adapted from Avalanche LvisDataset # https://github.com/ContinualAI/avalanche/tree/detection/avalanche/benchmarks/datasets/lvis # # Released under the MIT license, see: # https://github.com/ContinualAI/avalanche/blob/master/LICENSE ### from pathlib import Path from typing import List, Sequence, Union from PIL i...
python
import os import cv2 import numpy as np from constants import DATA_DIR MYPY = False if MYPY: from typing import Tuple, Union Pair = Tuple[int, int] def scale(image, scale_percent): height, width = image.shape[:2] return cv2.resize(image, (int(width * scale_percent), int(height * scale_percent))) ...
python
from django.contrib import admin # Register your models here. from .models import SiteConfiguration, SingleOrder, Order, UniqueFeature, Size, Color admin.site.register(Size) admin.site.register(Color) admin.site.register(SiteConfiguration) admin.site.register(UniqueFeature)
python
import pygame from pygame import draw from .player import Player, Enemy from .utils import Director, TileSet class lvl1(Director): def __init__(self) -> None: super().__init__(self) self.tile = TileSet("assets/tileset.png", 10, 28) self.tile.gen_map(self.alto, self.ancho, 52) self...
python
from django.urls import path, include from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('titles', TitleViewSet, basename='titles') router.register('categories', CategoryViewSet, basename='categories') router.register('genres', GenreViewSet, basena...
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-09 10:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_prices.models class Migration(migrations.Migration): dependencies = [ ('order', '0016_order_language_co...
python
# -*- coding: utf-8 -*- ## # @file goldman_equation.py # @brief Contain a function that calculates the equilibrium potential using the Goldman equation # @author Gabriel H Riqueti # @email gabrielhriqueti@gmail.com # @date 22/04/2021 # from biomedical_signal_processing import FARADAYS_CONSTANT as F from biom...
python
# Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
python
''' Given a binary string str of length N, the task is to find the maximum count of substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1. Example: Input: str = β€œ0100110101” Outp...
python
from Cocoa import * gNumDaysInMonth = ( 0, 31, 28, 31, 30, 21, 30, 31, 31, 30, 31, 30, 31 ) def isLeap(year): return (((year % 4) == 0 and ((year % 100) != 0)) or (year % 400) == 0) class CalendarMatrix (NSMatrix): lastMonthButton = objc.IBOutlet() monthName = objc.IBOutlet() nextMonthButton = objc.I...
python
import warnings from collections import OrderedDict from ConfigSpace import ConfigurationSpace from ConfigSpace.hyperparameters import CategoricalHyperparameter from mindware.components.feature_engineering.transformations import _bal_balancer, _preprocessor, _rescaler, \ _image_preprocessor, _text_preprocessor, _b...
python
# Copyright 2020 by Christophe Lambin # All rights reserved. import logging from prometheus_client import start_http_server from libpimon.version import version from libpimon.configuration import print_configuration from libpimon.cpu import CPUTempProbe, CPUFreqProbe from libpimon.gpio import GPIOProbe from libpimon.o...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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-...
python
# reference: https://github.com/open-mmlab/mmclassification/tree/master/mmcls/models/backbones # modified from mmclassification timm_backbone.py try: import timm except ImportError: timm = None from mmcv.cnn.bricks.registry import NORM_LAYERS from openmixup.utils import get_root_logger from ..builder import B...
python
import torch import os import pickle if torch.cuda.is_available(): device = torch.device('cuda') else: device = torch.device('cpu') class TrainUtil(): def __init__(self, checkpoint_path='checkpoints', version='mcts_nas_net_v1'): self.checkpoint_path = checkpoint_path self.version = versio...
python
from pymtl import * from lizard.util.rtl.interface import UseInterface from lizard.util.rtl.method import MethodSpec from lizard.core.rtl.messages import ExecuteMsg, WritebackMsg, PipelineMsgStatus from lizard.util.rtl.pipeline_stage import gen_stage, StageInterface, DropControllerInterface from lizard.core.rtl.kill_un...
python
# Copyright 2021 NVIDIA Corporation # # 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 wr...
python
import numpy as np import hmm x = np.random.randint(0, 500, 1000) m = 3 l = np.array([10, 250, 450]) g = np.array([[.8, .1, .1], [.1, .8, .1], [.1, .1, .8]]) d = np.array([.3, .3, .3]) (success, lambda_, gamma_, delta_, aic, bic, nll, niter) = hmm.hmm_poisson_fit_em(x, m, l, g, d, 1000, 1e-6) print(success, aic, bic...
python
import torch from torch import nn from buglab.models.layers.multihead_attention import MultiheadAttention class RelationalMultiheadAttention(MultiheadAttention): """ A relational multihead implementation supporting two variations of using additional relationship information between tokens: * If no e...
python
from django.shortcuts import render from datetime import datetime from notifications.models import Notification from users.models import Profile from django.core.urlresolvers import reverse from django.shortcuts import render from django.contrib.auth.decorators import login_required, permission_required from django.con...
python
from aoc import AOC aoc = AOC(year=2015, day=18) data = aoc.load() ## Part 1 # Initialize the array of lights to all off lights = [x[:] for x in [[0] * len(data.lines())] * len(data.lines())] # For every line in the input in_y = 0 for line in data.lines(): line = line.strip() in_x = 0 for c in line: ...
python
from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.tree import DecisionTree from pyspark.mllib.linalg import SparseVector from pyspark import SparkContext from operator import add import time import numpy from pyspark.mllib.linalg import Vectors import pyspark.mllib.clustering as cl import os...
python
#!/usr/bin/env python3 from aws_cdk import core from lab08.lab08_stack import Lab08Stack app = core.App() Lab08Stack(app, "lab08",env={"region":"us-east-1","account":"111111111111"}) app.synth()
python
import h5py import numpy as np import glob from mne import create_info from mne.io import RawArray def extract_blackrock_info(mat_file, blackrock_type): """ Extracts basic recording info from a blacrock extracted mat file. Extracts the data, sampling rate, channel names, and digital to analog conversion ...
python
import tensorflow as tf from tf_stft import Spectrogram, Logmel from tensorflow_utils import do_mixup class ConvBlock(tf.keras.Model): """ Convolutional Block Class. """ def __init__(self, out_channels): """ Parameters ---------- out_channels : int Number of ...
python
# -*- coding: utf-8 -*- def count_days(y, m, d): return (365 * y + (y // 4) - (y // 100) + (y // 400) + ((306 * (m + 1)) // 10) + d - 429) def main(): y = int(input()) m = int(input()) d = int(input()) if m == 1 or m == 2: m += 12 y -= 1 print(count_days(201...
python
import pytest from azure.ml import MLClient @pytest.fixture def environment_id() -> str: return "/subscriptions/5f08d643-1910-4a38-a7c7-84a39d4f42e0/resourceGroups/sdk_vnext_cli/providers/Microsoft.MachineLearningServices/Environments/AzureML-Minimal" @pytest.fixture def compute_id() -> str: return "testCom...
python
#!/usr/bin/env python3 # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
python
from rdflib.graph import ConjunctiveGraph from typing import ClassVar from rdflib import Namespace from test.testutils import MockHTTPResponse, ServedSimpleHTTPMock import unittest EG = Namespace("http://example.org/") class TestSPARQLConnector(unittest.TestCase): query_path: ClassVar[str] query_endpoint: Cl...
python
# Copyright 2021 TUNiB Inc. import torch import torch.distributed as dist from transformers import GPT2Tokenizer from oslo.models.gpt_neo.modeling_gpt_neo import ( GPTNeoForCausalLM, GPTNeoForSequenceClassification, GPTNeoModel, ) class TestPPInference: def __init__(self, num_gpus): self.num...
python
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" import ldap3 from epflldap.utils import get_optional_env, EpflLdapException def _get_LDAP_connection(): """ Return a LDAP connection """ server = ldap3.Server('ldap://' + get_optional_env('EPFL_LDAP_SERVE...
python
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Kyoto University (Hirofumi Inaguma) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Conduct forced alignment with the pre-trained CTC model.""" import codecs import logging import os import shutil import sys from tqdm import tqdm from n...
python
def my_reduce(value): number = 0 for v in value: number+=v return number
python
from playground.network.packet import PacketType, FIELD_NOT_SET from playground.network.packet.fieldtypes import UINT8, UINT16, UINT32, UINT64, \ STRING, BUFFER, \ ComplexFieldType, PacketFields from playground.network...
python
"""Base class for patching time and I/O modules.""" import sys import inspect class BasePatcher(object): """Base class for patching time and I/O modules.""" # These modules will not be patched by default, unless explicitly specified # in `modules_to_patch`. # This is done to prevent time-travel from...
python
#!/usr/bin/env python """ Pox-based OpenFlow manager """ import pox.openflow.libopenflow_01 as of from pox.core import core from pox.lib.recoco import * from pox.lib.revent import * from pox.lib.addresses import IPAddr, EthAddr from pox.lib.util import dpid_to_str from pox.lib.util import str_to_dpid from debussy.uti...
python
import cv2 as cv # noqa import numpy as np # noqa
python
r""" Module of trace monoids (free partially commutative monoids). EXAMPLES: We first create a trace monoid:: sage: from sage.monoids.trace_monoid import TraceMonoid sage: M.<a,b,c> = TraceMonoid(I=(('a','c'), ('c','a'))); M Trace monoid on 3 generators ([a], [b], [c]) with independence relation {{a, c}}...
python
from .handler import get_db_handle __all__ = ["get_db_handle"]
python
#!/usr/bin/env python3 import os # Third Party from flask import Blueprint from flask import request, jsonify from flask import render_template # main from . import routes main = Blueprint('main', __name__) # Routes main.add_url_rule("/", 'root', view_func=routes.root) main.add_url_rule("/api/", 'api', view_func=r...
python
"""scrapli.driver.core.cisco_iosxr""" from scrapli.driver.core.cisco_iosxr.driver import IOSXRDriver __all__ = ("IOSXRDriver",)
python
import pandas as pd import os import json from settings import * from src.utils.sampu import interp_multi, sel_pos_frame, normalize import seaborn as sns sns.set(style="darkgrid") """Given some keyframe numbers (normalized kf), encodes them and interpolates their latent datapoints. Saves the z interpolants and t...
python
#!/usr/bin/env python3 # # Copyright (c) 2019 Roberto Riggio # # 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 applicabl...
python
import pytest from aiosnow.exceptions import SchemaError from aiosnow.models import ModelSchema, Pluck, fields from aiosnow.query.fields import IntegerQueryable, StringQueryable def test_model_schema_field_registration(): class TestSchema(ModelSchema): test1 = fields.String() test2 = fields.Integ...
python
#!/usr/bin/env python2 # XXX: Refactor to a comand line tool and remove pylint disable """Merge columns of multiple experiments by gene id.""" from __future__ import absolute_import import argparse import csv import os import sys from itertools import chain import utils parser = argparse.ArgumentParser( descript...
python
from torchvision import models from PIL import Image import matplotlib.pyplot as plt import torch import numpy as np import cv2 import torchvision.transforms as T def decode_segmap(image, source, nc=21): label_colors = np.array([(0, 0, 0), # 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle ...
python
# -*- coding: utf-8 -*- from django.db.models.query import QuerySet class PublisherQuerySet(QuerySet): """Added publisher specific filters to queryset. """ def drafts(self): return self.filter(publisher_is_draft=True) def public(self): return self.filter(publisher_is_draft=False)
python
# # Copyright (c) 2019 Jonathan Weyn <jweyn@uw.edu> # # See the file LICENSE for your rights. # """ Upload settings to a theta-e website loaded dynamically from the theta-e.conf. """ import os import string template_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'template.txt') def main(config, s...
python
# Generated by Django 3.2.5 on 2021-09-01 16:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0008_alter_workspacerole_role'), ] operations = [ migrations.AlterModelOptions( name='upload', options={}, ),...
python
# Copyright 2015-2017 ARM 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 agreed to in w...
python
import os f = open("test.txt" "w") list1 = ["Shoes", "Socks", "Gloves"] quantity = [10, 5, 32] f.write("{:<10} {:10} {:10}\n".format("S/N", "Items", "Quantity")) for item in list1: f.write("{:<10} {:10} {:10}\n".format("S/N", "Items", "Quantity") + "\n") f.close()
python
import os import subprocess import sys try: import pty except ImportError: PTY = False else: PTY = True from mklibpy.common.string import AnyString from mklibpy.terminal.colored_text import get_text, remove_switch from mklibpy.util.path import CD __author__ = 'Michael' TIMEOUT = 0.5 print("""`mklsgit` ...
python
#coding: utf-8 ''' # * By : # * # * β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— # * β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β•šβ•β•β–ˆβ–ˆβ•”β•β•β• β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— # * β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•”β–ˆ...
python
from mySecrets import connectStr import json import pyodbc DATABASE_USERACCOUNTS = "[dbo].[UserAccounts]" DATABASE_PROBLEMS = "[dbo].[Problems]" DATABASE_SUBMISSIONS = "[dbo].[Submissions]" def executeCommandCommit(cmd: str) -> None: cnxn = pyodbc.connect(connectStr) cursor = cnxn.cursor() cursor.execute...
python
import csv import os import sqlite3 import pytest import shutil from tempfile import gettempdir from openpyxl import Workbook TMP_DIR = gettempdir() ws_summary_B5_rand = [ 'Cookfield, Rebuild', 'Smithson Glenn Park Editing', 'Brinkles Bypass Havensmere', 'Folicles On Fire Ltd Extradition', 'Pudd...
python
from . import * class TestDefaults(BrokerTestCase): def test_basic_submit(self): f = self.queue.submit_ex(name=self.id() + '.0', pattern=None) self.assertTrue(f.id) self.assertEqual(self.broker.fetch(f.id)['status'], 'pending') self.assertEqual(self.broker.fetch(f.id)['priority'],...
python
from django.db import models class Job(models.Model): """Class describing a computational job""" # currently, available types of job are: TYPES = ( ("fibonacci", "fibonacci"), ("power", "power") ) STATUSES = ( ("pending", "pending"), ("started", "started"), ("finished", "finished"), ...
python
from pathlib import Path from math import inf def get_image_layers(raw_data, width, height): digits = map(int, raw_data.strip()) layers = list() curr_layer = list() layer_size = width * height for digit in digits: curr_layer.append(digit) if len(curr_layer) == layer_size: ...
python
import matplotlib.pyplot as plt VIEW_BORDER = 0.1 plt.ion() class plotter(): def __init__(self, pos_bounds, plot_vor, plot_traj, plot_graph): self.p_bounds = pos_bounds self.plot_vor_bool = plot_vor self.plot_traj_bool = plot_traj self.plot_graph_bool = plot_graph if self.plot_vor_bool: ...
python
# -*- coding: utf-8 -*- import json with open('data.txt', 'w') as outfile: data = {"total": 10} json.dump(data, outfile) if __name__ == "__main__": print("ok")
python
from util import traceguard from gui.toolbox import GetTextFromUser from common import profile, pref import wx def change_password(protocol, cb): val = GetTextFromUser(_('Enter a new password for {username}:'.format(username=protocol.username)), _('Change Password'), ...
python
"""Module for dilation based pixel consensus votin For now hardcode 3x3 voting kernel and see """ from abc import ABCMeta, abstractmethod, abstractproperty import numpy as np from scipy.ndimage.measurements import center_of_mass from ..box_and_mask import get_xywh_bbox_from_binary_mask from .. import cfg class PCV_ba...
python
# coding: utf-8 """ Command Line Interface """ import sys import click from chipheures_sos import __version__ from chipheures_sos.app import App @click.group() @click.version_option(__version__) @click.option("--debug/--no-debug", default=False) @click.pass_context def cli(ctx, debug): """ Tool for database...
python
from unittest import TestCase from osbot_k8s.utils.Docker_Desktop_Cluster import DEFAULT_DOCKER_DESKTOP_NAME from osbot_utils.utils.Misc import list_set from osbot_utils.utils.Dev import pprint from osbot_k8s.kubectl.Kubectl import Kubectl class test_Kubectl(TestCase): def setUp(self) -> None: self.kube...
python
import queue from pynput.keyboard import Events, Key, Controller, Listener from random import choice from json import load thread_comms = queue.Queue() kb = Controller() class KeyboardEvents(Events): _Listener = Listener class Press(Events.Event): # key press event def __init__(self, ke...
python
import scipy import numpy as np import matplotlib.pyplot as plt from astropy.io import fits class DataLoader(): def __init__(self, dataset_name, img_res=(101, 101), norm=False): self.dataset_name = dataset_name self.img_res = img_res self.data = np.loadtxt("network/networkFrame.csv", delim...
python
from django.db.models.signals import post_save from django.dispatch import receiver from .models import Profile from .models import StudentUser from rest_framework.authtoken.models import Token @receiver(post_save, sender=StudentUser) def post_save_create_profile(sender,instance,created,**kwargs): if created: ...
python
import json class Operators(): @staticmethod def initFactory(): import planout.ops.core as core import planout.ops.random as random Operators.operators = { "literal": core.Literal, "get": core.Get, "seq": core.Seq, "set": core.Set, "index": core.Index, "array": core....
python
import nltk from models import * import torch from tokenization import * import time from torchtext.data.metrics import bleu_score from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import corpus_bleu from nltk.translate.meteor_score import meteor_score import sys device = torch.device(...
python
from django.conf import settings from ngw.core.models import Config, Contact def banner(request): """ This context processor just add a "banner" key that's allways available """ if hasattr(request, 'user') and request.user.is_authenticated: return {'banner': Config.objects.get(pk='banner').te...
python
import sys import os import logging import click import wfepy import wfepy.utils @click.command() @click.option('-d', '--debug', is_flag=True) @click.argument('example_name') def run_wf(debug, example_name): logging.basicConfig(level=logging.DEBUG if debug else logging.INFO) example_module = __import__(exa...
python
from abc import ABCMeta, abstractmethod, abstractproperty from pathlib import Path from PIL import Image, ImageFont, ImageDraw, ImageEnhance, ImageFilter import string import cv2 import numpy as np from numpy.random import uniform, choice from random import randint, choice as rand_choice import arabic_reshaper from b...
python
# Copyright 2019 Atalaya Tech, Inc. # 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, ...
python
# -*- coding: utf-8 -*- """ string normalizer exceptions module. """ from pyrin.core.exceptions import CoreException class StringNormalizerManagerException(CoreException): """ string normalizer manager exception. """ pass class InvalidStringNormalizerTypeError(StringNormalizerManagerException): ...
python
# https://www.blog.pythonlibrary.org/2010/03/08/a-simple-step-by-step-reportlab-tutorial/ # from reportlab.pdfgen import canvas # # c = canvas.Canvas("hello.pdf") # c.drawString(100,750,"Welcome to Reportlab!") # c.save() import time from reportlab.lib.enums import TA_JUSTIFY from reportlab.lib.pagesizes import lette...
python
import logging import time import config logging.basicConfig(level=logging.DEBUG, stream=open(config.LOGGING.format(int(time.time())), "w", encoding="utf-8"), format='[%(asctime)s-%(filename)s] [%(levelname)s] %(message)s', datefmt='%Y %H:%M:%S', ...
python
from hlt import * from networking import * def getValueMap(valueMap, gameMap): for y in range(gameMap.height): for x in range(gameMap.width): valueMap[y][x] = gameMap.getSite(Location(x,y)).production return valueMap myID, gameMap = getInit() valueMap = [ [0 for x in range(gameMap.width)]...
python
#!/usr/bin/env python3 import hmac import json import flask import flask_compress import flask_httpauth class Config: pass config = Config() with open("config.json") as f: config_data = json.load(f) if config_data["cloud_service"]["type"] != "azure storage datalake": raise NotImplementedError(...
python
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, 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
# Copyright 2009-2013 Nokia Siemens Networks Oyj # # 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 ag...
python
from connection import Connection import viewer.page def general_information(url: str) -> dict: con = Connection() soup = con.get(url).soup return { 'Imslp Link': url, 'Genre Categories': viewer.page.genre_categories(soup), 'Work Title': viewer.page.work_title(soup), 'Name ...
python
import fileinput import re lists = [['fileListGetter.py', 'fileListGetter', ['directory', '_nsns'], [], 'def fileListGetter(directory, _nsns): """ Function to get list of files and language types Inputs: directory: Stirng containing path to search for files in. Outputs: List of Lists. Lists are of form...
python
# Generated by Django 3.1.7 on 2021-07-07 17:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('messenger', '0023_auto_20210615_0956'), ] operations = [ migrations.AlterModelOptions( name='message', options={'ord...
python
import sys import numpy as np import cv2 as cv2 import time import yolov2tiny def open_video_with_opencv(in_video_path, out_video_path): # # This function takes input and output video path and open them. # # Your code from here. You may clear the comments. # #raise NotImplementedError('open_v...
python
""" Server receiver of the message """ import socket from ..constants import * class UDPMessageReceiver: def __init__(self, port=PORT): self.__port = port def receive_message(self): # Create the server socket # UDP socket s = socket.socket(family=socket.AF_INET, type=socket.S...
python
#!/usr/bin/env python # 参考 https://github.com/schedutron/CPAP/blob/master/Chap2/sleep_serv.py from socket import * HOST = '' PORT = 1145 BUFSIZ = 1024 ADDR = (HOST, PORT) with socket(AF_INET, SOCK_STREAM) as s: s.bind(ADDR) s.listen(5) clnt, addr = s.accept() print(f'连ζŽ₯到 {addr}。') with clnt: ...
python
from .CDx import * __version__ = '0.0.30'
python
$ make -C doc/sphinx html
python
# Create by Packetsss # Personal use is allowed # Commercial use is prohibited from player import Player from genotype import Genotype class Population: def __init__(self, size): self.players = [Player(box2d[i]) for i in range(size)] self.generation = 1 self.fitness_sum = 0 self.b...
python