text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- # author: Григорий Никониров # Gregoriy Nikonirov # email: mrgbh007@gmail.com # import sys sys.path.append('../src/') from GLib import * #~ from reportgenerator import * def main(): #~ a=TXTReportGenerator('/home/gbh007/report.txt') b=HTMLReportGenerator('/home/gbh007/report.h...
username = "EMAIL_ADDRESS" password = "YOUR_PASSWORD" receiver = "EMAIL_ADDRESS" sender = "EMAIL_ADDRESS" port = 0 host = "YOUR_HOST" radius = 5 mailing = False
# -*- coding: utf8 -*- import os.path import torch import torch.utils.data as data from data.image_folder import make_dataset from PIL import Image import random import nibabel as nib from abc import ABC, abstractmethod import numpy as np from util.myutils import normalizationminmax1 from util.myutils import...
import numpy as np import pyccl as ccl from scipy.integrate import simps def test_iswcl(): # Cosmology Ob = 0.05 Oc = 0.25 h = 0.7 COSMO = ccl.Cosmology( Omega_b=Ob, Omega_c=Oc, h=h, n_s=0.96, sigma8=0.8, transfer_function='bbks') # CCL calculat...
from datetime import datetime from spotify_api import SpotifyAuthAPI, MY_SPOTIFY_ID def get_playlist_track_ids(owner_id, playlist_id, client=None): client = client or SpotifyAuthAPI() playlist_obj = client.get('users/{}/playlists/{}'.format(owner_id, playlist_id)) track_objs = playlist_obj['tracks']['it...
from threading import RLock class LWW_implementation: def _init_(self): self.add_set = {} self.remove_set = {} self.lock_add = Rlock() self.lock_remove = Rlock() def add(self, element, timestamp): ''' Purpose: This function adds an element to the ad...
soundscapes = ['mountain', 'pond', 'sea'] ### GLOBAL PARAMS OF A SOUNDSCAPE vocal_parameters = None bass_parameters = None soundfont = None background = None ### POND pond_vocal_parameters = { 'type': 'vocals', 'dir': 'models/Anatra40K', 'threshold': 1, 'quiet': 20, 'autotune': 0, 'loudness_shift': 0, ...
#! usr/bin/python3 # Luis del Peso # Oct 2016 # prueba Biopython for HPBBM ## requires two arguments: file with TF binding sequences and fasta file with sequences to scan from Bio import SeqIO for seq_record in SeqIO.parse("MITF_reg.fasta", "fasta"): print(seq_record.id) print(repr(seq_record.seq)) print...
# CSV creation and writing import os from pathlib import Path import csv # REGEX for formatting/clean-up import re # Third party libraries # MARC processing/extraction import pymarc from pymarc import MARCReader from pymarc import marc8_to_unicode # CSV creation and writing import os from pathlib import Path import c...
print("HTTP/1.1 200 OK") print("Access-Control-Allow-Origin: *") print("Content-Type: text/json\n") import requests import json, settings import pandas as pd # import os, sys import os import pandas as pd import cgi, cgitb import numpy as np from os import getenv import pyodbc import os.path import base_leer as bl i...
#!/bin/env python import os, glob, ROOT, subprocess submitVersion = "2020-07-10" mainOutputDir = '/eos/cms/store/group/phys_egamma/tnpTuples/%s/%s' % (os.environ['USER'], submitVersion) def system(command): return subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT) # Check if valid ROOT file exi...
from project import * from Function import * def main(): #you can try by using a file to read in Station_Dic={ 1:Station(1,3,[498],[-400]), #注意这里要求是列表形式 2:Station(2,3,[498],[-400]), 3:Station(3,3,[498],[-400]), 4:Station(4,3,[498],[-400]), #注意这里的ID号是唯一标识,必须相同 5:...
from random import randint from time import sleep jogo = ['PEDRA','PAPEL','TESOURA'] pc = randint(1,3) print('-='*30) print(' VAMOS JOGAR JOKENPOW') print('-='*30) jogador = int(input('Digite O numero correspondente a sua Jogada: \n\n' 'PEDRA = [1]\n' 'PAPEL...
import pafy import concurrent.futures as fut from bs4 import BeautifulSoup as Soup import requests from concurrent.futures import ThreadPoolExecutor, as_completed from util import parseInput query = 'http://www.youtube.com' def generateUrls(query_str): URLS = list() links = list() html_page = requests.ge...
x = float(input('Podaj liczbe: ')) #if x == 7: # print ('Ta liczba to 7') #else: # print ("Ta liczba jest podzielna przez 3: ", x % 3 == 0) # print ("Ta liczba jest nieparzysta: ", x % 2 != 0) # print("Ta liczba jest wieksza od 10: ", x > 10) print ('Ta liczba to 7', x==7,'\n' "Ta liczba jest podzi...
from itertools import combinations from collections import deque import random # --------------- NOTES from instructions / instructors ------------ '''The functionality behind creating users and friendships has been completed already via functions below : addFriendship + addUser''' """ POPULATION GRAPH FUNCTION _ T...
import shelve with shelve.open("ShelfTest") as fruit: fruit["orange"] = "a sweet, orange, citrus fruit" fruit["apple"] = "red and round" fruit["grape"] = "a small, sweet fruit growing in bunches" print(fruit["apple"]) print(fruit["grape"])
import json from aws.rds.PatientPostgres import PatientPostgres from flask import Flask, request, Response from flask_restplus import Resource, Api from flask import jsonify from flask_api import status app = Flask(__name__) api = Api(app) api = api.namespace('', description="List Patients") db = PatientPostgres() _...
""" tags for common error attributes """ import traceback from ddtrace.constants import ERROR_MSG from ddtrace.constants import ERROR_STACK from ddtrace.constants import ERROR_TYPE from ddtrace.internal.utils.deprecation import deprecated from ddtrace.internal.utils.deprecation import deprecation __all__ = [ERROR_M...
from sklearn.dummy import DummyClassifier from sklearn.metrics import accuracy_score from sec_2a import split_data class TrivialClassifier(DummyClassifier): """ A trivial classifier that always predicts a constant label """ def __init__(self, label=-1): super().__init__(strategy='constant', ...
class section: def __init__(self,b,e): self.begin = b self.end = e def binarySearch(val,sections,begin,end): assert(begin>=0) assert(end<len(sections)) while begin<end: middle = (begin+end)/2 if sections[middle]<val: begin=middle+1 elif sections[middl...
import turtle import numpy class tplot: def __init__(self, func, interval: (float, float, float), margin=1.5): self.interval = interval self.func = func self.margin = margin def plot(self): # get all cords vals = [] s = self.interval[0] while s <= self....
""" Tests that do not need to connect servers """ from django.test import TestCase from django.db.models import DO_NOTHING from salesforce import fields, models class EasyCharField(models.CharField): def __init__(self, max_length=255, null=True, default='', **kwargs): return super(EasyCharField, self).__init__(max...
# ------------------------------------------------------- # Assignment 2 # Written by Johnston Stott (40059176) # For COMP 472 Section ABIX – Summer 2020 # -------------------------------------------------------- import math import os import numpy as np from matplotlib import pyplot as plt from sklearn.metrics import...
import sys sys.path.append(r'/run/media/pengfei/OTHERS/pythonlibs') import numpy as np from lib_time import MeasureT from lib_timetable import Stations, Timetable from lib_osm import queryRoute from lib_plot import jointplotFromLists ######### 加载车站位置数据 fl = "/run/media/pengfei/OTHERS/Code/Data/ChinaRailway/China_Statio...
# -*- coding: utf-8 -*- """ Created on Thu Dec 17 19:55:00 2020 @author: Lansana Diomande This script searches the French eAIP folder in order to insert in the database the list of charts for each airport. """ import os; import mysql.connector mydb = mysql.connector.connect( host="mysql-asanio.alwaysdata.net", ...
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if nums == []: return 0 cell = [1] for i in range(1,len(nums)): cell.append(1) for j in range(i): if(nums[j] < nums[i]): cell[i] = max(cell[i], cell...
# Generated by Django 2.0.6 on 2018-11-21 21:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('request', '0030_updateamountlog_comment'), ] operations = [ migrations.AddField( model_name='requestcandidate', name...
from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.contrib.auth.hashers import make_password # Create your models here. class UserManager(BaseUserManager): def create_user(self, username, password=None): if not userna...
# coding: utf-8 from sqlalchemy import BigInteger, Boolean, Column, DECIMAL, Date, DateTime, Float, ForeignKey, Index, Integer, Numeric, SmallInteger, Unicode, text from sqlalchemy.dialects.mssql import DATETIMEOFFSET, UNIQUEIDENTIFIER from sqlalchemy.sql.sqltypes import NullType from sqlalchemy.orm import relationship...
# Generated by Django 3.1 on 2020-10-07 18:28 import api.models import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0063_auto_20201006_1110'), ] operations = [ migrations.AlterField( ...
# -*- coding: utf-8 -*- """ Created on Fri Feb 14 21:01:06 2020 @author: 14001 """ import itchat from itchat.content import * import os import time import xlrd import xlwt # 文件临时存储页 rec_tmp_dir = os.path.join(os.getcwd(), 'tmp/') # 存储数据的字典 rec_msg_dict = {} # 特定的群聊id from_group = '' # 保存数据 def saveData(msg_id, ms...
@Subroutine def ExSkillInit(): MinimumDamagePct(10) Unknown30065(0) @Subroutine def InvSkillInit(): Unknown30065(100) @Subroutine def PartnerSkillInit(): AttackP1(70) Unknown11042(1) @State def EMB_CE(): def upon_IMMEDIATE(): Unknown2007() Unknown1007(240000) Unknown2...
from PIL import Image while 1!= 3: codeLib = '''@$#%!^. ''' count = len(codeLib) def transform(image_file): image_file = image_file.convert("L") codePic = '' for h in range(0,image_file.size[1]): #纵方向 for w in range(0,image_file.size[0]): gray = image_fi...
# -*- coding: utf-8 -*- """ Created on Tue Dec 3 17:15:07 2019 @author: hoeren """ import sys from PyQt5 import QtWidgets app = QtWidgets.QApplication(sys.argv) tree = QtWidgets.QTreeWidget() tree.setHeaderHidden(True) project = QtWidgets.QTreeWidgetItem(tree) project.setText(0, "HATC") doc...
# Tui Popenoe # Challenge 160 Trigonometric Triangle Trouble """ Implementation to solve for unknown values in a triangle given a variable number of known angles and sides. Accepts input as a file or a series of command line arguments. """ import math a = 0.0 b = 0.0 c = 0.0 A = 0.0 B = 0.0 C = 0.0 sid...
import networkx as nx import matplotlib.pyplot as plt import random N = 10 G = nx.grid_2d_graph(N,N) pos = dict( (n, n) for n in G.nodes() ) labels = dict( ((i, j), i * 10 + j) for i, j in G.nodes()) #Adding colors to nodes to represent diffrent type of people def display_graph(G): nodes_g = nx.draw_n...
import cv2 #image #img = "images/cars.png" video = cv2.VideoCapture("images/p.mp4") #pre defined detect = "CarDetector.xml" pedestrain_tracker = "haarcascade_fullbody.xml" #classifier carcv = cv2.CascadeClassifier(detect) Ptracker = cv2.CascadeClassifier(pedestrain_tracker) #run forever while True: #read current f...
numbers = [10086, 10000, 10010, 9558] names = ['中国移动', '中国电信', '中国联通'] for t in zip(numbers, names): print(t) for x, y in zip(numbers, names): print(y, '的客服电话是:', x) x, y = (10086, '中国移动') # 序列赋值 # zip函数的实现示例2: def myzip(iter1, iter2): it1 = iter(iter1) # 拿出一个迭代器 it2 = iter(iter2) while True...
#from django.http import HttpResponse from django.shortcuts import render_to_response#, get_object_or_404 from django.template import RequestContext from madrona.raster_stats.models import RasterDataset, zonal_stats from madrona.unit_converter.models import convert_float_to_area_display_units from analysis.utils import...
#!C:\Python27\python.exe import MySQLdb import cgi import os import Cookie print("Content-type: text/html") print if 'HTTP_COOKIE' in os.environ: cookie_string=os.environ.get('HTTP_COOKIE') c=Cookie.SimpleCookie() c.load(cookie_string) try: dat=c['mou'].value except KeyError: print "The cookie was not set or ...
''' Created on 01-Nov-2018 @author: techsid ''' from train import classifier from train import preprocess from prediction.predict import prediction preprocess.wav_to_spec('/Users/techsid/Desktop/eded/dur_1/eded/crawling_man/crawling_man_75m/') preprocess.wav_to_spec('/Users/techsid/Desktop/eded/dur_1/eded/crawlin...
from mock import MagicMock from nose.tools import * import concurrent from distdb import Object, ValueSet from .util import * from .util import _object_availability, _checkAsset def test__object_availability(): assert_equal(_object_availability(Object('qwe123', { }), 1500), (0, 0)) assert_equal(_object...
def solution(n): answer = 0 s = ''.join(sorted(str(n), reverse=True)) answer = int(s) return answer print(solution(118372))
# coding: utf-8 # comeco palavra # raquel ambrozioo n = int(raw_input("n? ")) c = raw_input("c? ") while n > 0: palavra = raw_input("palavra? ") n -= 1 if palavra[0].lower() == c or palavra[0].upper() == c: print "%s comeca com %s" % (palavra, c) else: print "%s nao comeca com %s" % (palavra, c)
import requests resp=requests.get("https://reqres.in/api/users") code=resp.status_code assert code == 200, "code doesn't match" print(resp.json()) print(resp.headers)
import requests print("hola mundo") lista = [] for i in range(1, 101): lista.append(i) print(lista) print("Nadie dice nada") def suma(a,b): return a+b tupla_ejemplo = ('Carla', 'F') print(tupla_ejemplo) lista = [10, "Hola", 40, "Este es otro texto", (3,4), [1,2,3,4,5], suma] funcion_suma = lista[6] prin...
#!/usr/bin/env python #! coding: utf-8 import os clear = lambda: os.system('clear') clear() print "Bienvenido" print "----------" salir = 2 while salir == 2: num = input("\nIngrese un número: ") print " " for i in range(1,11): print num,"x",i,"=",(num * i) print "\nDesea salir?:" print "1.Si" print "2...
from picamera import PiCamera import time camera = PiCamera() for i in range(5): camera.start_preview() time.sleep(5) camera.capture("./image%s.jpg" % i) camera.stop_preview()
from math import floor, ceil import time # Gives max depth of recursion error def power(a, b): if b == 0: return 1 if b == 1: return a return a * power(a, b - 1) # Works without error def power_opt(a, b): if b == 0: return 1 if b == 1: return a return power_op...
""" Library to handle fuzzy matching of amtrak station names to get amtrak station codes. """ import csv import pathlib import os from fuzzywuzzy import process AMTRAK_STATIONS_CSV = os.path.join(pathlib.Path(__file__).parent, 'Amtrak_Stations.csv') def load_stations(): """ Loads the stations CSV into a map k...
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ res=[] def helper(left,right,path): if right<left: return if not left and not right: res.append(path) i...
""" search each value in the list and return if value found """ def sequentialsearch(list,searchvalue): length = len(list) found = False pos = 0 while pos < length and not found: if list[pos] == searchvalue: found = True else: pos = pos + 1 testlist = [1,2,3,4,7...
from radical.entk import Task from pprint import pprint import os def create_analog_select_task(i, stage_cfg, global_cfg, files_dims): """ This function creates a analog selection task for the specified task number. :param i: The task number. :param stage_cfg: The configuration dictionary for this sta...
from flask.ext.wtf import Form, validators, Required, Length from flask.ext.wtf import TextAreaField, TextField, SubmitField, PasswordField, IntegerField, BooleanField, SelectField, RadioField, SelectMultipleField from model import * class LoginForm(Form): email = TextField('Email', [validators.Email(message= (u'I...
import tkMessageBox import copy import random from mapper import * class Scheduler(object): def __init__(self, observers, course_codes, semester, user_options, start_end_times): self._observers = observers self._course_codes = course_codes self._semester = semester self._user_filt...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Run rasim batchly Created on Wed Nov 12 02:50:02 2014 @author: Mehmet Emre """ import argparse parser = argparse.ArgumentParser(description="rasim - A radio network simulator") parser.add_argument('-j', '--jobs', action='store', help='number of parallel jobs to run'...
from __future__ import absolute_import from .base import ActivityEmail class NoteActivityEmail(ActivityEmail): def get_context(self): return {} def get_template(self): return 'sentry/emails/activity/note.txt' def get_html_template(self): return 'sentry/emails/activity/note.html'...
import requests import json db_id = '732149c4f1574f638da780692a2e7d4f' token = 'secret_MFhgeM2cnADVTdwet09QP6BF40bmLt7ltBlssPk5WK0' headers = { "Authorization": "Bearer " + token, "accept": "application/json", "Notion-Version": "2022-06-28" } url = 'https://api.notion.com/v1/databases/' + db_id res = req...
from django.shortcuts import render from django.http import JsonResponse from main import staticData import numpy as np import json def getFreSetViewData(request): res = [] if request.is_ajax(): temp = request.POST.get("key") freSet = eval(json.loads(temp)) freSets = staticData.get_valu...
import random import string from selenium import webdriver import time from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome(executable_path=r"C:\Selenium\chromedriver.exe") driver.get('https://www.dominospizza.cl') time.sleep(3) driver.find_element_by_xpath("//*[@id='iniciaSesion']").clic...
import json import conciliator import datetime class Document: id: str status: str totalPages: int name: str type: str comment: str fields: object user_tag: object nb_lines: int DATA_QUERY = [{ "id": "goupix_invoices", "pagination": { "sort": { ...
import networkx as nx import matplotlib.pylab as plt def plot_multigraph(graphs, n_rows, n_cols, node_size=100, fig_no=1): fig = plt.figure(fig_no) fig.clear() for k, (name, G) in enumerate(graphs): plt.subplot(n_rows, n_cols, k + 1) plt.title(name) nx.draw(G, node_size=node_size) return fig def ...
from django.contrib import admin from .models import article, article_comment admin.site.register(article_comment) admin.site.register(article)
import random from torch.autograd import Variable from torchtext.data import Dataset, Example, Field from rnng.iterator import SimpleIterator random.seed(12345) class TestSimpleIterator(object): TEXT = Field() examples = [ Example.fromlist(['John loves Mary'], [('text', TEXT)]), Example.fro...
''' Test Data Module ''' import mlab_api.data.data_utils as du from mlab_api.os_utils import read_json URL_DELIM = "+" def test_location_key_fields(): ''' Test get_location_key_fields ''' config_filename = 'bigtable_configs/client_loc_by_day.json' config = read_json(config_filename) assert le...
from .parser import Scraper from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from .utils import validate_url # Create your views here. @api_view(['POST']) # @validate_url def flatten_web(request, **kwargs): """ Send a post request ...
# -*- coding: utf-8 -*- import re import logging from pyramid.httpexceptions import HTTPServerError, HTTPOk, HTTPForbidden from pyramid.view import view_config from pyramid.response import Response from stalker.db.session import DBSession # The seemingly unnecessary imports in the next line are important for some fu...
import logging from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.executors.pool import ProcessPoolExecutor, ThreadPoolExecutor #from django_apscheduler.jobstores import register_events, register_job from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job ...
from django.db import models class Instance(models.Model): name = models.CharField(max_length=100,unique=True) status = models.CharField(max_length=30) created_at = models.DateTimeField() class Meta: ordering = ['name'] def __str__(self): return self.name class Test(models.Mode...
"""Definition of the Exam content type. """ import random from zope.interface import implements from Products.Archetypes import atapi from Products.ATContentTypes.content import folder from Products.ATContentTypes.content.schemata import finalizeATCTSchema from Products.CMFCore.utils import getToolByName from eduin...
import datetime as dt from django.conf import settings from workbench.accounts.features import FEATURES def workbench(request): today = dt.date.today() return { "WORKBENCH": settings.WORKBENCH, "FEATURES": FEATURES, "DEBUG": settings.DEBUG, "TESTING": settings.TESTING, ...
data = [] count = 0 sum_n = 0 large = [] nice = [] with open("reviews.txt", "r") as f: for line in f: data.append(line) count = count + 1 if count % 200000 == 0: print(len(data)) print("總共有", len(data), "筆資料") for n in data: sum_n = sum_n + len(n) print("平均每筆留言有", sum_n/len(data), "個字") for n in data...
import os from pathlib import Path module_path = os.path.dirname(__file__) # needed because sample data files are located in the same folder def get_path(fname=None): if not fname: return str(Path(module_path).parents[0]) return str(Path(module_path).parents[0]) + fname
from __future__ import division import sys from display import * class MyForm(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) self.sunrise_time = QtCore.QTime(7, 44, 00) self.ui.lcdSunriseTime...
import sys from collections import defaultdict class Node: def __init__(self, id): self.id = id self.status = 0 # 0 for peace, 1 for war self.sibling = set() self.owner = 0 # 0 for A, 1 for B def add_sibling(self, node): self.sibling.add(node) class Graph: def __in...
# *-- coding:utf-8 --* """Configuration for the Neutrona theme templates and regions. Attributes: verbose_name: name of theme to be displayed in the admin interface layout_templates: dictionary defining regions for the available templates """ from django.utils.translation import ugettext_lazy as _ verbose_na...
from util.imdb_scraper import ImdbScraper, FakeScraper import json FILENAME = "movies.db" class MovieDataSource: """Fetches movie data from either disk or the web. Handles persistence via file i/o.""" def __init__(self, scraper): self.scraper = scraper def movie_to_doc(self, movie): """C...
from rest_framework_nested import routers from . import views app_name = 'api' urlpatterns = [] # Начальные роутеры (пользователи для бота и списки покупок для обыного # пользователя) router = routers.SimpleRouter() router.register( 'purchaselist', views.PurchasesListsViewSet, basename='purchaselist') r...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging import copy import datetime from collections import OrderedDict from snisi_core.models.Periods import MonthPeriod, D...
from utils.constants import DB_NAME import json from typing import List from bson import json_util from bson.objectid import ObjectId from mongoengine import connect from mongoengine.connection import disconnect class DBEngine: def __init__(self, db_name: str = DB_NAME): self.db_name = db_name s...
from tkinter import * import tkinter.messagebox import adv_backend from tkinter import ttk from ttkthemes import themed_tk as tk import backend class make_contract: def __init__(self): root = tk.ThemedTk() root.get_themes() root.set_theme('radiance') root.title('Make a C...
""" JWT common implementations """ import jwt from src.config import CONFIG def sign(user_data): """ Create a new signature session token for a specific user :param user_data: JSON user information to be signed :return: signed token """ conf = CONFIG["jwt"] token = jwt.encode(user_data...
"""API that returns the user stats. I expect this to be called frequently as different actions occur.""" import datetime as dt from dateutil.relativedelta import relativedelta import pytz import traceback import pandas as pd from flask import jsonify, request, make_response from sqlalchemy import func from app import d...
# coding=utf-8 __author__ = 'Tang' from flask import render_template, url_for, request, redirect, session from app import app, file, model from time import time from datetime import datetime from bson import ObjectId, errors from werkzeug import secure_filename from helper.session import decompose_user, admin_session ...
import sys from collections import OrderedDict import numpy as np from pymodaq.daq_utils.config import Config from qtpy import QtWidgets, QtCore from qtpy.QtCore import QObject, Signal, Slot from pymodaq.daq_utils.parameter import ioxml from pymodaq.daq_utils.daq_utils import linspace_step, odd_even, greater2n from p...
import os import logging from inaugurator import sh USER_SETTINGS_DIR = "etc/default" USER_SETTINGS_FILENAME = "grub" def modifyingGrubConf(userSettingsFileHandler, existingConfiguration, serialDevices, passThroughArgs): serialDevices = serialDevices or [] passThroughArgs = passThroughArgs or "" wasGrub...
import requests from pprint import pprint import json url1 = "https://swapi.dev/api/vehicles/4/" resp_obj = requests.get(url1) print(resp_obj.status_code) print(type(resp_obj)) pprint(resp_obj.json()) print(resp_obj.headers["content-type"]) url2 = "https://www.yahoo.com" resp = requests.get(url2) print(resp.status_c...
def readfile(): #reads str into memory calls it f text_file = open("file.txt","r") f = text_file.read() return f
import deep_architect.utils as ut # Make sure that only one GPU is visible. if __name__ == '__main__': cfg = ut.get_config() if cfg['use_gpu']: import deep_architect.contrib.misc.gpu_utils as gpu_utils gpu_id = gpu_utils.get_available_gpu(0.1, 5.0) print("Using GPU %d" % gpu_id) ...
# Generated by Django 2.2.5 on 2020-01-28 05:37 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('carreras', '0014_carrera_activa'), ] operations = [ migrations.RemoveField( model_name='carreras', name='results', )...
""" https://leetcode.com/problems/maximum-subarray/ Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. """ class Solution: ...
# cross site request forgery prevention WTF_CSRF_ENABLED = True SECRET_KEY = 'cryptographic-token-change-tehe' # email server MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 465 MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_USERNAME = 'username@gmail.com' MAIL_PASSWORD = 'password' # administrator list ADMINS = ['username...
#!/usr/bin/env python """ Braccio Robotico Matera - Fanny Downloader daemon """ import urllib.request from pathlib import Path import time, signal import logging from logging.handlers import TimedRotatingFileHandler FOLDER_PATH = '/opt/fanny/Drawings/downloads/' BASE_URL = 'http://www.appius.it/matera/' #GCODE_FOL...
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.db.models import Sum from django.dispatch import receiver from django.template.defaultfilters import slugify from django.urls import reverse from autoslug import AutoSlugField # Fetching ...
from django.urls import path from django.contrib.auth.views import LogoutView from .views import login_page, register_page, guest_register_page urlpatterns = [ path("login/", login_page, name="login"), path("register/", register_page, name="register"), path("logout/", LogoutView.as_view(), name="logout"),...
class fraction: def __init__(self, num, den): self.top = num self.bottom = den def get_num(self): return self.top def get_den(self): return self.bottom
def _set_optionals(tx_json, kwargs, optional): for key, val in kwargs.iteritems(): if key in optional: tx_json[key] = val class Transaction(object): tfFullyCanonicalSig = 0x80000000 # AccountSet SetFlag/ClearFlag values asfRequireDest = 1 asfRequireAuth = 2 asfDisableMaster = 4 # account_set tf...
from .preprocessinglist import * from .motion import correct_motion, load_motion_info from .preprocessing_tools import get_spatial_interpolation_kernel from .detect_bad_channels import detect_bad_channels from .correct_lsb import correct_lsb # for snippets from .align_snippets import AlignSnippets
import random import pandas as pd import secrets from collections import OrderedDict def getAnswer(options): randnum = random.randint(0, options - 1) if randnum == 0: answer = "A" elif randnum == 1: answer = "B" elif randnum == 2: answer = "C" elif randnum =...