text:
Q: Need to do page refresh for reflecting new changes in the UI I am using angular6, and for showing some records i am using angular material data table.
When i  save or delete any customer, the changes are persisting in DB but not reflecting in the UI, i need to do page refresh for reflecting the changes.
I have given the code on below, first it will load customerList then customer component as a popup
I am doing Rest Call for CRUD operations.
customerList.component.ts
**************************

import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
import { MatTableDataSource,MatDialog,MatDialogConfig } from '@angular/material';
import { CustomerComponent } from '../customer/customer.component';

@Component({
  selector: 'customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {

  dataSource;
  searchKey:string;

  displayedColumns = ['name','actions'];

  constructor(private service : UserService,
              private dialog : MatDialog) { }

  ngOnInit() {
    this.fetchCustomer();
  }

  onSearchClear(){
    this.searchKey="";
    this.applyFilter();
  }

  applyFilter(){
    this.dataSource.filter = this.searchKey.trim().toLowerCase();
  }

  newCustomer(){
    this.service.initializeForm();
    const dialogConfig = new MatDialogConfig();
    //dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.width = "60%";
    this.dialog.open(CustomerComponent, dialogConfig).afterClosed().subscribe(() => this.fetchCustomer());
  }

  viewCustomer(customer){
    console.log(event.target);
    this.service.populateForm(customer);
    const dialogConfig = new MatDialogConfig();
    //dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.width = "60%";
    this.dialog.open(CustomerComponent,dialogConfig);
  }

  editCustomer(customer){
    this.service.populateForm(customer);
    console.log(customer);
    const dialogConfig = new MatDialogConfig();
    //dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.width = "60%";
    this.dialog.open(CustomerComponent,dialogConfig);
  }

    deleteCustomer(id){
    this.service.deleteCustomerData(id).subscribe(
      data => console.log("success", data),
      error => console.error("Error!",error)
    );
    this.populateTable();
  }

  fetchCustomer(){
    this.service.getUser().subscribe( results => {
      if(!results){

        return;
      }
      console.log(results);
      this.dataSource = new MatTableDataSource(results);
  })
  }
}

customerList.component.html
*******************************

Customer-List

    <button mat-raised-button (click)="newCustomer()" style="position: absolute; right: 0;">
      <mat-icon>add</mat-icon>New Customer
    </button>

    <mat-table [dataSource]="dataSource">
      <ng-container matColumnDef="name">
        <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
        <mat-cell *matCellDef="let user">{{user.name}}</mat-cell>
      </ng-container>
      <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions </mat-header-cell>
        <mat-cell *matCellDef="let row">
          <button mat-icon-button matTooltip="Click to View" (click)="viewCustomer(row)" class="iconbutton" color="primary">
                <mat-icon>visibility</mat-icon>
              </button>
          <button mat-icon-button matTooltip="Click to Edit" (click)="editCustomer(row)" class="iconbutton" color="primary">
              <mat-icon>edit</mat-icon>
            </button>
          <button mat-icon-button matTooltip="Click to Delete" (click)="deleteCustomer(row)" class="iconbutton" color="warn">
              <mat-icon>delete</mat-icon>
            </button>
        </mat-cell>
      </ng-container>

      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns:displayedColumns"></mat-row>
    </mat-table>

customer.component.ts
**********************
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl,FormBuilder,Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material';
import { UserService } from '../services/user.service';

@Component({
  selector: 'app-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {

  constructor(private customerService : UserService,
              public dialogRef : MatDialogRef<CustomerComponent>) { }

  ngOnInit() {
    this.customerService.getUser();
  }

  onSubmit(){
    this.customerService.customerData(this.customerService.cutsomerForm.value).subscribe(
      data => console.log("success", data),
      error => console.error("Error!",error)
    );
   this.onClose();
  }

  onClose(){
    this.clearForm();
    this.dialogRef.close();
  }

  clearForm(){
    this.customerService.cutsomerForm.reset();
    //this.customerService.initializeForm();
  }
}

customer.component.html
*************************

New Customer

    <form [formGroup]="customerService.cutsomerForm" (ngSubmit)="onSubmit()" #newCustomer="ngForm">

        Customer Name
        <input [class.is-invalid]="customerService.cutsomerForm.get('name').invalid &&
                                   customerService.cutsomerForm.get('name').touched" formControlName = "name" type="text" class="form-control">

      <input type="hidden" formControlName="id">

        userName
        <input formControlName = "username" type="text" class="form-control">

        email
        <input formControlName = "email" type="text" class="form-control">

        phone
        <input formControlName = "phone" type="text" class="form-control">

        <button class="btn btn-primary" [disabled] = !newCustomer.valid type="submit">Submit</button>

    </form>
    <button class="btn btn-danger" (click)="clearForm()">Clear</button>

user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Customer } from '../models/Customer.model';
import { FormGroup, FormControl,FormBuilder,Validators } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class UserService {

 private serviceUrl = "https://jsonplaceholder.typicode.com/users";

  // private findAllCustomers = "http://localhost:8080/findAllCustomers";

  // private insertNewCustomer = "http://localhost:8080/addCustomer";

  constructor(private http : HttpClient,
    private fb : FormBuilder) { }

  cutsomerForm = this.fb.group({
    id : [''],
    name : ['',Validators.required],
    username : [''],
    email : [''],
    phone : ['']
  })

  initializeForm(){
    this.cutsomerForm.setValue({
      id : '',
      name : '',
      username : '',
      email : '',
      phone : ''
    });
  }

  getUser() : Observable<Customer[]> {
      return this.http.get<Customer[]>(this.serviceUrl);
  }

  customerData(customer: Customer): Observable<Customer> {
    return this.http.post<Customer>(this.serviceUrl,customer);
  }

  populateForm(customer){
    this.cutsomerForm.setValue(customer);
  }
}

A: You are saving or deleting a customer from the table, but the dataSource is using the data that you have already fetched from the database. It cannot get the updated data unless you manually do it.
While saving a new customer, you'll have to make the getUser() request again ( or push the customer object in the results variable) and initialize the dataSource again.
While deleting, again, either make the call again, or iterate through the result variable, find the customer that was deleted, remove it from the array, and reinitialize the dataSource.

A: Akash's approach is correct. In addition to his approach you should use afterClosed() method to link MatDialog to current component and get notified when the dialog is closed. After the dialog is closed, just fetch users again.
  ngOnInit() {
    this.fetchUsers();
  }

  newCustomer(type) {
    this.service.initializeForm();
    const dialogConfig = new MatDialogConfig();
    //dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.width = "60%";
    dialogConfig.id = type;
    this.dialog.open(CustomerComponent, dialogConfig).afterClosed().subscribe(() => this.fetchUsers());
  }

  fetchUsers() {
    this.service.getUser().subscribe(results => {
      if (!results) {
        return;
      }
      console.log(results);
      this.dataSource = new MatTableDataSource(results);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
    })
  }

Also if you share the code for deletion and CustomerComponent it would be easier to analyse any potential problems.


text:
Q: Out Of Memory Exception While Getting AlbumArt Here i have created expandable list view which is having group row for Artist and in child it shows all albums for artist with album art. But It throws out of memory exception.
Here Is my code to get the Image :
public static Bitmap getArtwork(Context context, int album_id) {

        ContentResolver res = context.getContentResolver();
        Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
        if (uri != null)
        {
            InputStream in = null;
            try
            {
                in = res.openInputStream(uri);
                return BitmapFactory.decodeStream(in, null, sBitmapOptions);
            } catch (FileNotFoundException ex)
            {
                // The album art thumbnail does not actually exist. Maybe the user deleted it, or
                // maybe it never existed to begin with.
            } finally
            {
                    if (in != null)
                    {
                        try
                        {
                            in.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
             }
        return null;
    }

And for creating child album list i have done this :
private ArrayList<ArrayList<HashMap<String, Object>>> createChildList() {
    for (int i = 0; i < songsListData.size(); i++)
    {

        ArrayList<HashMap<String,Object>> secList = new ArrayList<HashMap<String,Object>>();
        String s[] = new String[]{songsListData.get(i).get("artistname")};
        String whereClause = MediaStore.Audio.Albums.ARTIST + " = ? ";

        Cursor cursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,null ,whereClause,s,null);

        if (cursor == null)
        {
              //Query Failed , Handle error.
        }
        else if (!cursor.moveToFirst())
        {
             //No media on the device.
        }
        else
        {
              int albumName = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM);
              int id = cursor.getColumnIndex(MediaStore.Audio.Albums._ID);
              int songcount = cursor.getColumnIndex(MediaStore.Audio.Albums.NUMBER_OF_SONGS);

              for(int j=0;j<cursor.getCount();j++)
              {
                    String Name = cursor.getString(albumName);
                    Integer albumid = cursor.getInt(id);
                    Bitmap bitmap = null;
                    bitmap = getArtwork(context, albumid); //calling function
                    if(bitmap == null)
                    {
                        bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.wallpaper);
                    }
                    HashMap<String, Object> album = new HashMap<String, Object>();
                    album.put("albumName",Name);
                    album.put("albumId", albumid);
                    album.put("image", bitmap);  //storing image
                    album.put("songcount",cursor.getString(songcount) + " song");
                    secList.add(album);
                    cursor.moveToNext();
               }
           }
           cursor.close();
           albumData.add(secList);
    }
    return albumData;
}

what should i do to handle out of memory exception.?? Pleaze give me some solution. Thanx.

A: Debug your code and trace heap size when it goes unexpectedly up
that must be due to increase image Size
you can use the Document to Get an idea that how Android calculate the Image Size
public static Bitmap getResizedBitmap(Bitmap image, int newHeight, int newWidth) {
    int width = image.getWidth();
    int height = image.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(image, 0, 0, width, height,
            matrix, false);
    return resizedBitmap;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get original HTTP response of a WCF call I'm calling a SOAP web service using WCF. When the server gots error or turns into maintenance state, it replies with a HTML document. With WCF client an TargetInvocationException will be thrown because the reply is not a soap message.
I want to intercept the HTTP response and do some process (logging for exemple) when the server turns into abnormal state. I tried the IClientMessageInspector with IEndpointBehavior, when the server replies well (even Soap Fault), the method IClientMessageInspector.AfterReceiveReply fires and i can catch the message.
But when the server replies with a HTML document (where i need that method fired), that method did not fired. i just got TargetInvocationException and within that exception i can not get the original http reponse.
Does any one faced the same problem and maybe a solution for this ?
Thanks.


text:
Q: Why can't docker see my template file in my node Run directly from my local directory, this works fine. I type 'localhost:3002' in the browser and up pops my 'find.html' page. However, when I dockerise it and try the same command, it craps out complaining that macro.njk can't be found.
Dockerfile:
FROM node:14.17.5
ENV NODE_ENV=production
WORKDIR /application
COPY ["package.json", "package-lock.json*", "./" ]
RUN npm install --production
COPY . .
CMD ["node", "app.js"]

In find.html:
{% extends "layout/layout.njk" %}

Nunjucks setup in app.js:
const express = require('express');
const path = require('path');
const nunjucks = require('nunjucks');

nunjucks.configure(['views',
  path.join(__dirname, 'node_modules/motluk-frontend/'),
  path.join(__dirname, 'node_modules/motluk-frontend/motluk/components/'),
  path.join(__dirname, 'app/views/'),
], {
  autoescape: true,
  express: app,
});

// view engine setup
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({
  extended: true,
}));

directory setup:
/app/views/layout/layout.njk
/app/views/pages/find.html
The error message I get:
Template render error: (/application/app/views/pages/find.html)
Error: template not found: input/macro.njk


text:
Q: Issue in setting up element value in IE I have a problem setting up a value of an element in IE 8.
document.getElementById("id28").value=" ";

Above code clears value for the element in Mozilla Firefox 26.0 and Chrome version 19.
But the same doesn't work for IE 8. I have also tried with IE 9 and IE 10, but no luck.
Can anyone please suggest any workaround or solution for this issue.
Thanks in advance

A: I tried the problem you have with IE8 first the element is not cleared but after I added the the site to trusted sites it works


text:
Q: Angularjs refreshing after action same page I'm trying to load a function on a link click, which works perfectly. Then angularjs does its magic until it arrives on the point where it shows the user feedback. I need to refresh the page after deleting an item, but it simply won't refresh.
Here's my href:

here's my Controller:
$scope.deleteGroup = function ($groupId) {
    $http({
        method: 'POST',
        url: apiUrl + 'group/delete',
        data: {'groupId': $groupId},  // pass in data as strings
        //headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        // set the headers so angular passing info as
        // form data (not request payload)
    })
    .success(function (data) {
        if (!data.success) {
            //$route.reload();
            alert('groep is verwijderd');
        } else {
            $scope.group = data;
            //$state.go('userDetail', {'user_id' : $userId});
        }
    });
};

and my html:

            {{group.title}}

A: Your $scope.deleteGroup function should remove its target group from the $scope.groups so the content of the ng-repeat is automatically updated and does not display the group anymore.
$scope.deleteGroup = function (group) {
    $http({
        method: 'POST',
        url: apiUrl + 'group/delete',
        data: {'groupId': group.$groupId},  // pass in data as strings
        //headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        // set the headers so angular passing info as
        // form data (not request payload)
    }).success(function(data) {
        $scope.groups.splice($scope.groups.indexOf(group));
    });
};

A: To force refreshing the page with uiRouter you can use $state.go(target, params, {reload: true}).
$scope.deleteGroup = function (group) {
  $http({
    method: 'POST',
    url: apiUrl + 'group/delete',
    data: {'groupId': group.groupId},  // pass in data as strings
    //headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    // set the headers so angular passing info as
    // form data (not request payload)
  }).success(function(data) {
    // This will reload the current state with the same stateParams
    $state.go($state.current.name, $stateParams, {reload: true});
  });
};


text:
Q: I don't know how to replace a line in notepad++ I don't now know how to do it
It's simple, I even made a short video https://youtu.be/3-fHpqXdK8c

A: One can replace text in Notepad++ and many other apps by using "Regular Expressions". (Research and study "regular expressions" if necessary.) In Notepad++, type Ctrl-Shift-F, which launches "find in files", click the "Regular Expressions" radio button in the lower-left quarter, then enter a regular expression and a replacement string. For example:
Regular expression string: ^ReplacedBlocks: (.*)$
Replacement string: ReversedClocks: $1
That would change THIS:
ReplacedBlocks: (AIR,LAVA,1,2)
into THIS:
ReversedClocks: (AIR,LAVA,1,2)


text:
Q: NodeJS Good way to chain method to scrape a slow web site Can not get access to the database so I have to scrape a web site to get his data back.
The site and server is poorly developed so some page made up to > 10s to render.
I use Node and request-promise to get the html and cheerio to build a JS Object that I want to convert to a JSON file. I have to loop over the all the day of serval year in the params of the URL (doing it for January 2016 to test first).
My problem is Node use async event. So all my loop are triggered at the same time as all the request are made (around 100ms so it's like instant). The web site cannot handle this so I started to get the first html then 500 error.
What I plan to do is to wait to fully scrape on iteration before calling the next request (to let the poor server breath a bit).
Like so :

Enter the loop => request => get html back (10s) => scrape it => write on the disk => i++ ; Enter the loop => ...

and not doing it async.
Here a bunch of my code :
var rp = require('request-promise')
var cheerio = require('cheerio')

[...]

console.log('Start ');

let array = []

for (var year = 2016; year < 2017; year++) {

for (var month = 1; month <= 1; month++) {

for (var day = 1; day <= 31; day++) {

const options = {
  url : 'http://myurl',
  Cookie: cookie,
  transform: function (body) {
        return cheerio.load(body);
    }
}

let data

rp(options)
    .then(function ($) {
       => My Scraping stuff return in data
    })
    .catch(function (err) {
        // Crawling failed or Cheerio choked...
    })
    .pipe(fs.writeFile(`./data/${timestamp}.json`, JSON.stringify(data), function(err) {
          if (err) {
            console.log(err);
          }
          console.log(` File successfully written! - ${timestamp}`)
        })

        }
    }
}

If I tweak the loop to work for like 2 or 3 days only everything is going well.

A: I use: Crawler package. It work very good for me :)


text:
Q: finding the previous Monday I'm looking for a way to find the date object for the PREVIOUS calendar week's Monday. For example, today is 1/15/2016; I need to build a function that will return '2016-01-04 UTC'

A: The question asks for the "previous calendar week's Monday".   We assume below that this means that you want the Monday on or before the input date.
Note that it would be better to use "Date" class since times are not needed and "Date" class has no time zone so it avoids potential time zone errors associated with "POSIXt" classes.
There is  nextfri function in the zoo vignette, zoo quickref vignette which we can use as the basis of a similar function.  We make these changes (1) ceiling is replaced with floor, (2) 5 (Friday) is replaced with 1 (Monday) and (3) we add the origin= argument to as.Date -- if zoo is loaded a default origin is provided so the origin= argument could be optionally omitted.
This function uses only base R and is vectorized.  It accepts a "Date" class vector and returns a "Date" class vector of dates for the Monday on or before the respective input dates.
lastmon <- function(x) 7 * floor(as.numeric(x-1+4)/7) + as.Date(1-4, origin="1970-01-01")

For example,
 > lastmon(as.Date(c("2016-01-15", "2016-01-11")))
[1] "2016-01-11" "2016-01-11"

The lastmon function could alternately be simplified to just:
lastmon2 <- function(x) x - as.numeric(x-1+4)%%7

Note: also see the SO answers here, here, here and here for more uses of nextfri or variations thereof.

A: There's also a lubridate solution (from martin.R):
library(lubridate)
ceiling_date(your_date, "week", 1)

Likewise, to find last Monday:
floor_date(your_date, "week", 1)

Documentation of the functions.


text:
Q: Apache: Issue with .profile in the URL I use Google Apps SSO to authenticate my users for all my WordPress sites. In the authentication process google returns few parameters to the given url and one of the parameters is scope which consists of https://www.googleapis.com/auth/userinfo.profile scope.
By default wordpress relies on apache for SEO friendly url's/permalinks. Now when google redirects me to https://example.com/wp-login.php?state=###&code=###&scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/userinfo.email server(apache) is giving me a 404 error. After some trial and error I found out if I remove the .profile from the url or just remove . (dot) redirection/behaviour happens as expected.
I'm not a apache expert so I want understand this behavior and how can I resolve this in global scope.
--- Edit ---
.htaccess file in the local scope
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

From my understanding if a file/directory specified in the url doesn't exist then the request is handed over to the WordPress index.php for processing.
@MrWhite: To answer your question, from the URL I mentioned above wp-login.php file exists but still apache passes down the request to index.php WordPress which return 404 error.
Using filters if I change the url from example.com/wp-login.php to example.com/login I get 403 error.
But if I remove . (dot) in the url before profile keyword everything works as expected.
-- edit 2 --
I found out this is happening because of mod_security rule to restrict access to OS files. https://github.com/SpiderLabs/owasp-modsecurity-crs/blob/c06e2f5f7efa1c24f18ddf9a3298e3db4cdfeaac/rules/restricted-files.data#L34 I understand this is a necessary rule but how do make mod_security allow https://www.googleapis.com/auth/userinfo.profile in the URL args (just this URL)?


text:
Q: S3 tagging and access control policies not working for limiting the tags keyset on an object Trying to restrict tags to only a given set of keys that can be attached to the objects. Using bucket level policies to define this condition. However, the logic is not working. Bucket policy (https://docs.aws.amazon.com/AmazonS3/latest/userguide/tagging-and-policies.html)
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<Account-Id>:user/AdminUser"
            },
            "Action": "s3:PutObjectTagging",
            "Resource": "arn:aws:s3:::test-notifications-per-prefix/*",
            "Condition": {
                "ForAllValues:StringLike": {
                    "s3:RequestObjectTagKeys": "LIFE"
                }
            }
        }
    ]
}

