text
stringlengths
38
1.54M
from flask import Blueprint from flask_restplus import Api from .authToken import api as ns1 from .getPackageList import api as ns2 from .activePackageCall import api as ns3 #blueprint_api = Blueprint('api', __name__, url_prefix="/api") api = Api( title='Digital Agency APP', version='1.0', description='Di...
# This file is part of Mylar. # # Mylar 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 later version. # # Mylar is distributed in the hope that...
''' match a control xform to a joint first select a joint, then the control ''' import pymel.all as pm def match_ctrl(jnt, ctrl): control_name = ctrl.name(long = None) control_shape = ctrl.getShape() transform = pm.group(parent = jnt, empty = True) transform.zeroTransformPivots() pm.parent(transfo...
from .widgets import CropForeignKeyWidget class ImageCroppingAdmin(object): def formfield_for_dbfield(self, db_field, **kwargs): formfield = super(ImageCroppingAdmin, self).formfield_for_dbfield(db_field, **kwargs) if hasattr(db_field, 'related') and db_field.name in self.model.crop_fk_fields.ke...
import os import petl from django.shortcuts import redirect from django.views.generic import DetailView, ListView from swapi.downloader import download_new_snapshot from swapi.models import PeopleDownload class PeopleDownloadListView(ListView): queryset = PeopleDownload.objects.all().order_by("-created_timestamp...
""" A model of the solar system. Created by Zella Henderson December 2011 """ from OpenGL.GLUT import * from OpenGL.GLU import * from OpenGL.GL import * import sys import time import imageLoader """ Notes: This program requires 10 gifs and imageLoader.py. This is a mostly-to-scale replica of our solar system. The pl...
from subprocess import check_call from time import strftime def make_report_dirs(): global history, acct, google timestamp = strftime("\%m%d%Y") rep_dir = "Reports" + timestamp history = rep_dir + '\History' acct = rep_dir + '\Account' google = rep_dir + '\Google' try: ...
#Functions are blocks of code that begin with the def keyword def fun_a(): #function declaration print("I have been called") fun_a() #calling the function #passing arguments to functions def fun_a(a,b): print(a+b) fun_a(1,4) #functions that take in keyword arguments def fun_a(a=6,b=7): print(a+b) fun...
import numpy as np import cv2 from matplotlib import pyplot as plt import torch import torch.nn as nn import csv import os # No ball bearing # 221-308 inclusive # 341 - 368 inclusive WIDTH = 512 HEIGHT = 384 with open("Ball Bearing Position Data.csv", 'r') as csvfile: csvreader = csv.reader(csvfile,delimiter=',...
# -*- coding:utf-8 -*- from BeautifulReport import BeautifulReport from base.mail import sendEmai import unittest import xlrd import os class boyunshikongTestRunner(object): # 遍历找出以Test.py 结尾的文件,导入 @staticmethod def find_pyfile_and_import(rootDir): list_dirs = os.walk(rootDir) ...
def rot13_letter(inLetter): alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" inLetter = inLetter.upper() if inLetter in alphabet: letterIndex = alphabet.find(inLetter) letterIndex = (letterIndex + 13)%26 return alphabet[letterIndex] else: return inLetter def rot13(inString): ...
n, m = [int(x) for x in input().split()] i = 0 while n != 0: n -= 1 i += 1 if i % m == 0: n += 1 print(i)
from tools import * from variables import m_Bu, nbin_Bu from cuts import cuts_Bu, prntCuts, mctrue from histograms import h1, h2 from model import model_Bu_mc as model_Bu from data import mc_Pythia6, mc_Pythia8, mc_total cuts_Bu += mctrue tBu = mc_total.data logger.info('DATA chain name is %s ' % (tBu.GetName())...
#! /usr/bin/env python #coding=utf-8 import rpy2.robjects as robj from rpy2.robjects.packages import importr from rpy2.rinterface import RRuntimeError import sys import os import time import getopt from zipfile import ZipFile, ZIP_DEFLATED import cPickle def drawRHist(Motif_Pos,outpath): grdevices = i...
#!/usr/bin/env python # encoding: utf-8 """ @author: skyxyz-lang @file: 1512.py @time: 2020/10/10 14:49 @desc: """ class Solution(object): def numIdenticalPairs(self, nums): """ :type nums: List[int] :rtype: int """ dic = {} ans = 0 for num in nums: ...
import pygame from pygame.locals import * import sys import time import random # import requests from urllib.request import urlopen # from BeautifulSoup import BeautifulSoup4 as BS from bs4 import BeautifulSoup as BS from urllib.parse import urlparse, urlsplit # import pandas as pd # from PIL import Image class Game:...
# # Proposal parser. A proposal follows this structure: # # <Proposal> # <Observation> # <Visit> # <VisitGroup> # <ParallelSequenceID> # <Activity> # <Exposure> # <Detector> # <base></base> # <subarray></subarray> # ...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-01-05 06:25 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cform', '0001_initial'), ] operations = [ migrations.RemoveField( model_na...
import csv years = [] life = [] with open('data.txt') as csvfile: reader = csv.reader(csvfile, delimiter = " " ) for row in reader: years.append(row[0]) life.append(row[10]) str = '[' for age in life: str += age + ', ' str += ']' print str
import asyncio import logging from contextlib import _AsyncGeneratorContextManager from functools import wraps from typing import AsyncGenerator, Awaitable, Callable, TYPE_CHECKING if TYPE_CHECKING: from .stateful import Stateful log = logging.getLogger(__name__) _DEFAULT = object() def retry_with_proxy(*excep...
# to check the file exists using luigi # run with a custom command # python luigiImageContent.py FileImageContent --local-scheduler --fileName macbookResultPage.txt import luigi from bs4 import BeautifulSoup class FileImageContent(luigi.Task): fileName = luigi.Parameter() def requires(self): ...
#!/usr/bin/env python3 from tsdb import TSDBClient import timeseries as ts import asyncio import numpy as np async def main(): print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&') client = TSDBClient() await client.add_trigger('KalmanFilter', 'insert_ts', ['sig_epsilon_estimate', 'sig_eta_...
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from pretrained_model import pretrained_densenetSR from dataLoader import DIV2K_TrainData, DIV2K_ValidData import time import copy from math import log10 from tqdm import tqdm use_cuda = torch.cuda.is_available() ...
#coding:utf-8 import re import urllib import string import matplotlib.pyplot as plt import numpy as np def gethtml(url): page=urllib.urlopen(url) html=page.read() return html def getdata(html,number): p=re.compile(r'<td><a href="http://data.eastmoney.com/bbsj/'+number+'.html" target="_blank">(.*)</td>'...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import deque import json from odoo import http from odoo.http import request from odoo.tools import ustr from odoo.tools.misc import xlwt from datetime import datetime from datetime import date import ...
# import cdsapi # import cdstoolbox as ct import numpy as np import h5py as h5 import matplotlib.pyplot as plt class Ecosystem(): def __init__(self, model, year): self.year = year self.catastrophy = Catastrophy() self.model = model # self.client = cdsapi.Client() self.dict_t...
# coding: utf-8 from copy import copy class ComponentHtml(object): """ <TAG></TAG> """ def __init__(self, tag_name, innerHtml='', **kwargs): self.tag_name = tag_name self.innerHtml = innerHtml self.kwargs = kwargs # Every component may have associated scripts. ...
while True: try: # 输入直接转列表,方便map s = [i for i in input()] # 只要不是字母,统统换成空格 s = ''.join(list(map(lambda x: x if x == ' ' or x.isalpha() else ' ', s))) # 倒序合并 print(' '.join(reversed(s.split()))) except: break
import numpy as np from keras import backend as K # tag one-hot化 def vec2one_hot(tags, vec_size): value = tags[0] temp = np.zeros(vec_size, dtype=np.int16) # 省内存 temp[value] = 1 return temp # one_hots = [] # for value in tags: # temp = np.zeros(vec_size, dtype=np.int16) # 省内存 # ...
from FindFiles import FindFiles from SetLegend import SetLegend from Fill_mg import Fill_mg #from ERDict import ERDict from ROOT import * from array import array def SepCan(params): from ER_Dict import ER_Dict # I'm not sure why this needs to be in definition and doesn't work in header. print'In SepCan' ...
from uuid import uuid4 from django.db import models from django_paranoid.models import ParanoidModel class Section(ParanoidModel): uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True) name = models.CharField(max_length=50, default='NOT INCLUDED') icon = models.CharField(max_length=50, ...
import random import bisect import numpy as np import pandas as pd #FROM THESIS #'Create Cumulative Distribution' def cdf(weights): total=sum(weights); result=[]; cumsum=0 for w in weights: cumsum+=w result.append(cumsum/total) return result #FROM THESIS def assignActivityPa...
# Diffk # Given an array 'A' of sorted integers and another non negative integer k, find if there exists 2 indices i and j such that A[i] - A[j] = k, i != j. # Example: # Input : # A : [1 3 5] # k : 4 # Output : YES as 5 - 1 = 4 # Return 0 / 1 ( 0 for false, 1 for true ) for this problem # Try doing this in l...
from django.conf.urls import url, include from django.views.generic.base import RedirectView from rest_framework.urlpatterns import format_suffix_patterns from django.views.generic.base import RedirectView from rest_framework_jwt.views import obtain_jwt_token from . import views app_name = 'manager' urlpatterns = [ ...
import scrapy from scrapy import * import os import sys import hashlib #from CevaShipmentTrackItem.items import * #import pdb;pdb.set_trace() print(sys.path) import datetime sys.path.insert(0,os.getcwd()+'/xpath') import xpath class CEVA_shipment_track(Spider): name="ceva_shipment" start_urls=["https://etrac...
#!/home/dippouch/bin/python print 'Content-type: text/html\n' ##import cgi, os ##try: from data import data ##except: data = {} ##form = cgi.FieldStorage() ##answer = form.has_key('vote') and form['vote'].value or None ##if answer != None: ## list = data.get(os.environ['REMOTE_ADDR'], []) ## list.append(answer) ## da...
""" Matching polynomials for a sequence of random regular bipartite graphs. Sequence of regular bipartite graphs constructed in the following way. Let $G_0$ be a cycle with $k$ vertices, with $k$ even. Add another cycle with $k$ vertices; the odd (even) vertices of this cycle are linked respectively to the even (odd) ...
import unittest from day4 import * class Day4Tests(unittest.TestCase): test_passport = { "byr": 100, "iyr": 100, "eyr": 100, "hgt": 100, "hcl": 100, "ecl": 100, "pid": 100 } def test_passport_is_valid_part1(self): for key in self.test_passpo...
# coding= utf-8 """ ===================================================================== Main UI for VI - Vehicle Performance Test&Validation ===================================================================== Open Souce at https://github.com/huisedetest/VI_Project_Main Author: SAIC VP Team > """ from PyQt5.QtWidg...
# coding: utf-8 # References: Bare bones fireworks algorithm. by Junzhi Li (ljz@pku.edu.cn) # https://www.sciencedirect.com/science/article/pii/S1568494617306609 import numpy as np from numpy import * import matplotlib.pyplot as plt class BBFWA: def __init__(self,dim,maxeval,n,Cr,Ca,mapping_rule,plot_episode,ru...
from django.db import models from django.urls import reverse from datetime import datetime class Key(models.Model): key = models.CharField(max_length=15) # keys = [ # 'Ab Major', 'A Major', 'Bb Major', 'B Major', 'C Major', 'Db Major', 'D Major', 'Eb Major', 'E Major', 'F Major', 'Gb Major', 'G ...
''' Owner - Rawal Shree Email - rawalshreepal000@gmail.com Github - https://github.com/rawalshree ''' from caesar import * from hillCipher import * from rowTransposition import * from railfence import * from vigenre import * from playfair import * from monoalphabetic import * from threerotorenigma import * import sys...
nilai =0 a = 0 while True: jumlah = int(input('Masukkan total bilangan yang akan anda input:')) for a in range(1,jumlah+1): nilai2 = int(input('Masukkan bilangan ke-%d :' % a)) nilai += nilai2 mean = nilai / jumlah print('rata-rata bilangan tersebut = ',mean) break
""" Copyright John Persano 2017 File name: log.py Description: A log utility for colored Python printing. Commit history: - 03/19/2017: Initial version """ class Log: """ Log utility that will print messages according to a message level. """ class Colors: """ ...
if 'ef' not in dir(): execfile('go') basedir = '/Users/dcollins/scratch/Paper42_NewForcing/r01_test' if 'frame' not in dir(): frame = 0 for frame in [0,5]: ds = yt.load('%s/DD%04d/data%04d'%(basedir,frame,frame)) g0 = ds.index.grids[0] d= g0['density'].v db=g0['DivB'].v stat(db,frame) #...
""" Rest api urls v1 for domain """ from django.conf.urls import url from rest_framework import routers from .models.race_data.views import RaceDataViewSet, RaceDataReplayViewSet from .models.race.views import (RaceViewSet, TournamentRacesViewSet, RaceOnlineViewSet, RaceDoneViewSet, Ra...
import numpy as np from scipy import interpolate import matplotlib.pyplot as plt data1 = np.loadtxt("y2.dat") def analytical1(x): return np.cos(x)/2 + np.exp(-x)*(x/2 + 1/2) def analytical2(t): return -(np.exp(t) * np.sin(t) + t) / (2 * np.exp(t)) x = np.arange(0,2,0.01) fig1 = plt.figure() fig2 = plt.f...
TOKEN = 'NDQ0NjI2NTM3ODgzNTAwNTY0.Dd_CcQ.ddcRM8iauw9I4VkNgyNUQ3cElEM' LOOKUP_ALL = 2 LOOKUP_SEASON = 3 SEASONS = {'season3', 'season4'} INVALID_COMMAND = "**ERROR** Invalid command"
#!/usr/bin/env python3 """Calculate Shannon entropies .""" import numpy as np def HP(Di, beta): """Calculate hp function""" exponent = np.exp(-Di/beta) Pi = exponent / exponent.sum() Hi = -(Pi*np.log2(Pi)).sum() return Hi, Pi
# Author: Jenna Kwon """ LU factorization subroutine input: .dat file containing an input matrix A Output: A, L, U, error """ import numpy as np import sys import os # Subroutine to output A, L, U, and error by taking in input file from cmd line def lu_fact(file_name): array = np.loadtxt(file_name) # Dimen...
"""Routines for numerical differentiation.""" from __future__ import division import numpy as np from numpy.linalg import norm from scipy.sparse.linalg import LinearOperator from ..sparse import issparse, csc_matrix, csr_matrix, coo_matrix, find from ._group_columns import group_dense, group_sparse EPS = np.finfo(n...
from IPython.nbformat.current import reads, read from runipy.notebook_runner import NotebookRunner import json import ast import os def convert_to_endpoint(string, is_filename=True): # remove extension if is_filename: string = string.partition('.')[0] ''.join(e for e in string if e.is...
#!/usr/bin/env python # Import necessary module import os from sqlalchemy import create_engine, MetaData, Table, select print(engine.table_names()) # ['Person', 'Site', 'Survey', 'Visited'] """ survey = Table('Survey', metadata, autoload=True, autoload_with=engine) ssmt = select([survey]) print(ssmt) results...
from rest_framework import serializers from .models import College, Students, Professors class Collegeserializer(serializers.ModelSerializer): class Meta: model= College fields = '__all__' class Studentserializer(serializers.ModelSerializer): class Meta: model= Students fields ...
__all__ = ['BaseCipher', 'aes_gcm', 'plain'] import os from typing import Tuple from cryptography.hazmat.primitives.ciphers.aead import AESGCM class BaseCipher(): is_aead = False class Key(): def __init__(self, key: bytes): pass def export(self) -> bytes: return b''...
## http://developer.tobiipro.com/python/python-step-by-step-guide.html import tobii_research as tr import time import pandas as pd import keyboard from datetime import datetime output_dir = 'C:/github/ORCL_VR_EyeTracking/Data/EyeTrakcing/TobiiProPython/' # 1. Find the Eye Tracker found_eyetrackers = tr.find_all_eyetr...
""" ID: ten.to.1 TASK: fact4 LANG: PYTHON3 """ #!/usr/bin/python #Naive solution seems to work! import math file_in = open("fact4.in", "r") file_out = open("fact4.out", "w") N = int(file_in.read()) factorial = str(math.factorial(N)) for n in range(len(factorial) - 1, 0, -1): if(factorial[n] != "0"): f...
Import('*') env = env.Clone() env.PrependUnique(delete_existing=1, CPPPATH = [ '#/src/gallium/drivers', ]) nvfx = env.ConvenienceLibrary( target = 'nvfx', source = env.ParseSourceList('Makefile.sources', 'C_SOURCES') ) Export('nvfx')
from PySimpleGUI import PySimpleGUI as sg from docx import Document from docx.shared import Inches from datetime import datetime from docx.shared import Pt from docx.enum.text import WD_ALIGN_PARAGRAPH import os def doc(cliente, img=0): now = datetime.today() today = f'{now.day}{now.month}{now.year}--{now.hou...
''' 王者荣耀五杀 ''' import time hero = '诸葛亮' action = '团灭' enemy = '敌方' number = 5 unit = '人' gain = '获得' achieve = '五连绝世' #-------------击杀信息------------------- print(hero+action+enemy+str(number)+unit) time.sleep(1) #-------------获得成就------------------- print(gain+achieve)
import datetime import random import pika from pvs.utils import write_report, config class PVReport(object): def __init__(self, meter_value): """Init params: meter_value (int) incoming value from meter pv_value (int) generated photovoltaic (PV) value result_value (int) sum if meter...
import voxelocc import numpy as np import numpy.testing as npt import time import os import numpy.testing as npt import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def load_pc_file(filename): # returns Nx3 matrix pc = np.fromfile(os.path.join("./", filename), dtype=np.float64) if(pc.s...
from django.contrib import admin from .models import UserService # Register your models here. admin.site.register(UserService)
def bright(fn, x, lo, hi): """ lo から hi-1 のうち、fn の結果が x 以下となる、最も右の値 + 1 :param callable fn: :param x: :param int lo: 最小値 :param int hi: 最大値 + 1 :return: lo <= ret <= hi """ while lo < hi: mid = (lo + hi) // 2 if x < fn(mid): hi = mid else: ...
import pytube if __name__ == "__main__": video_url = "https://www.youtube.com/watch?v=Qma7wnicDnk" youtube = pytube.YouTube(video_url) video = youtube.streams.first() video.download('./video')
from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from .models import User class UserProfileSerializer(serializers.ModelSerializer): avatar = serializers.ImageField() phone = PhoneNumberField() class Meta: model = User fields = ('url',...
import os #Comentario """ Para la colocaion de de encerrar algo largo en comentarios utilizamos comillas """ os.system('cls') print('-'*15) #Porque no se pueden poner mas??? print('\tPrograma de tipo de datos',end=' ',sep= ' ') print("\tSEGUNDO PROGRAMA") #Tipo de datos #cadenas, caractere,etc... ####COMO ...
# -*- mode: python -*- # vi: set ft=python : """ Downloads a precompiled version of buildifier and makes it available to the WORKSPACE. Example: WORKSPACE: load("@drake//tools/workspace:mirrors.bzl", "DEFAULT_MIRRORS") load("@drake//tools/workspace/buildifier:repository.bzl", "buildifier_repositor...
import FWCore.ParameterSet.Config as cms HFRecalParameterBlock = cms.PSet( HFdepthOneParameterA = cms.vdouble( 0.004123, 0.00602, 0.008201, 0.010489, 0.013379, 0.016997, 0.021464, 0.027371, 0.034195, 0.044807, 0.058939, 0.125497 ), HFdepthOneParameterB = cms.vdouble( -4e-06,...
import struct class Disk: BLOCK_SIZE_BYTES = 512 # 4096 ENCODING = 'utf8' # a row is a block @classmethod def disk_init(cls, diskname, nbrOfBlocks=32): blank_block = bytearray(Disk.BLOCK_SIZE_BYTES) with open('data/{}'.format(diskname), 'wb+') as f: [ f.write(blank_bl...
nomeAtleta = True numAtleta = 0 while nomeAtleta != '': notaJurado = [] nomeAtleta = input("Nome do atleta: ") if nomeAtleta == '': break else: nota = 1 for i in range(7): jurNota = float(input("{}° jurado: ".format(nota))) notaJurado.append(j...
""" write the function of pop() or pop(index) in the DynamicArray, and also decreases 50% of the size when element numbers decreases to N//4 """ from example_dynamic_array import DynamicArray class DynamicArray2(DynamicArray): """dynamic array, add pop and associated resizing method""" def pop(self, index=No...
# Copyright 2002-2018 MarkLogic Corporation. All Rights Reserved. import boto3 import logging import hashlib log = logging.getLogger() log.setLevel(logging.INFO) # global variables ec2_client = boto3.client('ec2') def get_physical_resource_id(request_id): return hashlib.md5(request_id.encode()).hexdigest() de...
# Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count. # count_code('aaacodebbb') → 1 # count_code('codexxcode') → 2 # count_code('cozexxcope') → 2 def count_code(str): n = 0 for i in range(len(str)-3): ...
import subprocess as proc _opensslPath = None def openssl_path(): """Get full path of the openssl command line tool. Uses "which" to get the path of the "openssl" command. This can be used to execute openssl directly without setting shell = True in Popen. """ global _opensslPath if _opensslPath...
from flask import Flask, jsonify, request, render_template, redirect, url_for, flash, session from flaskext.mysql import MySQL from flask_cors import CORS, cross_origin from werkzeug.utils import secure_filename import os from flask_mail import Mail, Message import smtplib app = Flask(__name__) CORS(app) mysql = MyS...
import os class PathDataRaw: """ class generated for reading data """ data = 'data' data_abreviacion = os.path.join(data, 'abreviacion_estados.csv') class PathOutput: """ class generated for output data """ output = 'output' output_EDA_tables = os.path.join(outp...
import pycxsimulator from pylab import * import networkx as nx functioning = 1 failed = 0 capacity = 1.0 maxInitialLoad = 0.6 def initialize(): global time, network, positions time = 0 network = nx.watts_strogatz_graph(200, 4, 0.02) for nd in network.nodes: network.nodes[...
#!/usr/bin/env python3 import os import sys import subprocess from typing import TextIO import jsonpickle # python3 -m pip install jsonpickle import argparse ####################################################################################################################### ##Class Definitions #################...
from Errors.Exceptions import RepoError class Repository: def __init__(self): self._entities = [] def add(self, elem): if elem in self._entities: raise RepoError("Id already exists!\n") self._entities.append(elem) def get_all(self): return self._entities[:] ...
class GuseeGame: def guessing(self,number): if number<=100: low=0 high=100 mid=0 while low<=high: mid=(low+high)//2 c = int(input("enter 1 if number b/w "+str(low)+" -- "+str(mid)+" enter 2 if number b/w "+str(mid+1)+" -- "+str(...
import sys # print( "Name of the script: ", sys.argv[0]) eps_current = int(sys.argv[1]) print ("Input eps =" , int(sys.argv[1])) import tensorflow as tf import numpy as np import os # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=...
from django.shortcuts import render, redirect from django.views import View from django.http import HttpResponse from django.views.generic import CreateView, ListView, TemplateView, View, UpdateView from django.urls import reverse_lazy, reverse from accounts.forms import SignUpUserForm, SignUpCompanyForm, UpdateUserFor...
from bs4 import BeautifulSoup import requests string = "Zynerba Pharmaceuticals" list_1 = string.split() url="https://news.google.com/search?q=" + list_1[0] + "%20" + list_1[1]+"&hl=en-US&gl=US&ceid=US%3Aen" print(url) code=requests.get(url) print(code.text) page_soup=BeautifulSoup(code.text,'html.parser') bio_tech_com...
from django.urls import path, re_path from geofr.views import ( MapView, DepartmentBackersView, ) urlpatterns = [ path("", MapView.as_view(), name="map_view"), re_path( r"^(?P<code>[0-9AB]{2,3})-(?P<slug>[\w-]+)/porteurs/$", DepartmentBackersView.as_view(), name="department_bac...
#list is a collection of data elements which is ordered and is muttable lst=[1,5,"hii",0.5] print(lst) print(lst[1]) print(lst[-2]) print(lst[:2]) print(len(lst)) lst[2]="hello" print(lst) for x in lst: print(x) #inserting into the list lst.append(50) print(lst) lst.insert(0,"lup") print(lst) #copying a lis...
import random import numpy as np import pandas as pd from operator import add import collections from random import randint import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import copy DEVICE = 'cpu' # 'cuda' if torch.cuda.is_available() else 'cpu' class DQNAgent(torch.nn....
# See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and # rationale. from pydrake.common.cpp_param import List def _AbstractValue_Make(value): """Returns an AbstractValue containing the given ``value``.""" if isinstance(value, list) and len(value) > 0: inner_cls = type(value[0]) ...
''' Created on Jun 1, 2018 @author: pjdrm ''' import urllib.request import json import wget def gyms_info(): response = urllib.request.urlopen('https://raw.githubusercontent.com/pjdrm/PgP-Data/master/data/region-map.json') html = eval(str(response.read())) print(html) #region_map_json = json.loads(htm...
# -*- coding:UTF-8 -*- #!/usr/bin/env python3 import json schema = { "股权质押信息": ['股东名称', '是否为第一大股东及一致行动人', '质押股数', '质押开始日期', '解除质押日期', '本次质押占其所持股份比例', '质权人', '用途'] } print(schema) with open('股东股权质押事件', 'w') as fo: fo.write(json.dumps(schema, ensure_ascii=False, indent=4))
import math #수학 모듈 사용 #절댓값 알고리즘 1 (부호 판단) #입력 : 실수 a #출력 : a의 절댓값 def abs_sign(a): if a >= 0: return a else: return -a #절댓값 알고리즘 2 (제곱-제곱근) #입력 : 실수 a #출력 : a의 절댓값 def abs_square(a) : b = a * a return math.sqrt(b) #수학 모듈의 제곱근 함수 print(abs_sign(5)) print(abs_sign(-3)) p...
import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mcdonalds.settings') app = Celery('mcdonalds') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'print_every_5_secon...
import json import urllib2 from flask import Blueprint, request, Response from utils.RobinhoodUtil import RobinhoodUtil robinhood_api = Blueprint('robinhood_api', __name__) robinhood_service = RobinhoodUtil() rh_client = robinhood_service.get_client() @robinhood_api.route("/login", methods=['POST']) def login(): ...
from apps.yvr.forms import PledgeLanding, ShareStatus, EmailInvites from . import YVRRequestHandler from tipfy import Response, abort, redirect #### MAIN LANDING class LandingHandler(YVRRequestHandler): def get(self): """Simply returns a Response object with an enigmatic salutation.""" p...
from django.apps import AppConfig class FirstApp1184077Config(AppConfig): name = 'first_app_1184077'
# -*- coding: utf-8 -*- """ Various support functions for NSS work """ # Imports import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import neighbors from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.utils import shuffle from sklearn.model_selection imp...
import discord from discord.ext import commands from near.database import get_embeds from near.database import get_main from time import time as nowtime from platform import python_version as cur_python_version from datetime import timedelta as dttimedelta class General(commands.Cog): def __init__(self, client: co...
""" Process small MIDI files into a Numpy-Trainingssetfile Files have to be in seperate folders for train, test and valid -> cli-options """ from math import floor from typing import List, Dict import numpy as np from common import * import click def get_multiple_number_greater_than(factor: float, target: float): ...
# -*- coding:utf-8 -*- import unittest import os import sys import traceback import json import time import shutil sys.path.append('..') sys.path.append('../..') testpath = os.path.dirname(os.path.realpath(__file__)) sys.path.append(testpath) from utils.logger import LoggerInstance as logger from utils.parametrizedte...
#=============================================================================== # Project Euler: Problem 5 - Smallest multiple # # __author__ = "Zenith" # __copyright__ = "Copyright 2013 by RockStone" # __license__ = "GPL" # __email__ = "zenith at rockstone dot me" #====================================================...