content
stringlengths
5
1.05M
import fastapi from fastapi.responses import JSONResponse from fastapi import Depends from services.db_service import get_one_course, all_courses from models.course import Course router = fastapi.APIRouter() @router.get('/api/rec/{course_id}') def rec(crs: Course = Depends()): result = get_one_course(crs.course_...
import shutil from fastapi import APIRouter, File, UploadFile, Query from fastapi.responses import FileResponse # from starlette.responses import FileResponse from typing import List # this is referencing fastapi/app... from services.s3 import get_s3, get_s3_bucket_name router_custom_app_s3 = APIRouter( tags=["cust...
import os import math import pandas as pd import datetime variables = [ 'date_stamp', 'cnt_confirmed', 'cnt_recovered', 'cnt_active', 'cnt_hospitalized', 'cnt_hospitalized_current', 'cnt_death', 'cnt_probable' ] def deleteFiles(path): today = datetime.date.today(); one_week = datetime.timedelta(days=7) week...
text = input('Введите текст: ') try: file = open('res.txt', 'w') file.write(text) except: print('Возможна ошибка!') else: print('Успешно записано!') finally: file.close()
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ============= Cadc TAP plus ============= """ from astroquery.cadc.tests.DummyJob import DummyJob class DummyTapHandler(object): def __init__(self): self.__invokedMethod = None self.__parameters = {} def reset(self): ...
import re import sys input = sys.argv[1] output = sys.argv[2] print("input:",input) print("output:",output) count=0 with open(input,'r') as inputFile: with open(output,'a') as outputFile: for line in inputFile: if(line.split(",")[1]=="\"0\""): print(line) output...
"""A new print function that adds new and exciting functionality.""" from .print import print, render from .table import table from .putil import clear_fmt, join, span, pad, number from .div import hfill, center, div from .constants import * from .exception import RenderedException __all__ = [ # Functions "p...
from collections import Counter def longest_palindrome(s): s=s.lower() check=Counter(s) even=0 odd=0 for i in check: if check[i]%2==0 and i.isalnum(): even+=check[i] elif check[i]%2==1 and i.isalnum(): odd=max(odd, check[i]) even+=check[i]-1...
from dbnd import PipelineTask, namespace, output, parameter from test_dbnd.factories import FooConfig, TTask namespace("n_tv") class FirstTask(TTask): foo = parameter(default="FooConfig")[FooConfig] param = parameter(default="from_first")[str] class SecondATask(FirstTask): param = "from_second" clas...
# Generated by Django 3.2.9 on 2021-11-23 12:50 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), ('core', '0007_alter_avali...
from allauth.socialaccount.tests import create_oauth2_tests from allauth.tests import MockedResponse from allauth.socialaccount.providers import registry from .provider import PaypalProvider class PaypalTests(create_oauth2_tests(registry.by_id(PaypalProvider.id))): def get_mocked_response(self): return Mo...
#!/usr/bin/env python #! -*- coding:utf-8 -*- """ TODO: Short description TODO: Details description """ #TODO: all import block import sys import requests __author__ = "Paweł Siergiejuk" __date__ = "16/04/2019" __version__ = "v0.0" __email__ = "pawelsiergiejuk@gmail.com" __status__ = "Development" class NetExcepti...
import logging log = logging.getLogger(__name__) class NFS(object): # TODO: Implement it pass
from __future__ import annotations from watchmen_model.system import DataSource, DataSourceType from .data_source_oracle import OracleDataSourceHelper, OracleDataSourceParams from .storage_oracle import StorageOracle, TopicDataStorageOracle # noinspection PyRedeclaration class Configuration: dataSource: DataSource ...
from dolfin import * import numpy as np import pickle ####################### Nx=20 Ny=40 Nz=41 Ly=1.0 Lx=2.0 M=10 #Lx=1*Ly Lz=0.1 Ho=1.2*(Lz/Nz) #Ho=0.5 #DH=Hx #DHZ=Hx Hb=2.0*Lx/Nx dx1=Lx/10 ####################### parameters["form_compiler"]["cpp_optimize"]=True parameters["form_compiler"]["representation"]='uf...
from pycket import interpreter as interp from pycket import values, values_string, vector, util, values_regex from pycket.prims.correlated import W_Correlated from pycket.error import SchemeException from pycket.hash import simple, equal, base from pycket.assign_convert import assign_convert from pycket.util import Per...
import unittest from activity.activity_VerifyLaxResponse import activity_VerifyLaxResponse import activity import settings_mock from ddt import ddt, data from mock import patch def fake_emit_monitor_event(settings, item_identifier, version, run, event_type, status, message): pass @ddt class TestVerifyLaxResponse...
# -*- coding: utf-8 -*- # # Copyright (C) 2018 CERN. # Copyright (C) 2018 RERO. # # Invenio-Circulation is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """."""
import getpass import json import logging import warnings from collections import Counter, defaultdict, namedtuple from json import JSONDecodeError from typing import Any, Dict, List, Tuple import apteco_api as aa import PySimpleGUI from apteco.data.apteco_logo import APTECO_LOGO from apteco.exceptions import ( A...
from tt_web import s11n from tt_web import handlers from tt_web import exceptions as tt_exceptions from tt_protocol.protocol import properties_pb2 from tt_protocol.protocol import data_protector_pb2 from . import protobuf from . import operations @handlers.protobuf_api(properties_pb2.SetPropertiesRequest) async de...
class Solution: def firstUniqChar(self, s): """ :type s: str :rtype: int """ letters = set(s) index=[s.index(l) for l in letters if s.count(l) == 1] return min(index) if len(index) > 0 else -1
"""The pynamd package provides classes and routines for interacting with NAMD output in Python. This is generally limited to _energy_ based analysis, as a number of excellent packages are available for performing trajectory analysis. """ __version__ = '1.0' __author__ = 'Brian K. Radak' from pynamd.log import NamdLog...
############################################################################### # # Test cases for xlsxwriter.lua. # # Copyright 2014-2015, John McNamara, jmcnamara@cpan.org # import base_test_class class TestCompareXLSXFiles(base_test_class.XLSXBaseTest): """ Test file created with xlsxwriter.lua against a f...
""" Flagship file for the StickyJump platformer game Proprietary content of StickyAR, 2019 Brought to you by Luke Igel, Fischer Moseley, Tim Gutterman, and Zach Rolfness """ import pygame as pg import time import random from settings import * from stickys import updateSticky, clearSticky, calibrate, uncalibrate from s...
from datetime import datetime from django.db import models from django.utils.translation import gettext_lazy as _ from ..get_settings import extract_model_kwargs as ek __all__ = [ "CreationDateMixin", "EditCreationDateMixin" ] class CreationDateMixin(models.Model): """Adds an `created_at` field, which stor...
#!/usr/bin/python3 """ Printing files module Functions: number_of_lines: get the number of lines and return it """ def number_of_lines(filename=""): """ Write the file in a list of lines and return the len filename: string containing the name or "" if not given. Return:...
#!/usr/bin/env python3 import os import json from imdbpie import Imdb import requests from pprint import pprint import re import logging from logging import info, debug, warning, error import subprocess logging.basicConfig(level=logging.DEBUG) movie_dir = "/home/arti/Videod/Filmid" YTKEY = os.environ.get("YTKEY") i...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jan 31 13:42:05 2017 This script is for post processing data produced by other parts of the codebase. It contains function definitions which may also be useful to other modules. eventually this should write the models to a csv for use by XID+ @author...
import os from flask import Flask, render_template, redirect, url_for, request, session, flash from flask_migrate import Migrate from werkzeug.security import generate_password_hash, check_password_hash def create_app(test_config=None): # Previous code omitted @app.route('/log_in', methods=('GET', 'POST')) ...
from persistence.repositories.exam_solution_repository_postgres import ExamSolutionRepositoryPostgres from exceptions.http_exception import NotFoundException from application.serializers.exam_solution_serializer import ExamSolutionSerializer import logging logger = logging.getLogger(__name__) esrp = ExamSolutionRepos...
def test_update_log_weights(part_updater): temperature_step = 0.1 exp_w = 0.2 - 0.2 * temperature_step part_updater.update_log_weights(temperature_step) assert all([exp_w == p.log_weight for p in part_updater.step.get_particles()]) def test_resample_if_needed_no(part_updater): part...
#! /usr/bin/env python # -*- coding: utf-8 -*- from collections import defaultdict import os from lab.environments import LocalEnvironment, BaselSlurmEnvironment from lab.experiment import Experiment from downward.reports import PlanningReport from downward.reports.absolute import AbsoluteReport from downward.report...
""" A class to keep information about faces of a polyhedron This module gives you a tool to work with the faces of a polyhedron and their relative position. First, you need to find the faces. To get the faces in a particular dimension, use the :meth:`~sage.geometry.polyhedron.base.face` method:: sage: P = polytop...
from RestrictedPython import compile_restricted_function from RestrictedPython import PrintCollector from RestrictedPython import safe_builtins from types import FunctionType def test_compile_restricted_function(): p = '' body = """ print("Hello World!") return printed """ name = "hello_world" global_...
from .pylunasvg import Bitmap, Box, Matrix, Document from .extensions import loadFromUrl import os import numpy as np from PIL import Image def svg2png( svg_file: str, width: int, height: int, scale: float = 1.0, output_file: str = None ): doc = Document.loadFromFile(svg_file).scale(scale, scale) if widt...
from contextlib import contextmanager from ..image import Image from . import Rect class SpriteNode(Rect): def __init__(self, im, width, height, fname=None, pad=(0, 0)): Rect.__init__(self, (0, 0, width, height)) self.im = im self.fname = fname (self.pad_x, self.pad_y) = pad ...
import unittest from rdp.symbols import to_symbol, Symbol, Terminal class SymbolsTest(unittest.TestCase): def test_to_symbol(self): self.assertTrue(isinstance(to_symbol(','), Symbol)) self.assertTrue(isinstance(to_symbol(Terminal(',')), Symbol)) self.assertRaises(TypeError, to_symbol, 42...
""" Functions to read and write ASCII model (.dat) files used by SPECFEM2D """ import os import numpy as np from glob import glob from shutil import copyfile from seisflows3.tools.tools import iterable def read_slice(path, parameters, iproc): """ Reads SPECFEM model slice(s) based on .dat ASCII files ...
import logging import functools from xml.parsers.expat import ExpatError import xmltodict from rtcclient.exception import RTCException, BadValue import six from lxml import etree def setup_basic_logging(): logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(name)s:...
from twisted.internet import defer, reactor class __Node(object): def execute(self): pass class BlackBoard(object): pass class ParallelNode(__Node): def __init__(self, blackboard=None): self.children = [] self.blackboard = blackboard def execute(self): if len(...
from collections import defaultdict from random import random, randint from glob import glob from math import log import argparse from nltk.corpus import stopwords from nltk.probability import FreqDist from nltk.tokenize import TreebankWordTokenizer kTOKENIZER = TreebankWordTokenizer() kDOC_NORMALIZER = True import ...
# coding: utf-8 # tests/conftest.py import pytest from app import guard from app import create_app from app.database import init_test_db, db_test_session from app.orm import start_mapper start_mapper() @pytest.fixture def app_instance(): app_test = create_app() yield app_test db_test_session.remov...
from django.conf import settings from celeryutils import task from tower import ugettext as _ import amo from addons.tasks import create_persona_preview_images from amo.decorators import write from amo.storage_utils import move_stored_file from amo.utils import LocalFileStorage, send_mail_jinja from editors.models im...
# Copyright 2019 Huawei Technologies Co., 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-2.0 # # Unless required by applicable law or agreed to...
# Copyright 2022, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
# -*- coding: utf8 -*- import pycurl import sys from unittest.case import SkipTest from tests import online class TestPyCurl: def test_pycurl_download_progress(self): if not online: raise SkipTest("Can't test download offline") def progress(download_t, download_d, upload_t, upload_d)...
import csv import json with open('./orion_generated_connectivity.csv') as f: reader = csv.DictReader(f) connections = list(reader) with open('./orion_full_node_list.csv') as f: reader = csv.DictReader(f) network_nodes = list(reader) nodesById = {} links = [] def processNode(name, nodeDesc, machineT...
from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField() document2 = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.description
"""Application config module.""" from django.apps import AppConfig from githubnavigator import container from . import views class WebConfig(AppConfig): name = 'web' def ready(self): container.wire(modules=[views])
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import GenericRepr, Snapshot snapshots = Snapshot() snapshots['test_interface_type_raises_error_when_extended_dependency_is_wrong_type 1'] = GenericRepr('<ExceptionInfo ValueError("ExtendExam...
from numpy import array, sum import cv2 """ File:Screen_Regions.py Description: Class to rectangle areas of the screen to capture along with filters to apply. Includes functions to match a image template to the region using opencv Author: sumzer0@yahoo.com """ class Screen_Regions: def __init__(self, ...
#!/bin/python3 import sys n = int(input().strip()) unsorted = [] unsorted_i = 0 for unsorted_i in range(n): unsorted_t = int(input().strip()) unsorted.append(unsorted_t) # your code goes here unsorted.sort() for idx, val in enumerate(unsorted): print(val)
""" Problem: https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach/problem """ from collections import deque # read amount of test cases testCases = int(input()) # solve each test case while testCases > 0: # read number of nodes and edges nodes, edges = map(int, input().split()) # intialize emp...
#! /usr/bin/env python ########################################################################## # NSAp - Copyright (C) CEA, 2013 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # ...
#!/usr/bin/env python3 """ Copyright 2021 Leon Läufer 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, pub...
from src import DistributionFamilyType from src.Distributions import Distributions import math class TriangularDistribution(Distributions): _c = 0 def probability_random_number(self, x): if isinstance(x, str): raise Exception("x must be non string type") if not self.__a <= x <= se...
# This code is used in the 'Run MATLAB from Python' example # Copyright 2019-2021 The MathWorks, Inc. import torch from torch.utils.data import Dataset, DataLoader import torch.nn as nn import torch.onnx import time import os cudaAvailable = torch.cuda.is_available() if cudaAvailable: cuda = torch.device('cuda'...
import pyautogui import screengrab as sg import time def find_direction(x, y, cx, cy, size): """ Gets the direction of the arrow from the centre (cx, cy) """ width, height = size max_match = (0, 0, width) x_dist = width // 40 x_s = width // 2 - x_dist x_b = width // 2 + x_dist y_dist = ...
# Generated by Django 3.0.1 on 2019-12-26 16:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lancamentos', '0013_auto_20190621_1316'), ] operations = [ migrations.AddField( model_name='journal', name='descrica...
#!/usr/bin/env python # coding=utf-8 import os import random import numpy as np class DataConfig(): base_dir='/data/dataset/' dict_dir=base_dir+'dict/' py2id_dict=dict_dir+'py2id_dict.txt' hz2id_dict=dict_dir+'hz2id_dict.txt' py2hz_dict=dict_dir+'py2hz_dict.txt' py2hz_dir=base_dir+'pinyin2hanzi...
import toml as toml_ def dumps(*a, **kw): kw.pop('indent', None) return toml_.dumps(*a, **kw) loads = toml_.loads
import sys import unittest import logChunk from chunkingConstants import * sys.path.append("../util") import Util from Util import ConfigInfo class logChunktest(unittest.TestCase): def readHelper(self,filename): inf =open(filename,"r") text="" for line in inf: text+=line ...
# The following code is based on the ProcHarvester implementation # See https://github.com/IAIK/ProcHarvester/tree/master/code/analysis%20tool import pandas as pd import numpy as np import config import math import distance_computation def init_dist_matrices(file_contents): dist_matrices = [] for fileContent...
from flask import render_template from . import datasrc @datasrc.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @datasrc.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500
# # PySNMP MIB module CISCO-PORT-STORM-CONTROL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-PORT-STORM-CONTROL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:53:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
""" constraint-expression: logical-or-expression """ import glrp from ...parser import cxx98 from be_typing import TYPE_CHECKING @glrp.rule('constraint-expression : logical-or-expression') @cxx98 def constraint_expression(self, p): # type: (CxxParser, glrp.Production) -> None pass if TYPE_CHECKING: ...
from dataclasses import dataclass from pdip.cqrs import ICommand @dataclass class StartExecutionProcessCommand(ICommand): DataOperationId: int = None JobId: int = None DataOperationJobExecutionId: int = None
# coding:utf-8 import functools import collections import MaterialX from LxGraphic import grhCfg from . import mtxCfg class Mtd_MtxBasic(mtxCfg.MtxUtility): MOD_materialx = MaterialX MOD_functools = functools class Mtd_MtxFile(Mtd_MtxBasic): @classmethod def _getNodeDefDict(cls, fileString): ...
import pytest import pandas as pd import numpy as np from check_univariate_outliers import pick_univariate_outliers s = np.random.seed(54920) def make_df_with_outliers(mean, std, size, colname, values_to_insert=None, **kwargs): data = np.random.normal(loc=mean, scale=std, size=size) if values_to_insert: ...
import asyncio import random import os from aiocache import cached, Cache import aiohttp import discord from discord.commands import Option from discord.ext import commands from alttprbot.util.holyimage import HolyImage ALTTP_RANDOMIZER_SERVERS = list(map(int, os.environ.get("ALTTP_RANDOMIZER_SERVERS", "").split(',...
# lec6.4-removeDups.py # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python # Lecture 6, video 4 # Demonstrates performing operations on lists # Demonstrates how changing a list while iterating over it creates # unintended problems def removeDups(L1, L2): for e1 in L1: if e1 ...
import time # from login import LogIn import setup from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup as bs from tkinter import * from instascraper.scraper_interface import Sc...
""" File Name: no_style.py Description: This program takes one text file as an argument and ouputs the frequencies of valid tokens it contains. Valid tokens are considered as a sequence of alphanumeric characters along with a few special characters [a-zA-Z0-9_]. The tokens are then redu...
from src import Parameters from src import Preprocessing from src import TextClassifier from src import Run class Controller(Parameters): def __init__(self): # Preprocessing pipeline self.pr = Preprocessing(Parameters.num_words, Parameters.seq_len) self.data = self.prepare_data() # Initialize the mode...
import numpy as np class PathBuilder(dict): """ Usage: ``` path_builder = PathBuilder() path.add_sample( observations=1, actions=2, next_observations=3, ... ) path.add_sample( observations=4, actions=5, next_observations=6, .....
from django.test import TestCase from .models import Image,User,Comments,Profile # Create your tests here. class ImageTestClass(TestCase): ''' Test case for the Image class ''' def setUp(self): ''' Method that creates an instance of Image class ''' # Create a image inst...
import pytest from progress_keeper import Progress @pytest.fixture def prog_no_var(): return Progress('tests/tmp/progress.cfg') @pytest.fixture def prog_with_vars(): return Progress('tests/tmp/progress_with_vars.cfg', vars=['tracker_1', 'tracker_2', 'tracker_3']) def test_initialize_no_vars_def(prog_no_v...
from .base import * from .naive import * from .naive_fast import *
class Solution(object): def balancedStringSplit(self, s): """ :type s: str :rtype: int """ # Runtime: 20 ms # Memory: 13.5 MB stack = 0 n_balanced = 0 for char in s: if char == "L": stack += 1 else: ...
""" PLAYERS MANAGEMENT """ from season.models import Player __all__ = ['isPlayerValid','getAllPlayers','getPlayerName'] def isPlayerValid(player_id): """ check whether player id is valid in the DB """ try: Player.objects.get(id=player_id) except Player.DoesNotExist: return False ...
from unittest import skipIf from decouple import config from django.test import TestCase, override_settings from google.api_core.client_options import ClientOptions from google.auth.credentials import AnonymousCredentials from google.cloud.exceptions import NotFound from google.cloud.storage import Blob, Bucket, Clien...
from __future__ import annotations import json import statistics from pathlib import Path from typing import Iterable, Union import numpy as np from vmaf.tools.bd_rate_calculator import BDrateCalculator import tester.core.test as test from tester.core.log import console_log from tester.core.video import VideoFileBas...
# TODA VEZ TEM QUE INSTALAR O DJANGO # pip install django # django-admin startproject projeto . # Criar a pasta principal do django OBS: sempre lembrar do ponto no final # python manage.py startapp blog # Criar o blog # python manage.py runserver # Mostra o django no navegador
from AWERA import config, reference_locs from AWERA.validation.validation import ValidationPlottingClustering import time from AWERA.utils.convenience_utils import write_timing_info since = time.time() if __name__ == '__main__': settings = { 'Data': {'n_locs': 500, 'location_type': 'europe...
"""Exceptions used by the thermostat module.""" class SendFailure(Exception): """Failed to send a message to the remote XBee.""" class CrcVerificationFailure(Exception): """CRC calculation didn't match expected value.""" class RetryException(Exception): """Multiple tries have failed.""" class Failed...
class Menu: def __init__(self, x, y): self.menu_items:list = [] self.active_item:int = 0 self.menu_title:str = '' self.x = x self.y = y self.visible = True self.priority = 2 def __str__(self) -> str: return_string = '' for item in self.men...
#!/usr/bin/env python from siconos.io.mechanics_run import MechanicsHdf5Runner import siconos.numerics as Numerics import chute import rocas import random import sys import numpy if (len(sys.argv) < 2): dist = 'uniform' mu = 0.1 else: dist = sys.argv[1] mu = sys.argv[2] if not dist in ['uniform', '...
import json import requests import os def main(): folder_setup() download_trials() def folder_setup(): current_directory = os.getcwd() studies_directory = os.path.join(current_directory, r'Full_Studies') if not os.path.exists(studies_directory): os.makedirs(studies_directory) d...
# -*- coding: utf-8 -*- """ Created on Thu Apr 30 14:47:24 2020 @author: ToshY """ import numpy as np import itertools import matplotlib.pyplot as plt from itertools import cycle from sklearn.metrics import accuracy_score, f1_score, cohen_kappa_score, \ confusion_matrix, precision_recall_curve, roc_curve,...
from plugin import Plugin class Playlist(Plugin): def help_text(self, bot): return bot.translate("playlist_help") def on_msg(self, bot, user_nick, host, channel, message): if message.lower().startswith('!np'): bot.send_message(channel, bot.translate("playlist_str1"), user_nick)
# Copyright (c) 2015, Dataent Technologies Pvt. Ltd. and Contributors # License: See license.txt # pre loaded from __future__ import unicode_literals import dataent test_records = dataent.get_test_records('Currency')
#!/usr/bin/env python3 """ Author:hms5232 Repo:https://github.com/hms5232/NCNU-etutor-reposter-telegram-bot Bug:https://github.com/hms5232/NCNU-etutor-reposter-telegram-bot/issues """ from telegram.ext import Updater, CommandHandler from configparser import ConfigParser import requests import time import threading i...
state = {'params': { 'in_i_l': 1.9158910803943378e-07, 'in_i_w': 1.052548978774763e-06, 'infold_l': 1.7824932088861794e-07, 'infold_w': 6.776028281502987e-07, 'infoldsrc_w': 5.394307669756082e-06, 'inpair_l': 1.6674022226091898e-07, 'inpair_w': 8.110062940175877...
############################################################# ## ## ## Copyright (c) 2003-2017 by The University of Queensland ## ## Centre for Geoscience Computing ## ## http://earth.uq.edu.au/centre-geoscience-computing ## ## ...
import gtk.gdk w = gtk.gdk.get_default_root_window() sz = w.get_size() print "The size of the window is %d x %d" % sz pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1]) pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1]) if (pb != None): pb.save("screenshot.png","png") print "Screen...
#!/usr/bin/env python3 # Print the first three multiples of a given number `num`, # and finally return the third multiple. def first_three_multiples(num): for i in range(1, 4): print(num * i) return num * i first_three_multiples(10) first_three_multiples(15)
import logging import datetime import bisect from django.conf import settings from django.contrib.localflavor.us.us_states import STATE_CHOICES from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.db import transaction from djang...
# -*- coding: utf-8 -*- import tkinter as tk from .gui_canvas import CanvasImage class Rectangles(CanvasImage): """ Class of Rectangles. Inherit CanvasImage class """ def __init__(self, placeholder, path, rect_size): """ Initialize the Rectangles """ CanvasImage.__init__(self, placeholder, pat...
import numpy as np import matplotlib.pyplot as plt plt.switch_backend('agg') import model_list, models, fitting import matplotlib.lines as mlines import corner import copy as cp from utils import rj2cmb plt.style.use('seaborn-colorblind') #plt.rc('text', usetex=True) #plt.rc('font', family='serif') print "hello!" m...
# Generated by Django 2.1.1 on 2019-10-06 00:51 from django.conf import settings import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import simple_history.models class Migration(migrations.Migration): dependencies = [ ...