text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- import hashlib import os import re import subprocess # nosec: B404 from typing import TYPE_CHECKING import requests # with open(os.path.expanduser('~/GitHub/poseur/poseur.py'), 'r') as file: # for line in file: # match = re.match(r"^__version__ = '(.*)'", line) # if match...
"""15-1. Cubes: A number raised to the third power is a cube. Plot the first five cubic numbers, and then plot the first 5000 cubic numbers. 15-2. Colored Cubes: Apply a colormap to your cubes plot.""" import matplotlib.pyplot as plt x_values = range(1, 5001) y_values = [x**3 for x in x_values] plt.style.use(...
#!/usr/bin/python3 import fabric def do_pack(): from fabric.operations import run, sudo, local, get, put, prompt, reboot import os import datetime if ((os.path.exists('./versions') is True) and (os.path.isfile ('./versions') is False)): pass ...
from clean_read_data import read_data import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from pprint import pprint import os ## Imports for Tweet Text Cleaning Pipeline import preprocessor as p import re import nltk from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.snowball impor...
from tkinter import * import tkinter.font as tkFont import time, socket, threading, json tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.bind(('', 8080)) tcp_socket.listen(5) def send_Message(new_socket, inputtext, receive_text, user_name): mess = inputtext.get('1.0', END) message =...
from base.mobileApp.lanxi.patientBase import patientBase from Utils.appium_config import DriverClient as DC import unittest from Utils.public_action import skip_dependon from Utils.public_action import pub_action class patientList(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = DC()...
def sayHello(): print("你好,我是sayhello"); if __name__=="__main__": print(__name__); print("小明开发的模块"); sayHello();
# -*- coding: utf-8 -*- import feedparser import re import json def convertTime(time): time = time.split(":") amOrPM = "AM" if int(time[0]) > 12: time[0] = str(int(time[0]) - 12) amOrPM = "PM" return time[0]+":"+time[1]+ " "+amOrPM rssFeed = feedparser.parse('https://olemisssports.com...
from django.db import models from django.utils import timezone #from ..models import Loi from ..models import Competence, Charge from ..fonctions_base import * class Maison(models.Model): #user = models.ForeignKey(auth.User) active = models.BooleanField(default=True) priorite = models.SmallIntegerField(default=9) ...
from .base import ScalarVariable from .global_global_step import global_step from .global_global_step import get_value as current_step from .global_keep_prob import keep_prob from .global_batch_size import batch_size from .utils import create_global_scalars
from django.test.simple import * import os def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): """ worsk exactly as per normal test but only creates the test_db if it doesn't yet exist and does not destroy it when done tables are flushed and fixtures loaded between tests as p...
#!/usr/bin/env python3 """ :Author: Anemone Xu :Email: anemone95@qq.com :copyright: (c) 2019 by Anemone Xu. :license: Apache 2.0, see LICENSE for more details. """ import unittest from tf import tf_lstm class TestLSTMMethods(unittest.TestCase): def test_load_json(self): label_dict = tf_lstm.load_label(...
from django.shortcuts import render from Account.models import Users, ApiToken, UserDevice,PushNotification from Account.serializers import UserSerializer,UserLoginSerializer from rest_framework.response import Response from rest_framework.views import APIView class RegisterAPIView(APIView): def post(self, reque...
# https://www.hackerrank.com/challenges/python-sort-sort/problem n, m = map(int, input().split()) t = [tuple(map(int, input().split())) for _ in range(n)] k = int(input()) for r in sorted(t, key=lambda x: x[k]): print(*r)
from flask import request,session,abort from planner_project.common import api_response,custom_error from planner_project.data_access import mysql from planner_project.sql.backweb import user_sql,home_sql def get_token(): token = request.cookies.get("token") if token != None: return token raise cu...
r""" POSTORDER TRAVERSAL WITH PARENT LINK Given the root to a binary tree, where nodes have a link to value, left, right, and parent, write a function that prints an postorder traversal with O(1) space complexity. Without a link to the parent node, postorder traversal requires O(h) space, where h is t...
# Below are the global variables from datetime import datetime from threading import Thread from ibapi.client import * from ibapi.wrapper import * from message.chatbot import ChatBot from traders.ma.raivo_trader import RaivoTrader logging.basicConfig(format='%(asctime)s-%(levelname)s:%(message)s', level="WARN") c...
# encoding: utf-8 # Copyright 2013 maker # License from django.test.simple import DjangoTestSuiteRunner from django.conf import settings class CustomTestRunner(DjangoTestSuiteRunner): """ Custom DjangoTestSuiteRunner to remove Django modules from tests """ def __init__(self, *args, **kwargs): ...
#ArgumentParser:変数名,型,初期値を記録するのに用いる import argparse def get_args(): #ArgumentParserを宣言し,説明としてdab-rを加える parser = argparse.ArgumentParser(description='dib-r') #4つの引数があり前から順に,変数名,型,初期値,この変数の説明(なくてもよい) #ファイルリスト(ここではデータセット)の名前 parser.add_argument('--filelist', type=str, default='test_list.txt', hel...
import numpy as np import pandas as pd import matplotlib.pyplot as plt def plot_iterations(data, net_width): iterations = data.groupby('net_width').get_group(net_width)\ .groupby(['discretization', 'solver']).count()\ .unstack().iteration axis = iterations.plot.bar(ro...
# Shahriyar Mammadli # Import required libraries import pandas as pd import helperFunctions as hf from sklearn.model_selection import train_test_split # Read the train and test data trainDf = pd.read_csv('../Datasets/KaggleDigitRecognizer/train.csv') predDf = pd.read_csv('../Datasets/KaggleDigitRecognizer/test.csv') ...
from flask import Flask from flask_sqlalchemy import SQLAlchemy DBUSER = 'lustri' DBPASS = 'lustri' DBHOST = 'postgres' DBPORT = '5432' DBNAME = 'db' db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = \ 'postgresql+psycopg2://{user}:{passwd}@{host}:{por...
from keras.models import Sequential from keras.layers import LSTM, Dense, GRU from keras.callbacks import TensorBoard from data_prep import gen_cosine_amp_for_supervised batch_size = 128 sequence_length = 64 cos, expected = gen_cosine_amp_for_supervised(xn=sequence_length*100) cos = cos.reshape((-1, 64, 1)) print(ex...
from typing import Optional from pymodelextractor.learners.learner import Learner from pymodelextractor.learners.learning_result import LearningResult from pymodelextractor.learners.observation_table_learners.observation_table import ( epsilon, ObservationTable, TableInconsistency) from pymodelextractor.lear...
from moha import * mol,orbs = IOSystem.from_file('../data/water.xyz','sto-3g.nwchem') ham = ChemicalHamiltonian.build(mol,orbs) wfn = HFWaveFunction(10,7,{'alpha':5,'beta':5}) hf_solver = PlainSCFSolver(ham,wfn) hf_results = hf_solver.kernel() pa_m_results = PopulationAnalysisMulliken(mol,orbs,ham,wfn).kernel() pa_l...
import click from toapi import __version__ @click.group(context_settings={"help_option_names": ["-h", "--help"]}) @click.version_option(__version__, "-v", "--version") def cli(): """ Toapi - Every web site provides APIs. """
from django.contrib.auth.models import User from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from apps.users.models import ParentProfile, StudentProfile, TeacherProfile from apps.school.models import Grade, Section class ParentResource(resources.ModelResource): userna...
a1 = input('输入任意数字') # print(len(a1)) a2 = a1.split(',') print(a2)
""" We need to use the QC'd 24h 12z total to fix the 1h problems :( """ import Nio import mx.DateTime import Ngl import numpy import iemre import os import sys import netCDF4 def merge(ts): """ Process an hour's worth of stage4 data into the hourly RE """ # Load up the 12z 24h total, this is what we ...
import re print(re.search(r"[a-zA-Z]{5}","a ghost")) # find exactly 5 char word print(re.search(r"[a-zA-Z]{5}","a ghost appeared")) # find exactly 5 char # word, finds only first word print(re.findall(r"[a-zA-Z]{5}","a scary ghost appeared")) # find exactly 5 # char # word, finds all words print(re.findall(r"\b[a-zA-Z...
seats = """ LLLLL.LLLL.LLLLLLLLL.LLLLLL.LLLLLLL.LLLLLL.LLLLLLLLLL.LLLLLLLL.LLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLL LLLLLLLLLL.LLL.LLLLL.LLLLLL.LLLLLLL.LLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLL..LLLLL.LLLLLLLLLLLLLLLL LL.LLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLL.LLLLLL LLLLLLLLLLL...
import datetime import unittest from unittest import mock import freezegun from tests.plugins import PluginTestCase from plugins.conversion import get_currency_data class GetCurrencyDataTest(unittest.TestCase): def test_uses_cached_data_if_recent_enough(self): currency_data = {"_timestamp": datetime.dat...
import sys inp = open("in.txt", "r") out = open("out.txt", 'w') n = int(inp.readline()) last = [] costs = {} last.append([]) for i in range(1, n + 1): str_t = inp.readline() l = str_t.split(" ") tmpL = l[:-1] if len(tmpL) == 0: last.append(tmpL) else: listNodes = [] for k i...
import numpy as np import mycsv #** Intuition # The strategy with overall higher rankings will be the best. def findStrategy(path,year,exchange): data=mycsv.getCol(path+str(year)+"_"+exchange,range(7)) #data=np.array([[1,2.2],[2,2.2],[1,2.2],[2,3.2],[1,2.2],[2,3.2],[1,3.2],[2,3.2],[1,3.2],[2,2.2]]) data=np.as...
import os import sys import cv2 import json import numpy as np import skimage.draw from imgaug import augmenters as iaa ROOT_DIR = os.path.abspath("./") print("ROOT_DIR", ROOT_DIR) AUGMENT_SIZE_PER_IMAGE = 10 args = sys.argv if len(args) != 2: print("Need option target directory") sys.exit() target = args[1...
import pymongo DB = None def connect(host, database, auth=None, port=27017, ssl=True): mc = pymongo.MongoClient(host, port=port, ssl=ssl) db = getattr(mc, database) if auth: db.authenticate(auth['username'], auth['password']) globals()['DB'] = db
from extruder_turtle import ExtruderTurtle import math import random HAIRLENGTH = 1 HAIR_ANGLE = math.pi/3 EXT_DENSITY = 0.05 FEEDRATE = 500 NUM_HAIRS = 15 LAYER_HEIGHT = 0.15 SIDELENGTH = 25 NUM_SIDES = 5 LAYERS = 100 dx = SIDELENGTH/(NUM_HAIRS+1) t = ExtruderTurtle() ## Set up the turtle t.name("furry-prism.gcode...
# -*- coding: utf-8 -*- """ """ from openpyxl import load_workbook def got_drink(item_dict, item): """ item_dict 는 { 상품명 : 수량 } 형식으로 되어있는 Dict item_dict[item] ==> 해당 item에 대한 수량을 return Ex) print(item_dict['사이다']) ==> 10 (사이다 수량) item_dict[item] -= 1 은 item_dict[item] = item_dict[item] - 1 을 줄인...
from Backend_API.database import database_config class FlaskConfig(object): DEBUG = False TESTING = False BABEL_DEFAULT_LOCALE = "en" SEND_FILE_MAX_AGE_DEFAULT = 0 class FlaskProductionConfig(FlaskConfig): SECRET_KEY = "FA848613990667D31E2875021B945130E4A37EDED8035E83EC2426C3366737B2" SESSI...
import os import matplotlib.pyplot as plt import cv2 import torch import pandas as pd from ..util.paths import process from ..util import torch2cv, map_range, make_grid def _get_tensor(x): x = x[0] if torch.typename(x) in ['tuple', 'list'] else x return x def save_image(img, title): to_save = ((img / img....
import controls import pytest import pandas as pd import prediction def test_update_a_share_list(): try: controls.update_a_share_list()[0] except ValueError as ex: print(ex) assert {'label': 'sh.600000-浦发银行', 'value': 'sh.600000-浦发银行'} def test_get_A_stock_list(): try: len(con...
import sqlite3 import sys def printProfile(skypeDB): conn = sqlite3.connect(skypeDB) c = conn.cursor() c.execute("SELECT datetime(timestamp,'unixepoch'),dialog_partner,author,body_xml FROM Messages;") print ("--Found Messages--") for row in c: try: if 'parlist' not in str...
# 일 평균 30만주이상 거래되는 nasdaq, newyork, amex 중(step2_300k_day_coms.xlsx) # 최근 3개월간 10%(연간 100%) 이상 상승한 종목 중(step3_3mon_10p_up.xlsx) <-- <월봉 양호한 종목 추출 목적> # 볼린저밴드 상단 접근 종목(밴드 상단의 -20%선 이상) 중 시가가 기준선 위에 있고 종가가 상단선 80% 이상이며, 전일 시가, 종가 갭의 2배이상 상승한 종목 # 일일 1회 가동 from pandas_datareader import data as pdr import yfinance a...
# this is 'The Coin Change Problem' using dynamic programming # source hackerrank def getways(SUM, index) : global dp global d global size_of_d if SUM < 0 or index >= size_of_d: return 0 elif SUM == 0 : return 1 elif dp[index][SUM]!=-1 : return dp[index][SUM] else : count = getways(SUM - d[index], inde...
# -*- coding:gbk -*- # auther : pdm # email : ppppdm@gmail.com import socket #import time import threading import sys import getopt HOST = '' SERVER_ADDR = 'localhost' PORT = 4001 TOTAL_CLIENT = 65536 # default is 1000 CREATE_THREAD_SLEEP_TIME = 0.001 # default is 0.001 gConnectList = [] gClientLi...
# Copyright 2019 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. from recipe_engine import post_process DEPS = [ 'assertions', 'properties', 'step', ] def RunSteps(api): msg = api.properties.get(...
import os import sys import time import serial import serial.tools.list_ports ports = [] ports = serial.tools.list_ports.comports() for port in ports: print("Find port " + port.device) ser = serial.Serial(port.device) if ser.isOpen(): ser.close() ser = serial.Serial(port.device, 9600) """ free buffer ""...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt dataset= [11,10,12,14,12,15,14,13,15,102,12,14,17,19,107, 10,13,12,14,12,108,12,11,14,13,15,10,15,12,10,14,13,15,10] # Detect outliers using z-score outlier = [] def detect_outlier(data): threshold = 3 mean = ...
from .util import Xmleable, default_document from .Party import Party from .Accounting import AdditionalAccountID, CustomerAssignedAccountID class AccountingCustomerParty(Xmleable): def __init__(self, party=None, customer_assigned_account=None, additional_account=None): self.party = party ...
from car_information.model.Car import Car import os.path import json import unittest class TestCar(unittest.TestCase): def test_load_car_data(self): a = Car() b = Car() data = self.get_mock_car_data() a.load_data_from_json(json.dumps(data)) self.assertNotEqual(a, b) de...
'''Largest palindrome product Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' def is_num_palindrome(number): return str(number) == str(nu...
#!/usr/bin/env python """make some postprocessing plots/reports by the predictions and true labels usage: python xgbreporter.py -d <OUTPUTDIR> [-t <TRAINDATA> -k <KEY>] An `xgbreport.txt will be dumped under <OUTPUTDIR>, including info below: * prediction distribution * roc curve * auc score * accuracy score * class...
# https://www.codewars.com/kata/delete-occurrences-of-an-element-if-it-occurs-more-than-n-times/train/python def delete_nth(order,max_e): deleted = list() for element in order: if deleted.count(element) < max_e: deleted.append(element) return deleted
class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: answer = [] for word in words: check = {} find = True for char, pa in zip(word, pattern): if pa not in check and char not in check.values(): ...
import json import requests class GitApi(object): def __init__(self, user=None, passwd=None, repo=None) -> None: super().__init__() if user is None or passwd is None or repo is None: raise IOError("Invalid arguments") self.user = user self.passwd = passwd self.repo = repo def get_commit(self, sha=Non...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # File Name : sql.py '''Purpose : Intro sth ''' # Creation Date : 1435545244 # Last Modified : # Release By : Doom.zhou ############################################################################### from flask import Flask, g import sqlit...
file = open("lista.txt", "a+") add_student = True print("Podaj studentów do wczytania:") students = [] while(add_student == True): print("Imie:") name = input() print("Nazwisko:") surname = input() print("Grupa:") group = input() student_data=(name, surname, group) students.append(studen...
#! /usr/bin/env python """ Date: 2023/03/27 Author: Ziwei Pan Extract per-read CpG information from Guppy modified-base BAM Input: Guppy modified-base BAM is 0-based file. Output: Per-read file: """ import argparse import csv import os import pysam from Bio.Seq import reverse_complement from modbampy import ModBam...
from abc import ABC, abstractmethod from enum import Enum from typing import List, Callable import numpy as np class ColorSpace(Enum): RGB = 1 HSV = 2 BGR = 3 GRAY = 4 class VideoFormat(Enum): MOV = 1 WMV = 2 OGG = 3 AVI = 4 FLV = 5 MP4 = 6 MPEG = 7 class VideoMetaInfo...
# pacmanAgents.py # --------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst....
from django.db import models from django.contrib.auth.models import User class Event(models.Model): title = models.CharField(max_length = 100) description = models.TextField() location = models.CharField(max_length = 60) datetime = models.DateTimeField() seats = models.PositiveIntegerField() own...
import json import unittest import responses import htq from htq import service from htq.db import get_redis_client from requests.utils import parse_header_links as phl url = 'http://localhost/' client = get_redis_client() app = service.app.test_client() def parse_header_links(value): _links = phl(value) ...
# -*- coding: utf-8 -*- import re from xkeysnail.transform import * # [Global modemap] Change modifier keys as in xmodmap define_modmap({ Key.MUHENKAN: Key.LEFT_META, Key.HENKAN: Key.RIGHT_CTRL, }) # [Conditional modmap] Change modifier keys in certain applications # define_conditional_modmap(re.compile(r'Em...
import random f = open("palavras.txt", "rt") bank = f.readlines() palavra = bank[random.randint(0, len(bank))].strip('\n') print(palavra) '''string = [] cont = 0 for c in palavra: string.append(c) cont += 1 print(string) if 'w' in palavra: print('Sim') else: print("Não") print(cont) print(len(palavra))...
''' Created on Nov 30, 2016 @author: Yuval Pinter ''' from __future__ import division import unittest from evaluate_morphotags import Evaluator from utils import split_tagstring from numpy import nan from numpy.testing.utils import assert_almost_equal from numpy.testing.utils import assert_equal class Te...
def solution(n): num = ['1','2','4'] division = [] if n < 4 : return num[n%3-1] while(n>3): r = n % 3 division.append(r) n = int(n/3) if n<4 : division.append(n) answer = '' while(division): d = division.pop() answer += num[d-1] return an...
import torch import torch.nn.functional as F from torch.optim import Adam from SAC.models import GaussianPolicy, QNetwork device = 'cuda' if torch.cuda.is_available() else 'cpu' GAMMA = 0.99 TAU = 0.005 lr = 3e-4 HIDDEN_SIZE = 256 def soft_update(target, source, tau): for target_param, param in zip(target.param...
# https://leetcode.com/problems/keyboard-row/ class Solution: r1 = ['Q','W','E','R','T','Y','U','I','O','P'] r2 = ['A','S','D','F','G','H','J','K','L',] r3 = ['Z','X','C','V','B','N','M'] def check(self, word, row): for x in word: if x not in row: return False ...
class TestOverload: def __init__(self): print('inside init') def __init__(self, name): print(f'name:{name}') def __init__(self, name, age): print(f"n:{name}, a:{age}") # i = TestOverload() # print(i) # Traceback (most recent call last): # File "C:/Users/DattatrayaTembare/Pychar...
# cook your dish here t=int(input()) for i in range(t): w,s=map(str,input().split()) days=["mon", "tues", "wed", "thurs", "fri", "sat", "sun"] ans=[int(w)//7]*7 j=0 while days[j]!=s: j+=1 extra=int(w)%7 while extra>0: if j<7: ans[j]+=1 j+=...
import vcenter # Connect to Vcenter Server vcenter.connect() # Get the current Date from the Vcenter server vcenter.currentDate() # Crete Vm_template #Disconnect from Vcenter vcenter.disConnect()
""" logging_utils.py Utility functions for logging experiments to CometML and TensorBoard Collaboratively developed by Avi Schwarzschild, Eitan Borgnia, Arpit Bansal, and Zeyad Emam. Developed for DeepThinking project October 2021 """ import os # Ignore statements for pylint: # Too many b...
# Generated by Django 2.2 on 2019-07-14 08:33 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('hosts_manager', '0001_initial'), ] operations = [ migrations.AddField( model...
class BankAccount: def __init__(self, name, acct_num, int_rate, balance): self.name = name self.acct_num = acct_num self.int_rate = .05 self.account_balance = 0 def deposit(self, amount): self.account_balance += amount return self def withdraw(self, amount):...
from funcao.funcao import formata_data_americana from banco.bancodado import BancoDado from cliente.cliente import Cliente from funcao.funcao import escreve_tela, limpa_tela from menu.opcao_menu_cliente import entra_opcao banco_dado = BancoDado() #entra_opcao(banco_dado=banco_dado, opcao="3", codigo_cliente="1") #e...
#!/usr/bin/python import re from HTMLParser import HTMLParser regex_for_finding_links = "^/fakebook/*[0-9]" # HTML Data to analyse HTMLdata = """<html><head><title>Fakebook</title><style TYPE="text/css"><!--\n#pagelist li { display: inline; padding-right: 10px; }\n--></style></head><body><h1>Fakebook</h1><p><a href="...
# # @lc app=leetcode id=9 lang=python3 # # [9] Palindrome Number # # @lc code=start class Solution: def isPalindrome(self, x: int) -> bool: if x >= 0: temp = 0 xCopy = x while xCopy > 0: temp = (temp * 10) + (xCopy % 10) xCopy = xCopy // 1...
""" The test module for the babysitter class """ from babysitter import Sitter def test_event_occurred(): """ First test simulating a babysitting event occurred. """ expected = "Total amount owed: $0.00" e1 = Sitter() assert expected == e1.babysit() def test_event_occurred_with_hours(): """ Put...
import unittest from arepl import * import typing as t T = t.TypeVar('T') def await_pure(awaitable: t.Awaitable[T]) -> T: iterable = awaitable.__await__() try: next(iterable) except StopIteration as e: return e.value else: raise Exception("this awaitable actually is impure! it y...
from requests_html import HTMLSession import re class HtmlScraper: def __init__(self): self.session = HTMLSession() self.success_code = 200 def request_html(self, url): page = self.session.get(url) if page.status_code != self.success_code: raise Exception("HTML re...
import numpy as np import matplotlib.pyplot as plt numpyDizisi = np.linspace(0,10,20) numpyDizisi2=numpyDizisi**2 (benimFigur,benimEksen)=plt.subplots() benimEksen.plot(numpyDizisi,numpyDizisi2,color="#3A95A8",alpha=0.9,linewidth=1.0,linestyle="--",marker="o",markersize=4,markerfacecolor="r") benimEksen...
import pickle from pprint import pprint from typing import Dict from src.utils.helper import Helper def get_commands_pickle() -> Dict: with open(f'{Helper.get_project_root()}/commands_dict.pickle', 'rb') as file: data = pickle.load(file) return data def main(): commands_pickle = get_commands_pi...
# ############################################################################################### #################################### ANALIZADOR SINTACTICO ################################# ###################################################################################################### import scan...
import os import sys import subprocess from multiprocessing import Process import time import os def launchTor(n): print('TOR %d' %i) command = 'tor -f /etc/tor/torrc.' + str(i) subprocess.check_call(command.split()) if __name__ == '__main__': process_count = int(input("How Many Process?")) d...
from flask import Flask, request, render_template from requests import post, exceptions from configparser import ConfigParser import os app = Flask(__name__) # If config file location is setup in environment variables # then read conf from there, otherwise from project root if 'WALDUR_CONFIG' in os.environ: confi...
#code #from heapq import merge class VirArr(object): def __init__(self, arr1,arr2): self.arr1 = arr1 self.arr2 = arr2 def __getitem__(self, t): if t < len(self.arr1): return self.arr1[t] else: return self.arr2[t - len(arr1)] def __setitem__(self, t, val): if t < len(arr1): self.arr1[t] = val ...
import asyncio import threading from pytg.exceptions import NoResponse, IllegalResponseException, ConnectionError class PGThread(threading.Thread): def run(self): try: if self._target: self._target(*self._args, **self._kwargs) except (asyncio.TimeoutError, GeneratorExi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ this file contains pre-training and testing the mention proposal model """ import os import math import logging import numpy as np import tensorflow as tf from utils import util from utils.radam import RAdam from data_utils.input_builder import file_based_input_...
#!/usr/bin/python # -*- coding: utf-8 -*- DOCUMENTATION = ''' ''' EXAMPLES = ''' ''' RETURN = ''' '''
import numpy as np import dfa import matplotlib.pyplot as plt import scipy.signal as ss np.random.seed(42) print("1. Test") np.random.seed(42) X = np.random.randn(1000) X = np.abs(ss.hilbert(X)) #X = np.ones(1000) #np.array([[1.,1.], [2., 1.], [3., 1.2], [4., 1.], [5., 0.8], [6., 1.]]) scales, fluct_to_array, coeff_to...
import Command as Cmd from terminaltables import AsciiTable import JFIO import JEnum import JTarget class Command(Cmd.Command) : def __init__(self) : super().__init__() # Instruction of this command self.command = "targets" # Title of this command self.title ...
from dfa import DFA # Nome do arquivo contendo o AFD a ser lido filename = 'exemplo2.txt' # Nome do arquivo contendo a lista de palavras listname = "lista_exemplo.txt" # Cria o DFA baseado no arquivo dfa = DFA(filename) print(dfa) # Minimiza o dfa dfa.minimize() print(dfa) # Pede uma palavra para verificar se ela ...
import socket UDP_IP = "192.168.0.24" UDP_PORT = 5005 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) print "received message:", data
from application import create_app app = create_app("app_name") if __name__ == '__main__': app.run(app.config.get("SERVER_ADDRESS", "0.0.0.0"), port=app.config.get("SERVER_PORT", 5000))
# -*- coding: utf-8 -*- ''' @author: Dioooooooor (曹琛) @time: 2019.1.21 @version: 1.0 @desc: 资源视图 ''' from flask import jsonify, request, current_app, url_for, g from flask.views import MethodView from CakeOrderSys.apis.v1 import api_v1 from CakeOrderSys.models import Admin, Commodity from C...
#!/usr/bin/env python3 import sys import os sys.path.append(os.getenv("XRAY_DIR") + "/tools") import simpleroute print() print('ready') def load_design(f): ''' name node pin wire clk CLK_HROW_TOP_R_X60Y130/CLK_HROW_CK_BUFHCLK_L0 W5 HCLK_VBRK_X34Y130/HCLK_VBRK_CK_BUFHCLK0 din[0] INT_R_X9Y100/NE2BEG3 ...
# Copyright (c) 2010-2018, Emmanuel Blot <emmanuel.blot@free.fr> # Copyright (c) 2016, Emmanuel Bouaziz <ebouaziz@free.fr> # 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 o...
import numpy as np import tensorflow as tf import keras from keras.models import Sequential from keras.layers.core import Dense, Activation, Flatten, Dropout from keras.datasets import mnist import os # Load MNIST (X_train, y_train), (X_test, y_test) = mnist.load_data() # One-hot encode the labels y_train = keras.uti...
r''' use with eliduprees_3d_designs_path = r"C:\Users\Eli\Documents\eliduprees-3d-designs\" exec(open(eliduprees_3d_designs_path+"freecad_autorun.py").read()) autorun(eliduprees_3d_designs_path+"freecad_experiments.py") or eliduprees_3d_designs_path = open("/n/elidupree-autobuild/share_prefix").read().strip() + "/elid...
import numpy as np fock_N=10 N = 7 # number of spins # array of spin energy splittings and coupling strengths. here we use # uniform parameters, but in general we don't have to # init='mixed' init='xbasis' # dephasing rate # gamma = 0.01 * np.ones(N) g=0.05 kappa=1e-1*g beta=kappa # beta=0 gamma=1e-3*g detune= 1 # s...