text
stringlengths
38
1.54M
from django.contrib import admin from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', views.adminview, name='adminview'), path('adminauth/', views.authenticateadmin, name='adminauth'), path('admi...
##Arthur A. Burkey III ##Python Drill: PyDrill_scripting_27_idle ##Title: Daily File Transfer scripting project - Python 2.7 - IDLE ##Scenario: Your company's users create or edit a collection of text files ##throughout the day. These text files represent data about customer ##orders. ##Once per day, any files that a...
import re import numpy as np import pandas as pd import pytest from woodwork.datacolumn import DataColumn from woodwork.exceptions import ColumnNameMismatchWarning, DuplicateTagsWarning from woodwork.logical_types import ( Categorical, CountryCode, Datetime, Double, Integer, NaturalLanguage, ...
#!/usr/bin/env python3 from typing import Optional, Generator from datetime import date, datetime from collections import namedtuple import re import requests AUTORENKALENDER_URL = "https://www.projekt-gutenberg.org/info/kalender/autoren.js" AUTHOR_URL_BASE = "https://www.projekt-gutenberg.org/autoren/namen/" CAMEL...
#!/usr/bin/env python # coding: utf-8 # # U-Netを用いたUAV画像セグメンテーションについて # ①データの確認、探索 # ②データの前処理 # ③U-Netのモデルの定義、トレーニング # ④U-Netモデルの性能評価の確認 # OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized. # OMP: Hint This means that multiple copies of the OpenMP runtime have been link...
# 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 u...
import threading import traceback import sys import time __author__ = 'paoolo' def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] def decode(val): bin_str = '0b' for char in val: val = ord(char) - 0x30 bin_str += '%06d' % int(bin(val)[2:]) return int(bin_str, ...
from sqlalchemy import * from migrate import * from migrate.changeset import schema pre_meta = MetaData() post_meta = MetaData() user = Table('user', pre_meta, Column('id', INTEGER, primary_key=True, nullable=False), Column('fname', VARCHAR(length=128)), Column('lname', VARCHAR(length=128)), Column('n...
import numpy as np from scipy.special import binom import time from itertools import combinations_with_replacement as cwr, starmap import matplotlib.pyplot as plt from decimal import Decimal """ Citation: https://gist.github.com/Juanlu001/7284462 """ def bernstein(n, k): coeff = binom(n, k) def _bpoly(x): ...
import sys sys.path.append(r'../engine') sys.path.append(r'../rule') import re import os from flask import Flask, request import app.settings as settings from .scanner import * # from web.upload import handle_upload # from web.git import clone from web.dashboard import ( home, scan_result, scans, vie...
""" Copyright (c) 2017-2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
from django.views.generic import ( ListView, CreateView, DetailView, UpdateView, DeleteView ) from django.urls import reverse, reverse_lazy from django.db.models import Q from django.utils.http import urlencode from webapp.models import Product, Category from webapp.forms import ProductForm, Search...
import unittest from LAB7 import * class EncryptTestCase(unittest.TestCase): # Tests for 'LAB7' def test_recursive_triangle_1(self): self.assertEqual(recursive_triangle(2,4), ' **\n *') def test_recursive_triangle_5(self): self.assertEqual(recursive_triangle(5,5), '*****\n ****\n ***...
# implement caesar cipher import cs50 import sys if len(sys.argv) != 2: print("Usage: python caesar.py k") sys.exit(1) else: # prompt user for input uin = cs50.get_string("plaintext: ") # declare variables k = int(sys.argv[1]) ascii = 0 caesar = 0 position = 0 out = "" upp...
"""Module for scanning system values""" import shutil import platform from uuid import getnode as get_mac import getpass import socket import time import threading from datetime import datetime import psutil from custom_logger import logger class SystemValue: """Class for getting system values""" def __init__...
import hashlib import time from flask import Blueprint, render_template, redirect, url_for, flash, session, request from flask_login import current_user, login_user, logout_user from aat_main.forms.auth_forms import LoginForm from aat_main.models.account_model import AccountModel from aat_main.utils.pillow_helper imp...
import os import pytest from azureml.core import Model from azure_utils.configuration.notebook_config import project_configuration_file from azure_utils.configuration.project_configuration import ProjectConfiguration from azure_utils.machine_learning.contexts.realtime_score_context import ( RealtimeScoreAKSContex...
#---------Archana Bahuguna 6th Jan 14 ------------------------- # To check how a functions arguments are passed when it is # passed as an arg to another fn #--------- Incomplete ------ def fn2call(n): print 'From inside fn2call' print n n +=1 return None def fn1(f): print 'From inside fn1...
# Robosample tools import numpy as np def func0(series): result = np.zeros((series.size)) for i in range(series.size): result[i] = (np.mean(series[:i]) / np.mean(series[i:])) return result # def func1(series): result = np.zeros((series.size)) for i in range(series.size): result[i] = (np.mean(series[:i]) / np...
import os import sys import gc import numpy as np import pandas as pd from datetime import datetime pd.options.display.max_columns = 1000 pd.options.display.max_rows = 1000 pd.options.mode.use_inf_as_na = True pd.options.display.float_format = '{:.3f}'.format float_formatter = lambda x: "%.4f" % x np.set_printoptions(...
from .duet_core import * from .duet_envs import * import pandas as pd import numpy as np def load(filename): source = DataSource(filename) senv = SensEnv({source: 1}) return DuetWrapper(np.load(filename), senv, LInf()) def zeros(x): if isinstance(x, DuetWrapper): y = unwrap(x) r = np.z...
# coding: utf-8 # # A simple tutorial to Stellar LAbel Machine (SLAM) # # **Bo Zhang** (<mailto:bozhang@nao.cas.cn>), Created on Thu Jan 19 15:48:12 2017 # # # # In[2]: import numpy as np import matplotlib.pyplot as plt import os from slam.slam import Slam from slam.diagnostic import compare_labels from slam.ap...
GCE_PARAMS = ('service_account_info', '/path/to/credentialfile') GCE_KEYWORD_PARAMS = {'project' : 'project_name', 'datacenter' : 'asia-northease1-c'}
# Copyright 2015 Google Inc. 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 law or a...
""" Binary CW example: Semicoherent MCMC search ========================================================== MCMC search of a CW signal produced by a source in a binary system using the semicoherent F-statistic. """ import os import numpy as np import pyfstat # If False, sky priors are used directed_search = True # ...
# -*- coding: utf-8 -*- import time import settings from bson import ObjectId from log import logger from mongokit import Connection, IS from ext import DynamicType, BaseModel import datetime from utils import get_year_month_day_str_ch from utils import get_hour_minute_str from utils import get_hour_minute_second_str...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Channel class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1'] ...
import threading as th class PallThread(th.Thread): stop_request = th.Event() def run(self): pass def stop(self): self.stop_request.set() if self.is_alive: self.join()
import pandas as pd import networkx as nx import numpy as np import timeit import argparse from networkx import eccentricity from networkx.algorithms import approximation as approx if __name__ == "__main__": parser = argparse.ArgumentParser(description='magic features graph compute') parser.add_argument('...
from flask import Blueprint, render_template from flask_login import current_user import os from app.forms import Print1 import datetime test = Blueprint('test', __name__) @test.route('/select_pay', methods=['GET', 'POST']) def test_select(): form = Print1() datetimes = datetime.datetime.now() now = str(...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-10-03 04:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('postfeed', '0002_auto_20170905_2350'), ] operations = [ migrations.AlterMod...
# Generated by Django 3.0.3 on 2020-02-10 19:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ghostpost', '0006_auto_20200210_1954'), ] operations = [ migrations.RemoveField( model_name='ghostpost', name='submitDate', ...
#pip install google-cloud-container google-api-python-client from google.cloud import container_v1 from googleapiclient import discovery client = container_v1.ClusterManagerClient() service = discovery.build('compute', 'v1') project_id = '' ip=[] #response = client.get_cluster(project_id,zone,cluster_name) response ...
from django.http import Http404 from api.models import TaskList, Task from api.serializers import TaskListSerializer2, TaskSerializer2 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import permis...
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: count = [0] * 101 for n in arr: count[n] += 1 res = 0 if target % 3 == 0 and count[target//3] >= 3: cnt = count[target//3] res += cnt * (cnt-1) * (cnt-2) // 6 f...
from django.db import models from django.utils import timezone from users.models import User from django.shortcuts import get_object_or_404 # Create your models here. ACCOUNT_TYPE_CHOICES = ( ('BİRİKİM HESABI','BİRİKİM HESABI'), ('KREDİLİ MEVDUAT HESABI','KREDİLİ MEVDUAT HESABI'), ('NORMAL HESAP','NORMAL H...
import psycopg2 from psycopg2 import Error try: # Connect to an existing database connection = psycopg2.connect(user="postgres", password="postgres", host="127.0.0.1", port="4000", ...
import argparse import os from os.path import split,join,splitext import xml.etree.ElementTree as ET import re import numpy as np from shapely.geometry import Polygon from debug_tool import paint_polygons from matplotlib import pyplot as plt def parse_point(s): s.split(',') _, p1, p2, _ = re.split(',|\\(|\\)...
import tkinter from datetime import * from tkinter import * from tkinter import messagebox import random from random import randint from tkinter import ttk window = Tk() window.geometry = ("300x300") window.title("Ithuba Lottery: Age Restriction") #random_no = random.randint(range(1,49),6) lottery = [] name_ = Entry(...
import scramble.puzzle import time DUMMY_SCRAMBLE = scramble.puzzle.Scramble('000', '0', '', '') class Game(object): def __init__(self, gid, time_limit, users, puzzle_database): self.gid = gid self.time_limit = time_limit self.solved = False self.solved_count = 0 self.user...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import ( setup, find_packages, ) setup( name='py-geth', # *IMPORTANT*: Don't manually change the version here. Use the 'bumpversion' utility. version='2.0.1', description="""Run Go-Ethereum as a subprocess""", long_description_m...
import argparse import math import os import subprocess import sys import tempfile import srt parser = argparse.ArgumentParser( description="Turn a video into a picture book by taking screenshots with subtitles." ) parser.add_argument("video", help="Input video") parser.add_argument("out_dir", help="Output direc...
#This object is used to represent the response data #This data will usually be destined for a database from colored import fg, bg, attr class ResultObject: #Initialize our result object def __init__(self, respID, responseSize, statusCode, time, numHeaders, numTokens): self.rs = at...
from fe_code.data_structures import geometry_data from fe_code.data_structures import process_data class systemData: def __init__(self): self.geometryData = geometry_data.geometryData() self.processesData = process_data.processData() self.displacements_calculated = False self.SIMP_c...
from lm.util import lm_tag_reader from lm import lm_consts import lm_tag_base class CTag(lm_tag_base.CTag): def __init__(self, ctx, tag): super(CTag, self).__init__(ctx, tag) d = self.parse_tag(ctx, tag) self._data = [] for info in d["symbol_list"]: self._data.append(info["symbol"] or "") self._data ...
import unittest from linkedlist import LinkedList from linkedlist import Node 23 class TestMethods(unittest.TestCase): def test1(self): ''' Test on empty list. ''' l = LinkedList() self.assertEqual(l.traverse(), []) def test2(self): ''' Test on non-empty...
from django.conf.urls import url # from django.core.urlresolvers import reverse_lazy from .views import * urlpatterns = [ url(r'^index/$', IndexView.as_view(), name="app_index"), ]
#在函数中定义函数,也就是嵌套函数 def hi(name='sixbo'): print("now you are inside the hi() function") def greet(): print("now you are inside the greet() function") def welcome(): print("now you are inside the greet() function") print(greet()) print(welcome()) print("now you are back in the hi...
import numpy as np import matplotlib.pyplot as plt from scipy.ndimage.filters import maximum_filter from scipy.ndimage.morphology import generate_binary_structure, iterate_structure, binary_erosion from scipy.signal import stft from scipy.io import wavfile from os.path import exists DEFAULT_AMP_MIN = 10 PEAK_NEIGHBORH...
# -*- coding: utf-8 -*- # GMate - Plugin Based Programmer's Text Editor # Copyright © 2008-2009 Alexandre da Silva # # This file is part of Gmate. # # See LICENTE.TXT for licence information import gtk import gnomevfs from GMATE import files from GMATE import i18n as i def error(message): """Displays on error di...
#!/usr/bin/python # -*- coding:UTF-8 -*- # Copyright (C) 2017 - All Rights Reserved # 模块名称: szt_ceph_type.py # 创建日期: 2017/8/25 # 代码编写: fanwen # 功能说明: class ItemType: osd = 0; host = 1; diskcluster = 2; root = - 3; null = -1; @staticmethod def format(): ft = '''\ type 0 osd ty...
import cv2 import os from basic_lib import Get_List from PIL import Image import numpy as np # 剪切图片生成video 为openpose做准备 def img_process(img,loadsize): try : h, w ,_= img.shape except: print("hah") result = np.zeros((loadsize,loadsize,3)) if h >= w: w = int(w*loadsize/h) ...
import pygame import sys import random """© reyan mehmood All right reserved""" # general setup pygame.init() clock = pygame.time.Clock() # Setting up the main window ScreenWidth = 1200 ScreenHeight = 700 screen = pygame.display.set_mode((ScreenWidth, ScreenHeight)) pygame.display.set_caption('Pong') # shapes ball =...
# Parses all files from WID and loads them into the DB from django.core.management.base import BaseCommand, CommandError import csv from api.models import Indicator, Country, IndicatorType class Command(BaseCommand): help = 'Load pertinent data from WID (located in WID_DATA folder) into DB' def handle(self, *...
import os, sys import shutil from datetime import datetime from chart_generate import topn_requests_donut, yearoveryear_reqeusts_volume, delete_directory from data_fetch import data as dframe from tweet_generate import api, tweet ## create directory to store program logs if not os.path.exists('logs'): os.mkdir('...
# Generated by Django 2.2.8 on 2020-01-30 08:51 import autoslug.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blogs', '0005_auto_20200130_1144'), ] operations = [ migrations.AlterField( model_name='post', name='...
import urllib dataset='mnist.pkl.gz' origin = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz' print 'Downloading data from %s' % origin urllib.urlretrieve(origin, dataset)
class HangmanLetter: def __init__(self, letter): self.letter = letter self.show = False def display_letter_space(self) -> str: if self.show: return self.letter else: return '_' def display_letter(self) -> str: return self.letter
from packet import Packet import threading class PacketConstructor: window_size = 10 data_type = 0 ack_type = 1 syn_ack_type = 2 syn_type = 3 """ Packet represents a simulated UDP packet. """ def __init__(self): self.next_seq_num = 0 self.received_packets = {}...
""" Functions for Exploratory Data Analysis Script containing functions used for performing exploratory data analysis on the cleaned headers. """ import numpy as np import matplotlib.pyplot as plt import operator from wordcloud import WordCloud, STOPWORDS import progressbar import util def analyze_basic(headers): ...
from syntax_expr import Expr ############################################################################# # # Array Operators: It's not scalable to keep adding first-order operators # at the syntactic level, so eventually we'll need some more extensible # way to describe the type/shape/compilation semantics of a...
import numpy as np output = 'coordinates_v2.dat' y1 = 25.6 y2 = 18.4 y3 = 11 data_file = '../interface_analysis/6layer_surface_data.txt' data = np.loadtxt(data_file) center_file = '6layer_thincenter_data.txt' center_data = np.loadtxt(center_file) center = data[7] width = data[5] x1 = center + (width/2) x3 = x1 x2...
import os from pathlib import Path import requests def main(): filepath = "./images/pug.png" # "./images/0-pug.png" -> "0-pug.png" file_name = filepath.split("/")[-1:][0] headers = { "pinata_api_key": os.getenv("PINATA_API_KEY"), "pinata_secret_api_key": os.getenv("PINATA_API_SECRET") ...
from collections import deque def solution(values,edges,quries): arr = [ [] for _ in range(len(values)+1) ] for i, e in enumerate(edges): arr[e[0]-1].append(e[1]-1) def firstQurie(root): vis = [0]*(len(arr)+1) q = deque() q.append(root) vis[root]=1 a...
def get_plural(number, case1, case2, case5): if 11 <= number % 100 <= 19: return case5 if number % 10 == 1: return case1 if 2 <= number % 10 <= 4: return case2 return case5
#!/usr/bin/python # -*- coding: utf8 -*- from urllib.request import urlopen from bs4 import BeautifulSoup import bs4 import requests from datetime import datetime import datetime import csv import time import re import json def save_to_file(data, filename): text_file = open(filename, "w") text_file.write(data...
# from django.db import models from djongo import models class Point(models.Model): _id = models.ObjectIdField(db_column='_id', primary_key=True) points = models.CharField( max_length=1000, verbose_name=('Json of points'), ) def __str__(self): return self.points
# 1) Open Python shell in the same location like the script # 2) >>> import prepare_jobs # 3) >>> data = prepare_jobs.rewrite() # 4) Access M by 'prepare_jobs.M' import numpy as np def rewrite(): f = open('shops.dat', 'r') d = f.readlines() cities = ['Z', 'D', 'B', 'N'] k = [] cnt ...
import sys import sqlite3 import logging from datetime import datetime from sales import load_sales_data from catalog import load_catalog_by_item_id def main(): if len(sys.argv) < 4: print("Usage: {} <catalog-file.csv> <sales-file.csv> <output.db>".format(sys.argv[0])) return 2 # TODO: check...
from cvxpy import * from cvxpy.tests.base_test import BaseTest class TestSolvers(BaseTest): """ Unit tests for solver specific behavior. """ def setUp(self): self.a = Variable(name='a') self.b = Variable(name='b') self.c = Variable(name='c') self.x = Variable(2, name='x') ...
""" Program for initial training of models """ from variables import MAX_TITLE_LENGHT, DIMENSIONS from variables import WORD_VEC_MODEL from variables import TITLE_MODEL_JSON, TITLE_MODEL_H5 from variables import TITLE_ARCH1, TITLE_ARCH2, TILE_PLOT import logging import time import pandas as pd from numpy import random...
class Solution: # @param nums, an integer[] # @return an integer def findPeakElement(self, nums): startIdx = 0 endIdx = len(nums) - 1 mid = endIdx / 2 while startIdx < endIdx : if (mid == startIdx or nums[mid-1] < nums[mid]) and (mid == endIdx or nums[mid...
import urllib, json import numpy as np import mysql.connector def compute_boundary_limit(metricsValArray,metric): #print("inside function") print "mean",np.mean(metricsValArray) print "sd",np.std(metricsValArray) lbound = np.mean(metricsValArray) - (2 * (np.std(metricsValArray))) ubound = np.mean(metricsVal...
#config file containing credentials for rds mysql instance db_username = "awsuser" db_password = "<redacted>" db_name = "testdb" db_endpoint = "<redacted>.amazonaws.com"
# -*- coding: utf-8 -*- str1="Never say Never! Never say Impossible!" str2="浪花有意千重雪,桃李無言一隊春。\n一壺酒,一竿綸,世上如儂有幾人?" s1=str1.count("Never",15) s2=str1.count("e",0,3) s3=str2.count("一") print("{}\n「Never」出現{}次,「e」出現{}次".format(str1,s1,s2)) print("\n{}\n「一」出現{}次".format(str2,s3))
import datetime import pytz from sklearn.base import BaseEstimator, TransformerMixin class ActualsAdder(BaseEstimator, TransformerMixin): def __init__(self, actuals_frame): self.actuals_frame = actuals_frame def fit(self, X, y=None): return self # Join actuals to a set of vehicle datapo...
import csv import argparse import re from urllib import request url = 'http://s3.amazonaws.com/cuny-is211-spring2015/weblog.csv' fileOpen = request.urlopen(url) readFile = fileOpen.read() decFile = readFile.decode('ascii').split('\n') for line in decFile: print(line) x = re.findall("\.jpg|\.JPG", st...
from django.db import models # Create your models here. class InsureType(models.Model): name = models.CharField(max_length=20) is_active = models.BooleanField(default=True) create_date = models.DateTimeField(auto_now_add=True) class Meta: db_table = "insure_type" def __str__(self): ...
from model.cluster import Grid from programs import Haplotyper import Readers, logging, traceback class AllelicDiversity(): """The class AllelicDiversity includes all methods and variables needed for calculation of the allelic diversity. """ def __init__(self, pool,gffFile): """The ...
import networkx as nx def findTiers(G): t1 = [] t2 = [] t3 = [] for u in G.nodes(): if G.out_degree(u) > 0 and G.in_degree == 0: t1.append(u) elif G.out_degree(u) > 0 and G.in_degree > 0: t2.append(u) else: t3.append(u) return t1,t2,t...
#!/usr/bin/python3 # -*- coding: utf-8 -*- #http://www.linux.org.ru/forum/development/1788460 #http://ps.readthedocs.io/ru/latest/strings.html #http://stackoverflow.com/questions/41204234/python-pyqt5-qtreewidget-sub-item #http://ru.stackoverflow.com/questions/511955/pyqt5-Контекстное-меню-только-на-элементах-qtreewidg...
""" biosignatures: elemental signature analysis of cyanobacteria ------------------------------------------------------------ """ from distutils.core import setup setup(name='biosignatures', packages = ['biosignatures'], package_dir = {'biosignatures':'.'}, package_data={'biosignatures': ['./*.py']...
#!/usr/bin/env python """reads stdin, removes line breaks, replaces whitespace with one space, and pipes to pbcopy""" import sys, re, os, optparse, commands class UsageException(Exception): pass def main(): parser = optparse.OptionParser(usage='stdin | %prog [options]') (options, args) = parse_input(parser)...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import mysql.connector class GuxinlangPipeline(object): def process_item(self, item, spider): db=mysql.connector.co...
from sys import stdin s = str(stdin.readline().strip()) result = [] while(s != '.'): array = [] flag = 0 for i in range(len(s)): if s[i] == '(' or ')' or '[' or ']': if len(array) == 0 and s[i] == '(' or s[i] == '[': array.append(s[i]) print(...
#create a password password= input("Create a password : ") x = True while x: if (len(password)<8 or len(password)>16): print("Password length between 6 and 12 please") break elif not re.search("[a-z]",password): print("You need at least one lower case letter") break elif not re.search("...
# https://leetcode.com/problems/sort-colors/ def sortColors(nums): counter = [0] * 3 for i in nums: counter[i] += 1 idx = 0 for color in range(3): for _ in xrange(counter[color]): nums[idx] = color idx += 1 if __name__ == '__main__': print sortColors([0, ...
# Copyright 2015 Dimitri Racordon # # 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 writi...
from mamba import description, it, before, context from expects import expect, have_key, be_none import securecscc from securecscc import origins from specs.support import fixtures from specs.support.matchers import be_an_uuid with description(origins.Falco) as self: with before.each: self.settings = se...
from keras.utils.visualize_util import plot from keras import backend as K from keras.models import load_model import numpy as np import h5py, pickle, cv2 from os.path import abspath, dirname from os import listdir import scipy as sp from datetime import datetime from shutil import copyfile from random import randint f...
from flask import Flask, request from logging.handlers import RotatingFileHandler from flask_restful import Api, Resource import json,subprocess,logging,traceback import pandas as pd app = Flask(__name__) api = Api(app) #logging.basicConfig(filename='app.log', format="%(asctime)s:%(filename)s:%(message)s") STATES_LI...
N = int(input()) # 約数をリストで返す def divisor(N): i = 1 l = [] while i**2 <= N: if N % i == 0: l.append(i) if i**2 != N: l.append(N//i) i += 1 return (sorted(l)) l = divisor(N) res = N for i in range(len(l)): a, b = l[i], N//l[i] res = min(a+...
import os import json currentDirPath = os.path.dirname(__file__) jsonFile = open(os.path.join(currentDirPath, 'source\UpperDarby.geojson')) jsonString = jsonFile.read() jsonParsed = json.loads(jsonString) mappedRecords = [] for feature in jsonParsed["features"]: sourceProperties = feature["properties"] reco...
def solution(citations): citations.sort(reverse=True) ans = 0 for idx, cite in enumerate(citations): if (idx+1) <= cite: ans = idx+1 return ans print(solution([3, 0, 6, 1, 5])) print(solution([7, 3, 3, 3, 3])) print(solution([7, 3]))
import os fName = 'Hello.txt' fPath = 'Users/slims/Documents' abPath = os.path.join(fPath, fName) print(abPath)
# -*- coding: utf-8 -*- """ Created on Mon Jul 16 17:10:14 2018 @author: OPHIR - Josh Clark """ import os import pandas as pd import xlwt import xlrd import re import datetime # 0. Set variables #Set size of basket sstkcount = 50 #Set borrow cost threshold bct = 0.05 #Set total short weight sw = -0.50 #Define Fundam...
import json from util_chat import send_prompt from util_json import save_json_to_file text = f""" You should express what you want a model to do by \ providing instructions that are as clear and \ specific as you can possibly make them. \ This will guide the model towards the desired output, \ and reduce the chanc...
import numpy as np import math import matplotlib.pyplot as plt def findProducts(index,x,value): pro = 1 for i in range(index): pro = pro*(value-x[i]) return pro def calculateTable(x,y,n): for i in range(1,n): for j in range(n-i): y[j][i] = (y[j][i-1] - y[j+1][i-1])/(x[j] -...
from django.core.management.base import NoArgsCommand, BaseCommand from django.core.mail import send_mail, EmailMessage from optparse import make_option from texas.models import * from datetime import datetime import random import string import time class Command(BaseCommand): args = "<tier_id> <count>" help =...
""" utility functions""" import re import os from os.path import basename import subprocess import gensim import torch from torch import nn from evaluate import eval_rouge from ConfManager import ConfManager def count_data(path): """ count number of data in the given path""" matcher = re.compile(r'[0-9]+\.j...