content
stringlengths
5
1.05M
# Copyright 1996-2019 Cyberbotics 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 in...
#### TESTED from typing import Tuple import pandas as pd from pandas import DataFrame from dbnd import parameter, task from dbnd_examples.data import data_repo from targets.target_config import FileFormat class TestDocDataSerializationDeSerialization: def test_prepare_data_save_result_with_no_header(self): ...
"""Implements the astroplan-based sky target visibility web tool using Flask. """ import matplotlib matplotlib.use('agg') from matplotlib import pyplot as pl import flask import json from astropy import units as u from astropy.time import Time from astropy.coordinates import SkyCoord from astropy.utils.data import ge...
import os from collections import namedtuple try: from shutil import which except ImportError: def which(name): if os.path.exists("/usr/local/bin/" + name): return "/usr/local/bin/" + name elif os.path.exists("/usr/bin/" + name): return "/usr/bin/" + name class ARN(name...
""" autotask dbip mmdb下载,由server控制 """ # from ..autopluginbase import AutoPluginBase # # # class Dbip(AutoPluginBase): # # def __init__(self): # AutoPluginBase.__init__(self) # # def start(self): # pass import gzip import shutil from pathlib import Path import requests from commonbaby.mslog im...
# -*- coding: utf-8 -*- """ Created on Fri May 21 19:56:54 2021 @author: Paschalis Giakoumoglou 10054 @author: Christos Kyratsous 10105 """ import matplotlib.pyplot as plt import numpy as np def euler(F, x0, t0, tmax, dt): t = np.arange(t0, tmax + dt, dt) x = np.zeros((len(t), len(x0)), np.float6...
import re from simpleeval import simple_eval, NameNotDefined class Expression: def __init__(self, expr): self.expr = expr def eval(self, context): raise NotImplementedError class Bind(Expression): def eval(self, context): return simple_eval(self.expr, names=context) class Cond...
# -*- coding: utf-8 -*- from . static import Base_RM_Field class RM_Field_FEFILT0_IPVERSION_IPVERSION(Base_RM_Field): def __init__(self, register): self.__dict__['zz_frozen'] = False super(RM_Field_FEFILT0_IPVERSION_IPVERSION, self).__init__(register, 'IPVERSION', 'FEFILT0.IPVERSION....
""" base.py The base agent, which should be inherited by the other agents. """ from warnings import warn class Agent: __slots__ = { 'training', 'last_score', 'tag' } def __init__(self, training: bool = False, tag: str = 'base'): """ Initialis...
from mitmproxy import contentviews from mitmproxy.test import tflow from mitmproxy.test import tutils from mitmproxy.test import taddons from mitmproxy.http import Headers from ..mitmproxy import tservers class TestScripts(tservers.MasterTest): def test_add_header(self, tdata): with taddons.context() as ...
""" *Product Formation* A, B: Type _proves_ A x B: Type An element here amounts to a construction taking an element of A to an element of B. In the case of mere propositions, an element of the function type is a proof of the implication, a mapping of a warrant for A to a warrant of B. (Corfield 39) "...
import json import requests from src.sdk.auth.auth_sdk import login from src.utils.header_utils import build_headers def import_topics(site,topics): headers = build_headers(login(site)) for topic in topics: # print(topic["name"]) response = requests.post(site["host"] + "import/admin/topic", ...
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from users.models import User class SignUpForm(UserCreationForm): def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) for fieldname in ["email", "password1", "password2"]: se...
from imageai.Prediction import ImagePrediction import os execution_path = os.getcwd() prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() prediction.setModelPath(os.path.join( execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5")) prediction.loadModel() predictions, probabilities = ...
__all__ = ["LatentDataset", "LatentDataModule"] from pathlib import Path from functools import partial from typing import Tuple, Dict import pandas as pd import torch from dotenv import find_dotenv from torch.utils.data import Dataset from src.data.base import DataModule from src.data.snp import SNPDataset from src....
from flask import Flask, request import os import time app = Flask(__name__) app.debug = True @app.route("/") def delay(): delay = request.args.get("delay") if delay: time.sleep(float(delay)) return "delay app" if __name__ == "__main__": app.run(host="0.0.0.0", port=8888)
# coding=utf-8 from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models class Station(models.Model): name = models.CharField(max_length=30) managers = models.ManyToManyField(User, related_name='stations', blank=True) def __unicode__(self): ...
from django.core.management.base import BaseCommand from pprint import pprint from faker import Faker class Command(BaseCommand): def handle(self, *args, **options): fake = Faker() print(fake.name()) print(fake.text()) print('========') print(fake.word()) pprint(f...
# Unit tests for P10_21.py # IMPORTS from nose.tools import ok_, eq_ from P10_21 import CheckingAccount class TestCheckingsAccount(): def setup(self): self.c = CheckingAccount() def test_is_free(self): ok_(True, self.c.is_free()) def test_deposit(self): self.c.deposit(500) ...
""" adaptive time stepping for dg shallow water equation model """ from __future__ import division from __future__ import absolute_import from mpi4py import MPI from flooddrake import * from flooddrake.min_dx import MinDx import numpy as np class AdaptiveTimestepping(object): def __init__(self, V, max_timest...
""" Copyright (c) 2021, Electric Power Research Institute All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this li...
from django.shortcuts import render, redirect, HttpResponse from .forms import UserForm, LoginForm from django.contrib.auth.models import User from django.contrib.auth import login, authenticate # Create your views here. def signup(request): if request.method == "POST": form = UserForm(request.POST) ...
from chatbotapp.cnudata.cafeteria.studenthall1_info import * # from chatbotapp.cnudata.studenthall2_info import make_answer_food_menu from chatbotapp.cnudata.cafeteria.food_court_time import * from chatbotapp.cnudata.cafeteria.dorm_info import * from chatbotapp.cnudata.cafeteria.new_studenthall2_info import * def get...
#!/usr/bin/python # -*- coding: utf-8 -*- # Sets are mutable. But since they are unordered, indexing have no meaning. # there is no way of determining which item will be popped # set initial way myword = set('Hello World') mybasket = {'orange', 'apple', 'pear', 'orange', 'banana', 'apple'} mynumber = {500,99,900,2,3...
""" 8-8 code """ # def squsum(*param): # sum = 0 # for i in param: # sum += i*i # print(sum) # # # squsum(1, 2, 3) def city_temp(**param): for key,value in param.items(): print(key, ':', value) # city_temp(bj='32c', xm='23c', sh='31c') a = {'bj': '32c', 'xm': '23c', 'sh': '31c'} c...
# Copyright (c) 2018 Trail of Bits, 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 ...
#!/usr/bin/env python3 import aiohttp import logging import sys logging.basicConfig( format="%(asctime)s %(levelname)s:%(name)s: %(message)s", level=logging.DEBUG, datefmt="%H:%M:%S", stream=sys.stderr, ) logger = logging.getLogger("http_fetcher") logging.getLogger("chardet.charsetprober").disabled = ...
from .. import config config.setup_examples() import infermedica_api if __name__ == "__main__": api: infermedica_api.APIv3Connector = infermedica_api.get_api() age = 38 print("Parse simple text:") response = api.parse("i feel stomach pain but no coughing today", age=age) print(response, end="\n\...
__all__ = ['__version__'] __version__ = '0.1.10'
import os import pymongo from mongodb.exceptions import MongoURLNotFoundError __all__ = ("MONGO_CLIENT", "new_mongo_session",) _url = os.environ.get("MONGO_URL") if _url is None: raise MongoURLNotFoundError() MONGO_CLIENT = pymongo.MongoClient(_url) def new_mongo_session(): """ Create a new mongo ses...
# 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, software # distributed under th...
from ..factory import Type class maskPointChin(Type): pass
""" script to merge or split model parallel checkpoints This script: - assumes a checkpoint directory with pipeline parallel checkpoints (i.e. a global_step directory with files named like 'layer_00-model_00-model_states.pt') - assumes that the checkpoint names haven't been changed, since it makes the script much clea...
"""Illustrates a method to intercept changes on objects, turning an UPDATE statement on a single row into an INSERT statement, so that a new row is inserted with the new data, keeping the old row intact. This example adds a numerical version_id to the Versioned class as well as the ability to see which row is the most...
class Solution: """ @param nums: A list of integers @return: A integer indicate the sum of max subarray @ time: O(n) Space:O(1) """ def maxSubArray(self, nums): # greedy ''' if not nums: return 0 cur_sum = max_sum = nums[0] # 初始值 设为列表第一元素 ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. #...
from .disclaimer import Disclaimer from .glossary import Glossary
# Python Lists # @IdiotInside_ print ("Creating List:") colors = ['red', 'blue', 'green'] print (colors[0]) ## red print (colors[1]) ## blue print (colors[2]) ## green print (len(colors)) ## 3 print ("Append to the List") colors.append("orange") print (colors[3]) ##orange print ("Insert to the List") colors....
# -*- coding: utf-8 -*- def in_range(num, minimum, maximum): return minimum <= num <= maximum def decode_to_string(data): """ Decode the strings in the list/set so we can call print the strings without the 'u' in front Args: data (list(str) or set(str)) """ return str([x.encode('UTF8') ...
# -*- coding: utf-8 -*- """ Building Skills in Object-Oriented Design V4 Card Definition for unit testing. Note that Unicode ``\u1f0a1`` (🂡) to ``\u1f0de`` (🃞) has the images of the cards themselves. There's an interesting wrinkle: Unicode has 14 ranks; it includes a "knight" rank. Since we use 13 ranks, we'll skip...
# Importing the libraries import numpy as np import pandas as pd import pickle import matplotlib.pyplot as plt dataset = pd.read_csv('50_Startup.csv') #Importing data set X=dataset.iloc[:,:-1].values y=dataset.iloc[:,3].values from sklearn.tree import DecisionTreeRegressor reg=DecisionTreeRegressor(max_depth=5) reg....
import sys from collections import OrderedDict from knack import CLI, ArgumentsContext, CLICommandsLoader from knack.commands import CommandGroup class MyCommandsLoader(CLICommandsLoader): def load_command_table(self, args): with CommandGroup(self, "repository", "repository#{}") as g: g.comma...
import sc2 from sc2.data import race_townhalls, ActionResult from sc2.player import BotAI from sc2.unit import Unit from sc2.constants import OVERLORD, QUEEN, CREEPTUMOR, CREEPTUMORBURROWED, CREEPTUMORQUEEN,\ BUILD_CREEPTUMOR_QUEEN, BUILD_CREEPTUMOR_TUMOR,\ CANCEL_CREEPTUMOR, BEHAVIOR_GENERATECREEPON, HATCHERY,...
import os import pandas as pd from pandas import DataFrame from data_loader import load_train_genes_for_cell_line data_small_folder = "data_small/" def created_gct_file_train_plus_val() -> dict[int, DataFrame]: """ Create gct files for cell line 1 and cell 2 (train and val data merged) for visualization re...
from django.urls import path, include from rest_framework.routers import DefaultRouter from courses import views app_name = 'courses' urlpatterns = [ path('', views.CourseListView.as_view(), name='course-list'), path('<str:slug>', views.CourseDetailView.as_view(), name='course-detail'), path('user/buy', vi...
#! python3 # -*- coding: utf-8 -*- """Internal module to interact with gui """ __version__ = "0.4.6" class Gui: # pylint: disable=too-few-public-methods """Class to interact with gui """ @staticmethod def warning(message): """Starts Tkinter window with message to user <br>`param messa...
import os from kubernetes.config import load_incluster_config, load_kube_config, incluster_config as kubernetes_config from kubernetes import client from kubernetes.client.rest import ApiException from django.conf import settings # override service token mounts when running with telepresence from comic.eyra.models ...
import torch import torch.nn as nn import torch.optim as optim from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader from torchnet.meter import ConfusionMeter import argparse import os import sys import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from dat...
import unittest from os.path import join from mock import patch from enot.packages.config.rebar import RebarConfig from enot.packages.dep import Dep from test.abs_test_class import TestClass class RebarConfigTests(TestClass): def __init__(self, method_name): super().__init__('rebar_config_tests', method...
import os import sys import glob import joblib import numpy as np from tqdm import tqdm from joblib import delayed from scipy.misc import imsave from pyvirchow.misc.parallel import ParallelExecutor folder = sys.argv[1] aprun = ParallelExecutor(n_jobs=8) img_files = glob.glob(os.path.join(folder, '*.img.joblib.pickle'...
from .StructureBuilder import StructureBuilder, ResidueBuilder from .structure import inverse_trig_transform, trig_transform
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt # x, y coordinates on sine and cosine curves x = np.arange(0, 4 * np.pi, 0.1) f_sin = np.sin(x) f_cos = np.cos(x) # first subplot with height 2 and width 1 plt.subplot(2, 1, 1) plt.plot(x, f_sin) plt.title('Sine') # second subplot plt.subplot(2, ...
from heuristics import CompositeHeuristic, PathLengthHeuristic, RegionHeuristic from policies import ActionSearchPolicy pol = ActionSearchPolicy( CompositeHeuristic( [ PathLengthHeuristic(15), RegionHeuristic(), ], weights=[15, 1], ), depth_limit=6...
#!/usr/bin/python import sys import re """ Read the ToolsOfTheTrade Markdown file (readme.md) and alpha-sort the contents - currently markdown "Header 3" and table rows. This is a terrible 5-minute hack for this particular readme.md But it does work. """ file_object = open("./readme.md") lines = file_object.readline...
# 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, software # d...
from __future__ import unicode_literals from django.urls import reverse from cradmin_legacy.demo.webdemo.views.sharable_link.mixins import QuerysetForRoleMixin from cradmin_legacy.viewhelpers.detail import DetailView class ShowView(QuerysetForRoleMixin, DetailView): template_name = 'webdemo/sharable_link/show.dja...
import torch as th import numpy as np import sys class Device: gpu = False dummy = None @staticmethod def set_device(gpuid: int): if gpuid != -1: Device.gpu = True th.cuda.set_device(gpuid) sys.stderr.write(f"Device set to GPU {gpuid}\n") Device...
# A new bid can be at minimum, the current bid times this factor. MINIMUM_BID_FACTOR = 1.15 # factors should be calculated, using regression on a real-estate data set. FACTORS = { 'BASE': 500, 'ROOMS': lambda x: {1: 1, 2: 1.15, 3: 1.25, 4: 1.50}[x], 'SALOONS': lambda x: {1: 1, 2: 1.25}[x], 'BUILDING_TY...
from datetime import datetime, timezone from http import HTTPStatus from test_api.conftest import USER_URI, login, make_db_record from dynamo.util import format_time def test_get_user(client, tables, monkeypatch): monkeypatch.setenv('MONTHLY_JOB_QUOTA_PER_USER', '25') request_time = format_time(datetime.now...
from django.urls import path from .views import * app_name = "warriors_app" urlpatterns = [ path('warriors/', WarriorAPIView.as_view()), path('profession/create/', ProfessionCreateView.as_view()), path('skill/create/', SkillCreateView.as_view()), path('skill/', SkillView.as_view()), path('warriors/sk...
from utils.bbox import BBoxes from utils.bbox import stack_bboxes import torch import unittest class TestBBoxes(unittest.TestCase): def setUp(self): self.tensor = torch.tensor([[0,0,20,20]]) self.fmt = "xyxy" def test_init(self): bbox = BBoxes(self.tensor, self.fmt) self.asse...
import os import time class WorkSplitter(object): def __init__(self): try: _, columns = os.popen('stty size', 'r').read().split() self.columns = int(columns) except: self.columns = 50 def section(self, name): name_length = len(name) left_len...
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 10:20:34 2020 @author: miketaylor """
from . import test_foo, test_bar
#!/usr/bin/env python3 # coding=UTF-8 # # CWA Data Conversion Tool # # Copyright (c) 2011 Technische Universität München, # Distributed Multimodal Information Processing Group # http://vmi.lmt.ei.tum.de # All rights reserved. # # Stefan Diewald <stefan.diewald [at] tum.de> # # Redistribution and use i...
# # test_siteconfig.py # # Tests for site config generation (siteconfig.py). # # Copyright (C) 2018-2021 by # Nikhil Ramakrishnan. # # This file is part of the FreeType project, and may only be used, # modified, and distributed under the terms of the FreeType project # license, LICENSE.TXT. By continuing to u...
# Copyright 2017 The UAI-SDK Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
from __future__ import annotations import abc import datetime import typing import pydantic from src import core __all__ = ("Todo",) class Todo(pydantic.BaseModel, abc.ABC): advance_days: int category: core.TodoCategory date_added: datetime.date date_completed: typing.Optional[datetime.date] d...
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from collections import OrderedDict import re from mpi4py import MPI from pyfr.bases import BaseBasis from pyfr.inifile import Inifile from pyfr.util import proxylist, subclass_map class BaseSystem(object): __metaclass__ = ABCMeta # Relevant...
# REMINDER: this code needs to be rewritten for the new framework. Remove this comment when the code is fully converted. import os import transformers from lm_eval.base import LM from lm_eval import utils class GPT3LM(LM): MAX_LENGTH = 2048 def __init__(self, engine, truncate=False): """ :...
import os import nback.lib.db.mongodb as mongodb_dump import nback.lib.db.mysql as mysql_dump import nback.lib.db.postgresql as postgresql_dump import nback.lib.logger as logger import nback.lib.notification as notification import nback.lib.utils as utils import nback.lib.storage.aws_s3 as aws_s3 import nback.setting...
from .swag_tr import train_swag from .sgld_tr import train_sgld from .gp_tr import train_gp from .bbp_tr import train_bbp from .dun_tr import train_dun
""" A collection of timeseries pipelines """ import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin class AlignPandas(BaseEstimator, TransformerMixin): def __init__(self, LAGS, HORIZIONS): self.max_lag = max(LAGS) self.max_horizion = max(HORIZIONS) ...
import json def create_user(uid, fname, lname, major, classes, redis_client, isTutor, schedule): redis_client.hset("user{}".format(uid), key="fname", value=fname) redis_client.hset("user{}".format(uid), key="lname", value=lname) redis_client.hset("user{}".format(uid), key="major", value=major) redis_cl...
from django.db import transaction from drf_spectacular.openapi import OpenApiParameter, OpenApiTypes from drf_spectacular.utils import extend_schema from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from baserow.api.applications...
from estado import * ''' Created on 12/09/2013 @author: Ronaldo ''' class turing(): def __init__(self,alfabeto,estados,est_inicial,alfabeto_aux,simb_inicio,simb_branco): self.alfabeto = alfabeto self.estados = estados self.estados.append(estado('?')) self.estado_inici...
import numpy as np from deformations.utility.mesh3d import mesh3d from deformations.utility.bernstein import get_bernstein_polynomial def get_min_max(x, *args, **kwargs): return np.min(x, *args, **kwargs), np.max(x, *args, **kwargs) def stu_to_xyz(stu_points, stu_origin, stu_axes): return stu_origin + s...
import os import flask from pyravin.google.oauth import OAuth from pyravin.google.calendar import Calendar from pyravin.google.constant import Scope app = flask.Flask(__name__) # Note: A secret key is included in the sample so that it works. # If you use this code in your application, replace this with a truly secre...
from examples.exampleRunner import runExample runExample("mitigation_examples/realisticSupplyChain.json")
import json from django.conf import settings from django.core.cache import cache from django.http import JsonResponse from django.core import serializers from rest_framework.views import APIView from Apps.Api.utils import Authtication, VisitThrottle, AuthticationWithoutPackageId from Apps.ARExperiences.models import AR...
import copy import csv import os import json from functools import reduce import collections from lxml import etree import nltk import numpy import networkx nltk.download('punkt') """ ## examples # parse OAB exam, return generator of OABQuestion instances oab = parse_xml('/home/bruno/git/oab-exams/OAB/raw/2010-01.xm...
import marshmallow as mm from emannotationschemas.schemas.base import ReferenceAnnotation class FlyNeuropil(ReferenceAnnotation): neuropil = mm.fields.Str( required=True, description="neuropil name", )
# ============================================================================ # 第三章 暖冷房負荷と外皮性能 # 第四節 日射熱取得率 # Ver.11(住宅・住戸の外皮性能の計算プログラム Ver.03~2021.4) # ---------------------------------------------------------------------------- # 付録B 大部分がガラスで構成されている窓等の開口部における取得日射熱補正係数 # ----------------------------------------------...
import os import numpy as np from PIL import Image from PIL import ImageDraw from PIL import ImageFont from typing import Any from typing import Tuple from cftool.dist import Parallel tight = False padding = 0.1 """ Expected file structure: -- /path/to/your/fonts/folder |- font_type0 |- font_file0 |- font_file...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not...
import torch import logging from datasets import INT2CHAR, FILE_START, FILE_END, PAD, CharSequenceToTensor logger = logging.getLogger("genpyseq") def generate_charseq( nn, prime_str=FILE_START, max_window_size=None, print_output=True, max_generate_len=1000, temperature=None): logger.info(" • max w...
# 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, software # distributed ...
""" Defines the character objects """ from random import randint # set the level boundaries LEVEL_BOUNDS = [ [0, 5], [5, 10], [10, 25], [25, 50], [50, 100], [100, 250], ] class ItTech: """Defines the player character""" def __init__(self, name, level): """Inititalizes the cha...
import logging import cupy as cp import numpy as np __all__ = ["RescaleIntensity"] logger = logging.getLogger(__name__) class RescaleIntensity(object): """ Return image after stretching or shrinking its intensity levels. The algorithm is based on the implementation in `skimage`_. .. _skimage: ...
import tensorflow as tf from tensorflow.python.framework import graph_util class BaseModel: def __init__(self, config, logger): self.config = config self.logger = logger # init the global step self.init_global_step() # init the epoch counter self.init_current_epoch()...
# -*- coding: utf-8 -*- # # Copyright (C) 2018 NII. # # invenio-iiif-manifest is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """API tests.""" from flask import Flask from invenio_iiif_manifest import InvenioIIIFManifest from invenio...
# -*- coding: utf-8 -*- """ Created on Fri Jun 15 21:13:04 2018 @author: HuyNguyen """ import pandas from bs4 import BeautifulSoup import requests from copy import deepcopy import re import numpy def get_page(page_link): return requests.get(page_link).content def get_table(page): page_soup...
## @file taskList.py # @author Arkin Modi, Leon So, Timothy Choy # @brief Dict of Tasks # @date Mar 21, 2020 from task import * from dict import Dict ## @brief Dict of Tasks class TaskList(Dict): pass
# Generated by Django 2.1.1 on 2018-10-06 13:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('catalog', '0003_auto_20181006_1706'), ] operations = [ migrations.RenameField( model_name='language', old_name='lang', ...
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.postgres.fields import JSONField from polls.models import Poll class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) voted = JSONField(...
import functools from log import log @log class RetryOnException: def __init__(self, retries): self._retries = retries def __call__(self, function): functools.update_wrapper(self, function) def wrapper(*args, **kwargs): self.logger.info(f"Retries: {self._retries}") ...
# 3D Spatial Transformer Network ## Introduction This is the TensorFlow implementation for 2D & 3D Spatial Transformer Network in [1] Jaderberg M, Simonyan K, et al. Spatial transformer networks[C]. International Conference on Neural Information Processing Systems. MIT Press, 2016:2017-2025. Re-implemented by Lizh...
import sys import warnings idx = 0 while idx < len(sys.path): if 'sawyer_control' in sys.path[idx]: warnings.warn("Undoing ros generated __init__ for parallel until a better fix is found") del sys.path[idx] else: idx += 1
import datetime from models.base import Base from models.const import CommonStatus from peewee import CharField, DateTimeField, IntegerField class UserPhoneDAO(Base): user_id = IntegerField(index=True) phone = CharField(index=True) status = IntegerField(index=True, default=CommonStatus.NORMAL) create...
import json import logging import os import falcon import requests from weather import get_weather TOKEN = os.environ['TELEGRAM_BOT_TOKEN'] BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/' class GetMeResource(object): def on_get(self, req, resp): result = requests.get(BASE_URL + 'getMe') ...