text
stringlengths
8
6.05M
# --------------------------------------------------------------------------- # # Network in Network, ICML2014, https://arxiv.org/abs/1312.4400 # pytorch implementation by Haiyang Liu (haiyangliu1997@gmail.com) # --------------------------------------------------------------------------- # import torch import torch.n...
import math n,m=[int(x) for x in raw_input().split(" ")] listA=[int(x) for x in raw_input().split(" ")] listM=[] for i in range(m): listM.append([int(x) for x in raw_input().split(" ")]) sum=0 Phi=(1+math.sqrt(5))/2.0 phi=(1-math.sqrt(5))/2.0 diff=Phi-phi def NthFib(x): return int((math.pow(Phi,x) - math.pow(phi,x))...
import csv import re from Levenshtein import distance from .itm2utm import itm2geo L_FACTOR = 3 F_CENTRES = ('datasets/Centres_of_Population_-_OSi_' 'National_Placenames_Gazetteer.csv') F_TOWNLANDS = ('datasets/Townlands_-_OSi_' 'National_Placenames_Gazetteer.csv') F_COUNTIES = ('datasets/...
# 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...
#!/usr/bin/env python #-*- coding:utf-8 -*- import re # 除外文字列の集合 exclude_words = set() def split_space(text): ''' 指定したテキストから単語を抽出します @param text: unicode @return: iter ''' words = re.split(u"\s+", text.strip()) for word in words: if word not in exclude_words: yiel...
train_results_root_folder = "/change_this_placeholder_folder" # For example "/Users/your-user/train-results" trained_using_aws_spot_instance = False
r""" Utilities (:mod:`meshless.utils`) ================================= """ import numpy as np def area_of_polygon(x, y): """Area of an arbitrary 2D polygon given its vertices """ area = 0.0 for i in range(-1, len(x)-1): area += x[i] * (y[i+1] - y[i-1]) return abs(area) / 2.0 def unitvec...
import unittest import json from .common import ApiTestBase, compat_mock class CollectionsTests(ApiTestBase): """Tests for CollectionsEndpointsMixin.""" @staticmethod def init_all(api): return [ { 'name': 'test_create_collection', 'test': CollectionsTe...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Cidade', fields=[ ('id', models.AutoField(verbo...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python ################################################################################################# # # # find_cron_records.py:reads cron job file and find ...
def bubble(lst): length = len(lst) - 1 result = [] no_swap = False while not no_swap: no_swap = True for a in range(length): if lst[a] > lst[a + 1]: lst[a], lst[a + 1] = lst[a + 1], lst[a] result.append(list(lst)) no_swap = Fals...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent # noqa: PNT20 from pants.backend.helm.util_rules.chart_metadata import DEFAULT_API_VERSION, ChartType def gen_chart_file...
name=[] age=[] gender=[] location=[] flag=0 no= int(input("Enter number of customers :")) for i in range(no): n=input("Enter name : ") name.append(n) a=input("Enter age : ") age.append(a) g=input("Enter gender : ") gender.append(g) l=input("Enter location : ") loc...
import numpy as np import tensorflow as tf from tf_util.tf_util import get_array_str import dsn.util.tf_integrals as tfi from dsn.util.tf_langevin import bounded_langevin_dyn, bounded_langevin_dyn_np import dsn.util.np_integrals as npi import os DTYPE = tf.float64 def rank1_spont_static_solve( mu_init, delta_0_i...
from city import City from population import Population from tour import Tour from tour_manager import TourManager import algorithm def parse_args(): import argparse parser = argparse.ArgumentParser(description='Using Genetic Algorithm to solve Traveling Salesman Problem.') parser.add_argument('...
import cv2 as cv import numpy as np def nothing(position): print(position) img = np.zeros((300, 512, 3), np.uint8) cv.namedWindow('image') cv.createTrackbar('B', 'image', 0, 255, nothing) cv.createTrackbar('G', 'image', 0, 255, nothing) cv.createTrackbar('R', 'image', 0, 255, nothing) switch = '0 : OFF\n 1 : ...
from flask import render_template, request from app import app import flask_mobility.decorators as mobdec from scriptMaps import n1_MapaclassMaxPB from scriptDivCompare import Compareclass from scriptPacotes import n1_PacotesclassMaxPB from pprint import pprint from dbmongo import * from datetime import * import time ...
import solver from ..translators.caesartranslator import * from ..keygenerators.numberkeygenerator import * from ..keygenerators.keygenerator import * from ..scorers.czechscorer import * class BruteForceSolver(solver.Solver): """Tries out all possible solutions""" def __init__(self, keyGenerator=NumberKeyGenerator(...
# -*- coding: utf-8 -*- # # Copyright (c) 2012, Clément MATHIEU # 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, thi...
# -*- encoding:utf-8 -*- # __author__=='Gan' # In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other # rabbits have the same color as them. Those answers are placed in an array. # Return the minimum number of rabbits that could be in the forest. # Examples: # In...
name =1 age =1 name = 2 age =2
import torch from torch import nn from torch.nn import functional as F class ResBlk(nn.Module): """ resnet block """ def __init__(self, ch_in, ch_out, stride=1): super(ResBlk, self).__init__() self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1) self...
import unittest import best_travel as b class BestTravelTest(unittest.TestCase): def test_best_sum(self): self.assertEqual(b.choose_best_sum([50, 55, 57, 58, 60], 3, 174), [55,58,60])
#!/usr/bin/env python3 # Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com # miTorch: Medical Imaging with PyTorch # Deep Learning Package for 3D medical imaging in PyTorch # Implemented by Mahdi Biparva, April 2021 # Brain Imaging Lab, Sunnybrook Research Institute (SRI) import os import time ...
import os import re dirpath = os.getcwd() dirpath+='/' chr_names=['chr1','chr2','chr3','chr4', 'chr5','chr6','chr7','chr8', 'chr9','chr10','chr11','chr12', 'chr13','chr14','chr15','chr16', 'chr17','chr18','chr19','chr20', 'chr21','chr22','chrX','chrY'] outp=open(...
#!/usr/bin/env python import re import os import time import hashlib orig_text = open('pf.scala').read() def compute_tempvalue(prog_text): digest = hashlib.sha1(prog_text).hexdigest() tempvalue = hashlib.sha1('42' + digest).hexdigest() return tempvalue for x in range(10000, 99999): new_text = re.su...
from itertools import combinations import pandas as pd from sklearn.preprocessing import (PolynomialFeatures, OneHotEncoder, StandardScaler) def onehot_conversion(X_cat, model=None): if model: X_onehot = pd.DataFrame(model.transform(X_cat), ...
from . import inline
EnsureSConsVersion(1,2) import os import sys import inspect import platform import re import subprocess from SCons import SConf def getTools(): result = [] if os.name == 'nt': result = ['nvcc', 'default', 'msvc'] elif os.name == 'posix': result = [ 'nvcc', 'default','g++'] else: ...
from django.core.cache import cache, get_cache cachekey_usr_session_profix = 'usr_session_'#roleid class cache: @staticmethod def loc_setValue(key, val): """ set local memery cache. """ c = get_cache('in_memery') c.set(key, val) @staticmethod def loc_getValue(key): """ get local memery cache. ...
# I pledge my honor that I have abided by the Stevens Honor System. # Jeffrey Eng def sum(p): total = 0 for i in p: total += float(i) return total def main(): numbers = input("Enter a list of numbers separated by spaces: ") x = numbers.split() print("The sum is", sum(x)) main()
import os import math from work.models import Site, ShiftedQty, ProgressQty, SurveyQty, ShiftedQtyExtra, ProgressQtyExtra, SiteExtra, DprQty, Log, Resolution, ResolutionLink, Log, Loa import pandas as pd from work.data import DISTRICTS_ALLOWED, DIVISIONS_ALLOWED, PROGRESS_QFIELDS, SURVEY_QFIELDS, REVIEW_QFIELDS, DPR_IN...
from itertools import groupby # -*- coding: utf-8 -*- """ Created on Fri Nov 15 12:04:27 2019 @author: CNEA """ class MATERIAL(object): _KEY__ = '' _NUM__ = None _TYPE__ = 'MATERIAL' def __init__(self, *args, **kwargs): self._NUM__ = args self._KEY__ = kwargs['KEY'] def string(...
#### Class 03 #### Reading and writing files ## Reading text files ------------------------------------------------ import sys import os os.chdir("C:/Users/wooki/Documents/GitHub/pythoncourse2018/day04") ## Read all lines as one string with open('test_readfile.txt') as f: the_whole_thing = f.read() print the_who...
import numpy as np import math class Pegasos(object): """docstring for Pegasos""" def __init__(self, reg, k, maxiter = 1000000, X=None, Y=None, check = False ): super(Pegasos, self).__init__() self.reg = reg self.k = k self.W = None self.iteration = 2 self.maxiter = maxiter self.X = X self.Y = Y s...
import time x=int(input("Please enter the first number :")) y=int(input("Please enter the second number :")) i=1 factorsof_x=set() factorsof_y=set() for i in range(1,x+1): if x%i==0: factorsof_x.add(i) print("Calculating factors of",x,"...") time.sleep(1) print(factorsof_x) for i in range(1,y+1): if y...
import numpy as np import logging from omegaconf import DictConfig import torch import torch.nn.functional as F from torch.utils.data import IterableDataset from torch.nn.utils.rnn import pad_sequence from transformers import AutoTokenizer from typing import Dict, Tuple logger = logging.getLogger(__name__) # pylint:d...
import pandas as pd import numpy as np df = pd.read_csv('../dataset/googleplaystore.csv') df['new'] = pd.to_datetime(df['Last Updated']) df['lastupdate'] = (df['new'] - df['new'].max()).dt.days df.to_csv('../dataset/pre-processed/lastUpdated.csv')
#!/usr/bin/env python # -*- coding: utf-8 -*- __mtime__ = '2019/5/5' from selenium import webdriver from time import sleep import unittest class Login(unittest.TestCase): ''' 禅道登录 ''' @classmethod def setUpClass(cls): cls.driver = webdriver.Firefox() def setUp(self): self.dri...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from models import * # Register your models here. admin.site.register(Movie) admin.site.register(Keyword) admin.site.register(Actor) admin.site.register(UserMovie)
from Pyskell.Language.PyskellTypeSystem.TypeSignature import * from Pyskell.Language.PyskellTypeSystem.TypedFunction import * from Pyskell.Language.PyskellTypeSystem.AlgebraicDataType import * from Pyskell.Language.PyskellTypeSystem.TypeClass import * from Pyskell.Language.PyskellTypeSystem.PatternMatching import *
from app.models.article import Tags async def create_tag(name: str): return await Tags.objects.create(name=name) async def get_tags(): return await Tags.objects.all()
#!/usr/bin/env python """ This uses the spotify web API to get analysis data for the track. The analysis is used to create a "smart fast forward" that advances to sections of the song (n-key). It also uses the analysis data to send note data over OSC to a synthesizer creating a very strange sort of automatic accompian...
# -*- coding: utf-8 -*- class Solution: def wordBreak(self, s, wordDict): if not s: return True wordSet = set(wordDict) result = [False] * (len(s) + 1) for i in range(len(s) + 1): if not result[i] and s[: i + 1] in wordSet: result[i] = True...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.python.target_types import ( PythonRequirementFindLinksField, PythonRequirementModulesField, PythonRequirementResolveField, PythonRequirementsField, ...
import gpt_2_simple as gpt2 import pandas as pd from tqdm import tqdm import os input_data_file = './data/2-quotes_filtered.csv' output_folder = "output/" split_quotes = pd.read_csv(input_data_file) print(split_quotes.head()) ## These were the top 20 most common topics in the dataset topics_to_keep = ['life', 'love'...
# -*-coding: utf-8-*- import numpy as np '''将文件中的数据读取至矩阵''' def openFile(filename): file_object = open(filename) fileContext = file_object.readlines() tempData = np.array(fileContext) # print tempData size = tempData.size # print size data = np.zeros([size, 5], dtype=basestring) for i ...
import pyrealsense2 as rs import numpy as np import cv2 import open3d as o3d from floodfill import Grid import scipy import matplotlib.pyplot as plt import time from tracking import processObjects NUMBER_OF_OBJECTS = 100 MAX_DIST = 0.5 config_perception = { "IMAGE_WIDTH":640, "IMAGE_HEIGHT":480, ...
# -*- coding: utf-8 -*- A=int(input()) list=['программист','программиста', 'программистов'] iA = A % 100 if iA >=9 and iA <=20: print(str(A) + " " + list[2]) else: iA = iA % 10 if iA == 1: print(str(A) + " " + list[0]) elif iA > 1 and iA < 5: print(str(A) + " " + list[1]) else: ...
import unittest from expense import Expense class TestCategoryIncome(unittest.TestCase): def setUp(self): self.expense = Expense(10, 'Food', '12-12-1234') def test_str(self): self.assertEqual(str(self.expense), '10$ - Food - 12-12-1234 - Expense') def test_repr(self): self.assert...
from xml.etree import ElementTree as et import os from sys import exit from time import sleep import traceback as trace def main(): for filename in os.listdir(path=os.getcwd() + "\\xml"): if filename.endswith(".xml"): root = et.parse("xml/" + filename).getroot() for elemen...
# -*- coding: utf-8 -*- import math import numpy as np from numpy import array from operator import add from regions import * ################################################################################ ############################### Vertices buffer ################################ ############################...
from waitress import serve from newProject.wsgi import application if __name__ == '__main__': serve(application, host = 'localhost', port='8080')
"""This contains all of the model filters for the Ghostwriter application.""" import django_filters from django import forms from .models import Client class ClientFilter(django_filters.FilterSet): """Filter used to search the `Client` model.""" name = django_filters.CharFilter(lookup_expr='icontains') ...
# preprocessing for machine learning import numpy as np import pandas as pd import pickle def process_data_for_labels(ticker): hm_days = 7 df = pd.read_csv('sp500_joined_closes.csv', index_col=0) tickers = df.columns.values.tolist() df.fillna(0, inplace=True) for i in range(1, hm_days+1): ...
import numpy as np import h5py input_lm_files = ['_prerun_result.lm'] output_figfile_prefix = "Pre" output_figfile_dir = 'figs' ## Offscreen rendering # mlab.options.offscreen = True ## Define molecules and volume cyt = 1 NA = 6.022e23 f = h5py.File(input_lm_files[0],'r') data = f['Model']['Diffusion']['Latti...
# coding: utf-8 # Part of PIT Solutions AG. See LICENSE file for full copyright and licensing details. import datetime import logging from odoo import fields, models, api, _ from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT _logger = logging.getLogger(__name__) EXCEPTION_LOG_TYPE = { ('red', _("Danger")), ...
# Generated by Django 3.1.3 on 2021-01-04 14:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0011_booking_service'), ] operations = [ migrations.AlterField( model_name='booking', name='date', ...
# _______________________________________________ ## Introduction # _______________________________________________ # Creating a prognostic model from Wisconsin Breast Cancer Data # by Victor Wan # Desc: Visualising Breast Cancer Wisconsin data and creating a predictive model based on nuclear features # Importing lib...
#__init__ constructor yapıcı metot class Personel: isim = "" soyisim = "" yas = 0 def __str__(self): return "{} {}".format(self.isim,self.soyisim) def __init__(self, firstname, lastname, age): self.isim = firstname self.soyisim = lastname self.yas = age # ...
import tkinter as tk from tkinter import messagebox class Application(tk.Frame): def __init__(self,master=None): super().__init__(master) self.master=master self.pack() self.createWidget() def createWidget(self): self.btn01= tk.Button(self,text='insert point',command=self...
import os import math import logging import time import pickle import pandas as pd import numpy as np import datetime from pygooglenews import GoogleNews import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer def tanh(x): t=(np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x)) return t def get_sta...
def sort_me(lst): lst.sort(key=lambda a: str(a)[-1]) return lst # return sorted(key=lambda a: str(a)[-1])
import sys import requests from datetime import datetime from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import sessionmaker engine = create_engine('postgresql+psycopg2://likit@localhost/research_dev') Base...
""" orignal author: Andreas Rene Geist email: andreas.geist@tuhh.de website: https://github.com/AndReGeist license: BSD addition and modification of file by Patrick Phillips summer 2019 email: pphill10@u.rochester.edu website: https://github.com/peweetheman """ import time # import resource import os import numpy as n...
from django.db import models from django.urls import reverse class Roaster(models.Model): name = models.CharField(max_length=120) city = models.CharField(max_length=120) country = models.CharField(max_length=120) website = models.CharField(max_length=120) def get_absolute_url(self): return reverse("roasters:ro...
def reverse(self): llist = self.__reverse_recursive(self.begin) llist.next = None self.begin, self.tail = self.tail, llist def __reverse_recursive(self, curr): if curr.next == None: return curr else: node = self.__reverse_recursive(curr.next) ...
# /* # Copyright 2011, Lightbox Technologies, 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 b...
t = int(input()) while t > 0: a,b,c,d = map(int,input().split()) x,y,x1,y1,x2,y2 = map(int,input().split()) x = x + (b - a) y = y + (d - c) if abs(a + b) > 0 and x1 == x2: print("NO") elif abs(c + d) > 0 and y1 == y2: print("NO") elif x1 <= x <= x2 and y1 <= y <= y2...
import sqlite3 conexion = sqlite3.connect("Tienda de mascotas") puntero = conexion.cursor() ########################################### """ puntero.execute(''' CREATE TABLE MASCOTA( ID_MASCOTA INTEGER PRIMARY KEY AUTOINCREMENT, NOMBRE VARCHAR(10), PESO INTEGER) ''') """ """ puntero.execute('INSERT INTO MASCOTA VA...
#modified maka package from https://github.com/gfhuertac/maka import os import sys import json from os.path import join, dirname from random import randint from queue import Queue from threading import Thread from time import sleep from dotenv import load_dotenv from optparse import IndentedHelpFormatter, OptionGroup,...
#!/usr/bin/env python3 import hanlp, re #, pdb from .ret_semantics import analyze_ret from .causal_semantics import analyze_causal from .arg_semantics import analyze_arg_pre, analyze_arg_post ''' dependency labels: https://universaldependencies.org/u/dep/ pos labels: https://universaldependencies.org/u/pos/ ''' HanLP...
from appium.webdriver.webdriver import WebDriver class Page(object): """ Base Class for all pageobject classes. """ def __init__(self, driver: WebDriver): self.driver = driver def set_driver(self, driver: WebDriver): """ Set class attribute driver with the input WebDriver element ...
from pandac.PandaModules import loadPrcFileData # loading prc files loadPrcFileData("", "framebuffer-multisample 1") loadPrcFileData("", "multisamples 1") #loadPrcFileData("", "fullscreen #t") #loadPrcFileData("", "window-resolution x y") # global python imports import math, sys, random #------------------------...
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.template import loader from django.urls import reverse from django.views import generic class IndexView(generic.ListView): template_name = 'typo/index.html' def get_queryset(self): ...
import tensorflow.keras as keras import tensorflow as tf import pandas tf.random.set_seed(1) dataframe = pandas.read_csv("data/breast-cancer/data.csv", index_col="id") y = dataframe.diagnosis x = dataframe.drop("diagnosis", 1) print(x.shape) model = keras.Sequential([ keras.layers.Dense(25, input_shape=(x.shape...
#!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import ColorSensor from pybricks.parameters import Port, Color ev3 = EV3Brick() colourLeft = ColorSensor(Port.S2) steering_drive = steering.drive(Motor(Port.B), Motor(Port.C)) def testing_blackline (correction, speed): ...
import jsonfield from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.db import models # Create your models here. TIME_UNIT_SELECTION = ( ('0', 'Hours'), ('1', 'Days') ) # COMPLEXITY_SELECTION = ( # ('0', '1'), # ('1', '2'), # ('2', '3'), # ...
#coding:utf-8 #!/usr/bin/env python from gclib.facility import facility from gclib.utility import currentTime, is_same_day, randint from game.utility.config import config from game.utility.email import email class infection_arena(facility): def __init__(self): """ 初始化 """ facility.__init__(self) self.b...
locators= { 'url':'https://qa-pro.domclick.ru/', 'Шапка':{'Войти в шапке': ['[class^="js-topline-auth-button-text topline__icon-link__text"]', 0] }, 'Лендинг':{ 'Кнопка Зарегистрироваться': ['[class^="ui bulky green button head-button js-signup"]', 0], 'Смотреть видео': ['...
# -*- coding: utf-8 -*- # flake8: noqa # Model changes with django-simple-history 1.5.4 from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('webplatform...
from django.contrib import admin from .models import Stock, Company, Excel # .models is models file in current directory # Register your models here. admin.site.register(Excel) admin.site.register(Company) admin.site.register(Stock)
import numpy as np # シグモイド関数 def sigmoid(x): return 1.0/(1.0+np.exp(-x)) # シグモイド関数の微分形 def sigmoid_grad(x): return (1.0 - sigmoid(x)) * sigmoid(x) # ステップ関数 def step(x): y = x > 0 return y.astype(np.int) # Relu関数 def relu(x): return np.max(0, x) # 恒等関数 def identity(x): return x # オーバーフロー...
""" CCT 建模优化代码 GPU 加速示例(3) 作者:赵润晓 日期:2021年5月6日 """ # 因为要使用父目录的 cctpy 所以加入 from os import error, path import sys sys.path.append(path.dirname(path.abspath(path.dirname(__file__)))) from hust_sc_gantry import HUST_SC_GANTRY from cctpy import * ga32 = GPU_ACCELERATOR(float_number_type=GPU_ACCELERATOR.FLOAT32) ga64 = GP...
import wx, yaml import wx.lib.scrolledpanel as scrolled from passlib.hash import sha256_crypt import collections from collections import OrderedDict import serial, glob, sys import time import struct class PasswordSettings(wx.Frame): def __init__(self, config, config_file_name): wx.Frame.__init__(sel...
#! -*- coding: utf-8 -*- from libs.pontovitoria import PontoVitoria from linhas import Linha class RotaIndireta(): def __init__(self, p1,p2, l1,l2, pontos_intersecao): self.l1 = l1 self.l2 = l2 self.p1 = p1 self.p2 = p2 self.pontos_intersecao = pontos_intersecao self...
""" Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account b...
import os def repo_exists(repo): os.chdir(f"D:\\MyProjects\\Python Projects") return os.path.isdir(repo) def check_status(repo): os.chdir(f"D:\\MyProjects\\Python Projects\\{repo}") os.system("git status") os.chdir(f"D:\\MyProjects\\Python Projects") def delete_local_repo(repo): os.chdir("...
# -*- coding: utf-8 -*- import json, base64, traceback, logging import inject, psycopg2 import pytz, datetime import dateutil.parser import uuid import pytz from model.systems.assistance.date import Date from model.systems.issue.issue import Issue class IssueModel: issue = inject.attr(Issue) ''' '...
''' Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars have been changed to 'y' chars. ''' def replaceX (str): print 'input:',str if len(str) == 0: return str if len(str) == 1 and str == 'x': return 'y' elif len(str) == 1 and str != 'x': return ...
#!/usr/bin/env python2 # # Copyright 2017-present Open Networking Foundation # # 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 requi...
from django.shortcuts import render, redirect,HttpResponseRedirect from .forms import RegisterForm from users.models import Resulttable,Insertposter from django.db import models def register(request): # 只有当请求为 POST 时,才表示用户提交了注册信息 if request.method == 'POST': form = RegisterForm(request.POST) #...
""" https://leetcode.com/problems/jump-game-vi/ You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1...
import math import os import random import re import sys # # Complete the 'nonDivisibleSubset' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER k # 2. INTEGER_ARRAY s # def nonDivisibleSubset(k, s): # Write your code here # Cre...
from re import compile, match REGEX = compile(r'((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}' r'(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$') def is_valid_IP(strng): """ is_valid_ip == PEP8 (forced mixedCase by CodeWars) """ return bool(match(REGEX, strng))
# # Copyright © 2021 Uncharted Software 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 l...
from baselines import main from dp_utils import get_noise_mul, get_renyi_divergence MAX_GRAD_NORM = 0.1 MAX_EPS = 5 BATCH_SIZES = [512, 1024, 2048, 4096, 8192, 16384] BASE_LRS = [0.125, 0.25, 0.5, 1.0] TARGET_EPS = 3 TARGET_EPOCHS = [30, 60, 120] BN_MULS = [6, 8] GROUPS = [9, 27, 81] for target_epoch in TARGET_EP...
# Generated by Django 2.0.3 on 2018-04-08 10:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('recipes', '0004_auto_20180407_1005'), ] operations = [ migrations.AlterField( model_name='medic...
#!/usr/bin/env python # coding: utf-8 import os import numpy as np from PIL import Image import matplotlib.pyplot as plt import torch import core.transforms as T from utils.plot_utils import plot_single_image from datasets.coco_to_pd import read_coco_classes from torchvision.models.detection.faster_rcnn import fast...
import multiprocessing import argparse import pprint import sys #=========1=========2=========3=========4=========5=========6=========7= def load_arguments(): argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument('--dataset_path', type=str, default='') argparser....