Sunday, June 6, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Terraform Error refreshing state: BucketRegionError: incorrect region

Posted: 06 Jun 2021 08:34 AM PDT

I have the terraform file main.tf that used to create AWS resources:

provider "aws" {      region = "us-east-2"  }    resource "aws_instance" "example" {        ami = "ami-0c55b159cbfafe1f0"      instance_type = "t2.micro"      vpc_security_group_ids = [          aws_security_group.instance.id]        user_data = <<-EOF                #!/bin/bash                echo "Hello, World" > index.html                nohup busybox httpd -f -p "${var.server_port}" &                EOF        tags = {          Name = "terraform-example"      }  }    resource "aws_security_group" "instance" {        name = "terraform-example-instance"        ingress {            from_port = var.server_port          to_port = var.server_port          protocol = "tcp"          cidr_blocks = [              "0.0.0.0/0"]      }  }    resource "aws_security_group" "elb" {      name = "terraform-example-elb"      # Allow all outbound      egress {          from_port = 0          to_port = 0          protocol = "-1"          cidr_blocks = [              "0.0.0.0/0"]      }      # Inbound HTTP from anywhere      ingress {          from_port = 80          to_port = 80          protocol = "tcp"          cidr_blocks = [              "0.0.0.0/0"]      }  }    variable "server_port" {        description = "The port the server will use for HTTP requests"      type = number      default = 8080  }      variable "elb_port" {        description = "The port the server will use for HTTP requests"        type = number      default = 80  }      resource "aws_launch_configuration" "example" {        image_id = "ami-0c55b159cbfafe1f0"      instance_type = "t2.micro"      security_groups = [          aws_security_group.instance.id]        user_data = <<-EOF                #!/bin/bash                echo "Hello, World" > index.html                nohup busybox httpd -f -p "${var.server_port}" &                EOF      lifecycle {          create_before_destroy = true      }  }      resource "aws_elb" "example" {        name = "terraform-asg-example"      security_groups = [          aws_security_group.elb.id]        availability_zones = data.aws_availability_zones.all.names        health_check {          target = "HTTP:${var.server_port}/"          interval = 30          timeout = 3          healthy_threshold = 2          unhealthy_threshold = 2      }        # This adds a listener for incoming HTTP requests.      listener {          lb_port = var.elb_port          lb_protocol = "http"          instance_port = var.server_port          instance_protocol = "http"      }  }      resource "aws_autoscaling_group" "example" {        launch_configuration = aws_launch_configuration.example.id      availability_zones = data.aws_availability_zones.all.names        min_size = 2      max_size = 10        load_balancers = [          aws_elb.example.name]      health_check_type = "ELB"        tag {          key = "Name"          value = "terraform-asg-example"          propagate_at_launch = true      }  }    data "aws_availability_zones" "all" {}      output "public_ip" {        value = aws_instance.example.public_ip      description = "The public IP of the web server"  }  

I successfully created the resources and then, destroyed them afterward. Now, I would like to create an AWS S3 remote backend for the project and appended the extra resources in the same file -

resource "aws_s3_bucket" "terraform_state" {        bucket = "terraform-up-and-running-state12345"      # Enable versioning so we can see the full revision history of our      # state files      versioning {          enabled = true      }      # Enable server-side encryption by default      server_side_encryption_configuration {          rule {              apply_server_side_encryption_by_default {                  sse_algorithm = "AES256"              }          }      }  }      resource "aws_dynamodb_table" "terraform_locks" {        name = "terraform-up-and-running-locks"      billing_mode = "PAY_PER_REQUEST"      hash_key = "LockID"        attribute {          name = "LockID"          type = "S"      }  }        output "s3_bucket_arn" {        value = aws_s3_bucket.terraform_state.arn      description = "The ARN of the S3 bucket"  }    output "dynamodb_table_name" {        value = aws_dynamodb_table.terraform_locks.name      description = "The name of the DynamoDB table"  }  

Then, I created a new file named backend.tf and add the code there:

terraform {              backend "s3" {            # Replace this with your bucket name!          bucket = "terraform-up-and-running-state"          key = "global/s3/terraform.tfstate"          region = "us-east-2"              # Replace this with your DynamoDB table name!          dynamodb_table = "terraform-up-and-running-locks"          encrypt = true      }  }  

When I run the $ terraform init, I get the error below:

Initializing the backend...  Error refreshing state: BucketRegionError: incorrect region, the bucket is not in 'us-east-2' region at endpoint ''      status code: 301, request id: , host id:  

I created the S3 bucket from the terminal:

$ aws s3api create-bucket --bucket terraform-up-and-running-state12345 --region us-east-2 --create-bucket-configuration LocationConstraint=us-east-2  

Then, I tried again and receive the same error again.

Can someone explain to me why is that and how to solve it?

playing audio file during fetch react js

Posted: 06 Jun 2021 08:34 AM PDT

I have a node.js API which returns music file path on API call.

my.api.com/musics/1

I can get audio file and then play it with audio.play() function

const playAudio = async (id) => {      try {        const response = await axiosClient.get(`my.api.com/musics/${id}`)        const mp3 = new Blob([response.data], { type: 'audio/mp3' })        const url = window.URL.createObjectURL(mp3)        const audio = new Audio(url)        audio.load()        await audio.play()      } catch (e) {        console.log('play audio error: ', e)      }  }  

the problem is that I have to wait for the 10mb mp3 file to fully download and then play it. which is so bad on slow connections. I want to play the music as it is being fetched. can I do that only in client side and if yes how? I wanted to try this: socket.io-session but I'm not sure if it is the right way to do this. my goal is something like YouTube Music music player.

Dafny prove lemmas in a high-order polymorphic function

Posted: 06 Jun 2021 08:34 AM PDT

I have been working on an algorithm (Dafny cannot prove function-method equivalence, with High-Order-Polymorphic Recursive vs Linear Iterative) to count the number of subsequences of a sequence that hold a property P. For instance, how many subsequences hold that 'the number of positives on its left part are more that on its right part'.

But this was just to offer some context.

The important function is this CountAux function below. Given a proposition P (like, x is positive), a sequ sequence of sequences, an index i to move through the sequences, and an upper bound j:

function  CountAux<T>(P: T -> bool, sequ: seq<T>, i: int, j:int): int     requires 0 <= i <= j <= |sequ|    decreases j - i //necessary to prove termination    ensures CountAux(P,sequ,i,j)>=0;  {    if i == j then 0    else (if P(sequ[i]) then 1 else 0) + CountAux(P, sequ, i+1,j)  }      

To finish with it, now, it turns out I need a couple of lemmas (which I strongly believe they are true). But I have no idea how to do prove, could anyone help or provide the proofs? Do not seem difficult, but I am not used to prove in Dafny (sure they can be done using structural induction).

These are the lemmas I would like to prove:

  lemma countLemma1<T>(P: T -> bool, sequ: seq<T>,i:int,j:int,k:int)  requires 0<=i<=k<=j<=|sequ|  ensures CountAux(P,sequ,i,j)==CountAux(P,sequ,i,k)+CountAux(P,sequ,k,j)  //i.e. [i,k) [k,j)    lemma countLemma2<T>(P: T -> bool, sequ: seq<T>,i:int,j:int,k:int,l:int)  requires 0<=i<=j<=|sequ| && 0<=k<=l<=j-i  ensures CountAux(P,sequ[i..j],k,l)==CountAux(P,sequ,i+k,i+l)  //that is, counting the subsequence is the same as counting the original sequence with certain displacements    

How I can add a badge on my Dock icon using Cocoa?

Posted: 06 Jun 2021 08:34 AM PDT

I can't add a badge to my cocoa App icon on macOs BigSur. I'm trying to update icon's badge in Dock with this code:

NSApp.dockTile.badgeLabel = "12"  NSApp.dockTile.showsApplicationBadge = true  NSApp.dockTile.display()  

But nothing happens. And I received a message in Xcode console:

setShowsApplicationBadge: is not yet implemented for the NSApp dockTile  

Anybody can help with this?

Looking for an exact pattern not to get repetitive regexes

Posted: 06 Jun 2021 08:33 AM PDT

Is there a way to search if the text where I look for my pattern contains "exactly" the pattern I'm looking for.

More understandably : For example I want to know if my term, which can either be a numbered variable like this "x37" or simply a float like this : "8.65" is exactly a float when I'm looking for a float

The desired regexes can be :

pattern_var = re.compile("x\d+")  pattern_float = re.compile("\d+")  

The problem is the second one will also match when I have a numbered variable, which I don't want to Any clue ?

Thank you for your help

Converting HTML to PDF works only when conversion command is given in separate file

Posted: 06 Jun 2021 08:33 AM PDT

I would like to generate invoices with a little Python program I've written. I want it to output the invoice first as an HTML file, then convert it to a PDF. Currently my code is creating the HTML doc as desired, but it is outputting a blank PDF file:

import pdfkit   import time     name = input('Enter business name: ')  date = input('Enter the date: ')  total = 1000 # Fixed number for now just for testing purposes    f = open('invoice.html','w')  message = f"""<html>  <head>  <link rel='stylesheet' href='style.css')>  </head>  <body>  <h1>INVOICE<span id="invoice-number"> {invoice}</h1>  <h3>{date} </h3>   <h3>{name} </h3>  <h3>Total: ${total}</h3>  </body>  </html>"""    f.write(message)  time.sleep(2)    options = {      'enable-local-file-access': None  }  pdfkit.from_file('invoice.html', 'out.pdf', options = options)  

When I run the code above, the HTML doc it puts out looks fine, but the PDF it creates is blank. I receive no error messages at all. The output in Terminal is:

Loading pages (1/6)  Counting pages (2/6)                                                 Resolving links (4/6)                                                         Loading headers and footers (5/6)                                             Printing pages (6/6)  Done    

However, I have another file called test.py in the same directory. This file contains the import statement, exactly the same last four lines as the first code, and nothing else:

import pdfkit     options = {      'enable-local-file-access': None  }  pdfkit.from_file('invoice.html', 'out.pdf', options = options)  

If I run this file after the previous file, it correctly outputs the PDF to look just like the HTML version. Why does this code work when run in a separate file, but doesn't work when included in the original file? How can I get it to run in the same file so I don't have to execute two commands to get an invoice?

angular reactive forms - styling field color on invalid input

Posted: 06 Jun 2021 08:33 AM PDT

I'm using ReactiveForms and I can't seem to find a way to change the color of the form field outline when the input is invalid.

I need to change this color because the current red color isn't really optimal considering the background gradient, as you can see:

enter image description here

Here is my template:

<mat-form-field appearance="outline" hideRequiredMarker>      <mat-label>{{ matLabel }}</mat-label>      <input          #input          matInput          type="{{ inputType }}"          [formControl]="control"          style="caret-color: white"          autocomplete="off"      />      <mat-error style="color:white" *ngIf="control.invalid">{{ getErrorMessage() }}</mat-error>      ...  </mat-form-field>  

How can I change the outline color?

Thanks in advance.

WordPress rest api publish using custom type

Posted: 06 Jun 2021 08:33 AM PDT

I try to use WordPress rest api to publish using a custom type.
enter image description here Usually post_type is post, but I want to use api to use circle classification when publishing articles.

The following is the status in the database
The picture below is the state normally released. enter image description here
The picture below is the desired state enter image description here

Why does nothing appear ? Laravel?

Posted: 06 Jun 2021 08:33 AM PDT

web.php

<?php    use Illuminate\Support\Facades\Route;    /*  |--------------------------------------------------------------------------  | Web Routes  |--------------------------------------------------------------------------  |  | Here is where you can register web routes for your application. These  | routes are loaded by the RouteServiceProvider within a group which  | contains the "web" middleware group. Now create something great!  |  */    Route::get('/', function () {      return view('welcome');  });    Auth::routes();    Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');    Auth::routes();    Route::get('/pingu/{id}', [App\Http\Controllers\HomeController::class, 'pingu']);    Auth::routes();    Route::prefix('jobs')->group(function(){      Route::get('create', function () {          return "create";      });          Route::get('update', function () {          return "update";      });  });  

TaskController.php

<?php    namespace App\Http\Controllers;    use Illuminate\Http\Request;    class TaskController extends Controller    {    public function create(){              return view ('create');      }  }  

create.blade.php`

@extends('layouts.app')    @section('content')  <div class="container">      <div class="row justify-content-center">          <div class="col-md-8">              <div class="card">                  <div class="card-header">{{ __('Dashboard') }}</div>                    <div class="card-body">                      <form action="{{route('jobs.store')}}" method="POST">                          <input type="text" name="title" class="form-control">                          <button type="submit" class="btn btn-success">Submit</button>                      </form>                  </div>              </div>          </div>      </div>  </div>  @endsection    

I did exactly what to do in the turtorial but it dind't appear , please find fix that works. I use laravel 8 i tried to config :cache clear a nd then artisan serve again butdind't work .If you know a laravel enough ( 8 ) you should know that everything is done right .

Picture 1

Where to put function [closed]

Posted: 06 Jun 2021 08:34 AM PDT

My form is suppose to allow a user to enter 7 numeric grades, output the average of the numeric grades; As well convert the course grades into a letter grade and also display the course average letter grade. I created a string function that converts the grade percentage to a letter grade but I do not know exactly where to put the function in the btnCalculate as shown below.

namespace NETD2202Boychyn100752815GrdeCalculator  {      public partial class frmEdensGradeCalculator : Form      {          public frmEdensGradeCalculator()          {              InitializeComponent();          }            #region GLOBAL VARIABLES            TextBox[] courseEntries;          Label[] letterGrade;          const int MaxEntries = 7;          const int MinGrade = 0;          const int MaxGrade = 0;          int gradePercent = 0;            

No comments:

Post a Comment