text
stringlengths
38
1.54M
import csv import argparse from os.path import join if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--data-dir', default='data_dir/testing') args = parser.parse_args() prediction_files = [ '7-bert-large-cased.csv', '11-roberta-base.csv', '12-roberta-large.csv', '13-albe...
import os import numpy as np def ListFilesToTxt (dir, file, wildcard, recursion): exts = wildcard.split (" ") files = os.listdir (dir) for name in files: fullname = os.path.join (dir, name) if (os.path.isdir (fullname) & recursion): ListFilesToTxt (fullname, file, wildcard, recursion) else: for ext in...
''' def copie(tab): copie_tab = tab return copie_tab print(copie([1, 2, 3]))''' def copie(tab): copie_tab=[0]*len(tab) for i in range(len(tab)): copie_tab[i]=tab[i]
import time from datetime import datetime as dt import os path = os.path.realpath(__file__)[:-7] file = open('{}setup.txt'.format(path), 'r') file_ar = file.readlines() length = int(file_ar[0]) time1 = int(file_ar[1]) time2 = int(file_ar[2]) print(length) print(time1) print(time2) website_list = [] for i in range...
input_numero = int(input("¿Que numero quieres introducir en la tabla? ")) numeros = [] for numero in range(1, 11): numeros.append(numero) revnumeros = reversed(numeros) for num in revnumeros: print("{} x {} = {}".format(input_numero, num, input_numero * num))
from django.urls import path from order.views import * app_name ='order' urlpatterns =[ path('generate', generate_order,name='generate'), path('commit', order_commit,name='commit'), path('pay', order_pay,name='pay'), path('check', check_order, name='check'), path('comment', order_comment, name='c...
import os import sys from deepdrive_zero.experiments import utils from spinup.utils.run_utils import ExperimentGrid from spinup import ppo_pytorch import torch experiment_name = os.path.basename(__file__)[:-3] notes = """Try boost_explore 0.6 to get back to normal start entropy of 0.9""" results = 'Entropy decreased ...
# -*- coding: utf-8 -*- """ Created on Tue Nov 13 17:48:47 2018 @author: Gebruiker """ import csv import matplotlib.pyplot as plt import numpy as np from copy import deepcopy truearea = 1.50659 def makePlots(alist, rangelist, area,typeof): islist = [] arealist = [] ilist = [3000,3500,4000,4500,5000...
from django.conf.urls import patterns, include, url from rest_framework_mongoengine import routers from amspApp.Bpms.views import LunchedProcessView router = routers.SimpleRouter() router.register(r'LunchedProcess', LunchedProcessView.LunchedProcessViewSet,base_name='LunchedProcess') urlpatterns = patterns( '', ...
from django.contrib.auth import authenticate,login,logout from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render from store.forms import UserForm,CustomerForm from store.models ...
CMD1 = """ SELECT S_CON_WINDCODE, I_WEIGHT FROM AIndexHS300Weight WHERE TRADE_DT = '{date}' """ CMD2 = """ SELECT S_CON_WINDCODE, WEIGHT FROM AIndexCSI500Weight WHERE TRADE_DT = '{date}' """
import matplotlib matplotlib.use('Agg') from matplotlib import rc from brian import * rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) rc('text', usetex=True) # use latex ''' Plot CV vs freq est error and histogram ''' filename = 'lotsofdata.npz' archive = np.load(filename) CV = archive['CV'] freq_est ...
# -*- coding: utf-8 -*- import LINETCR from LINETCR.lib.curve.ttypes import * from datetime import datetime from gtts import gTTS from bs4 import BeautifulSoup import time,random,sys,re,goslate,requests,urllib,os,json,subprocess,codecs,threading,glob,wikipedia cl = LINETCR.LINE() #cl.login(qr=True) cl.login(token="Ep...
from PIL import Image, ImageDraw, ImageFont import cv2 import numpy as np def change_cv2_draw(image,strs,local,sizes,colour): cv2img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) pilimg = Image.fromarray(cv2img) draw = ImageDraw.Draw(pilimg) # 图片上打印 font = ImageFont.truetype("SIMYOU.TTF",sizes, encoding="...
from ECG.ecg import read_ecg,find_peaks import numpy as np import time import os import numpy as np import plotly.offline as pyo import plotly.graph_objects as go import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from collections import dequ...
from django.contrib import admin from api.models import Estate, EstateImage, Tracking import cloudinary.uploader """ Custom view of admin page """ # ------------------------------------------ class EstateFilter(admin.SimpleListFilter): """ Reference: https://medium.com/elements/getting-the-most-out-of-...
import re import os import sys sys.path.append(os.path.join(os.path.dirname(__file__),"..", "basics")) # from timecourse_an_config import * <--- included in calc_lbl_timecourse from calc_time_indices import * from prepare_ttest_results import * from get_lbl_indices import* from scipy import stats from scipy import...
from auth.models import RidUser def get_dept_names(request): context = {} context['dept_names'] = RidUser.department_labels context['batch_names'] = RidUser.batch_labels return context
import numpy as np import cv2 def stochastic_universal_sampling(weight_vec): sample_set = [] cdf = [] n = len(weight_vec) cdf.append(weight_vec[0][2]) for i in range(1, n): cdf.append(cdf[i - 1] + weight_vec[i][2]) u = 1.0/n i = 0 for j in range(0, n): whi...
import unittest from accounts.models import Alert from accounts.tests.factories import SuperUserFactory from django.core import mail class AlertTestCase(unittest.TestCase): def setUp(self): self.alert = Alert(1, 'code', 'template') self.alert.save() def testAlertAdded(self): x = Aler...
# Copyright Clement Schreiner, 2019 # Transformer class based on: # https://github.com/nshepperd/gpt-2/blob/e99ee3748b6a41e9532538bfc3af17f0b64a5caf/src/interactive_conditional_samples.py # (MIT/Expat license) import json import numpy as np import os import random import tensorflow as tf import sopel.module, sopel.to...
import torch from flytracker import run from flytracker.analysis import annotate from time import time movie_path = "data/experiments/bruno/videos/seq_1.mp4" mask = torch.ones((1080, 1280), dtype=bool) mask[:130, :] = 0 mask[-160:, :] = 0 mask[:, :270] = 0 mask[:, -205:] = 0 mask[:190, :350] = 0 mask[:195, -270:] =...
import numpy as np import matplotlib.pyplot as plt import sklearn.svm as svm from sklearn.svm import LinearSVR from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split from nltk.corpus import sentiwordnet as swn import ast from sklearn.ensemble import RandomForestClassifie...
from sklearn.model_selection import train_test_split from Utils import plot_utils as plt_ut, datasets import numpy as np import Adaline.GradientDescendentAdaline as gd import time import yaml def main(): stream = open('configurations/runConfigurations.yml', 'r', encoding='utf-8').read() configurations = yaml....
from model import Spinenet from dataloader import DataLoader, get_Idx from util import get_image from params import Parameter import matplotlib.pyplot as plt import numpy as np import tensorflow as tf #create model params = Parameter().get_args() sp = Spinenet(params) #training if params.train: dl = DataLoade...
import time import weakref from serf.publisher import Publisher # Chat service models for Person, Room and RoomList. class Person(object): def __init__(self, client_addr): self.client_addr = client_addr self.name = None self.rooms = {} def say(self, room_name, msg): room = sel...
#!/usr/bin/python3 # coding: utf-8 # Copyright (c) 2019-2020 Latona. All rights reserved. import os from pathlib import Path from aion.mysql import BaseMysqlAccess from aion.logger import lprint, lprint_exception class RobotBackupDB(BaseMysqlAccess): def __init__(self): super().__init__("Maintenance") ...
# 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. # Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. my_file = open("task_05_file.txt", "r", encoding='utf-8') numbersLine = my_file.readline() numbers = numbersLine.split(" ") numbersAmount...
""" A program to determine convergence points of bunny-fox populations. Author: Joe Noel (noelj) """ def next_pop(bpop, fpop): bpop_next = max(0,int((10*bpop)/(1+0.1*bpop) - 0.05*bpop*fpop)) fpop_next = max(0,int(0.4 * fpop + 0.02 * fpop * bpop)) return (bpop_next, fpop_next) def check_converg...
def isPrime(n): if n == 2: return True elif n == 3: return True if n % 2 == 0: return False elif n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True n = 2 s...
import subprocess import hashlib import requests import pickle import struct p32 = lambda(x): struct.pack('<I', x) u32 = lambda(x): struct.unpack('<I', x)[0] p64 = lambda(x): struct.pack('<Q', x) u64 = lambda(x): struct.unpack('<Q', x)[0] url_base = 'http://0/' url_base = 'https://school.fluxfingers.net:1531/' def d...
#coding=UTF-8 from haystack import indexes from home.models import * #注意格式 class HomeIndex(indexes.SearchIndex,indexes.Indexable): text = indexes.CharField(document=True, use_template=True) #给title,content设置索引 source_name = indexes.NgramField(model_attr='source_name') source_name = indexes.NgramField(...
from abc import ABC from abc import abstractmethod from typing import Dict from model.logger import Logger from threading import RLock import collections class Worker(ABC): def __init__(self, attr: Dict, pipe: int): self.pipe = pipe self.lock = RLock() self.attributes = attr self....
#各種檔案寫讀範例 新進暫存 ''' import sys, ast filename = 'C:/_git/vcs/_1.data/______test_files1/__RW/_csv/scores.csv' scores = dict() with open(filename,'r') as fp: filedata = fp.read() #scores = ast.literal_eval(filedata) print("以下是{}成績檔的字典型態資料:".format(filename)) import sys std_data = dict() with open(filename, e...
from ctypes import sizeof, addressof, c_ubyte, Structure, memmove import pyads import struct from pyads.structs import SAdsNotificationHeader # Modified version of Connection.notification def notification(plc_datatype=None, pyqtSignal=None): # type: (Optional[Type[Any]]) -> Callable """Decorate a callback func...
#! /usr/bin/env python ################################### # Davi Ortega 9/8/2014 ################################### import sys import bitk import random import json if '-h' in sys.argv: print 'Reads a list of names of strain and outputs a list of mist organism id' sys.exit() genomes = [] with open(sys.argv[1]...
from openerp.osv import osv,fields class res_company(osv.Model): _inherit = "res.company" _columns = { 'purchase_note': fields.text('Default Purchase Terms and Conditions', translate=True, help="Default terms and conditions for purchases."), } class purchase_order(osv.Model): _inherit = "purchase...
from django.db import models from django.contrib.auth.models import User # for handling signal of user model # this will extend the user model from django.db.models.signals import post_save from django.dispatch import receiver # for quick aggregate to average from django.db.models import Avg # global variable that ...
# %load q03_plot_innings_runs_histogram/build.py import pandas as pd import numpy as np import matplotlib.pyplot as plt ipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None) def plot_innings_runs_histogram(): pivot = ipl_df.pivot_table(values=['runs'], index=['match_code'], columns='inning', aggfunc='count...
from django.shortcuts import get_object_or_404 from rest_framework import generics, mixins from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from .models import Profile, Like, Message from .serializers import ProfileSerializer, LikeSerializer, Messag...
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2016, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
# Print the size of the dataset import numpy as np import datetime as dt import matplotlib.pyplot as plt import os, json, requests, pickle from scipy.stats import skew from shapely.geometry import MultiLineString, Polygon, Point, MultiPoint, MultiPolygon, LinearRing from scipy.stats import ttest_ind, f_oneway, lognorm...
# App stuff from app.resources.auth import blueprint as auth_blueprint from app.resources.health import blueprint as health_blueprint
## Helper functions for reading the configuration import sys, os import yaml import results checks = None def read_default_config(): if len(sys.argv) < 2: print "Specify the configuration file on the command-line." exit() return read_config(sys.argv[1]) def read_config(filename): with o...
# Importing header files import numpy as np import warnings warnings.filterwarnings('ignore') #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Reading file data = np.genfromtxt(path, delimiter=",", skip_header=1) census = np.concatenate((data,new_record)) print(data.shape,census.shape) #Finding mean age ...
try: from ._version import version as __version__ except ImportError: __version__ = "0.12.3" from ._function import napari_experimental_provide_function from ._dock_widget import napari_experimental_provide_dock_widget
from fastapi import FastAPI, HTTPException import db app = FastAPI() @app.get("/reservas/") async def obtener_reservas(): reservas = db.obtener_reservas() return reservas @app.post("/reservas/crear/") async def crear_reserva(reserva: db.Reserva): creada_exitosamente = db.crear_reserva(reserva) if c...
""" Quantum teleportation game demo @author: Christian B. Mendl """ import numpy as np import itertools from enum import IntEnum import pyglet from pyglet.window import key #============================================================================== # Level geometry class TileTypes(IntEnum): """Types of til...
#!/usr/bin/env python3 from randomuser import RandomUser import random import time import psycopg as pg import uuid from datetime import timedelta, datetime NUM_USERS=100 NUM_FACILITIES=20 MAX_ACCESS_PER_USER=20 CONNECTION_DATA="dbname='ipm2122_db' host='localhost' port='5438' user='ipm2122_user' password='secret'" ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Decorator takes a function as a parameter and adds functionality to the second function without explicitly modifying it. """ def p_decorate(func): """ Simple decorator :param func: The function that the decorator encapsulates :return: the functions out...
#!/usr/bin/env python ### Example purdy library code # # Displays a REPL session without any token processing using the "none" lexer, # highlighting the first three lines in succession from purdy.actions import Append, Wait, HighlightChain from purdy.content import Code from purdy.ui import SimpleScreen screen = Sim...
import pandas as pd import numpy as np from sklearn.cluster import KMeans data = pd.read_csv('C:\\Users\\Preetham G\\Documents\\Research Projects\\Forecast of Rainfall Quantity and its variation using Envrionmental Features\\Data\\Normalized & Combined Data\\All Districts.csv') dist = ['Ariyalur','Chennai','Coimb...
def solve(n, w, val, weight): dp = [[0 for i in xrange(w+1)] for j in xrange(n+1)] for i in xrange(n+1): for j in xrange(w+1): if i == 0 or j == 0: dp[i][j] = 0; elif weight[i-1] > j: dp[i][j] = dp[i-1][j] else: dp[i][j] = max(val[i-1]+dp[i-1][j-weight[i-1]], dp[i-1][j]) i = w # for s in dp: ...
from modules import * driver = webdriver.Chrome(executable_path=executable_path) driver.get("https://www.oyorooms.com/") driver.maximize_window() driver.find_element_by_xpath('//*[@id="root"]/div/div[3]/div[1]/div[3]/div/div/div/div[1]/div/div/div/div/div/span[2]').click() time.sleep(3) list_of_hotel = [] address_of...
import matplotlib.pyplot as plt import pandas as pd from pylab import mpl mpl.rcParams['axes.unicode_minus'] = False data = pd.read_csv(".\data\PDOS.csv", header=None) plt.figure() x1 = input("请输入x起始值\n") x2 = input("清输入x结束值\n") plt.xlim(int(x1),int(x2)) for i in range(data.shape[1]): if i % 2 == 0: plt.p...
from . import UMRLogging from . import UMRConfig from typing import List import asyncio __ALL__ = [ 'BaseExtension', 'register_extension', 'post_init' ] logger = UMRLogging.get_logger('Plugin') class BaseExtension: def __init__(self): """ Pre init logic, registering config validator,...
import httpretty import json from mock import patch from skills_ml.datasets.sba_city_county import county_lookup, URL COUNTY_RESPONSE = json.dumps([ { "county_name": "St. Clair", "description": None, "feat_class": "Populated Place", "feature_id": "4609", "fips_class": "C1",...
import logging, os from glob import glob from random import choice from emoji import emojize from utils import get_user_emo, get_keyboard, is_cat import settings def talk_to_me(bot, update, user_data): emo = get_user_emo(user_data) user_text = "Привет {} {}! Ты написал: '{}'".format(update.message.chat.first...
#!/usr/bin/python # # Find 4 sided polygons from a kinect # # Copyright (C) 2012 Mike Stitt # # 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 limitatio...
# -*- coding: utf-8 -*- import json from datetime import date, datetime from django.http import HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.db.models import F from django.contrib.auth.decorators import login_required # from a...
import grouptestdocument import logging import mdiag import pymongo import re from conversion_tools import jiraGroupToSFProjectId # TODO move this elsewhere def _stringToIntIfPossible(s): # if (typeof s == "object" && "map" in s) { # return s.map(_stringToIntIfPossible); # } else { if isinstance(...
import cv2 import os import numpy as np import h5py from keras.preprocessing.image import img_to_array from keras.applications.vgg16 import VGG16 from keras.applications.vgg16 import preprocess_input model = VGG16(weights='imagenet', include_top=False) data_dir = "/tmp/Virat_Trimed/" annotation_path = "/tmp/virat_a...
""" Tool Name: CalcADT Source Name: calc_adt_eq.py Author: Ethan Rucker Required Arguments: The path to the Geodatabase Workspace Description: Calculates average daily traffic for each speed hump request location. Calculation is the maximum sum of recorded traffic ...
import os from cpath import at_output_dir from data_generator.tokenizer_wo_tf import get_tokenizer from data_generator2.segmented_enc.runner.run_nli_tfrecord_gen import mnli_asymmetric_encode_common from data_generator2.segmented_enc.seg_encoder_common import SingleChunkIndicatingEncoder, ChunkIndicatingEncoder from m...
from .averages import my_mean def my_cov(list_x, list_y): assert len(list_x) == len(list_y) N = len(list_x) xbar = my_mean(list_x) ybar = my_mean(list_y) total = 0 for i in range(len(list_x)): total += ((list_x[i] - xbar) * (list_y[i] - ybar)) return total / N def my_var(list_x): ...
import json import gspread from oauth2client.service_account import ServiceAccountCredentials import backend.config as cf class SheetGetter(object): def __init__(self): #APIを認証 scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentia...
import cv2 import time import argparse import statistics import pandas as pd import configparser import re import os import Janus_v2_0 # Load in configuration config = configparser.ConfigParser() config.read('configurations.cfg') parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101)...
""" Roleplaying Character Generator """ from random import randint from time import sleep print("RPG Character Generator v1") print("What class would you like to be?") print("Press 1 for Elf") print("Press 2 for Warrior") print("Press 3 for Halfling") print("Press 4 for Amazon") choice = int(input("Who do you choose?...
from confidant.routes import static_files # noqa from confidant.routes import v1 # noqa from confidant.routes import saml # noqa
import collections from typing import Deque, Mapping, Optional, Sequence, Tuple from pddlenv import env from pddlenv.base import Action def generate_plan(end_state: env.EnvState, parents: Mapping[env.EnvState, Optional[Tuple[env.EnvState, Action]]] ) -> Sequence[Action]: plan:...
# 첫번째 학생은 0번을 받아 제일 앞에 줄을 선다 # 두번째 학생은 0번 또는 1번 둘 중 하나의 번호 # if 0번을 ㄷ뽑으면 그 자리에 그대로 있고 1번을 뽑으면 바로 앞의 학생 앞으로 # 세번째 학생은 0,1,2 중 하나의 번호를 뽑는다. 그리고 뽑은 번호만큼 앞자리로 # 마지막 학생까지.... # 각자 뽑은 번호는 자신이 처음에 선 순서보다는 작은 수 T = int(input()) order_nums = list(map(int,input().split())) result = [] for i, order_num in enumerate(order_num...
# Generated by Django 2.1 on 2019-07-26 23:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('siteApp', '0004_lifemodel'), ] operations = [ migrations.AlterField( model_name='lifemodel', name='extra', ...
#!/usr/bin/env python # encoding: utf-8 from lang.classfile.ConstantMemberRefInfo import ConstantMethodRefInfo from vm.runtime import MethodLookup from vm.runtime.ConstantPool import ConstantPool from vm.runtime.CpMemberRef import MemberRef class MethodRef(MemberRef): def __init__(self, constant_pool: ConstantPo...
""" 문제: - 배열의 크기 [ N ], - 숫자가 더해지는 횟수[ M ] - 그리고 K가 주어질 때 동빈이의 큰 수의 법칙에 따른 결과를 출력하시오. - K는 [ 특정한 인덱스의 수가 연속해서 더해지는 횟수 ] < 입력조건 > - [ 첫째 줄 ]에 N(2<= n <= 1,000), M(1<=M <= 10,000), K(1<= K <= 10,000)의 자연수가 주어지며 [ 각 자연수는 ] [ 공백으로 구분 ]한다. - [ 둘째 줄에 ] N개의 자연수...
from os import environ benchmark = environ['BENCHMARK'] NVBITFI_HOME = environ['NVBITFI_HOME'] THRESHOLD_JOBS = int(environ['FAULTS']) all_apps = { 'simple-faster-rcnn-pytorch': [ NVBITFI_HOME + '/test-apps/simple-faster-rcnn-pytorch', # workload directory 'simple-faster-rcnn-pytorch...
""" Реализовать некий класс Matrix, у которого: 1. Есть собственный конструктор, который принимает в качестве аргумента - список списков, копирует его (то есть при изменении списков, значения в экземпляре класса не должны меняться). Элементы списков гарантированно числа, и не пустые. 2. Метод size без аргументов, кото...
from django.conf import settings from django.shortcuts import redirect from django.core.mail import send_mail from django.shortcuts import render import sys from .forms import ContactForm, SignUpForm from .models import SignUp from django.views.generic import DetailView from django.views.generic import CreateView, Upd...
""" ЗАДАНИЕ -------------------------------------------------------------------------------- пользователь вводит 3 строки: - строка для проверки (check_str) - искомая строка (search_str) - заменяемая строка (replace_str) если в строке для проверки содержится искомая строка - заменить ее на заменяемую строк...
from flask import Flask, render_template,redirect,url_for,request from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from aplicacion import config from aplicacion.forms import formCategoria,formArticulo from werkzeug.utils import secure_filename app = Flask(__name__) app.config.from_object(c...
#!/usr/bin/env python # Copyright 2017 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import string import subprocess import sys BUILD_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__fil...
# ========================================================================================= # Copyright 2016 Community Information Online Consortium (CIOC) and KCL Software Solutions Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') def schedulingProcess( process_data): start_time = [] exit_time = [] s_time = 0 process_data.sort(key=lambda x: x[1]) ''' Sort processes according to the Arrival Time ''' for i in range(len(process_data)): read...
#!/usr/bin/env python import rospy from mavros_msgs.srv import SetMode from mavros_msgs.srv import CommandBool from mavros_msgs.srv import CommandTOL import time rospy.loginfo("Setting up ros node") rospy.init_node('mavros_takeoff_python') rospy.loginfo("Setting up rate") rate = rospy.Rate(10) def start(): setMo...
r""" .. _ref_ex_composite: Creating a Composite Section ---------------------------- Create a section of mixed materials. The following example demonstrates how to create a composite cross-section by assigning different material properties to various regions of the mesh. A steel 310UB40.4 is modelled with a 50Dx600W...
import uuid from django.core.paginator import Paginator from django.http import HttpResponse from django.shortcuts import render from uploadapp.models import User import os.path # Create your views here. # index 视图函数 def index(request): return render(request,'uploadapp/index.html') # 提交 逻辑函数 def form_logic(requ...
##Local Metrics implementation . ##https://www.kaggle.com/corochann/bengali-seresnext-training-with-pytorch import numpy as np import sklearn.metrics import torch def macro_recall(pred_y, y, n_grapheme=168, n_vowel=11, n_consonant=7): pred_y = torch.split(pred_y, [n_grapheme, n_vowel, n_consonant], dim=1) pre...
# # 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 # ...
import json import pytest from app import app @pytest.fixture def gateway_factory(): from chalice.config import Config from chalice.local import LocalGateway def create_gateway(config=None): if config is None: config = Config() return LocalGateway(app, config) return creat...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile #This form created so that we can use it instead if usercreation form. Has the add-on # of asking for eail when an account is created class UserRegisterForm(UserCrea...
from boto3.dynamodb.conditions import Key from elasticpypi import name from elasticpypi import s3 from elasticpypi.config import config TABLE = config['table'] def list_packages(dynamodb): table = dynamodb.Table(TABLE) dynamodb_packages = table.scan(ProjectionExpression='package_name') package_set = set(...
/* * @turlapatykaushik * github url : github.com/turlapatykaushik * problem description : This problem is 'Life, the universe and Everything' from HackerEarth */ while(1): x = input() if(x == 42): break else: print x
# https://www.hackerrank.com/challenges/any-or-all/problem # solution, Python 3 n, a = (input(), input().split(" "))# input list print((any([j == j[::-1] for j in a]) and (all((int)(x) > 0 for x in (a)))))
def chan_le(n): mang = [] for i in range(n): if i % 2 == 1: mang.append(-1) else: mang.append(2 - i * 0.25) return mang
from skimage import color from skimage.transform import rescale, resize, downscale_local_mean from typing import Tuple import numpy as np import torch class Converter(object): @classmethod def list2numpy(cls, mat, dtype='long'): mat = np.asarray(mat) if dtype == 'long': mat = mat.a...
# -*- coding: utf-8 -*- import llbc class pyllbcBitSet(object): """ pyllbc bitset class encapsulation. """ def __init__(self, init_bits=0): self._bits = long(init_bits) @property def bits(self): return self._bits def set_bits(self, bits): self._bits |= bits d...
from ConfigParser import SafeConfigParser from argparse import ArgumentParser from cmd import Cmd from refugee.inspector import dump_sql from refugee.manager import migration_manager from refugee.migration import Direction class RefugeeCmd(Cmd): """The command line interface for Refugee""" intro = 'Welcome ...
# -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. import logging import random import select import socket import ssl import time import io from socketpool import Connector from socketpool.util import is_connected CHUNK_SIZE = 16 * 1024 MAX_...
#!python3 import pickle import numpy from scipy import misc import matplotlib.pyplot as plt from keras.utils import plot_model from keras.models import load_model import tensorflow as tf import itertools from skimage import util from skimage import transform from argparse import ArgumentParser import sys import os imp...
# Generated by Django 3.0.7 on 2020-08-26 21:22 from django.db import migrations, models import django.db.models.deletion import django_countries.fields class Migration(migrations.Migration): initial = True dependencies = [ ('profiles', '0001_initial'), ] operations = [ migrations....
# Generated by Django 3.2.3 on 2021-05-13 20:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caretaker', '0003_auto_20210514_0151'), ] operations = [ migrations.AlterField( model_name='caretaker', name='age', ...