Boto3 code to upload the object
s3 = boto3.client('s3')
response = s3.put_object_tagging(
    Bucket='test-notifications-per-prefix',
    Key="file.txt",
    Tagging = {
        'TagSet': [
            {
                'Key': "TEST",
                'Value': "SHORTTERM"
            }
        ]
    }
)

The object is still getting uploaded when i run the above code.
I am not able to figure out as why this is happening. Tried denying object tagging in the bucket policy (removed the condition from the policy and made the effect as Deny) then any object uploaded with a tag was throwing an access denied error. (so, the rules are being applied for sure)
Can you please let me know as what i am doing wrong here?

A: {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Deny",
            "Principal": {
                "AWS": "arn:aws:iam::<account-id>:user/AdminUser"
            },
            "Action": "s3:PutObjectTagging",
            "Resource": "arn:aws:s3:::<bucket-name>/prefix1/*",
            "Condition": {
                "StringNotEquals": {
                    "s3:RequestObjectTag/LIFE": [
                        "2",
                        "15"
                    ]
                }
            }
        }
    ]
}

Able to restrict the key and value pairs in my S3 bucket using the following bucket policy. An explicit deny is denying all the requests coming from the principal that do not have the following tags.
However, this policy will not work for object that are uploaded without tags.
EDIT:
We can define the below policy defined for a role to enforce the tags that are uploaded with given key and value pairs
{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "s3:PutObject",
        "Resource": "arn:aws:s3:::<bucket-name>/prefix1/*",
        "Condition": {
            "ForAnyValue:StringEquals": {
                "s3:RequestObjectTagKeys": "LIFE"
            },
            "ForAllValues:StringEquals": {
                "s3:RequestObjectTag/LIFE": ["2", "15"]
            }
        }
    }
]

}


