text
stringlengths
8
6.05M
import os import json from argparse import ArgumentParser import corenlp os.environ.setdefault('CORENLP_HOME', 'stanford-corenlp') def main(args): num_sentences = 0 with open(args.input, encoding='utf-8') as f, open(args.output, mode='w', encoding='utf-8') as out: with corenlp.CoreNLPClient(annotator...
import sys sys.path.append('../pyastrohog/') from astrohog2d import * import matplotlib.image as mpimg import matplotlib.pyplot as plt from astropy.io import fits hdul=fits.open('../data/image1.fits') image1=hdul[0].data hdul.close() hdul=fits.open('../data/image2.fits') image2=hdul[0].data hdul.close() circstats, ...
from django.conf.urls.defaults import * urlpatterns = patterns( 'trade.views', url(r'^$', 'home', name='trade-home'), url(r'^init_trade_request/$', 'init_trade_request', name='init-trade-request'), )
import ev3dev.ev3 as ev3 from time import sleep from classed_line_trace import LineTrace ts = ev3.TouchSensor('in3') lt = LineTrace() if __name__ == "__main__": while not (ts.value()): lt.line_trace() lt.stop()
#glassclient.py #*********************************************** #Client program for RJGlass to display guages #*********************************************** import time, sys import logging def init_log(): level = logging.INFO if '-debug' in sys.argv: level = logging.DEBUG logging.basicConfig(lev...
import parmed as pmd lib_file = 'GF2.lib' mol2_red = '/home/haichit/research/rna_project/resp_fit/GF2/download_RED/P25049/Data-R.E.D.Server/Mol_MM/INTER/CT-A_m1-c1_m2-c1.mol2' resname = 'GF2' output = 'GF2_RED_update.lib' # load off file and get 1st residue res0 = pmd.load_file(lib_file)[resname] res1 = pmd.load_file...
import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from keras.models import load_model from pyAudioAnalysis import audioFeatureExtraction, audioBasicIO import pandas as pd import numpy as np import argparse import imutils import pickle import cv2 import os ap = argparse.ArgumentParser() ap.add_ar...
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('response/<str:query>', views.graphData, name='response'), path('list/<str:pq>',views.options,name='list') ]
def main(): Read_character() line() def Read_character(): infile = open("/Users/again/Desktop/GIT/ProblemSolving/essay_file/Example.txt",'r') readcharacter = infile.read() infile.close() read_charlen = len(readcharacter) print(read_charlen) def line(): infile = open("/Users/again/Desktop...
# the highest level conftest file in a project determines the starting point of your pytest suite # all fixtures are visible to all lower level test files # multiple conftest files can exist in a directory. # lower level conftest files are applied after higher level ones import pytest @pytest.fixture() def teardown_...
# socket模块负责socket百年城 import socket # 模拟服务器的函数 def serverFunc(): # 1.建立socket # socket.AF_INET:使用ipv4协议族 # socket.SOCK_DGRSM:使用UDP通信 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 2.绑定ip和port # 127.0.0.1:这个ip地址代表是机器本身 # 7852:随手指定的端口号 # 地址是一个tuple类型(ip,port) addr = ("127....
# Generated by Django 2.1.7 on 2019-04-20 10:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('amazon', '0009_auto_20190420_1306'), ] operations = [ migrations.CreateModel( name='clothes', fields=[ ...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import threading import time from pants.pantsd.service.store_gc_service import StoreGCService from pants.testutil.rule_runner import RuleRunner def test_run() -> None: interval_secs...
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-10-01 17:57 from __future__ import unicode_literals import benchmarklib.charts.models from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
# Python Coroutines and Tasks. # Coroutines declared with async/await syntax is the preferred way of writing asyncio applications. # # To actually run a coroutine, asyncio provides three main mechanisms: # # > The asyncio.run() function to run the top-level entry point “main()” function. # > Awaiting on a corout...
# Generated by Django 2.1.5 on 2019-02-12 15:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('updd', '0003_auto_20190206_2149'), ] operations = [ migrations.AddField( model_na...
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains as AC from selenium.common.exceptions import NoSuchElemen...
# Generated by Django 3.1.4 on 2020-12-13 10:10 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Users', '0002_auto_20201213_1005'), ] operations...
import csv import random import datetime import sys __author__ = 'jambo' import numpy as np MAX_ITER = 100 class SVDModel: def __init__(self, dataset, num_of_factors, regularization_constant, learning_rate): self.dataset = dataset self.average = self._average_rating() self.b_users = np.ze...
# activate theano on gpu import os; #os.environ['THEANO_FLAGS'] = "device=gpu"; #import theano; #theano.config.floatX = 'float32'; import numpy as np; import sys, os; import gzip; from six.moves import cPickle; from vae_conv import conv_variational_autoencoder; from keras import backend as K; import pdb channels = 1; ...
from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect from .models import BlogUser from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate,login,logout from json import dumps from .forms import UserForm,UserProfileForm from django.contrib...
#!/usr/bin/env python3 # # QT Buttons 1 # # Converts all images in a dir to greyscale adding a prefix from PIL import Image import os prefix='inactive' included_extenstions = ['jpg', 'bmp', 'png', 'gif'] file_names = [fn for fn in os.listdir() if any(fn.endswith(ext) for ext in included_extenstions)] for f in fil...
# Generated by Django 2.0.3 on 2018-11-11 08:23 from django.conf import settings from django.db import migrations class Migration(migrations.Migration): atomic=False dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('orders', '0006_orders_checkedout'), ] o...
import unittest from header import Header from packer import Packer from unpacker import Unpacker class TestHeader(unittest.TestCase): def test_pack(self): buf = bytearray(256) packer = Packer(buf) header = Header() header.version = 2 header.length = 23 header.id ...
#!/usr/bin/env python # -*- coding: utf-8 -*- "Link Class mapping to SQL table" from django.db import models from django.utils.html import format_html from labman2.data.subdata.ReST.models import ReST #from labman2.data.models import rest_to_html #====================================================================...
from model import AmbarFileMeta, AmbarFileContent from datetime import datetime from hashlib import sha256 from subprocess import call from os import walk, path import hashlib import re import io class PstProcessor(): def __init__(self, Logger, ApiProxy): self.logger = Logger self.apiProxy = ApiPro...
#!/usr/bin/python import pyOTDR import sys import os import xlsxwriter import re import time from config import * import matplotlib.pyplot as plt import kvCreateXLSReport def processReports(filenames): createXLSReports(filenames) def convertPair(s): return map(float, re.findall(r'(.*)\t(.*)\n', s)[0]) de...
"""A CNC-CR-DQN agent training on Atari. """ # pylint: disable=g-bad-import-order import collections import itertools import sys import typing from absl import app from absl import flags from absl import logging import dm_env import haiku as hk import jax from jax.config import config import jax.numpy as jnp import ...
from ..base.handlers import BaseHandler class RelativesIndexHandler(BaseHandler): def get(self): self.render('monitor/index.html') class TemplatesIndexHandler(BaseHandler): def get(self): self.redirect("http://falcon-portal.nosa.me/templates") class ExpressionsIndexHandler(BaseHandler): ...
from hylite import HyLibrary import numpy as np from scipy.spatial.qhull import ConvexHull from tqdm import tqdm def polynomial(data, degree = 1, method='div'): """ Detrend an image data array using a polynomial fit and np.polyfit( ... ). *Arguments*: - data = numpy array of the format image[x][y][b...
from django.shortcuts import render from .models import address import csv import codecs from django.shortcuts import HttpResponse, render, render_to_response from django.template import RequestContext from django.contrib import messages from .forms import AddForm#, UploadFileForm from django.core.files.storage import...
# 唉没想到枚举,一开始想着怎么直接模拟到给定时间了 class Solution: def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int: a, res = [0] * 4, sys.maxsize for i in range(1, 10000): a[0], a[1] = i // 1000, i//100 % 10 a[2], a[3] = i // 10 % 10, i % 10 ...
"""Extension management.""" from django.conf import settings from django.urls import include from django.urls import re_path from django.utils.encoding import smart_str class ModoExtension(object): """ Base extension class. Each Modoboa extension must inherit from this class to be considered as vali...
#!/usr/bin/python from Emakefun_MotorDriver import PWM import time class Emakefun_StepperMotor: MICROSTEPS = 8 MICROSTEP_CURVE = [0, 50, 98, 142, 180, 212, 236, 250, 255] #MICROSTEPS = 16 # a sinusoidal curve NOT LINEAR! #MICROSTEP_CURVE = [0, 25, 50, 74, 98, 120, 141, 162, 180, 197, 212, 225, 236, 244, 250, 25...
import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('E:\csvdhf5xlsxurlallfiles\percent-bachelors-degrees-women-usa.csv') year=df['Year'] physical_science=df['Physical Sciences'] computer_science=df['Computer Science'] plt.style.use('ggplot') plt.subplot(2,2,1) plt.plot(year, physical_science,...
#!/usr/bin/env python ''' Tests ParseTree and downstream ParseTreeNode. ''' __author__ = 'Aditya Viswanathan' __email__ = 'aditya@adityaviswanathan.com' import os import sys import unittest from parse_tree import ParseTree # Append parent dir to $PYTHONPATH to import ReportTraverser, whose public # methods have bind...
# -*- coding: utf-8 -*- ''' Created on Oct 27, 2009 @author: sxin ''' import MySQLdb from MySQLdb.cursors import DictCursor #import MySQLdb.cursors class MySql: _conn = '' def __init__(self, host, user, password, db, port=3306): i = host.find(':') if i >= 0: host, port = host[:i]...
# @Time : 2018-9-10 # @Author : zxh import threading import traceback import os import datetime import sys _file_path = os.path.realpath(__file__) _src_index = _file_path.rfind('src') if _src_index == -1: _file_path = sys.argv[0] _src_index = _file_path.rfind('src') if _src_index == -1: PROJECT_PATH = No...
from flask import Flask, render_template, request, jsonify import pickle import numpy as np import pandas as pd from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import MinMaxScaler app = Flask(__name__) app.config['TEMPLATES_AUTO_RELOAD'] = True @app...
#!/usr/bin/python import re import sqlite3 from BeautifulSoup import BeautifulSoup SELECT_TMPL = '''SELECT asin, html FROM fresh;''' INSERT_TMPL = '''INSERT INTO fresh_categories VALUES (?,?,?)''' conn = sqlite3.connect('../../data/data') c = conn.cursor() c.execute('''DELETE FROM fresh_categories where 1''') conn....
# url https://www.cnblogs.com/wuzhanpeng/p/4261015.html#3767420 import pygame # 导入 pygame 库 from pygame.locals import * # 导入 pygame 库中的一些常量 from sys import exit # 导入 sys 库中的exit 函数 import time from random import randint class Enemy(pygame.sprite.Sprite): def __init__(self, enemy_s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 18 11:51:58 2018 Code to test models of PSFs @author: ppxee """ import numpy as np from astropy.io import fits import matplotlib.pyplot as plt from scipy.stats import norm from scipy.optimize import curve_fit plt.close('all') def radial_profile(...
def printList(value): print(value[0], end='') for i in range (1, len(value)): if i == (len(value) - 1): print(', and ' + value[i]) else : print(', ' + value[i], end = '') spam = ['apples', 'bananas', 'tofu', 'cats'] printList(spam)
import numpy as np xs = [] ys = [] try: while True: x, y = map(float, input().split()) xs.append([1,x]) ys.append(y) except: pass for i in range (0,len(xs)): for j in range (2,len(xs)): xs[i].append(pow(xs[i][1],j)) ans = np.linalg.solve(xs,ys) for i in range (0,len(ans)): print('a'+str(i)...
""" Convert a Peglet grammar to a Parson one. """ import re from parson import Grammar, alter name = r'[A-Za-z_]\w*' grammar = Grammar(r""" grammar : _? rule* !/./. rule : name _ '= ' :equ token* :'.' _?. token : '|' :'|' | /(\/\w*\/\s)/ | name !(_ '= ') | ...
#!/usr/bin/env python """ @file routeGenerator.py @author Simon Box @date 31/01/2013 Code to generate a routes file for the "simpleT" SUMO model. """ import random routes = open("grid.rou.xml", "w") print >> routes, """<routes> <vType id="typeCar" accel="0.8" decel="4.5" sigma="0.5" length="5" minGap="2.5" m...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from textwrap import dedent import pytest from pants.build_graph.address import Address, ResolveError from pants.core import register from pants.core.target_types import GenericTarget fro...
from turtle import * def paint_4(len): if(len>5): circle(len) right(90) forward(5) paint_4(len-5) def paint_Concentric_circle(radius): if(radius>10): paint_Concentric_circle(radius-20) circle(radius) penup() right(90) ...
#!/usr/bin/python # -*- coding:UTF-8 -*- import urllib2 import re import requests from HTMLParser import HTMLParser import time import urllib2 from bs4 import BeautifulSoup # re.S 整个字符串看成一行不去关注是否有换行符 # re.I 忽略大小写 # Python2.7 def crawl_joke_list(page=4): url = "http://www.qiushibaike.com/8hr/page/" + str(pag...
from django import forms from .models import * from time import time from django.core.exceptions import ValidationError from django.utils.text import slugify class TagForm(forms.ModelForm): obj_id = None #using when edit class Meta: model = Tags fields = ['title'] widgets = { 'title': forms.TextInput(at...
from sortedcontainers import SortedSet from util import _get_hash class GodelHashSet2: def __init__(self, iterable): if not isinstance(iterable, (str, list)): raise ValueError("value must be string or list") self.collision_prob = 0.2 self.container = [SortedSet()] * len(iterable) * 2 ...
import numpy as np from datetime import datetime, timedelta from olanalytics.dt import DatetimeDescription from olanalytics.generators import timeseries, CustomTimedCurve def test_dt_generation(): X = timeseries( start=datetime(2020, 1, 1), end=datetime(2020, 1, 2), step=timedelta(hours=...
# Generated by Django 3.0.3 on 2020-03-26 01:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Batch', fields=[ ...
import os import sys import csv from pathlib import Path try: from pampers import log except Exception as e: sys.path.insert(0, str(Path(os.path.dirname(os.path.realpath(__file__))).parents[1])) from pampers import log from pampers import CHAIN, APP def csv_writer(fname: str = 'airdrop', header: list = ['p...
import logging import sys import simpy from entities.delivery_boy import DeliveryBoy class DeliveryBoyManager: def __init__(self, env, config, xy_generator): speed = config['speed'] self.hireCount = config['hires'] self.algoConfig = config['algo'] self.env = env self.free...
from time import sleep import xlrd from xlutils.copy import copy # from wrapt_timeout_decorator import * import db import tools import importlib import ip_test import traceback import Chrome_driver import random import Changer_windows_info as changer import traceback import os import json import thread_tokill import sy...
import json import logging from django.shortcuts import render from django.http import HttpResponse from forms import AccountRegisterForm, AccountLoginForm, AccountUpdateForm from services import AccountService, AuthJWT, require_loggin from django.core.urlresolvers import reverse from django.http import HttpResponseRe...
""" Base password hashers. Contains weak hashers (the original ones) available with Modoboa. """ import base64 import crypt import hashlib import string from random import Random from django.utils.crypto import constant_time_compare from django.utils.encoding import force_bytes, force_str class MetaHasher(type): ...
# -*- coding: utf-8 -*- ''' Obtener justificaciones de un usuario @author Ivan @example python3 getJustificationRequestsToManage.py userId group statusList @example python3 getJustificationRequestsToManage.py 1 ROOT APPROVED PENDING CANCELED ''' import sys sys.path.insert(0, '../../../python') import inject import lo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from test.Test import Test from test.AllAssignmentsTest import AllAssignmentsTest from test.AllConditionsTest import AllConditionsTest from test.AllDefinitionsTest import AllDefinitionsTest from test.AllDecisionsTest import AllDecisionsTest from test.AllILoopsTest import ...
# Generated by Django 3.1.1 on 2020-10-11 10:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('BreastCancerApp', '0006_auto_20201011_1042'), ] operations = [ migrations.AlterField( model_name='stories', name='im...
n = int(input()) card_numbers = list(map(int, input().split())) result = [0, 0] i = 0 while card_numbers: # print(card_numbers[0], card_numbers[-1]) result[i % 2] += max(card_numbers[0], card_numbers[-1]) card_numbers.remove(max(card_numbers[0], card_numbers[-1])) # print(card_numbers) ...
print('===== Exercicio 027 =====') print('Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o ultimo nome separadamente') nome = input('Qual seu nome completo? ').strip().split() print('Seu primeiro nome é {} e o ultimo é {}'.format(nome[0], nome[-1]))
import pygame import time import random pygame.init() wx = 600 wy = 600 WINDOW_SIZE = (wx,wy) WINDOW_NAME = 'Slither' #color definitions white = (255,255,255) orange = (255,100,50) red = (255,0,0) green = (10,155,50) blue = (0,0,200) window = pygame.display.set_mode(WINDOW_SIZE) pygame.display.se...
#!/usr/bin/env python # -*- coding: utf-8 -*- def score(seq): # You need to write this method str_seq = [] list_str = [] result = 0 if len(seq) == 0: return result else: for num in seq: print 'initial',num , seq, result ...
from torch.utils.data import DataLoader from .dataset_lmdb import Dataset from .sampler import StratifiedSampler def get_datasets(args): train_set = Dataset(args, 'train') val_set = Dataset(args, 'test') test_set = Dataset(args, 'val') return train_set, val_set, test_set def get_data_loaders(train_se...
from itertools import chain, izip def isSolved(board): """ is_solved == PEP8 (forced mixedCase by CodeWars) """ cats_game = True diagonals = [[], []] for i, row in enumerate(board): current = set(row) if current == {1}: return 1 elif current == {2}: retu...
from rest_framework.permissions import BasePermission class IsLoggedUser(BasePermission): """ Only exposes the endpoint for the logged user """ def has_object_permission(self, request, view, obj): return request.user == obj
# -*- coding: utf-8 -*- """ django_async_test.tests.testcase ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests for :py:class:`django_async_test.TestCase`. """ import unittest from django.test import TestCase from django_async_test.tests.testapp.models import ModelWithBasicField class TestCaseTestCase(TestCase): ...
# -*- coding: utf-8 -*- """ Created on Fri May 24 10:40:34 2019 @author: andre """ import os import sys import h5py import numpy as np import pandas as pd import copy from scipy.signal import butter, lfilter import scipy.ndimage from sklearn import preprocessing as pre from matplotlib import pyplot as plt # Do some...
#!/usr/local/bin/python3 import socket import subprocess import sys import argparse from datetime import datetime def scan_ports(remoteServer, start_port='1', end_port='1024'): # Clear the screen """ :rtype : object """ subprocess.call('clear', shell=True) # Ask for input remoteServer =...
from __future__ import absolute_import, division from __future__ import print_function, unicode_literals import collections from copy import deepcopy import json import multiprocessing import numpy as np import os import six import tempfile from six.moves import zip from smqtk.algorithms.nn_index import NearestNeigh...
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton main_keyboard = ReplyKeyboardMarkup( keyboard=[ [ KeyboardButton(text='Главный раздел') ], ], resize_keyboard=True )
#cost function import tensorflow as tf import numpy as np import matplotlib.pyplot as plt #그래프에서 즉시 실행모드로 변환 tf.compat.v1.enable_eager_execution() X = np.array([1, 2, 3]) Y = np.array([1, 2, 3]) def cost_func(W, X, Y): hypothesis = X * W return tf.reduce_mean(tf.square(hypothesis - Y)) #-3에서 5까지를 15로...
import random; import Queue; import BayesianNetwork; MAX_SAMPLES = 10; class IdealUpdate: def __init__(self, addition, vertex, parentInQuestion): self.addition = addition; self.vertex = vertex; self.parentInQuestion = parentInQuestion; class Sample: def __init__(self, joint): self.joint = j...
# Traverse through the tree and return the youngest common ancestor # for the given 2 child nodes. class AncestralTree: def __init__(self, name): self.name = name self.ancestor = None def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo): oneDepth = getDepth(descendantOne,...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class FreetypeToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017...
import machine from machine import Pin,I2C,SPI import ssd1306 #i2c = I2C(scl=Pin(14), sda=Pin(2), freq=100000) #display = ssd1306.SSD1306_I2C(128,64, i2c) spi = SPI(baudrate=10000000, polarity=1, phase=0, sck=Pin(14,Pin.OUT), mosi=Pin(13,Pin.OUT), miso=Pin(12)) display = ssd1306.SSD1306_SPI(128, 64, spi, Pin(5),Pin(4),...
# System Imports import pytest from unittest import mock from unittest.mock import MagicMock # Framework / Library Imports # Application Imports from main import create_app import config # Local Imports @mock.patch('comms_rabbitmq.get_connection') def test_no_rootpatch(get_conn): """ Tests that a blank rout...
#!/usr/bin/env python3 #Aurel Onuzi import csv import os.path import sys #user input names_file = input('Enter a text file with a list of name: ') nickname_file = input('Enter a file with a list of nicknames, or just enter 0 to skip this step: ') name_var = input('Select name variation: Single Line or Multiple Lines ...
# coding: utf-8 class Digraph(object): """ Digraph is a simple and more or less efficient implementation of a directed graph. It aims to provide all necessary methods for digraphs and to be simple to understand. Therefore, Digraph isn't efficient in any way. When you are looking for an efficient digraph implementa...
from .base import BasePaymentMethod class CardPaymentMethod(BasePaymentMethod): pass
import json from flask import Flask, request, jsonify from os import path, makedirs from subprocess import Popen, PIPE from govr.util import is_dir_empty from govr.test_runner import TestRunner from govr.shields import update_shield PROJECT_DIR_NAME = "project" IMG_DIR_NAME = "img" REPORTS_DIR_NAME = "reports" COVERA...
import pyrebase #import pyrebase import datetime #import datetime import time #import time config = { #sets up judge-prefs-pfd firebase "apiKey": "apiKey", "authDomain": "judge-prefs.firebaseapp.com", "databaseURL": "https://judge-prefs.firebaseio.com/", "storageBucket": "judge-prefs.appspot.com" } firebase =...
###########tumpukan # tumpukan = [1,2,3,4,5,6] # print('data sekarang : ',tumpukan) # # #memasukkan data baru # tumpukan.append(7) # print('data masuk: ',7) # tumpukan.append(8) # print('data masuk: ',8) # # print('data sekarang : ',tumpukan) # # out = tumpukan.pop() # print('data keluar : ',out) # print('data sekarang...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from colors import red from setuptools import Extension, setup native_impl = Extension("native.impl", sources=["impl.c"]) setup( name="native", version="2.3.4", packages=["na...
import grequests import requests from PIL import Image from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry import time import os import logging import random import math from io import BytesIO from typing import List, Tuple from dataclasses import dataclass import progressbar _GOOGLE_MAP_UR...
import pdb import os, platform import matplotlib if matplotlib.rcParams['backend'] == 'nbAgg': print('Use IPython notebook backend for matplotlib.') elif platform.system() == 'Linux': try: os.environ['DISPLAY'] matplotlib.use('TkAgg') print('Use TkAgg backend for matplotlib.') except...
from rxdrug import drugs_list ZERO = 0 class Patient: def __init__(self, name, ailment, drugs): self.name = name self.ailment = ailment self.drugs = drugs def __str__(self): # self.self = self return '{n}'.format(n=self.name) + 'is taking {n}'.format(n=self.drug) + 'f...
import uopy class U2Message: def __init__(self): self.items = [ {'id': 1, 'name': 'Flight', 'barcode': '893212299897', 'price': 500}, {'id': 2, 'name': 'Flight', 'barcode': '123985473165', 'price': 1000}, {'id': 3, 'name': 'Tour', 'barcode': '231985128446', 'price': 150...
play = True while play is True: operation = raw_input("Do you want to add, subtract, multiply, or divide?") number1 = int(raw_input("Enter a number")) number2 = int(raw_input("Enter another number")) if operation == "add": print number1 + number2 elif operation == "subtract": print ...
#!/usr/bin/python #coding=utf-8 #__author__:TaQini from pwn import * # rop1 for i in range(20): p = remote('192.241.138.174',9998) offset = 64+i payload = 'A'*offset print "[+] ",i p.sendline(payload) print p.recvall() p.close() # p.interactive()
# Write a Python program to find the list of words that are longer than n from a given list of words def lonerthanN(n,listprovided): for i in range(len(listprovided)): if len(listprovided[i])>n: print(listprovided[i]) n = int(input(" Please enter the value of n :")) listprovided = ['Red', 'Gre...
#!/usr/bin/env python3 ''' Label image with Google Cloud Vision API. Before use it, check "vision_api_test.sh" in google-vision-setting directory. cred.json is required. Usage : ./auto_labler.py --meme_dir=./meme_cut/ --output_dir=./output_xml/ ''' import sys from subprocess import call import subprocess import json im...
import os import json import logging logging.getLogger().setLevel(logging.INFO) class DoProcessing() : def __init__( self, JSON_FILE_URL, LOG_FILE_URL, STORAGE_DIR ) : ''' Constructor for this class ''' self.JSON_FILE_URL = JSON_FILE_URL self.LOG_FILE_URL = LOG_FILE_URL self.STORAGE_DIR = STORAGE_DIR ...
'''VoidFinder - Hoyle & Vogeley (2002)''' ################################################################################ # # IMPORT MODULES # ################################################################################ from voidfinder import filter_galaxies, find_voids from astropy.io import fits from astrop...
import sys from collections import defaultdict import pyparsing as pp def stripped_lines(filename): with open(filename) as f: for line in f.readlines(): yield line.strip() def make_grammar(): color = pp.Combine(pp.Word(pp.alphas) + pp.Word(pp.alphas), adjacent=False, joinString=' ') ...
from flask import g, jsonify,request,session from flask.ext.httpauth import HTTPBasicAuth from .response import unauthorized, forbidden from . import api from ..models import User #initializes the HTTPBasic auth library to be used for regular authenticaiton auth = HTTPBasicAuth() #Login Error Handler @auth.error_ha...
from . import onmt from . import torchtext
from django.contrib import admin from django.urls import path,include from .views import * urlpatterns = [ path('getauth',AuthURL.as_view()), path('redirect',spotify_callback), path('checkauth',IsAuthenticated.as_view()), path('currentsong',CurrentSong.as_view()), path('play',PlaySong.as_view()), ...