text:
Q: Extending a function beyond the completion/closure of its domain In  analysis there are certain theorems that tell under which conditions you can continuously extend a continuous functions to the closure/completion of its domain (which actually give the same set, since when talking about completions we have to be (at least) in a metric space).
The theorems I have in mind are these three:

*

*Every uniformly continuous mapping between a metric space and a complete metric can be extended uniformly continuous to a mapping between the completion of the domain and the range.

*Every continuous function on a dense subset can be continuously extend to the closure of that subspace (which is by definition of "dense", the whole space).

*The theorem from here.

What I'm looking for is a collection of theorems that tell me under which circumstances one can extend a  continuous function beyond the completion or the closure of it's domain.
The only theorem of this kind that I know of is the famous Tietze-Urysohn extension theorem (which applies to function whose domain is already a closed set).
I'd be also happy with a reference, as long as the theorems listed there are quickly accessible (i.e. don't require reading through a thicket of abstract/very specialized definitions before getting to the theorems - the more "concrete" the theorems are (as in $\mathbb{R}^n$, or a metric space), the better.

A: Extensions problems come in two basic shapes:

*

*unique extension from a non-closed set to its closure

*non-unique extension from a closed set to a larger set

So it makes sense that many extension theorems fall into one or the other class. Sometimes you just have to use two of them.
But extension theorems for Lipschitz functions, from the simple McShane-Whitney theorem to the more sophisticated Kirszbraun's theorem and its generalizations, do not care whether the domain is closed or not.
The recent two-volume book Methods of geometric analysis in extension and trace problems by Brudnyi and Brudnyi looks like the reference you want. It has separate chapters for results for $\mathbb R^n$ and for general metric spaces.


text:
Q: NodeJS Creating a REST Post API I'm trying to learn how to create REST endpoints with NodeJS.
Could you give me an idea of how I'd write the business logic for the following POST endpoint?
Feature: Add a measurement
  I want to be able to capture a measurement of several metrics at a specific time

  Scenario: Add a measurement with valid (numeric) values
    # POST /measurements
    When I submit a new measurement as follows:
      | timestamp                  | temperature | dewPoint | precipitation |
      | "2015-09-01T16:00:00.000Z" | 27.1        | 16.7     | 0             |
    Then the response has a status code of 201
    And the Location header has the path "/measurements/2015-09-01T16:00:00.000Z"

  Scenario: Cannot add a measurement with invalid values
    # POST /measurements
    When I submit a new measurement as follows:
      | timestamp                  | temperature    | dewPoint | precipitation |
      | "2015-09-01T16:00:00.000Z" | "not a number" | 16.7     | 0             |
    Then the response has a status code of 400

  Scenario: Cannot add a measurement without a timestamp
    # POST /measurements
    When I submit a new measurement as follows:
      | temperature | dewPoint | precipitation |
      | 27.1        | 20       | 0             |
    Then the response has a status code of 400

this how I have my server.js and routes.js setup so far, now I'm wondering how I'd add business logic and the appropriate routing that would comply with the requests above.
// server.js
import { createServer } from 'http';
import handler from './routes';

const PORT = +process.env.PORT || 5000;

const server = createServer(handler)
  .on('listening', () => {
    const { port } = server.address();
    console.log(`Server listening on port ${port}`);
  })
  .on('close', () => console.log('Server closed.'));

server.listen(PORT);

// routes.js
const server = express();
server.use(parseJsonBody());

server.get('/', (req, res) => res.send('server is running!'));

registerMeasurements(server);
registerStats(server);

export default server;

A: We used to have to use bodyParser, but now you can use instead of bodyParser
Body parser example

npm install --save body-parser

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies

app.post('/measurement', function(req, res) {
    var timestamp = req.body.timestamp; // Post body value, ex. measurement
    var temperature = req.body.temperature;
});

Now we do not have to use bodyParser, we could do the following which is the equivalent
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

Here is an example for some basic if logic after the post request
const express = require('express');
const app = express();

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
}));

app.post(`/mesurement`, (req, res) => {
    var temperature = req.body.temperature;
    let timestamp = req.body.timestamp;
    let dewPoint = req.body.dewpoint;
    let precipitation = req.body.precipitation;
    if (temperature && timestamp && dewPoint && precipitation !== undefined) {
        temperature = parseFloat(temperature);
        dewPoint = parseFloat(dewPoint);
        precipitation = parseFloat(precipitation);
        if (Number.isInteger(temperature)
            && Number.isInteger(dewPoint)
                && Number.isInteger(precipitation)) {
            console.log("We recieved, ", temperature, dewPoint, precipitation)
            res.status(201)
        }
    }

});

app.listen(3000);

Test your post endpoints with https://www.getpostman.com


text:
Q: "Grouping" dictionary by value I have a dictionary: Dictionary<int,int>. I want to get new dictionary where keys of original dictionary represent as List<int>. This is what I mean:
var prices = new Dictionary<int,int>();

The prices contain the following data:
1   100
2   200
3   100
4   300

I want to get the IList<Dictionary<int,List<int>>>:
int      List<int>
100      1,3
200      2
300      4

How can I do this?

A: You can use GroupBy.
Dictionary<int,List<int>> groups =
             prices.GroupBy(x => x.Value)
                   .ToDictionary(x => x.Key, x => x.Select(i => i.Key).ToList());

A: var prices = new Dictionary<int, int>();
prices.Add(1, 100);
prices.Add(2, 200);
prices.Add(3, 100);
prices.Add(4, 300);

Dictionary<int,List<int>> test  =
                   prices.GroupBy(r=> r.Value)
                  .ToDictionary(t=> t.Key, t=> t.Select(r=> r.Key).ToList());

A: Here is my reply. When the dictionaries get large, you will likely find the GroupBy() extension methods less efficient than you would like, as they provide many guarantees that you don't need, such as retaining order.
public static class DictionaryExtensions
{
    public static IDictionary<TValue,List<TKey>> Reverse<TKey,TValue>(this IDictionary<TKey,TValue> src)
    {
        var result = new Dictionary<TValue,List<TKey>>();

        foreach (var pair in src)
        {
            List<TKey> keyList;

            if (!result.TryGetValue(pair.Value, out keyList))
            {
                keyList = new List<TKey>();
                result[pair.Value] = keyList;
            }

            keyList.Add(pair.Key);
        }

        return result;
    }
}

And an example to use in LinqPad:
void Main()
{
    var prices = new Dictionary<int, int>();
    prices.Add(1, 100);
    prices.Add(2, 200);
    prices.Add(3, 100);
    prices.Add(4, 300);

    // Dump method is provided by LinqPad.
    prices.Reverse().Dump();
}

A: You can use GroupBy followed by the Func<TSource, TKey>, Func<TSource, TElement> overload of Enumerable.ToDictionary:
var d = prices.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.ToList());

A: You can use Lookup instead.
var prices = new Dictionary<int, int> { {1, 100}, { 2, 200 }, { 3, 100 }, { 4, 300 } };
ILookup<int, int> groups = prices.ToLookup(x => x.Value, y => y.Key);
foreach (var group in groups)
{
    foreach (var item in group)
    {
        Console.WriteLine(item);
    }
}

A: In particular case, when we use the .NET framework 2.0, we can do as follows:
var prices = new Dictionary<int, int>();
prices.Add(1, 100);
prices.Add(2, 200);
prices.Add(3, 100);
prices.Add(4, 300);

Dictionary<int, List<int>> grouping = new Dictionary<int, List<int>>();

var enumerator = prices.GetEnumerator();
while (enumerator.MoveNext())
{
    var pair = enumerator.Current;
    if (!grouping.ContainsKey(pair.Value))
        grouping[pair.Value] = new List<int>();
    grouping[pair.Value].Add(pair.Key);
}


text:
Q: Commands return data I'm trying to clean up some of my controllers by moving the functionality from the controller methods to reusable commands that I can just pass on to a command bus. As I've understood, though, a command is not supposed to return data (or did I misunderstand something?). But how else would you suggest for the controller to act on the outcome of the command?
For instance I have a Create endpoint in my ClientController. The controller method dispatches a CreateClient command, and then I'd like to redirect the user to the new Client's edit page. Something like
class ClientController extends Controller
{
    public function create($request)
    {
        try {
            $this->dispatch(new CreateClient(/*get something from the request to pass*/));
        } catch (\Exception $e) {
            return $this->json(['error' => $e->getMessage()]);
        }

        $client = ...;
        $this->redirect('/client/' . $client->id);
    }
}

If the creation failed I can throw an exception, which can be handled by the controller. I could of course create a method in my ClientRepository to get the newest created Client, but that seems error prone. But how would you suggest that I got a hold of the newly created client?
Edit:
At the end of https://www.youtube.com/watch?v=fbSYZFZCFS0 they discus this actual problem. Their main suggestions are using UUIDs so the ID can be generated by the controller, or using an asynchronous method to poll for the new item.
They also mention the possibility of using event listeners, but argue that it's an anti-pattern in PHP.
I'm still undecided on how I'll prefer to do it.


text:
Q: df -h giving fake data? when i'm writing df -h in my instance i'm getting this data:
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        7.7G     0  7.7G   0% /dev
tmpfs           7.7G     0  7.7G   0% /dev/shm
tmpfs           7.7G  408K  7.7G   1% /run
tmpfs           7.7G     0  7.7G   0% /sys/fs/cgroup
/dev/nvme0n1p1   32G   24G  8.5G  74% /
tmpfs           1.6G     0  1.6G   0% /run/user/1000

but when i'm clicking sudo du -sh / i'm getting:
11G /

So in df -h, / size is 24G but in du -sh same directory the size is 11G.
I'm trying to get some free space on my instance and can't find the files that cause that.
What i'm missing?
did df -h is really giving fake data?

A: This question comes up quite often. The file system allocates disk blocks in the file system to record its data. This data is referred to as metadata which is not visible to most user-level programs (such as du). Examples of metadata are inodes, disk maps, indirect blocks, and superblocks.
The du command is a user-level program that isn't aware of filesystem metadata, while df looks at the filesystem disk allocation maps and is aware of file system metadata.  df obtains true filesystem statistics, whereas du sees only a partial picture.
There are many causes on why the disk space used or available when running the du or df commands differs.
Perhaps the most common is deleted files. Files that have been deleted may still be open by at least one process. The entry for such files is removed from the associated directory, which makes the file inaccessible. Therefore the command du which only counts files does not take these files into account and comes up with a smaller value. As long as a process still has the deleted file in use, however, the associated blocks are not yet released in the file system, so df which works at the kernel level correctly displays these as occupied.  You can find out if this is the case by running the following:
lsof | grep '(deleted)'

The fix for this issue would be to restart the services that still have those deleted files open.
The second most common cause is if you have a partition or drive mounted on top of a directory with the same name.  For example, if you have a directory under / called backup which contains data and then you mount a new drive on top of that directory and label it /backup but it contains no data then the space used will show up with the df command even though the du command shows no files.
To determine if there are any files or directories hidden under an active mount point, you can try using a bind-mount to mount your / filesystem which will enable me to inspect underneath other mount points. Note, this is recommended only for experienced system administrators.
mkdir /tmp/tmpmnt
mount -o bind //tmp/tmpmnt
du /tmp/tmpmnt

After you have confirmed that this is the issue, the bind mount can be removed by running:
umount /tmp/tmpmnt/
rmdir /tmp/tmpmnt

Another possible cause might be filesystem corruption.  If this is suspected, please make sure you have good backups, and at your convenience, please unmount the filesystem and run fsck.
Again, this should be done by experienced system administrators.
You can also check the calculation by running:
strace -e statfs df /

This will give you output similar to:
statfs("/", {f_type=XFS_SB_MAGIC, f_bsize=4096, f_blocks=20968699, f_bfree=17420469,
f_bavail=17420469, f_files=41942464, f_ffree=41509188, f_fsid={val=[64769, 0]},
f_namelen=255, f_frsize=4096, f_flags=ST_VALID|ST_RELATIME}) = 0
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/vda1 83874796 14192920 69681876 17% /
+++ exited with 0 +++

Notice the difference between f_bfree and f_bavail?  These are the free blocks in the filesystem vs free blocks available to an unprivileged user.  The used column is merely a calculation between the two.
Hope this will make your idea clear. Let me know if you still have any doubts.


text:
Q: Function 'on change' of javascript not working in asp.net mvc I tried viewing a list of products based on categories using js ASP.NET MVC 5. I am new to this, it will simply not act on the select box. this is my code:
My Select block:
<select class="SelectCategory" name="SelectCategory">
<option value="0">All</option>
@foreach (var item in ViewBag.categories)
{
    if (ViewBag.SelectedCat == item.Value)
    {
        <option selected="selected" value="@item.Value">@item.Text</option>
    }
    else
    {
        <option value="@item.Value">@item.Text</option>
    }
}

Js:
@section Scripts {
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script>

    $(function () {

        $("#SelectCategory").on("change",
            function() {
                var url = $(this).val();
                if (url) {
                    window.location = "/admin/shop/Products?catId=" + url;
                }

                return false;
            });
});

</script>
}

A: $("#SelectCategory").on("change",
That's wrong, as your element doesn't contain an ID element which is what the # symbol indicates in your jQuery selector.
If you want to target elements by the name attribute, you should use the following:
$("[name='SelectCategory']").on("change",

A: $("#SelectCategory") this will look for dom with id, but you have used class and name. You can add id attribute to select
<select id='SelectCategory' class="SelectCategory" name="SelectCategory">


text:
Q: 403 Forbidden after changing permission of files and folders Magento officially recommends to set the permission of all folders to 700 and of files to 600. (Source)
They instruct us to execute these commands to set the permissions:
find . -type d -exec chmod 700 {} \;
find . -type f -exec chmod 600 {} \;

However, now I get 403 forbidden when I try to access the site.
Should I change it to 766 (folders) and 666 (files) instead?

A: It depends very much on the configuration of your system.
When you are setting all permissions with the command of your question, executed as root, you are allowing only the root user to access these files.
The permission mask reads as follows:
000
^^^
|||
||+--- Other
|+---- Group
+----- Owner

So a permission mask of 600 with a root ownership wouldn't let the webserver's user (or php process' user) to read or access those files.
The first step would be to find out ther user that's running your webserver (Apache, Nginx, or whatever you are using), and the user assigned to your php process (in case you are using something like php-fpm).
If you are on an Ubuntu system, more likely than not that user is www-data. But you should make sure, since the details are configuration dependent.
Assuming the user you got is www-data, you go to the directory where you were runnig the chmod and change all the files so they are owned by this user:
chown -R www-data: {.??,}*

Later you apply the permissions from your question, and it should work.
Note: This is probably not how I would set up an installation, security wise, but that is beyond the scope of the question.

A: You should change the ownership like this:
sudo adduser <username> www-data
sudo usermod -a -G <username> www-data
sudo chown :www-data /var/www -R
sudo chmod g+rwX /var/www -R
sudo chmod g+s /var/www

Also set magento required permission to files and folder
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod 550 mage

Hope these help.


text:
Q: If module.exports creates a new class, is it newly created if called with require? Or does it only work with one? in node.js I'm worried about the memory increase.
If I use require as below, does the class create memory every time?
------------ a.js -------------`
class a {
 constructor(){
   }
}

module.exports = new a();
---------------

const IsMemoryIncrease = require('a');

A: Once a module is loaded, it is cached by the system.  Subsequent attempts to load that module again just return the exact same module.exports that was previously created.  The module initialization code is not run again.
So, in your case, every module that loads a.js will get the exact same instance of the a class.  There will only be one instance.

A: Run this
// b.js
const IsMemoryIncrease1 = require('./a');
const IsMemoryIncrease2 = require('./a');

console.log(IsMemoryIncrease1);
console.log(IsMemoryIncrease2);
console.log(IsMemoryIncrease2 == require('./a'));


text:
Q: How to get a single paragraph text from a richtextbox when double clicking on it I'm having some trouble getting control of the WPF richtextbox control.
What I want to is as follows :
I have a RichTextBox control called richTextBox1 that I filled up with data from a database.
I need to get the text on a single line (meaning - a single paragraph) when I click the control.
All I found over the net is a code to copy ALL the RTB text.
Any ideas how to get just the text in the line that was clicked ?

A: I made serious web digging and here is a working solution.
private void richTextBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
  TextPointer t = richTextBox1.GetPositionFromPoint(e.GetPosition(richTextBox1), true);

  string textAfterCursor  = t.GetTextInRun(LogicalDirection.Forward);
  string textBeforeCursor = t.GetTextInRun(LogicalDirection.Backward);

  string FullParagraphText = textBeforeCursor+textAfterCursor;
  MessageBox.Show(FullParagraphText);
}

(thanks to Justin-Josef with his post :
http://blogs.microsoft.co.il/blogs/justinangel/archive/2008/01/29/tapuz-net-getting-wpf-s-flowdocument-and-flowdoucmentreader-mouseover-text.aspx
)

A: The following code is correct:
private void richTextBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    TextPointer tp = richTextBox1.GetPositionFromPoint(e.GetPosition(richTextBox1), true);

    TextPointer line_start = tp.GetLineStartPosition(0);
    var nextStart = pos.GetLineStartPosition(1);
    TextPointer lineEnd = (nextStart != null ? nextStart : pos.DocumentEnd).GetInsertionPosition(LogicalDirection.Backward);

    TextRange tr = new TextRange(line_start, lineEnd);
    string line = tr.Text;
    MessageBox.Show(line);
}

A: OOPS, I concated the strings in reverse order.
Here is the revised code ... :)
Ohad.
   private void richTextBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        TextPointer t = richTextBox1.GetPositionFromPoint(e.GetPosition(richTextBox1), true);

        string textAfterCursor  = t.GetTextInRun(LogicalDirection.Forward);
        string textBeforeCursor = t.GetTextInRun(LogicalDirection.Backward);

        string FullParagraphText = textBeforeCursor+textAfterCursor;
        MessageBox.Show(FullParagraphText);

    }


text:
Q: QBO3 Workflow Dependencies I have a QBO3 workflow using compound dependencies:

*

*Step A

*Step B

*Step C

*Step D: depends on (Step A or Step B) and (Step C)

*Step E: depends on (Step A) or (Step B and Step C)

QBO3 appears to support my dependency requirement for Step D, but not for Step E.
Can QBO3 be configured to support the dependencies of Step E?

A: Yes, QBO3 supports (Step A) or (Step B and Step C), but you need to create an extra workflow step to configure it:

*

*Step A

*Step B

*Step C

*Step D: depends on (Step A or Step B) and (Step C)

*Step X: depends on (Step B and Step C)

*Step E: depends on (Step A) or (Step X)

Step X can be an If/Then step that evaluates to true (always). It simply won't be created until both Step B and Step C are created.

QBO3 dependencies implement and and or statements via a GroupNumber column. When evaluating whether or not a step's dependencies have been met, the SQL requires at least 1 dependency for each GroupNumber to have been met.
(Step A or Step B) and (Step C)
is configured as:

*

*Step A.GroupNumber = 0

*Step B.GroupNumber = 0

*Step C.GroupNumber = 1

(Step A) or (Step B and Step C)
might be configured as:

*

*Step A.GroupNumber = 0

*Step B.GroupNumber = 1

*Step C.GroupNumber = 1

but this executes as:
(Step A) and (Step B or Step C)
The solution above using an extra step is evaluated as:

*

*Step X: depends on (Step B and Step C)

*

*Step B.GroupNumber = 0

*Step C.GroupNumber = 1

*Step E: depends on (Step A) or (Step X)

*

*Step A.GroupNumber = 0

*Step X.GroupNumber = 0


text:
Q: Undelivered Mail Returned to Sender Just wondering if there is any way to change the mail subject "Undelivered Mail Returned to Sender" to something else, if the error code is 550.
If no then is there is any way to detect a correct email.I am not saying about the email validation.That part is ok.But sometimes if there is no mail box then we get 550 error code.
Thanks,

A: SMTP reply code 550 means:

The requested command failed because the user's mailbox was
  unavailable (for example because it was not found, or because the
  command was rejected for policy reasons).

Double check your email settings.
On the other hand, the default error reporting email subject is fixed and you cannot be changed, as it is set in remote email server.
Reference: List of SMTP Server Response Codes


text:
Q: Why is wired Ethernet losing its speed advantage over wireless? This has been bugging me for a while now. I did a couple wireless transmission courses back in my university days and it's a known fact that wireless transmission is hard. Partly because it's a shared channel, physical objects can be in the way, air provides quite a bit of loss, etc.
So why is wireless transmission catching up to Ethernet in terms of transmission speed?
We see MKBHD in this video going to some street with a phone and getting over 1Gbps. Surely a reserved and shielded Ethernet channel should give us 1Tbps right?
I feel we are just not trying enough on the Ethernet side of things. Is it the case?

A: A major advantage of wired Ethernet for some purposes, to which wireless Ethernet can never catch up, is that the amount of bandwidth available in one cable will be unaffected by bandwidth utilization in other cables nearby.  If one has 100 clients in a room each talking to its own server, and the cable topology allows every client to talk to its server without having to traverse any cables that are used by anyone else, each of those client/server pairs could have just as much bandwidth as if the other 99 didn't exist.  By contrast, if the clients and servers were all in the same room trying to communicate wirelessly, they would only be able to use a small fraction of the bandwidth they would have available if they were alone.
A related advantage is that wired connections can deliver bandwidth reliably and smoothly, without hiccups.  Although it's possible to stream video wirelessly with relatively short delay, it's not possible to guarantee 100% delivery of all frames within a short window.  By contrast, if one is using a dedicated wired Ethernet connection between a client and a server, and if the client and server are themselves fast enough to handle the traffic, every packet will be delivered within a fraction of a millisecond from when it was sent.

A: Wired ethernet is not losing its advantage. There are standards out there for 10Gig Ethernet (802.3ae), 40Gig Ethernet (802.3ba), and 25Gig Ethernet (802.3bq). These are primarily backbone/backhaul standards.
It's not an apples-to-apples comparison to compare 20-year-old (1 Gb Ethernet) or 25-year-old (100 Mb/s "Fast Ethernet") technology to the latest in wireless just because that's what's available in the consumer market.

A: Perhaps it's not about the networking at all, but the applications using the network.  The applications currently running on these networks do not require more bandwidth.  Consider, Netflix advises 25 Mbps for 4k video streaming.  In the consumer space, that may be one of the hungriest applications.  Since there are no consumer applications that need more bandwidth there is no evolutionary pressure to build networks with more bandwidth.  In terms of straight download speed you are probably more limited by the pace of the content buffering on the other end than you are by your own network.  Again, faster consumer bandwidth doesn't add any value.  If someday we have applications that need more bandwidth, then I would expect both wired and wireless (which caught up to wired by then) to simultaneously increase their bandwidth to support those applications.

A: There's one really big advantage of wireless over wired regarding attenuation.
A wired coax has ~X dB/m attenuation, whereas a wireless link has ~20 dB per tenfold distance attenuation (1/r^2).
This already pays off in favour of wireless for distances >100m.
This is why you could never do a wired cable link from earth to moon, but for a wireless radio link, NASA already did it 50 years ago.

A:
We see now the MKBHD guy going to some street with a phone and getting over 1Gbps. Surly a reserved and shielded Ethernet channel should give us 1Tbps right?

nope, why should it? Data rate is a function of SNR and bandwidth. (Shannon Capacity: you can only transport a limited amount of bits per second over a medium with limited bandwidth and limited signal fidelity; both applies to twisted pair; that's impossible to circumvent through research; it's mathematically proven.)
You'll need shielded ethernet cable that supports enormous bandwidths (that means, wavelengths from meters down to millimeters) to do terabit communications. That's physically not how twisted pair works; there's an inherent low-pass character to it that limits the usable bandwidth.
That's why we only have terabit/s communications over optical fiber: Whilst still electromagnetic waves, due to the extremely high carrier frequencies of light, dozens of Gigahertzes of bandwidth are achievable.
Note that doing high-rate electrical (e.g. on PCBs between your network card and your CPU, or even Gigabit ethernet) or optical links already needs basically all of the techniques that you see in wireless comms – synchronizers, equalizers, phase recovery, extensive channel coding, higher modulations¹.
Of course, the rates you get with a dedicated medium such as a fiber optic channel or a microwave guide on a PCB are higher than that in mobile comms, simply because of shorter distances (hence lower loss) and reliable channels (a lot of the rate of the channel in wireless comms is occupied to getting to know how the channel looks like, so that one can correct it at the receiver).
Your "factual" claim hence is plain wrong: You can certainly get higher rates over twisted pair then over some microwave link; 10 Gb/s ethernet over twisted pair is a thing. But the complexity of the receiver doesn't stand back behind that of a wireless receiver, in that case.

¹ And in fact, high-rate optical brings its own can of worms that's worse in at least one aspect than how we usually approach wireless comms: You'd drive the optical fiber in a power region that makes it a nonlinear medium; then suddenly, all of the precious assumptions about how different frequencies are orthogonal and how signals add up linearly break down, and that has catastrophic consequences for a lot of the math that we're used to.

A:
So why is wireless transmission catching up to Ethernet in therms of transmission speed?

Wireless is not catching up to Ethernet in terms of transmission speed, but it is becoming fast enough that most people don't need to use faster wired systems. However, if you want to buy faster wireless devices, checking the prices ethernet modules on fs.com is instructive:

*

*10gbit SFP+:  $18.00

*40gbit QSFP+: $39.00

*100gbit QSFP28: $99.00

So to put that in perspective, a typical Intel branded Wifi card costs a few dollars less than an ethernet module with a real world bandwidth about 100 times greater. From that point of view, wireless is not very fast.
However, the real advantage of wireless in terms of cost is that the bandwidth is shared between all clients, whereas in wired ethernet, the bandwidth increases as the number of devices increases.  This makes highspeed ethernet switches (which may require terabit/s switching speeds) extremely expensive.  They also have hundreds or thousands of times more bandwidth.

A: As others have noted, there are Ethernet standards for far higher than 1GB transmission. However, these have relatively small penetration into anything other than specialised datacentre installs.
The average home user, or business "office floor" user is still using Cat5 or maybe Cat6 cabling. The latter can theoretically do 10G, but in most cases probably only runs at 1GB. The reason for this is the cost of 10G is probably far greater than the real benefit of it. That is, the average desktop/laptop user, even the "power" users simply don't need that much bandwidth all of the time. For the few times in the month/year when they do, sure, it goes a bit slower, but the cost of that delay is less than the cost of provisioning 10G to them.
As noted elsewhere is that the higher "rated" bandwidths of wireless technologies are shared amongst all clients on that same network. Thus contention can dramatically reduce the real, available bandwidth to any given client. Further, there tends to be a larger protocol overhead for wireless networks compared to wired - so (say) a 1GB wireless connection, dedicated to one client will actually download data slightly slower than a 1GB wired connection (my rule of thumb is about 10% protocol overhead for wired, and 20% for wireless, but I'm doubtless waaay inaccurate there). Thus, higher bandwidths look good in marketing brochures, but don't necessarily mean that's what you'll actually get.
Just to labour the point a bit further... Bandwidth (and the equipment to provide it) is demand driven. Right now at least, the average user simply doesn't need the bandwidth of a simple Cat5/6 cable, let alone the additional bandwidth of later standards. Most users just need to download a few files, maybe watch some videos and send some emails. As such, "1G is enough for anyone", at least right now. I'm sure when we start getting full-brain implants that need more bandwidth, the cabling and connection standards will appear to support it, and with enough people to buy it, the price will be low enough that it'll become consumer technology.
All the while though, even the average household could completely consume many of the more common wireless standards - just by doing the "simple" activities I mentioned above with phones and laptops. Those people will absolutely want additional bandwidth, and so will be looking to upgrade to ever faster wireless networks for a few more years at least. Another solution for some of those people would be to use more Wireless Access Points to divide users amongst channels which don't affect each other. That more than doubles the install cost though, so the demand for higher bandwidth remains.

A:
So why is wireless transmission catching up to Ethernet in therms of transmission speed?

Money.  Time is money, but convenience is REAL money.
Because the speed-per-user cost is relatively low, and because the portability of wireless has a value almost beyond price.   Yes, the infrastructure to get GHz data to hundreds (thousands?) of phones per cell tower simultaneously is really expensive, but the alternative - a fiber optic cable to every moving car on the highway - is flat out impossible.  That guaranteed money flow drives what is, if you stop and really think it through, near-alien-technology development.  Once the cell people have developed the tech, and the illusion of need, trickling it down to consumer home networks is relatively simple.
And again, running wires is hard.  Especially in homes.  Outside walls have insulation, inside walls have wiring, plumbing, and god know what else, and the cosmetics, esthetics, and budget are very different from what is considered normal for a commercial building.  Think about the inconvenience of moving an ipad from room to room by unplugging and plugging cables.  That's money, and that money drives astounding development.  Using 1980's chips, a $30 home wireless router would be the size of a microwave oven and cost as much as a car.

A: There's room for argument about some of the details. For example, I've omitted some of the rarely-used standards such as the original 802.11 and 802.11a, as well as some of the early 100 GBps Ethernet standards, in attempt at getting at least some approximation of speeds that were used fairly widely, not things that ended up as little more than technology demos. Depending on what you decided to include, you could get a somewhat different graph from this.
With that proviso, I get a graph of relative speeds something like this:

That looks to me like since the introduction of 802.11b, the two have been tracking fairly closely in terms of speed growth. Even though this is on a logarithmic scale, it looks like Ethernet (ignoring the pre-1995 period) has marginally faster growth, but given the small number of data points, I don't think either has a really massive advantage (note, that is to say: Ethernet has a speed advantage at all times, but its speed advantage has remained approximately constant for quite a while).
It's also worth noting that as speeds have gone up, distance has gone down (for both technologies). The newest/fastest 802.11 (802.11ad) operates at high enough frequency that its target range is "at least a meter", and generally won't go through walls at all. At least to me, that seems to leave some room for question whether we're likely to see it continue growing a whole lot. If I were being entirely fair about things, I'd probably have left it off the chart entirely--actual use seems to be extremely limited, at best. Even if I included it, I probably should have cut the speed in half (or so). What I've shown is the 8 Gbps variant, but most of the wireless routers I've seen only do the 4 Gbps variant (though most can also do an 802.11ac and 802.11n stream at the same time, so they're around 5.5-6 Gbps total).
One other note: this is all based on theoretical maximum speed supported by a given standard. In terms of real speed, it seems (at least to me) that 802.11 is typically slower by an even larger factor than the theoretical maximum implies. With Ethernet you can routinely expect to use 80% of theoretical bandwidth, but with 802.11 you're lucky to use 50% of theoretical (and often substantially less than that).


text:
Q: Can someone explain why I'm getting this error in Java? Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at A_test.addButton(A_test.java:27)
    at A_test.<init>(A_test.java:17)
    at Main$1.run(Main.java:11)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Main class
import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new A_test();
            }
        });
    }
}

A_test class
import java.awt.event.*;
import javax.swing.*;

public class A_test implements ActionListener {

    private JFrame jf;

    public A_test() {
        JFrame jf = new JFrame("A simple swing Program");
        jf.setSize(275,100);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel jl = new JLabel("Swing powers the modern JAVA GUI");
        jf.getContentPane().add(jl);
        this.addButton();
        jf.setVisible(true);
    }

    public void addButton() {
        JButton jb = new JButton("Submit");
        jf.getContentPane().add(jb);
        jb.addActionListener(this);
        jf.getContentPane().add(jb);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        ((JLabel) jf.getContentPane().getComponent(0)).setText("test");
    }
}

I'm using the A_test class in order to create a JFrame with a label and a button in it. When I press the button I want the application to change the text of the label to "test" from what it was before.

A: Here
JFrame jf = new JFrame("A simple swing Program");
jf.setSize(275,100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jl = new JLabel("Swing powers the modern JAVA GUI");
jf.getContentPane().add(jl);
this.addButton();
jf.setVisible(true);

You are creating a new JFrame instead of assigning the private instance variable to a new JFrame.
By the time you reach this point:
  JButton jb = new JButton("Submit");
jf.getContentPane().add(jb);
jb.addActionListener(this);
jf.getContentPane().add(jb);

jf is still null;
Just do this:
jf = new JFrame("A simple swing Program");
jf.setSize(275,100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jl = new JLabel("Swing powers the modern JAVA GUI");
jf.getContentPane().add(jl);
this.addButton();

A: You have two instances of jf.  One is an member of the class and is not initialised.  The other is a local variable within the constructor which is initialised.  So when addButton is called you are trying to access the member variable which is null and hence the NullPointerException.

A: You should start using an editor like Eclipse or netbeans and Pay Attention To The Warnings.  They would have told you exactly what was wrong (That your variable was shadowing a member variable).
Java gives awesome warnings--Java's "Pickyness" causes many people to think the language is more "Difficult" but it actually makes it MUCH easier.  A language with a lax syntax is really much harder in the long run.


text:
Q: Как сделать slice в python? При парсинге данные выходят в таком формате:
22 Августа 2019 17:17 25

Как срезать, чтобы было так:
22 Августа 2019 17:17

без цифры 25? Как это лучше реализовать?
Вот функция, которая парсит дату:
def get_item_datetime(item_page, datetime_rule, datetime1_rule):
    soup = BeautifulSoup(item_page, 'lxml')
    item_datetime = soup.find(datetime_rule[0],{datetime_rule[1]:datetime_rule[2]})
    if item_datetime is not None:
        item_datetime = soup.find(datetime_rule[0],{datetime_rule[1]:datetime_rule[2]}).text
        item_datetime = dateparser.parse(item_datetime, date_formats=['%d %B %Y %H'])
    else:
        if (len(datetime1_rule) == 3):
            item_datetime = soup.find(datetime1_rule[0],{datetime1_rule[1]:datetime1_rule[2]}).text
            item_datetime = dateparser.parse(item_datetime, date_formats=['%d %B %Y %H'])
        else:
            item_datetime = ''

A: Если в конце всегда только 2 цифры, то легче всего так:
new_date = date[:-3]

Если же нет, то так:
last_space_index = date.rfind(" ") #Находим первое вхождение пробела с конца строки
new_date = date[:last_space_index]
print(new_date)

A: Можно попробовать собрать список по пробелам, удалить последний элемент списка и вернуть строку из списка.
date = '22 Августа 2019 17:17 25'
a = date.split()
a.remove(a[-1])
print(' '.join(a))

Либо вариант, который не будет учитывать любые символы после даты
date = '22 Августа 2019 17:17 250 ыуецеукц 45'
a = date.split()
print(' '.join(a[:4]))


text:
Q: popoverpresentviewcontroller with rectangle corner and without arrow I want a popover without rounded corners and with no arrow.
I have done the following code but it did not work:
//SerachPopViewController.swift
    //MARK: InitCoder
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    //popover settings
    //popoverPresentationController!.permittedArrowDirections = .Any
    modalPresentationStyle = .Popover
    popoverPresentationController!.delegate = self
    //permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
    self.preferredContentSize = CGSize(width:340,height:380)
}

//QueryTableViewController.swift
    @IBAction func searchFilter(sender: AnyObject) {

    let searchPopController = storyboard!.instantiateViewControllerWithIdentifier("SerachPopViewController") as! SerachPopViewController
    searchPopController.serachPopDelegate = self
    searchPopController.modalPresentationStyle = .Popover
    searchPopController.preferredContentSize = CGSize(width:340,height:380)

    let popoverPresentationController = searchPopController.popoverPresentationController

    popoverPresentationController!.sourceView = self.view;
    popoverPresentationController!.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds),0,0)
    popoverPresentationController!.permittedArrowDirections = UIPopoverArrowDirection();
    self.presentViewController(searchPopController, animated: true, completion: nil)
}

I am able to display popover view with arrow and rounded arrow.
Please help me to achieve:

*

*popup view with rectangle corner

*popup view without direction arrows

A: In iOS 11 its not possible to use @SHN solution for removing rounded corners. The corner radius is set to default value after viewWillAppear.
Radius must be set in viewDidAppear method
override func viewDidAppear(_ animated: Bool) {
    view.superview?.layer.cornerRadius = 0
    super.viewDidAppear(animated)
}

A: To get popover without arrow when you are initiating popover, use:
popover!.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)

For popover without corner radius, in the popover content view controller use:
override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // Do any additional setup after loading the view, typically from a nib.
        self.view.superview?.layer.cornerRadius = 0.0;
    }

A: Using the concept above, you can also set the corner radius in the completion parameter.
Swift 3
let popoverViewController: UIViewController = // Some view controller to be presented in a popover

// Set popover properties here...
// i.e. popoverViewController.modalPresentationStyle = .popover

present(popoverViewController, animated: true, completion: {
     popoverViewController.view.superview?.layer.cornerRadius = 0

    // Additional code here
})

A: I was not 100% happy with shawnynicole's answer because I realized the change from the rounded to the rectangular corners are notable/visible.
So I came up with this: subclass the view controller (in my case it was an UINavigationController) and override viewDidLayoutSubviews and update corners there. This is better because corners change animation is not visible and it will be updated every time needed (on rotations, etc).
It works in iOS11 and probably should work on others versions too.
class PopoverNavigationController: UINavigationController {

    @IBInspectable var cornerRadius: Int = -1

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let r = CGFloat(cornerRadius)
        if r >= 0 && view.superview?.layer.cornerRadius != r {
            view.superview?.layer.cornerRadius = r
        }
    }
}

A: I don't know why It does't work on my Simulator with iOS11.1 until trying setting backgroundColor.I added function viewWillTransition for rotating device.
override func viewDidAppear(_ animated: Bool) {
    view.superview?.backgroundColor = UIColor.white
    view.superview?.layer.cornerRadius = 0
    super.viewDidAppear(animated)
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    view.superview?.backgroundColor = UIColor.white
    view.superview?.layer.cornerRadius = 0
    super.viewWillTransition(to: size, with: coordinator)
}

A: For Swift 4, in case you present your popover embedded in a navigation controller:
override func viewDidAppear(_ animated: Bool) {
        navigationController?.view.superview?.layer.cornerRadius = 0
        super.viewDidAppear(animated)
}

A: That's the way I do it in order to achieve such a functionality which works also on device rotation:
In the view controller that you set as a popover add the following code:
override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        view.superview?.layer.cornerRadius = 0
}

extension MyPopoverViewController: UIPopoverPresentationControllerDelegate {
    func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) {
        self.view.setNeedsLayout()
    }

Finally, set your popover's delegate to the instance of this view controller before presenting it:
...
popover.delegate = myPopoverViewController
present(myPopoverViewController, animated: true)

A: Many of these answers fix the OP's question about corner radius, but you can get the same effect by changing your presented view controller's top view's background to clear. Then just round the corners of the next top view to the desired amount (or not, if you want it to be a straight top).
I prefer this way because it gives you more WYSIWYG control over the presented view. For example, you can present a floating square by just centering a view in the view controller and presenting it.


text:
Q: C++ Reading and Writing (same NAMED file) So... The idea is simple - opening and writing in the same file amout of wins(a) and loses(b) but i don't know how to do that. First problem i faced was: "Error with opening file just by string (s)", so i found a solution - using .c_str().
And now i see that there is no txt file that could save my data.
Any solution?
Thanks for help and Have a nice day!
#include <bits/stdc++.h>

using namespace std;

fstream in;

string s ;

char t;

int a, b;

int main(){

cout << "DECK NAME:";

cin >> s;

s += ".txt";

in.open(s.c_str(), ios::in | ios::out);

while(1){

 cout << "END: e" << endl;
 cin >> t;

 if(t == 'e'){
     in.open(s.c_str(), ios::in | ios::out);
     in << a << " " << b;
     in.close();
     return 0;
 }

 in >> a >> b;

 in.close();

 if(t == 'w') a++;
 else b++;

 cout << "Win: " << a << endl;

 cout << "Lost: " << b << endl;

 }
}

A: If you want to read and write from one file then you can use fopen() from stdio.h which would look like this:
#include <stdio.h>
#include <iostream>

FILE *file;

int main()
{
    file = fopen("myfile.txt", "w+");
    fputs("test", file);
    std::cout << "Writing test to myfile.txt" << std::endl;
    fflush(file);
    rewind(file);
    char *myString = new char[5];
    fread(myString, 1, 5 * sizeof(char), file);
    std::cout << "Reading " << myString << " from myfile.txt" << std::endl;
}

You can read more about these functions here: https://www.cplusplus.com/reference/cstdio/


text:
Q: Kafka consumer/producer service writing back to the same topic I'm looking at using Kafka for dealing with a system that handles large amounts of data, I'm planning on reading messages from a topic and upon processing these messages similar results will be returned, I will then produce these new results back into the same Kafka topic so that they can eventually be processed.
Could there be any issues with reading/writing into the same topic in this way? If each message was picked by two consumers would you still be able to identify if it had been consumed by a particular consumer? I'm concerned about this as I want to avoid processing the same messages multiple times by any given consumer (process once per consumer).
Example

*

*User action triggers first message in Topic foo.

*Topic now contains a message with value "/bar"

*"/bar" message consumed and processed, "/bar/baz" discovered during processing

*"/bar/baz" produced into topic foo

*"/bar/baz" message consumed and processed....

*Process continues until no further work is found


text:
Q: Selectsinglenode in IXMLDOMElement? can i perform select single node from IXMLDOMElement ,if its possible give me one example for that using MSXML

A: In what language?  To solve what problem?
For what it's worth, the MSDN documentation for IXMLDOMElement::selectSingleNode can be found here, and includes samples in a few different languages.


text:
Q: Angular Universal TypeError: Cannot read property 'assign' of undefined I have installed in current project angular universall@5.0.0
But when I start the project node server.js , it shows an error
>/Users/qfrost/Projects/project/node_modules/rxjs/util/assign.js:22
    return root.Object.assign || assignImpl;
                       ^

**TypeError**: Cannot read property 'assign' of undefined
    at getAssign

>(/Users/qfrost/Projects/project/node_modules/rxjs/util/assign.js:22:24)
    at Object.<anonymous> (/Users/qfrost/Projects/project/node_modules/rxjs/util/assign.js:25:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/qfrost/Projects/project/node_modules/rxjs/observable/dom/WebSocketSubject.js:15:16)

This is my packages:
{
  "name": "client",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build:browser": "ng build --prod --app 0",
    "build:server": "ng build --prod --app 1 --output-hashing none",
    "build": "npm run build:browser && npm run build:server",
    "serve": "node server.js"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.11",
    "@angular/cdk": "^5.1.1",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "^5.1.1",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/platform-server": "^6.1.7",
    "@angular/router": "^5.0.0",
    "@ngrx/core": "^1.2.0",
    "@ngrx/store": "^4.1.0",
    "@nguniversal/express-engine": "^5.0.0",
    "@nicky-lenaers/ngx-scroll-to": "^0.6.1",
    "@toverux/ngx-sweetalert2": "^4.0.0",
    "angular-read-more": "^1.0.7",
    "animate-sass": "^0.8.2",
    "bootstrap": "^4.0.0-alpha.6",
    "core-js": "^2.4.1",
    "fullpage.js": "^3.0.2",
    "hammerjs": "^2.0.8",
    "jquery": "^3.3.1",
    "ng2-scroll-to-el": "^1.2.1",
    "ngx-bootstrap": "^2.0.3",
    "ngx-carousel": "^1.3.5",
    "ngx-disqus": "^2.3.7",
    "ngx-fullpage": "^4.0.6",
    "ngx-highlight": "0.0.3",
    "ngx-slick": "^0.1.3",
    "reselect": "^3.0.1",
    "rxjs": "^5.5.2",
    "slick-carousel": "^1.8.1",
    "sweetalert2": "^7.22.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.5.0",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.3.5",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.4.2"
  }
}

My server.js
require('zone.js/dist/zone-node');

const domino = require('domino');
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.join(__dirname, '.', 'dist-browser', 'index.html')).toString();
const win = domino.createWindow(template);
global['Event'] = null;
global['window'] = win;

const express = require('express');
const { ngExpressEngine } = require('@nguniversal/express-engine');

// create express app
const app = express();

// import server module bundle
var { ServerAppModuleNgFactory } = require('./dist-server/main.bundle');

// set up engine for .html file
app.engine('html', ngExpressEngine({
    bootstrap: ServerAppModuleNgFactory
}));

app.set('view engine', 'html');
app.set('views', 'dist-browser');

// server static files
app.use(express.static(__dirname + '/dist-browser', { index: false }));

// return rendered index.html on every request
app.get('*', (req, res) => {
    res.render('index', { req, res });
    console.log('new GET request at : ${req.originalUrl}');
});

// start server and listen
app.listen(3000, () => {
    console.log('Angular server started on port 3000');
});

Angular CLI is build server and browser dists. But server didn't start. How i can resolve this problem?

A: You can just do the following:
//
const win = domino.createWindow(template);
win.Object = Object;
global['Event'] = null;
//


text:
Q: Using global props in my component with storybook doesn't work I'm having an issue with storybook. It seems that when I try to pass props from the component to my stories.js it doesn't find my global variable. Everything seems to work correctly, except for the props not showing, sending an error that my prop is undefined.
This is my Component.stories.js code
import Component from './Component';

export default {
  title: "Component",
  component: Component,
}

// prop1 and prop2 are gathered globally from a .json-file in my project
// prop1 and prop2 are lists
const Template = (args, { argTypes }) => ({
  props: Object.keys(argTypes),
  components: { Component },
  template: '<Component :prop1="prop1" :prop2="prop2" />',
});

// Here I want to chose which props I want to show to be able to see it in storybook
export const allProps = Template.bind({});
allProps.args = {
  prop1: ['prop1'],
  prop2: ['prop2']
}

Is this even possible or how can I reach a global variable in stories? If there is a possible way to do this I'd love to hear it. I have googled for two days and didn't find anything that worked.
I did try to import the global variable inside my peview.js file but that didn't seem to help either.
I've tried changing globalTypes, argTypes, preview.js. And googled for 2 days. I want storybook to show all fields in my Component. Feel free to ask any questions.


text:
Q: How to read / determine / check the foreground color of pipeline output? Question
I would like to suppress Yellow host output. How, if at all, can I do the following?
some-cli.exe | Where-Object { $_.ForegroundColor -ne Yellow }

The $_.ForegroundColor -ne Yellow is not supported. What, if anything, is supported?
The some-cli.exe could be anything that produces multicolored output. For instance, it could be choco, nuget, msbuild...

A: I don't believe this is possible if the foreground color wasn't set in PowerShell itself (and the method of detection in this case escapes me anyway). When you assign the output of an external command which produces color output to a variable for later processing (this would extend to passing the output down the pipeline), the color information is lost. For example, if you have Chocolatey installed (this is one example program I know which produces colorized output) running:
$output = choco install -y nonexistent-package
$output

loses the color which is normally red for the error text provided by choco.exe.

Note: As Jeroen pointed out in comments, "Console applications can explicitly set the color used for console output, but unless they use ANSI terminal sequences for it (supported in the new W10 console only, so not many do) there is no way for hosts to detect it, whether PowerShell or anything else."

However, based on your comments and specific use-case you should be able to pipe the output of nuget restore to a Where-Object clause and filter out any lines starting with WARNING:
nuget restore | Where-Object {
  $_ -notmatch '^WARNING'
}

I'm not sure if you tried filtering the way I showed above but based on your comment it sounds like perhaps all of the output might not be separated per line, but retrieved as a raw string for some reason. If that is the case you can make one modification for this to work, split the output on new lines:
( nuget restore ) -split "`r?`n" | Where-Object { ....

The downside to this approach is that if the warning spans multiple lines, it won't catch the subsequent line. The warning would have to be localized to one line for this to work.


text:
Q: Does the Import Statement add the entire framework/library to your project I'm trying to get a better understanding of what the Import statement does.  According to this post:

As far as performance and binary size goes, any unused symbols are
  already optimized out of the final binary by the Swift compiler. If
  there's no reference to it at compile time then it's removed, meaning
  that importing a framework but not using particular parts of it
  shouldn't have any negative implications.

The way I read this, is only those portions of the framework that you utilize are imported into your project
Yet in the same post above the fellow says:

We see that there are more precise imports that can be used if one is
  concerned about compile time. Such as import
  UIKit.UITableViewController

This seems to contradict the first statement.  Full post Here
Thanks!


text:
Q: Can someone help me out? Why isn't this working? //Auto Delete Expired Users

function delete_users(){
   $bloguser = get_users( array( 'role' => 'subscriber' ) );
   foreach ( $bloguser as $user ) {
       if ($user->user_url == 'http://day' and time() - $user->user_registered > 1){
           wp_delete_user($user->ID);
       }
   }
}
add_action('auto_delete_users','delete_users');

A: For the benefit of those who will come across this question, I have solved it.
This is how the functioning code works. Now this code helps me to delete Subscribers who have registered on the blog using a plan of their choice, I am working on a paid blog and figured I could do it all by myself without having to buy a plugin.
//Auto Delete Expired Users
function delete_users(){
    require_once(ABSPATH.'wp-admin/includes/user.php' );
   $bloguser = get_users( array( 'role' => 'subscriber' ) );
   foreach ( $bloguser as $user ) {

   //Monthly Subscribers
   if ($user->user_plan == 'month' and date('Y-m-d H:m:s') - $user->user_registered > 30){
   $id = ($user->ID);
       wp_delete_user($id);
   }

   //Yearly Subscribers
   if ($user->user_plan == 'year' and date('Y-m-d H:m:s') - $user->user_registered > 365){
   $id = ($user->ID);
       wp_delete_user($id);
   }
             }
}
add_action('wp_footer','delete_users');


text:
Q: Generating random array in Maple I'm trying to do simulation in Maple, but I can't figure out how to do the following:
How does one generate a set of random whole numbers in an array of 24 element (in 1 column) where the sum of the numbers has to be 10 and each numbers must be between 0 and 10?

A: Here is solution for $10$ elements :
with(RandomTools):
s:=0:
A10:=Vector(1..10):
while not(s = 10) do
for n from 1 to 10 do
a := Generate(integer(range =0..10)):
A10[n]:=a;
s:=s+a:
if s >10 then
n:=0;
s:=0;
A10:=Vector(1..10);
end if;
end do;
end do;
A10;

For some reason I couldn't generate Vector with 24 elements .

A: If we produce all the partitions of 10 (of which there are 42) then we can pick p from that collection randomly (uniformly, if you want). There will be np elements in the chosen partition. We can choose np of the naturals 1..24, and use those as the positions of the Vector V to which to assign the entries of p.
The following acts inplace on Vector V. Initialization to precompute the set of all partitions of 10, and to construct V and the random generating function (1..42), takes almost no time at all.
Subsequent generation of a solution, populating V, takes about 0.00125 sec on an Intel i7.
restart:
randomize(): # different results for each Maple session
interface(rtablesize=24):

G:=proc(v::Vector,y,all) local i,p,np,pos;
  ArrayTools:-Fill(0,v);
  p:=all[y()];
  np:=nops(p);
  pos:=[combinat[randcomb](24,np)[]];
  for i from 1 to np do v[pos[i]]:=p[i]; end do;
  NULL; # acts in-place on V
end proc:

st:=time():
All:=combinat[partition](10):
Y:=rand(1..nops(All)):
V:=Vector[row](24):
time()-st;
                           0.

G(V,Y,All);
V;

      [0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2]

G(V,Y,All);
V;

     [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 4, 0, 0, 4, 0, 0, 0, 0, 0]

G(V,Y,All);
V;

     [0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4]

st:=time():
for j from 1 to 10^3 do G(V,Y,All); end do:
time()-st; # time for 1000 regenerations

                         0.125

The above picks from the complete set of partitions of 10 (ie. "ways to split up 10 as a sum of positive integers") with each having an equal weight, hence a uniform discrete  distribution. That might not be what you want. Another way to generate each p is to randomly select values from {1..10} while computing a running total, stopping whenever the running total is exactly 10, and rejecting/reselecting each chosen value if it pushes the running total over 10.


text:
Q: Windows 11, File Explorer, detach tab into a new window? Is there a way to detach a tab into a new window?

A: I have Windows 11 22H2 and Insider here.
There is a new File Explorer Tab structure and I use it.
(a) The tabs do NOT detach (2 Production 1 Insider machine).
(b) Under Options, Folder Options, General, you can select "Show each folder in its own Window" and have multiple File Explorer windows. The default option is to have all Explorer views in one windows with tabs.
That is the design of the new tabbed Explorer.  It may change in time (but not so far in Insider), so what we have at this point is what we get.
Note: I also have Microsoft Power toys, but no change for tabs in Power Toys.


text:
Q: How to trigger Glue Job using AWS GlueOperator My Airflow script has only one task to trigger a glue job. I am able to create the DAG. Below is my code for DAG.
from airflow import DAG
from airflow.operators.email_operator import EmailOperator
from airflow.providers.amazon.aws.operators.glue import AwsGlueJobOperator
from datetime import datetime, timedelta

### glue job specific variables
glue_job_name = "my_glue_job"
glue_iam_role = "AWSGlueServiceRole"
region_name = "us-west-2"
email_recipient = "me@gmail.com"

default_args = {
    'owner': 'me',
    'start_date': datetime(2020, 1, 1),
    'retry_delay': timedelta(minutes=5),
    'email': email_recipient,
    'email_on_failure': True
}

with DAG(dag_id = 'glue_af_pipeline', default_args = default_args, schedule_interval = None) as dag:

    glue_job_step = AwsGlueJobOperator(
        job_name =glue_job_name,
        script_location = 's3://my-s3-location',
        region_name = region_name,
        iam_role_name = glue_iam_role,
        script_args=None,
        num_of_dpus=10,
        task_id = 'glue_job_step',
        dag = dag
        )

    glue_job_step

When I run the DAG it fails and gives the below error:

[2020-10-13 08:27:14,315] {logging_mixin.py:112} INFO - [2020-10-13
08:27:14,315] {glue.py:114} ERROR - Failed to run aws glue job, error:
Parameter validation failed: Invalid type for parameter Arguments,
value: [], type: <class 'list'>, valid types: <class 'dict'>
[2020-10-13 08:27:14,315] {taskinstance.py:1058} ERROR - Parameter
validation failed: Invalid type for parameter Arguments, value: [],
type: <class 'list'>, valid types: <class 'dict'> Traceback (most
recent call last):   File
"/usr/local/lib/python3.8/site-packages/airflow/models/taskinstance.py",
line 930, in _run_raw_task
result = task_copy.execute(context=context)   File "/usr/local/lib/python3.8/site-packages/airflow/providers/amazon/aws/operators/glue.py",
line 115, in execute
glue_job_run = glue_job.initialize_job(self.script_args)   File "/usr/local/lib/python3.8/site-packages/airflow/providers/amazon/aws/hooks/glue.py",
line 111, in initialize_job
job_run = glue_client.start_job_run(JobName=job_name, Arguments=script_arguments)   File
"/usr/local/lib/python3.8/site-packages/botocore/client.py", line 337,
in _api_call
return self._make_api_call(operation_name, kwargs)   File "/usr/local/lib/python3.8/site-packages/botocore/client.py", line 628,
in _make_api_call
request_dict = self._convert_to_request_dict(   File "/usr/local/lib/python3.8/site-packages/botocore/client.py", line 676,
in _convert_to_request_dict
request_dict = self._serializer.serialize_to_request(   File "/usr/local/lib/python3.8/site-packages/botocore/validate.py", line
297, in serialize_to_request
raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Arguments, value: [], type: <class 'list'>,
valid types: <class 'dict'> [2020-10-13 08:27:14,316]
{taskinstance.py:1089} INFO - Marking task as FAILED.

Any suggestions appreciated.

A: If you are running a existing GlueJob try this,
glue_job_step = AwsGlueJobOperator(
        task_id = "glue_job_step",
        job_name = glue_job_name,
        job_desc = f"triggering glue job {glue_job_name}",
        region_name = region_name,
        iam_role_name = glue_iam_role,
        num_of_dpus = 1,
        dag = dag
        )

Remove script_args if there are no input arguments.


text:
Q: Will Minor Compactions in Cassandra remove elapsed TTL records Below is the table schema i am using. Cassandra version is 2.1

CREATE TABLE metadata (
customerid int,
 user text,
messageid text,
subject text,
 PRIMARY KEY ((customerid, user), messageid) )
 WITH CLUSTERING ORDER BY (messageid ASC)
AND compaction = {'class':'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : '4'} AND gc_grace_seconds = 172800 ;

For the same (customerid,user)  records would get inserted continuously.  While inserting we set TTL which would be minimum 14 days and would be always greater than gc_grace_seconds.
No updates or deletion happens .
For the same (customerid, user) we could have data in multiple SSTable files.
While LCS compaction runs, would it drop records which have elapsed  even if other SSTable files that are not being compacted have data for the same partition key. In one of the cassandra mail archives I  read ,
"Tombstones will be expired by Minor Compaction if all fragments of the  row are contained in the SSTables being compacted."
Is this applicable for data with TTL also?

A: You will insert an entire row for the table "metadata".  As you mentioned that there are no updates and manual deletes, the entire row should reside in only one SSTable. So while minor compaction, the respective row will be removed from SSTable.
FYI, your TTL is 14 days. Your data will be marked as tombstones after 14 days. Your gc_grace_seconds is 172800 (2 days). So the tombstone will exist for next 2 days. So once 16 days are expired from the beginning, the next minor or major compaction will remove the data.


text:
Q: How to set proxy settings to view YouTube from China in Ubuntu? I am new for Ubuntu OS, now I am in China.
I cannot open YouTube so I want to know which proxy setting will allow to view YouTube videos?

A: The specific proxy, there are many.
Personally, I would recommend Tor for firewall jumping
https://www.torproject.org/
https://www.torproject.org/download/download-easy.html.en
Download the proper version that suits you (32bit or 64bit). I recommend using this link first.
Enjoy proxyjumping!


text:
Q: moving pipe around corner I worked at some problem with moving pipe around a corner and i was trying to fing the maximum length of pipe for corner with corridor lengths 1. It is pretty obvious that maximum length is ${\sqrt 2}$, since that is the length of pipe when it's in position, when the angles where it touches the outer walls are the same - $45$ degree.
It's obvious that if pipe can get through this point, it can move around the corner. But i don't know how to exactly mathematically prove it.

A: In this diagram, we see that for a given angle of $\theta$, the largest pipe that can fit at the corner at that angle has length
$$L=\sec\theta+\csc\theta$$

The largest pipe that can fit around the corner must fit for all angles $\theta$, thus the minimum value of $L$ is the maximum length of pipe that will go around the corner. We use the derivative to find the appropriate value of $\theta$:
$$\begin{align}
L'&=\sec\theta\tan\theta-\csc\theta\cot\theta \\[2 ex]
 &= \frac{\sin\theta}{\cos^2\theta}-\frac{\cos\theta}{\sin^2\theta}
\end{align}$$
Setting that equal to zero and solving,
$$\begin{align}
\frac{\sin\theta}{\cos^2\theta}-\frac{\cos\theta}{\sin^2\theta} &= 0 \\[2 ex]
\sin^3\theta-\cos^3\theta &=0 \\[2 ex]
\frac{\sin^3\theta}{\cos^3\theta} &=1 \\[2 ex]
\tan^3\theta &= 1\\[2 ex]
\tan\theta &= 1\\[2 ex]
\theta &=45°
\end{align}$$
You can easily use the first derivative or second derivative test to see that the minimum value of $L$ is indeed at that angle.