text:
Q: Using El Capitan, can I create a bootable Windows 7 USB? I have an El Capitan, can I create a bootable USB of Windows 7? I also have a Windows 7 ISO. I need to use a USB since I will be reformatting a netbook without DVD/CD-ROM drive.

A: As @hirnwunde has pointed in the comments, the article from Indiana University works!

*

*From the Finder, open the Applications folder, and then Utilities.

*Open the Boot Camp Assistant, and then click Continue. The next screen should give you a list of options.

*UITS recommends making the USB drive installer first. You don't need to install Windows or download the support software at this time, as it will be easier to do both later. To proceed:
 a. Verify that the USB drive you will be writing to is plugged in.
 b. Uncheck the Install Windows 7 or later version and Download the latest Windows support software from Apple options.
c. Check Create a Windows 7 or later install disk and click Continue.

*Your USB drive should be listed in the "Destination disk" area. Use choose to browse to your .iso file; after selecting it, click Continue.

*If prompted, confirm your action and/or provide an administrator's password. The process of writing the .iso file to the USB drive can take 20 minutes or longer.

A: In latest El Capitan there is no option to create USB disk in Boot Camp Assistance, but you can create USB drive in Terminal.app

A: If you're one of the people who no longer have the option to create a thumbdrive in Boot Camp Assistance, here's how to get around it.

*

*In Finder go to Applications/Utilities and copy Boot Camp Assistance

*Navigate to ~/Applications and paste Boot Camp Assistance there

*Using your favorite text editor open ~/Applications/Boot Camp Assistant.app/Contents/Info.plist

*Find the area that looks like this:
<key>ExternalInstallOnlyModels</key>
<array>
        <string>MacBook8,1</string>
        <string>MacBook9,1</string>
        <string>MacBookAir7,1</string>
</array>

*Add your model to the list (you can find your "Model Identifier" in About This Mac -> System Report). For me (MacBook Pro, Retina, 15-inch, Mid 2015), that means it now looks like:
<key>ExternalInstallOnlyModels</key>
<array>
        <string>MacBook8,1</string>
        <string>MacBook9,1</string>
        <string>MacBookAir7,1</string>
        <string>MacBookPro11,4</string>
</array>

*Check if your model is listed under PreUSBBootSupportedModels. If so, remove it.

*Now start Boot Camp Assistance from your Applications directory and you'll get the option to burn to USB.


text:
Q: Can you list iptables as a non-root user and why? Is it at all possible to execute  iptables --list ….  command without being root?
Running it as non-root prints this:
$ iptables --list
iptables v1.4.21: can't initialize iptables table `filter': Permission denied (you must be root)
Perhaps iptables or your kernel needs to be upgraded.

If you must be root to list iptables, what is the reasoning behind that ? Is there a security concern with viewing the rules ? Is there a resource or service used by iptables --list  that requires root access ?
Obviously, modifying iptables firewall rules requires privileged user. I am asking about viewing them.

Instead of being root, is there a capability that could permit listing the rules ?
Does iptables use netlink to interface with the kernel ? Because netlink documentation mentions that

Only processes with an effective UID of 0 or the CAP_NET_ADMIN
  capability may send or listen to a netlink multicast group.

Maybe that does not apply to iptables.
I am not sure whether this is the right way of doing it but adding a capability to iptables does not let me list the rules either:
bash-4.1$ echo $UID
2000
bash-4.1$ getcap /sbin/iptables-multi-1.4.7
/sbin/iptables-multi-1.4.7 = cap_net_admin+ep
bash-4.1$ /sbin/iptables-multi-1.4.7 main --list
FATAL: Could not load /lib/modules/3.10.0-514.21.1.el7.x86_64/modules.dep: No such file or directory
iptables v1.4.7: can't initialize iptables table `filter': Permission denied (you must be root)
Perhaps iptables or your kernel needs to be upgraded.

Here are some relevant questions q1 and q2. Both provide workarounds in my opinion and do not discuss the fundamental reason behind it.

A: Indeed, iptables uses the netlink interface to communicate with the kernel. It opens a netlink socket to xtables, then issues commands via this socket. Access control is performed when the socket is opened, not for individual commands, so the same permissions are required for listing and modifying rules. The only way to allow a user to list rules but not modify them is to give them a carefully-written setuid (or setcap) executable.
It would be nice if there was an interface to netfilter in /proc, but as far as I know the task of implementing it has never been completed.

A: It appears iptables needs both CAP_NET_RAW and CAP_NET_ADMIN to be able to read the tables. I tried
$ cp /usr/sbin/iptables ~/iptables  # note, it may be a symbolic link
$ sudo setcap CAP_NET_RAW,CAP_NET_ADMIN+ep  ~/iptables
$ ~/iptables  -nvL

and it was ok.

A: Here's what I did:
$ cat iptables-list.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    if (setuid(0) != 0)
    {
        perror("setuid");
        return EXIT_FAILURE;
    }
    execl("/sbin/iptables", "iptables", "-L", "-n", NULL);
    perror("execl");
}
$ gcc -Wall -Werror -o iptables-list -s iptables-list.c
$ sudo mv iptables-list /sbin/iptables-list
$ sudo chown 0.0 /sbin/iptables-list
$ sudo chmod 4755 /sbin/iptables-list
$ ls -l /sbin/iptables-list
-rwsr-xr-x 1 root root 5552 Feb 23 08:14 /sbin/iptables-list
$ iptables-list
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Удаление от начала / от конца строки Delphi XE4 В текстовом файле расположено много строк, все строки разной длины. Нужен алгоритм как сделать:

*

*В edit1 указываю число: Сколько Удалить символов - с начала строки.

*В edit2 указываю число: Сколько Удалить символов - с конца строки.

*Нажимаю кнопку и программа Обрезает все строки, в файле (1.txt), с начала и с конца. И сохраняет результат в файл 2.txt.

Пробовала переделать функцию с пробелами но опыта не достаточно. Может кто подскажет ?.
function Split(Str: String): String;
var
  I: Integer;
begin
  I := 1;
  while Str[1] in [' ',',','.',#13] do //удаление пробелов в начале
    Delete(Str, 1, 1);
  while I <= Length(Str) do
  begin
    if Str[I] in [' ',',','.',#13] then
    begin
      while ((Str[I+1] in [' ',',','.',#13]) or (Length(Str) = I)) and
      (Length(Str) >= I) do
        //удаление пробелы между словами и в конце
        Delete(Str, I, 1);
      Inc(I);
    end;
  end;
  Result := Str;
end;

A: Вот так будет попроще:
function MyTrim(aString: string; aFromFront, aFromBack: Integer): string;
begin
  if aFromFront + aFromBack >= Length(aString) then
    // Если от строки ничего не останется, то возвращаем "пусто"
    Result := ''
  else
    // Копируем часть строки
    Result := Copy(
                aString,
                1+aFromFront, // с aFromFront символа (строка считается с 1-цы)
                Length(aString)-aFromFront-aFromBack); // Сколько символов копируем
end;

A: Все задачу решила. Если кому еще пригодиться то вот алгоритм.
n := strtoint(Edit1.Text); //удаляем в начале
k := strtoint(Edit2.Text); //удаляем в конце

if k>=length(s) then s:=''
else delete(s,length(s)-k+1,k);

if n>=length(s) then s:=''
else delete(s,1,n);

if s=''then // вывод сообщения
else //вывод полученной строки


text:
Q: Matrix inversion using woodbury indentity inverse Consider closed-form solution of linear regression $$ \hat{\beta}=\left(\lambda I+X^TX\right)^{-1}X^Ty $$ where $X \in \mathbb{R}^{n \times d}, y \in \mathbb{R}^{n}$
Say we have extra data points $(X_{n+1}, y_{n+1})$.  We can define \begin{gather*}
X' = (\frac{X}{x_n+1}) \in \mathbb{R^{(n+1)\times d}} \\
y' = (\frac{t}{y_n+1}) \in \mathbb{R^{(n+1)}}
\end{gather*} and compute $$\hat{\beta'}=\left(\lambda I+X'^TX'\right)^{-1}X'^Ty'$$
Let \begin{gather*}
V_{n} = X^{T}X+\lambda I \\
V_{n+1} = X'^{T}X'+\lambda I
\end{gather*}  How to derive $V_{n+1}^{-1}$ as a function of $V_{n}^{-1}$ using Woodbury matrix identity?

A: $X^TX=\sum_{i=1}^n x_i^Tx_i$, where each $x_i$ is row $i$ within $X$ (with $x_i$ a row vector, $x_i^T$ a column vector).  Therefore,
$X'^TX'=X^TX+x_{n+1}^Tx_{n+1}$.
That identifies $x_{n+1}^Tx_{n+1}$ as the rank-one update for the Woodbury formula, or more simply, the Sherman-Morrison formula.


text:
Q: Unable to install Ethernet Driver in 14.04LTS **strong text**Recently i  had installed Ubuntu 14.04 LTS 64-bit.
It is dual-boot with Windows 7 Ultimate. The Ethernet works good in Windows but in Ubuntu does not work.Actually,it worked for 2-3 days,then suddenly it stopped .. so, i tried to reinstall the driver(RTL8101E/RTL8102E), but every time it shows error asking about the "PRIVATE KEY"...
What is this private key? ...
wireless works very much fine....
plzz post ur suggestions regarding this problem??

A: Sometimes when you add a custom repository you have to use the command apt-key add [whatever-the-key-is]. When you try to install something from the custom repository without the right apt key, you will get a key error like the one you are seeing. Go back and make sure you added the right key, and then apt-get update && apt-get install --reinstall [RTL8101E/RTL8102E driver packagename]


text:
Q: Deploying an App with Code Splitting on GCP App Engine - Loading chunk * failed We have a web application (frontend) using React created from Create React App. The app is running on Google Cloud Platform App Engine Standard. Our web application is code splitted. Each page is then loaded on user navigation.
It's working really well. The issue we have is for example user A is on the app home page. We deploy a fix that change the chunk file name. The user A then try to access another page and then got the error Loading chunk * failed. The url to get the file is now returning a 404 because the file has been replaced by some new chunk files.
It's a frequent problem as I can see during my research but I didn't find a solution that apply for Google App Engine.
Here's an article that explain the problem / solution: https://mitchgavan.com/code-splitting-react-safely/
I would like to use the solution "Solution 1: Keep old files on your server after a deployment" but I can't see how to do this using GCP ...
Here's the app.yaml file
service: frontend
runtime: nodejs14
env: standard
instance_class: F1

handlers:
  - url: /(.*\..+)$
    static_files: build/\1
    upload: build/(.*\..+)$
  - url: /.*
    static_files: build/index.html
    upload: build/index.html

We have the following dispatch file (* for masked url)
dispatch:
  - url: "*"
    service: frontend

  - url: "www.*"
    service: frontend

A: Haven't tried this before but see if it makes sense/works.

*

*We have a blog article about downloading your source code from GAE. It contains an explanation of where your source is stored when you deploy (a staging bucket), how long it stays there and how you can modify how long it stays before Google automatically deletes it.

*When you deploy to GAE, gcloud only deploys files that have changed (it doesn't deploy those that haven't). Since you now have 'new' files because new hashes were generated, the older files no longer exist on your local machine. I do not know if Google will automatically delete those files from the staging location in bullet 1 above.

*My proposal here is that you follow the steps in the blog article (from bullet 1) and alter (change) how long the files are retained in your staging bucket. Another option is to check the retention policy tab and see if you can change the rule so the files don't get deleted. If you're able to alter how long the files remain or the retention policy, it just might solve your problem. Let me know if this works


text:
Q: How to run a Service always in background (Non-Stop) - Android I have created a Service in my android application which starts running on BOOT_COMPLETE. I want to run my Service non-stop (run always), and for that I have used while(true) inside onStartCommand() method. So is this fine to use while(true) or there is any other better way to run a service always in background?
This is code of my Service:
package com.example.abc.project1;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class HelloService extends Service {

    private static final String TAG = "HelloService";
    private boolean isRunning  = false;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isRunning = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    /*non-stop work to be done in background always*/
                }
            }
        }).start();
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        isRunning = false;
    }

}

A: I have not tried this myself but if you change receiver to service it should work.


text:
Q: what is ''Size'' parameter size unit,In Set parameter Method? `parameter = command.CreateParameter ("Num",DB.adSmallInt,  DB.adParamInput,2, anyValue)`

I want to know in Case of the type was

DB.adSmallInt

and the

size = 2

will the size be
2 Byte ?
or
2 Bit ?
in which unit it will be Configured?

A: the size parameter will be ignored since an adSmallInt is two bytes in size,
and is getting converted to smallint in SQL server side.


text:
Q: How to make two build inside one CircleCI configuration? In my git repository, I have docker-compose.yml and two folders frontend and backend, each of which contains its Dockerfile.
docker-compose.yml:
version: "3.5"

services:
  Django:
    build:
      context: backend
    ...

  react:
    build:
      context: frontend
    depends_on:
      - django

How do I configure to build both of them into images and push them together to the docker hub after spotting new commit in the master branch?

A: In two words you should build images for the services you want & push them to the docker hub.
You can do it using commands like
    ...env configuration in your CI...
    - DOCKER_ACC=my_account_name
    - DOCKER_REPO_DJANGO=django-app
    - DOCKER_REPO_REACT=django-app

    ... post tests commands ...
    - echo $DOCKER_PWD | docker login -u $DOCKER_LOGIN --password-stdin
    - docker build -t $DOCKER_ACC/$DOCKER_REPO_DJANGO:latest -f ./path/to/Dockerfile.django .
    - docker push $DOCKER_ACC/$DOCKER_REPO_DJANGO:latest

    - docker build -t $DOCKER_ACC/$DOCKER_REPO_REACT:latest -f ./path/to/Dockerfile.django .
    - docker push $DOCKER_ACC/$DOCKER_REPO_REACT:latest

Where latest you can replace with your branch name, commit tag or etc and build multiple image versions for your app.
Everything depends on you, that's pretty flexible. But you have to do 2 steps - build images & push them. Built images tags should be equal to your github images urls.
Read more at articles like these ones:

*

*http://docs.shippable.com/ci/tutorial/build-push-image-to-docker-hub/

*https://circleci.com/blog/build-cicd-piplines-using-docker/

A: If you are building on circleci, you dont have to build from docker compose.
You can just add steps to the circleci config (.circleci/config.yml) to build and push your images.
The file can look something like that:
version: 2

jobs:

 build:
   docker:
    - image: docker:19.03.5

   working_directory: [YOUR REPO WORKING DIR]

   steps:
    - checkout
    - setup_remote_docker

    - run:
       name: build frontend
       command: docker build -t [FE DOCKER REPO NAME]:tag -f [FE DOCKERFILE PATH] .

    - run:
       name: build backend
       command: docker build -t [BE DOCKER REPO NAME]:tag -f [BE DOCKERFILE PATH] .

    - run:
       name: push frontend
       command: |
         docker login -u $DOCKER_USER -p $DOCKER_PASS
         docker push [FE DOCKER REPO NAME]:tag

    - run:
       name: push backend
       command: |
         docker login -u $DOCKER_USER -p $DOCKER_PASS
         docker push [BE DOCKER REPO NAME]:tag

Note that you'll have to add DOCKER_USER and DOCKER_PASS environment variables to your circleci build settings


text:
Q: Not able to get MAC address of client machine using php Unable to get mac address of client machine when my application is hosted on cloud. Code is working fine on localhost but fails to get MAC address when i deploy it on cloud server. Tried too many codes like this.
function GetMacAddress()
{
    $MAC = exec('getmac');
    return $MAC = strtok($MAC, ' ');
}


text:
Q: JS Scipt that detects if the message is in English or not I need to make a script that detects if a message that was sent by someone is in English and not in any other languages , I was thinking to create a DB with all the English words but I think that is gonna be too heavy for a bot and some people might spell the words wrong

A: Implementing your own solution for this is almost never what you want to be doing. My first step would be to look into an existing npm package like languagedetect. There are likely also multiple APIs that are designed for this purpose, here's a few:

*

*detectlanguage.com

*Microsoft's Text Analysis

*AWS' 'Detect the Dominant Language'


text:
Q: find the index of a string ignoring cases I have a string that I need to find index in a list ignoring cases.
MG
['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']

I want to find the index of MG in the following line as a list.

A: you can ignore the cases by converting the total list and the item you want to search into lowercase.
>>> to_find = 'MG'
>>> old_list =  ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> new_list = [item.lower() for item in old_list]
>>> new_list.index(to_find.lower())
3

A: One of the more elegant ways you can do this is to use a generator:
>>> list = ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> next(i for i,v in enumerate(list) if v.lower() == 'mg')
3

The above code makes a generator that yields the index of the next case insensitive occurrence of mg in the list, then invokes next() once, to retrieve the first index. If you had several occurrences of mg in the list, calling next() repeatedly would yield them all.
This also has the benefit of being marginally less expensive, since an entire lower cased list need not be created; only as much of the list is processed as needs to be to find the next match.

A: Same as first but I don't think there is need to create a new and old list if you are only interested in the index
>>> search_term ="MG"
>>> my_list = ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> [item.lower() for item in my_list ].index(search_term .lower())
3


text:
Q: javascript object : current or method? This is the code:
var x = document.getElementById("x");

This is the HTML:

text

This is the next javascript:
x.innerHTML = "newtext"
alert(x.innerHTML)

So what will happen? Will x

Save information when using var x = document.getElementById("x") and variable x will change but not HTML
 with id x?

A: Since x is a reference to the DOM element, it'd modify the innerHTML of id - x.
Demo: JSFiddle
var x = document.getElementById("x");
x.innerHTML = "newtext";
alert(x.innerHTML); //same as the below alert
alert (document.getElementById("x").innerHTML);

A: In this case, var x that is referring to
 element will change the HTML of
 element.
var x = document.getElementById("x");
x.innerHTML = "newtext"
alert(x.innerHTML); //return "newtext"

var y = document.getElementById("x");
alert(y.innerHTML); //returns "newtext"

Changing the innerHTMLproperty of
 element using javascript has actually changed the HTMLof
 element.

A: The variable x will still keep a reference to the DOM element with id "x" and the DOM element's innerHTML will change. So if you do like this afterwards
var content = x.innerHTML

then will content contain "newtext", but if you do like this afterwards
x.innerHTML = "new newtext"

then will content still contain "newtext" but then content of x will have changed. The variable x will still be a reference to the same DOM element.


text:
Q: how to store Uint8List in mysql I'm trying to store images in the database by converting them to Uint8List and then show images in flutter , I tried to store the Uint8List  as TEXT and as VARCHAR
and I have an error Expected value of type Uint8List  and got String
addimage(String x , Uint8List img)async{
    print (x);
    var url = 'http://ip/imageStore.php';
    var response = await http.post(Uri.parse(url), body :{
      'word': x,
      'imageByte': img,
    });

snapshot.data![index]['imageByte'] as Uint8List

A: I fixed it by using base64 encoding and decoding then storing the encoded image as Text in mysql
and when i want to display my Image i used image.memory
       image = base64Encode(Uint8List_image); // convert image to base64 (String);
       image.memory(base64Decode(image)); // convert encoded image to Uint8List and display it ;


text:
Q: MimeMessage emails - create a "in-reply" email Currently , I'm recieving emails with my server(imap through spring framework)
the messages i recieve are of type MimeMessage.
lets say i now got a new email (X)
I would like to create a new MimeMessage (Y) that in it's body it will say that this email is in response (reply) to (X)
how can i do this?
p.s the (Y) message is going to be sent from a different SMTP url later on, so X and Y are not related.
thanks.

A: Simply create the new message and set its content to whatever you want - presumably something like...
"In Reply To:\n\n" + copied_text_content_from_received_message;
However, be aware that the inbound content might have various formats, including multipart (see JavaDoc for MimeMessage.getContent().

A: Start with the Message.reply method.  Fill in the content of this new Message as suggested in the other answer here.


text:
Q: url naming issue in angularjs I am trying to pass a parameter through states by $stateProvider and having a display issue. The parameter I try to pass is something like "foo/bar/zoo", which means it contains / character.
In the URL, it looks as this: */foo%252Fbar%252Fzoo.
Also, the controller seems to be loaded twice, because when I put console.log(path); in the Controller, it prints the output twice. First is the original value and second is the encoded version looks like foo%2Fbar%2Fzoo.
The question is, how can I pass a parameter containing /, and how can I block controller to be loaded twice?
state provider:
$stateProvider
    ...
    .state('app.group.wiki.pages', {
        url         : "/pages/{path:.*}",
        templateUrl : "modules/group/wiki/pages.html"
    })


text:
Q: How to find branch point from binary skeletonize image I use Python OpenCV to skeletonize an image like this:

and I want to find the branch point of the skeleton

I have no idea how to do it. Any thoughts?

A: This question is already quite old but if anyone else stumbles across this and would like to have an answer that does not rely on additional packages and uses simple morphological operations you might find the following helpful.
The idea is simply to apply a hit-or-miss transform to search for pixels that satisfy the condition of a branchpoint. A branchpoint in a skeleton is a pixel that is connected to three or four other pixels. Given a list of appropriate structuring elements selems you can elegantly combine several hit-or-miss transforms in one output image like the following.
import numpy as np
import scipy.ndimage as ndi

branches = np.zeros_like(skeleton, dtype=bool)
for selem in selems:
    branches |= ndi.binary_hit_or_miss(skeleton, selem)

This is quite space efficient because you directly add the result of each transform to the same result array. The question now is how to create the list of structuring elements. One solution would be the following.
selems = list()
selems.append(np.array([[0, 1, 0], [1, 1, 1], [0, 0, 0]]))
selems.append(np.array([[1, 0, 1], [0, 1, 0], [1, 0, 0]]))
selems.append(np.array([[1, 0, 1], [0, 1, 0], [0, 1, 0]]))
selems.append(np.array([[0, 1, 0], [1, 1, 0], [0, 0, 1]]))
selems.append(np.array([[0, 0, 1], [1, 1, 1], [0, 1, 0]]))
selems = [np.rot90(selems[i], k=j) for i in range(5) for j in range(4)]

selems.append(np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]))
selems.append(np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]]))

The last two lines are only needed if you want to also detect branch points with four branches. If you're only interested in three branches you can omit the last two lines.
The complete solution would then be
import numpy as np
import scipy.ndimage as ndi

selems = list()
selems.append(np.array([[0, 1, 0], [1, 1, 1], [0, 0, 0]]))
selems.append(np.array([[1, 0, 1], [0, 1, 0], [1, 0, 0]]))
selems.append(np.array([[1, 0, 1], [0, 1, 0], [0, 1, 0]]))
selems.append(np.array([[0, 1, 0], [1, 1, 0], [0, 0, 1]]))
selems.append(np.array([[0, 0, 1], [1, 1, 1], [0, 1, 0]]))
selems = [np.rot90(selems[i], k=j) for i in range(5) for j in range(4)]

selems.append(np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]))
selems.append(np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]]))

branches = np.zeros_like(skeleton, dtype=bool)
for selem in selems:
    branches |= ndi.binary_hit_or_miss(skeleton, selem)

Likewise you can search for endpoints by using the following list of structuring elements.
selems = list()
selems.append(np.array([[0, 1, 0], [0, 1, 0], [0, 0, 0]]))
selems.append(np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]))
selems = [np.rot90(selems[i], k=j) for i in range(2) for j in range(4)]

A: You can use the library Skan to find the branch points.
from skan import skeleton_to_csgraph
from skimage import io, morphology

# loading image
image = io.imread('https://i.stack.imgur.com/FpSt9.jpg')

# make image binary
image_binary = image >= 200

# skeletonize
sk = morphology.skeletonize(image_binary).astype(bool)

# receive a degree matrix
_, _, degrees = skeleton_to_csgraph(sk)

# consider all values larger than two as intersection
intersection_matrix = degrees > 2

The result here is not a single pixel as multiple branches meet at one point. One could determine this center region with regionprops and then find the centroid if one needs exactly one pixel.

A: The main idea here is to look in the neighborhood. You can use a 8-conected neighborhood for every pixels ([1 1 1; 1 1 1; 1 1 1], and the center is the pixel for which the neighborhood being explored!).
At every branch point, the degree of the pixel will be > 2, while regular pixels will have a degree of 2 (i.e., connected to 2 pixels in their neighborhood).
In your case your objective is finding a 'crossing point', where the degree is > 3.

A: I found all the answers above a bit too technical. Here is a way to do this in the simplest terms I could think of.
First we need to agree on what a branch point is. A branch point in a binary image (matrix of 0's and 1s) is a 1 with at least three other 1's in its neighborhood.
We also need to agree on how to discern neighboring pixels (top/bottom/left/right only,
or with added diagonally adjacent pixels). This is up to us.
Having agreed on the above, we can now detect the branch points in the image.

*

*Traverse the image skipping zero pixels (these can't be branch
points)

*At each 1 look around its neighborhood. How many 1s are there?

*Let's use our definition to answer the  question: If there are at least three 1s you've found a branch point!

A: Output (overlaid on input image):

Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Find branch point in example image.
"""

import numpy as np
import matplotlib.pyplot as plt
from mahotas.morph import hitmiss as hit_or_miss
from skimage.morphology import medial_axis as skeletonize
# from scipy.ndimage import binary_hit_or_miss as hit_or_miss

def find_branch_points(skel):
    X=[]
    #cross X
    X0 = np.array([[0, 1, 0],
                   [1, 1, 1],
                   [0, 1, 0]])
    X1 = np.array([[1, 0, 1],
                   [0, 1, 0],
                   [1, 0, 1]])
    X.append(X0)
    X.append(X1)
    #T like
    T=[]
    #T0 contains X0
    T0=np.array([[2, 1, 2],
                 [1, 1, 1],
                 [2, 2, 2]])

    T1=np.array([[1, 2, 1],
                 [2, 1, 2],
                 [1, 2, 2]])  # contains X1

    T2=np.array([[2, 1, 2],
                 [1, 1, 2],
                 [2, 1, 2]])

    T3=np.array([[1, 2, 2],
                 [2, 1, 2],
                 [1, 2, 1]])

    T4=np.array([[2, 2, 2],
                 [1, 1, 1],
                 [2, 1, 2]])

    T5=np.array([[2, 2, 1],
                 [2, 1, 2],
                 [1, 2, 1]])

    T6=np.array([[2, 1, 2],
                 [2, 1, 1],
                 [2, 1, 2]])

    T7=np.array([[1, 2, 1],
                 [2, 1, 2],
                 [2, 2, 1]])
    T.append(T0)
    T.append(T1)
    T.append(T2)
    T.append(T3)
    T.append(T4)
    T.append(T5)
    T.append(T6)
    T.append(T7)
    #Y like
    Y=[]
    Y0=np.array([[1, 0, 1],
                 [0, 1, 0],
                 [2, 1, 2]])

    Y1=np.array([[0, 1, 0],
                 [1, 1, 2],
                 [0, 2, 1]])

    Y2=np.array([[1, 0, 2],
                 [0, 1, 1],
                 [1, 0, 2]])

    Y2=np.array([[1, 0, 2],
                 [0, 1, 1],
                 [1, 0, 2]])

    Y3=np.array([[0, 2, 1],
                 [1, 1, 2],
                 [0, 1, 0]])

    Y4=np.array([[2, 1, 2],
                 [0, 1, 0],
                 [1, 0, 1]])
    Y5=np.rot90(Y3)
    Y6 = np.rot90(Y4)
    Y7 = np.rot90(Y5)
    Y.append(Y0)
    Y.append(Y1)
    Y.append(Y2)
    Y.append(Y3)
    Y.append(Y4)
    Y.append(Y5)
    Y.append(Y6)
    Y.append(Y7)

    bp = np.zeros(skel.shape, dtype=int)
    for x in X:
        bp = bp + hit_or_miss(skel,x)
    for y in Y:
        bp = bp + hit_or_miss(skel,y)
    for t in T:
        bp = bp + hit_or_miss(skel,t)

    return bp

def find_end_points(skel):
    endpoint1=np.array([[0, 0, 0],
                        [0, 1, 0],
                        [2, 1, 2]])

    endpoint2=np.array([[0, 0, 0],
                        [0, 1, 2],
                        [0, 2, 1]])

    endpoint3=np.array([[0, 0, 2],
                        [0, 1, 1],
                        [0, 0, 2]])

    endpoint4=np.array([[0, 2, 1],
                        [0, 1, 2],
                        [0, 0, 0]])

    endpoint5=np.array([[2, 1, 2],
                        [0, 1, 0],
                        [0, 0, 0]])

    endpoint6=np.array([[1, 2, 0],
                        [2, 1, 0],
                        [0, 0, 0]])

    endpoint7=np.array([[2, 0, 0],
                        [1, 1, 0],
                        [2, 0, 0]])

    endpoint8=np.array([[0, 0, 0],
                        [2, 1, 0],
                        [1, 2, 0]])

    ep1=hit_or_miss(skel,endpoint1)
    ep2=hit_or_miss(skel,endpoint2)
    ep3=hit_or_miss(skel,endpoint3)
    ep4=hit_or_miss(skel,endpoint4)
    ep5=hit_or_miss(skel,endpoint5)
    ep6=hit_or_miss(skel,endpoint6)
    ep7=hit_or_miss(skel,endpoint7)
    ep8=hit_or_miss(skel,endpoint8)
    ep = ep1+ep2+ep3+ep4+ep5+ep6+ep7+ep8
    return ep

# --------------------------------------------------------------------------------
# script
# --------------------------------------------------------------------------------

img = plt.imread("test.jpg")

# for some reason (screenshot?), example image is not binary
binary = img >= 250

skeleton = skeletonize(binary)

branch_pts = find_branch_points(skeleton)

plt.imshow(binary + branch_pts, cmap='gray', interpolation='nearest'); plt.show()


text:
Q: GitHub Pages - " Your site is having problems building: Page build failed." I'm trying to troubleshoot a GitHub Pages failure. The Github Actions workflow completes successfully, and I can see that mkdocs has successfully updated the gh-pages branch. I've also confirmed that I can run mkdocs serve locally with a successful build.
After the workflow completes, I can go into the repository settings, into the GitHub Pages tab, and see the "Your site is having problems building: Page build failed." error, but no further context on what is causing it to fail.
Another interesting note, if I create a gh-pages-test branch from the gh-pages branch and then change the source value to the new test branch, I get a successful deployment. I can then switch back to the regular branch and it will also deploy successfully. If I run the GitHub Action workflow again though, the action succeeds but the page build fails.
This was working fine up until a week or two ago, but I'm not seeing any new changes in our code base that would have caused this. Is there any way to get more information on why it is failing?


text:
Q: If $R$ is a local ring with maximal ideal $m$ then show that $R_m \cong R$ If $R$ is a local ring with maximal ideal $m$ then show that $R_m \cong R$.
I know that maximals ideals are prime and every element in $R \setminus m$ is a unit, but how can I use this to solve the question?

A: Since $R$ is local, every element of $R\setminus M$ is an unit.
For any $\frac{r}{s}\in R_M$, map $\frac{r}{s}\mapsto rs^{-1}$. (If $s$ were not already a unit of $R$, this would not be possible.)
You can work to confirm that this map is

*

*well-defined

*a ring homomorphism

*a bijection


text:
Q: Adding dynamic content in rendered bootstrap popover template Actually I am facing problem while adding dynamic content with rendered template.
Popover Call:
$(selectorId).popover({
        placement: 'bottom',
        title: 'New Post',
        html: 'true',
        content: _template,
        container: 'body',
});

Rendered HTML template

     Name<input type="text" name="name" id="name" />
     Message<input type="text" name="message" id="messgae" />
     Select Article<select name="article" id="article"></select>
     <input type="button" value="submit">

Just need to focus on "Article". The select box is Empty in template and after rendering I am trying to append article data but its not working.
Appending data from db to select box
$.each(articles,function(){
   $("#article").append(this.articleName);
});

Article is a JSON array
[
  {
       'id': 1,
       'articleName': 'article1'

  },
  {
       'id': 2,
       'articleName': 'article2'

  },
  {
       'id': ,
       'articleName': 'article3'

  }
]

Problem: Select box is showing empty.
Goal: Whenever popover is opened user can able to select article from select box.

A: You are appending article names to select box, while you should append options there as html
So it should be something like this:
$.each(articles,function(){
   $("#article").append("<option value='"+this.articleName+"'>"+this.articleName+"</option>");
});

Update:
Another problem could be that you are trying to append options to select box while it doesn't exist yet on page.
So, if you are appending template as a string (via 'content' property), you can initially compose tem plate with necessary select options:
var _template = "<select>";
$.each(articles,function(){
     _template +="<option value='"+this.articleName+"'>"+this.articleName+"</option>";
};
_template+= "</select>";

or you can also use 'container' property and pass


text:
Q: How to read property from application.properties when using ConfigurationFactory (Log4j's Programmatic Configuration)? I am using programmatic configuration for log4j as shown in the following link: http://logging.apache.org/log4j/2.x/manual/customconfig.html.
@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(50)
public class CustomConfigurationFactory extends ConfigurationFactory {

    static Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
        builder.setConfigurationName(name);
        builder.setStatusLevel(Level.ERROR);
        builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL).
            addAttribute("level", Level.DEBUG));
        AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").
            addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
        appenderBuilder.add(builder.newLayout("PatternLayout").
            addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
        appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
        builder.add(appenderBuilder);
        builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG).
            add(builder.newAppenderRef("Stdout")).
            addAttribute("additivity", false));
        builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
        return builder.build();
    }

    @Override
    public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
        return getConfiguration(loggerContext, source.toString(), null);
    }

    @Override
    public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
        ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
        return createConfiguration(name, builder);
    }

    @Override
    protected String[] getSupportedTypes() {
        return new String[] {"*"};
    }
}

I wish to choose the appender based on application.properties
I have tried all answers shared on How to access a value defined in the application.properties file in Spring Boot. But none of them work, giving errors like Spring Boot - Environment @Autowired throws NullPointerException. The solutions mentioned in the above link also fail to work.


text:
Q: Gradle Offline Build Using Maven Repository I'm attempting to setup an offline Gradle build.
I would ideally like to have all my project dependencies in an arbitrary maven repository referenced as below:
repositories {
    maven {
        url 'file://PATH/TO/REPO'
    }
}

However, the above fails in a fresh Gradle install (no ~/.gradle cache) with the following:
* What went wrong
Plugin [id: PLUGINID, version: PLUGINVERSION] was not found in any of the
following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolvee plugin artifact     'PLUGINID:PLUGINNAME:PLUGINVERSION')
    Searched in the following repositories:
        Gradle Central Plugin Repository

I've tried a few different ways to specify the repository, including:

*

*Replacing "url..." with "flatDir { dir '/PATH/TO/REPO' }".

*Copying all dependencies to ~/.m2 and calling mavenLocal() as the repository.

To copy dependencies from ~/.gradle/caches/modules-2/files-2.1/ into my "offline" repository, I have tried:

*

*Straight copy/paste

*A Gradle task which converts the structure as such:
task cacheLocal(type: Copy) {
    from new File(gradle.gradleUserHomeDir, 'caches/modules-2/files-2.1')
    into '/PATH/TO/REPO'
    eachFile {
        List<String> parts = it.path.split('/')
        it.path = (parts[0] + '/' + parts[1]).replace('.','/') + '/' + parts[2] + '/' + parts[4]
    }
    includeEmptyDirs = false
 }

Other things:

*

*Running with "--offline" makes no difference.

*Build is successful if ~/.gradle is already present, but fails otherwise.

My plugins block (the above error statement will hit the first non-Gradle core plugin, so protobuf in this case):
plugins {
    id "com.google.protobuf" version "0.8.6"
    id "nebula.ospackage" version "4.9.3"
    id "java"
    id "eclipse"
}

This is out of my depth and any help would be greatly appreciated!

A: If you want also plugins to be resolved from a local repository, you have to configure the pluginManagement section to do so.
In your question, it looks like you only configured project repositories.
See the example in the documentation


text:
Q: How is the current limited through the LEDs in this LED matrix design? I was studying some LED matrix designs on the Net and came across the one below:

*

*DMD: Dot Matrix Display 32x16 (link to product)

*(somewhat poorly drawn) schematics of an old version of the product.
Its design puzzled me because I couldn't tell how it limits the current through each LED and through the shift registers outputs without any current limiting resistors.
For clarity, here are the relevant parts of the schematics diagram linked above.
VCC is 5V.

Here are the relevant datasheets:

*

*APM4953 - Dual P-Channel Enhancement Mode Mosfet

*74HC595 - 8-bit serial-in, serial or parallel-out shift register

*Unfortunately, I know nothing about the LED used (so I assumed common 2V, 20mA red LED indicators).

As far as I can tell, to light a LED, say D512, one has to:

*

*turn on the high-side PFET by setting HI1 to LOW, thus turning row HO1 on, and

*set the '595 shift register output QH (pin 7) to LOW
In this case, the current path would be the following:

My question is: what is limiting the current through the LED and '595 QH output?
My best guess is that, somehow, the '595 is clamping the current to the desired value of 20mA, which incidentally may be the forward current intended to be pushed through a common LED indicator. Is that it? If so, why does that happen?
Another guess is that there is a specific combination of VCC, multiplexing scheme, LED forward voltage and current that magically limits the current.
In any case, is this the Right Way of Designing It(TM)? Or is this just a trick in which the '595 is being used outside its specs?

A: I checked a few datasheets:

*

*74HC595 from NXP

*74HC595 from TI

*General HCMOS family specs from NXP
And I nowhere saw a current limit specified. The only thing that is specified is that you must not exceed 35mA output current (absolute maximum rating). But it doesn't say the chip itself limits the current to this value.
Now, I found another spec from TI:

*

*Input and Output Characteristics of Digital Integrated Circuits.

It gives (among other interesting things) the output characteristic of two 74HC chips
(74HC00, and 74HC240 whose specs are closer to those of the 74HC595), and we can indeed see that you can easily get more current than the specified 35mA max. Likely, the current will be limited to about 80mA (but it certainly isn't very accurate and may depend a lot on temperature and chance):

Anyway, it will be much more than the 20mA you'd like to see in your circuit. There is nothing, apart from the 595 internal resistance, really limiting the current in this circuit.
So, the 595 and the LEDs are driven above their specs. For the LED, it is certainly less of a problem since there is multiplexing. So you can tolerate higher than 20mA if the duty cycle is low enough (but this often isn't clearly specified for basic LEDs).
But for the 595, if you're driving a fully lit panel, it can become a problem and may damage the chip in the long run.
This design is bad, m'kaaayy.

A:
I couldn't tell how it limits the current through each LED and through the shift registers outputs without any current limiting resistors.

Through the internal resistance of the HC595s. Not uncommon - I do it all the time, on MCUs and logic devices. Certainly not advisable but done many times a day.


text:
Q: Soldering double deck pin headers Please take a look at a PCB like this one (STM32 Nucleo64 board):

They utilized so called "double deck" or "stacked" headers, meaning they can be used from both sized (top and bottom).
My question is- how does one solder them, since they come in such package:

Source: https://www.tme.eu/gb/details/zl2019-2x20/pin-headers/ninigi/zl2019-40/
I mean, you want the PCB to be in between the pin holding materials. It seems to me that one of them should be taken off after the initial soldering. The problem is that there is no good position for soldering without touching the holding bars:

Should the bards be altered by hand? That makes it easy for the pins to be soldered uneven... I just don't see it. I would appreciate all help regarding this topic.

A: The plastic pieces can be removed. Press gently and uniformly and extract one of the pieces. Then solder the whole and place the plastic piece back.
You can use a bit of heat or lubricant, but very carefully and in the latter be assured that it has been completely removed before soldering the pins.


text:
Q: Statistics combination question You are in charge of creating a "USELESS" committee. The committee shall consist of one Umpire, three Statisticians, two Electricians, and one Lawyer (get it?). You personally know two Umpires, five Statisticians, three electricians, and four lawyers. Unfortunately, one of the Statisticians and one of the Electricians refuse to work together. How many USELESS committees can you create?
The answer given to me was 144.
However, my answer is 208
what i did was 208 = (combination of not having both) + (combination removed one statistician) + (combination removing one electrician)
=[(4c1)(2c2)(4c3)(2c1)]+[(4c1)(3c2)(4c3)(2c1)]+[(4c1)(2c2)(5c3)(2c1)]
=32+96+80
=208
Thank you

A: You're double-counting some possibilities. For example every committee without either of the troublesome members is counted once in each of your three terms.
It would be easier to do this by subtraction than by addition -- first count the total number of legal committees, then subtract those that have both troublemakers on them:
$$ \binom21_U \binom 53_S \binom32_E \binom 41_L - \binom21_U \binom42_S \binom 21_E \binom 41_L $$


text:
Q: Popup after image onload I'm trying to create a popup window with an image in it and I want the popup to be in the same aspect ratio as the image. But I only know the image dimensions on image.onload.
So what I need is a popup that comes after the image.onload. But browsers see that as an unwanted popup and will block it. Even if it's the only popup after the user's click.
I have tried creating the popup first and alter the content and sizing later on but even when that works it sometimes causes the popup window to hide in the background with no way to get it back to the front again(chrome on windows)
Is there a way to make sure the delayed popup is still hooked to the user's click?
Or some other suggestions.
The code that I would like to have working:

    selectURL: function(url) {
        // Check for images, otherwise just simply open the file by the browser.
        if(url.match(/(jpe?g|png|gif|bmp)$/gim)) {
            // Check if colorbox exists and use if so.
            if($.colorbox) {
                $.colorbox({
                    maxWidth:'80%',
                    maxHeight:'80%',
                    fixed: true,
                    scrolling: false,
                    href: url,
                    open: true,
                    photo: true
                });
            } else {
                // New image object so we can calculate the required popup size on load
                var myImage = new Image();
                myImage.src = url;
                // Close current window to make sure focus works
                if(typeof(popupWindow) !== 'undefined') {
                    popupWindow.close();
                }
                // Temporary loading image
                popupWindow = window.open('/images/loading.gif','popupWindow','height=400,width=600,resizable=no,scrollbars=no,top=200,left=200');
                if (window.focus) {
                    popupWindow.focus();
                }
                // Calculator and actual image opener :)
                myImage.onload = function() {
                    var maxWidth  = 600,
                        maxHeight = 600;
                    // Close existing popup
                    if(typeof(popupWindow) !== 'undefined') {
                        popupWindow.close();
                    }

                    if(this.width < maxWidth && this.height < maxHeight) {
                        popupWindow = window.open(this.src,'popupWindow','height='+this.height+',width='+this.width+',resizable=no,scrollbars=no,top=200,left=200');
                    } else if(this.width === this.height) {
                        popupWindow = window.open(this.src,'popupWindow','height='+maxHeight+',width='+maxWidth+',resizable=yes,scrollbars=yes,top=200,left=200');
                    } else if(this.width < this.height) {
                        popupWindow = window.open(this.src,'popupWindow','height='+maxHeight+',width='+(maxHeight / this.height * this.width)+',resizable=yes,scrollbars=yes,top=200,left=200');
                    } else {
                        popupWindow = window.open(this.src,'popupWindow','height='+(maxWidth / this.width * this.height)+',width='+maxWidth+',resizable=yes,scrollbars=yes,top=200,left=200');
                    }
                    if (window.focus) {
                        popupWindow.focus();
                    }
                }
            }
        } else {
            window.open(url);
        }
    }

A: If your pop-up window that contains loading.gif is showing, then perhaps the browser does not like you opening two pop-ups with one click.
You could try opening a pop-up to show-image.html, in which you could show a loading image, whilst calculating the target image's size, and then resize the window using window.resizeTo() once you know the dimensions.
I would recommend telling show-image.html the target image filename by using a URL variable such as show-image.html?image=foo.bar or even show-image.html?foo.bar. Note that if you are to use such a method, you should ensure that you escape the necessary characters from the variable you gather from the URL, to avoid XSS.
I have created an example using jsFiddle. The page accepts an image's URL through a URL variable, purely for testing purposes - your own implementation should not include this (on this page). Also note that I have naturally not included protection from XSS, or null checks.
This is a link to the page, using a 1920 x 1080 target image.
This is a link to the page, using a 800   x 600   target image.
Remember that in order to see a true reload of the image, you will need to clear your browser's cache in order for the image to be loaded once again.
Here you can see the source for the above page. If you wish to tweak this demo I recommend that you save it to a local document, as jsFiddle's frames can throw off the position calculations.
The above page provides the means of creating a pop-up containing a second page that I created. It passes the image location to the second page through the URL. As previously stated, I recommend that on the second page, you ensure that the given image name will not lead outside your website (these checks were purposefully omitted in this example).
Here is the source for the page that the first page is creating a pop-up of.
If you need further clarification or examples, let me know.


text:
Q: fullscreen youtube video on external display / avoid changing desktops I'd like to entertain my 2 y.o. with cartoons while I' trying to work. The problem is that when I change desktops and use mission control it affects second display too.
How can I fix fullscreen youtube video to one display?
It's getting even worse with fullscreen quick time - the main display is blank...
So, is it possible to dedicate one display for entertainment while keeping the other for regular use?

A: I presume you are not on Mavericks. Multiple Displays support was improved in Mavericks and makes full-screen apps not interfere with other displays:

Full screen applications
  With Mavericks, you can use full screen apps on each display independently. Open an app full screen on one display. On your other display, open an additional app as either windowed, or full screen.

Source: OS X: Using multiple displays in Mavericks
You can update to Mavericks which should fix this.


text:
Q: Difference between session and outbound properties . If all the outbound properties are converted to inbound properties on crossing the transport barrier , and all the outbound properties set are available at the mule endpoint as inbound properties , why do we need session variable ?

A: You are right about the concept of outbound properties,but you need to consider following scenarios

*

*The outbound properties(which can later become inbound properties)
are visible only during execution of single flow i.e. they cannot be
used across multiple flows.

*when message is passed to a new flow via a flow-ref rather than a
connector, the outbound properties remain outbound properties and are
not converted to inbound property.

on the other hand for session variables

*

*They are available across all flows within a application.

so there is a specific purpose for which mule has both outbound properties and session variables.
You can use any one of those which cater to your specific requirements.
For further reference you can have a look here Mule Message
hope this helps!
Good luck!

A: Here is a link, which helped my through when I was asking your question:
https://m-square.com.au/mule-school-the-mulemessage-property-scopes-and-variables/
I hope it helps.

A: Session variables are used when you need the values within the application, as Session variables are Global throughout the application.
On the other hand, Outbound properties are used when you need the values outside the application into another application. Since outbound properties can cross across the transport barrier, we can easily get the value into other application, which the Session variable can't


text:
Q: What is the meaning behind "bloody jerry" I've heard this term in a pirate movie or video game, not sure where. Since, I've been wondering what real meaning this sentence have.

A: "Jerry" came from World War II, and is used to refer to the Germans in general.

by shortening of German, originally from the First World War.
Them Jerry planes are bombing Leicester!

It was also used in a derogatory way, so it evolved to be used as an insult on basically everything.


text:
Q: using R & paws how switch/assume different IAM Role? I'm logging in successfully to AWS via paws however am in the parent account.
library(paws)

Sys.setenv(
  AWS_ACCESS_KEY_ID = "*****************************************",
  AWS_SECRET_ACCESS_KEY = "************************************",
  AWS_SESSION_TOKEN = "******************************************************************",
  AWS_REGION = "us-west-2"
)

mys3<- paws::s3()
temp_s3 <- mys3$list_buckets()

I'm want to change to a child account and list the buckets under it.  Any ideas?

A: What you're looking for is Switching Role via API.
Provided that you have all the necessary rights and parameters, you should use the methods of the STS service, Paws seems to cover all the basic ones and you can find their documentation here.


text:
Q: Can not delete Document Set "The file is currently checked out or locked for editing by another user." I have a Doc Set I can not delete.  I've tried to delete it via Windows Explorer (in case that would help) and via the Content and Structure menu, but to no avail.
As you see in the pictures below, Sharepoint thinks there are checked out or locked documents.  The folders are actually empty.  There were 7 folders within the Doc Set, I have deleted 4 of them, three remain.
Any ideas as to what could be causing the error message?

A: Ah...I finally figured it out, having just posted the question...
There were invisible files inside the sub-folders, I've no idea why they were invisible.
I checked the Site Collection Recycle Bin, in case a file had been deleted, but the 30 days had not yet passed - since files are only deleted after 30 days I believe.
Then I found the answer:  Manage files which have no checked in version.  There were load of these files, so I took ownership of them.  Then Sharepoint allowed me to delete the document set (and all sub-folders contained within it AND all files contained within the sub-folders).


text:
Q: Need a value prompt to select multiple items and use wildcard I have this filter currently setup on my query and it works
[Replenishment Code] contains ?vendor?
However i need to replace "contains" with "in" to get multi select working in my value prompt
BUT, i am not able to add a wildcard to the "in" operator like so
[Replenishment Code] in ?vendor? + '%'
Is there any way to do this?
My replenishment code is setup like this
AIPRODU-WA
AIPRODU-SF
etc...
But i had to substring ?vendor? to everything before the "-". so you see
AIPRODU

A: Use a prompt macro function to generate a filter of
vendor like #prompt(sq('vendor','string') + '%'#
Macro functions allow you to change text of query before it's sent to datasource, it's quite flexible
http://pic.dhe.ibm.com/infocenter/cbi/v10r1m0/topic/com.ibm.swg.im.cognos.ug_cr_rptstd.10.1.0.doc/ug_cr_rptstd_id51759mac_prompt.html#mac_prompt


text:
Q: Serializing JSON to JSON API format in Ruby/Rails In my Rails 5 API project I am consuming SOAP services. With the use of the Savon gem, version 2, I parse the response from any SOAP web service to JSON format.
In my Rails project I am creating a facade for multiple SOAP services. Let's say 4 SOAP services that have 90% similar response format/structure. I would like my facade to be accepting and sending out the information from the services in JSON API format.
I found some solutions, but not an ideal and effective one:

*

*Parsing the JSON/SOAP response from the SOAP service into models/objects, and then outputting this to JSON API through existing libraries (e.g. jsonapi-resources gem)

*Building a serializer from scratch within Rails

*Use an ESB

The first option seems to be overkill and error prone.
The second option seems to be a very time consuming project, and it'll also be prone to a lot of errors if I have to do this by myself in a short amount of time.
The third option is a no go due to budget.
So my question is, do there exist tools out there that can assist me? I have been doing a great deal of research, but have not been able to find anything that seems to be a solution to my problem or fulfilling my needs.
Solution so far
I found it most pragmatic to go with option 1. I am doing something similar to the following:
# app/controllers/api/v1/some_resources_controller.rb
...
# Retrieve response from service
response = fetch_resources_from_service(query)
# Pick out the values from the response that we want to output
resource_params = strip_response(reponse, whitelist: [:id, :title, :date, ...]
# Create a model object from these stripped/whitelisted params
resource = Api::V1::SomeResource.new(resource_params)
# Render in JSON API format (with active_model_serializer)
render json: resource, adapter: :jsonapi, serializer: Api::V1::SomeResourceSerializer

A: I'm not a Ruby person but what about a ruby library for simply converting xml to json?  It seems like you're building something like a reverse proxy with a SOAP to json converter built in.  If so it could be tough to keep up with the backend API changes and your object models.  Using something like https://github.com/jnunemaker/crack could free you from creating object models for every endpoint.
Also found a similar SO question
Ruby XML to JSON Converter?


text:
Q: Installation problems with Mongo on Nitrous.io container I created an Ubuntu container on Nitrous.io so that I can develop on my chromebook without the chromebook's limitation. I am having trouble using mongodb. I followed these steps to install it:
~ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

~ echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

~ sudo apt-get update

~ sudo apt-get install -y mongodb-org

~ sudo service mongod start

I can't connect to mongo through the mongo shell. I get this error message:
MongoDB shell version: 3.0.6
connecting to: test
2015-10-02T21:13:56.629+0000 W NETWORK  Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2015-10-02T21:13:56.630+0000 E QUERY    Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed
    at connect (src/mongo/shell/mongo.js:179:14)
    at (connect):1:6 at src/mongo/shell/mongo.js:179
exception: connect failed

I have tried deleting the lock file and creating a 'data' directory and then setting the dbpath to that directory:
~ sudo rm /var/lib/mongodb/mongod.lock

~ sudo service mongodb restart

and
~ mkdir data

~ cd data

~ mongod --dbpath .

The Ubuntu container is 64 bit 14.04 I believe Nitrous uses Docker containers if that makes a difference. I don't think I have direct root access, but I have sudo access which doesn't require a password. More generally, has anyone else had a lot of problems installing Mongo? I can never seem to get it to just install smoothly.


text:
Q: Is the group action by a topological homeomorphism group continuous? Let $F$ be a topological space such that $G := Homeo(F)$ is a topological group in the compact-open topology. Let $\phi : G \times F \to F$ sending $(g,x)$ to $g(x)$ be the map for the action of $G$ on $F$. I'm wondering if this action is continuous. I can't seem to prove it nor can I find counterxamples, but here is what I have so far.
Let $U$ be open in $F$. I've shown that $\phi^{-1}(U) = \cup_{g \in G} \{g\}\times g^{-1}(U)$. Since $g$ is a homeomorphism, $g^{-1}(U)$ is open in $F$. I'm now struggling to use the compact-open topology to show that the union over $g$ is open, if this is even true.
Or do I need to assume more on $F$ or $G$ to make the group action continuous?
EDIT: In the comments we have that $F$ being locally compact as well is sufficient for $G$ to act continuously. But is it necessary?


text:
Q: Optimal DB structure for creating user segments I want to create a segmentation engine and can't seem to figure out the most optimal DB or DB structure to use for the task.
Currently I use MySQL as my primary DB, but the segmentation engine is a separate software component and thus can have a different DB if applicably.
Basically I have 10 million unique users identified with UserID (integer). Administrator of the Segmentation engine dynamically creates segments with some predefined rules (like age range, geolocation, transaction history etc.). Application should execute the rules of each segment periodically (once every 15 minutes) to get the current list of all users (can be upto 1 million users each) that belong to the segment and store it.
Later application is exposing the API to allow external systems use segmentation functionality, namely:
1. Get list of all segments that a particular UserID belongs to.
2. Get list of all UserIDs that a particular segment contains.
Note that because segments need to be updated very frequently (every 15 min) this causes massive transactions in DB to "maintain" the segments, where non-applicable users should be removed and new ones added all the time.
I have considered several approaches so far:
1. Plain MySQL where I have a table of users belonging to segments (SegmentID,UserID). (this approach has 2 drawbacks: storage space and constant delete/insert/update in MySQL which will degrade innodb performance by introducing page splitting).

*Using JSON data types in MySQL, where I can have table (UserID,Segments), where segments is a json containing an array of SegmentIDs. (drawbacks here are slow search and slow updates)

*Using Redis with Sets (UserID,Segments), where UserID will be the Key and Segments will be the Set of SegmentIDs. (drawbacks here are no simple way to search by SegmentID).
Has anyone worked with similar task and can provide any guidance?
Any feedback will be appreciated, so I can be pointed to a direction which I can further research.

A: I think you can use Elasticsearch for this task.


text:
Q: How to convert Hibernate Result Object to String? I implemented a hibernate query and would like to assign the result to one of my class variables.
The problem is that the results of hibernate queries seem to be objects or something, as the syso of a result looks very strange:
[exercise.java.basics.storage.WarehouseProduct@77f6d2e3]

This is the method executing the query:
 public void updateStock() {

    Session session = getSessionFactory().getCurrentSession();

    Criteria criteriaNail = session.createCriteria( WarehouseProduct.class );
    criteriaNail.add( Restrictions.like( "productName", String.valueOf( Product.NAIL ) ) );
    List nailCountResult = criteriaNail.list();

    System.out.println( nailCountResult.toString() );

    }

The database has only 2 colums and the value I need is in the second.
What I would like to do is something like this:
this.nailCount  = nailCountResult.[XYZ --> Get the value from the second column];

Is something like this possible? How can I cast these result objects to something readable?
best regards
daZza

A: First of all I suggest to change the line to
 List<WarehouseProduct> nailCountResult = criteriaNail.list();

And now it is not a ResultSet, it's a list of WarehouseProduct Objects.
You can access each object with index.
You can loop over the result list and  see them like
 for( WarehouseProduct wp : nailCountResult )   {
   System.out.println( wp.nailCount);
  }

As a side note, you are breaking encapsulation here. Please look in to it.

A: All you need to to is this
String value=nailCountResult.get(0).getXXXX();


text:
Q: RxJava filtering empty list and using firstOrDefault I'm trying to filter a list which might or might not be empty (or the item is not in the list). inboxData is filled by another observable:
private BehaviorSubject<InboxResponse> inboxData = BehaviorSubject.create();

public Observable<Item> getInboxItem(String id) {
    return inboxData
        .flatMap(response -> Observable.from(response.getData()))
        .filter(item -> item.getId().equals(id))
        .firstOrDefault(null);
}

In this case if response.getData() is empty firstOrDefault never runs. But why? It clearly says that it gives you back the default value if the preceeding observable emits nothing.

A: firstOrDefault emits the default if the stream completes without any items being passed through the observable. For your stream to complete the BehaviorSubject would need to signal completion. Since there is no indication that happens it would never realize it needs to send the default.
The solution is to move the filter and firstOrDefault to the inside of the flatMap so the end of the list provided by getData ends up completing the inner stream.
Note that if you're using RxJava2 as your tags suggest, null can never be an item in the stream, so passing it as default would cause an exception.

A: public Observable<Item> getInboxItem(String id) {
    return inboxData
        .flatMap(response -> Observable.from(response.getData()))

At this point, response.getData() returns null, right?
        .filter(item -> item.getId().equals(id))

That means that item here is null. So item.getId() throws a NullPointerException. An error like that is immediately passed to the subscriber's onError handler. The firstOrDefault method will not even be called anymore, because the stream is immediately terminated.
        .firstOrDefault(null);
}


text:
Q: For which (a, b) the subset is not a smooth curve in the plane R^2? The full question is:
For which (a, b) the subset
C = {(x, y) ∈ $R^2 : y^2 = x^3 + ax + b$} ⊂ $R^2$
is not a smooth curve in the plane $R^2$?
I found out one similar question here:
How to check whether a subset of R^2 is a smooth curve
and have the beginning of the solution. First, I wrote the equation as $x^3 + ax + b - y^2 = 0$   and found the gradient
($3x^2+a; -2y$).
One of the answers in the link above was: "You are considering curves f(x,y)=C. By the implicit function theorem, you can find a smooth patch of the curve around any point where the gradient of the equation exists and is different from the zero vector."
Do I have to just check when the gradient is zero vector?
If yes, does that mean this?
$3x^2+a=0$
$-2y=0$
Then
$a=-3x^2$
$y=0$
Is it enough for answering the question? What about the parametr "b"? Can it be any number?

A: Your solution is not enough yet. Define $f(x,y) := x^3+ax+b-y^2$. Then, by your two equations $3x^2+a=0$ and $-2y=0$, we have
$$
\text{grad}(f) = 0 \iff (x,y) = \left(\pm \sqrt{-\frac{a}{3}}, 0\right).
$$
Let's look at the case $(x,y) = (\sqrt{-a/3},0)$: we want to check in which cases this tuple lies in $C$. For this to hold, we must have that
\begin{equation}
0^2 = \left(\sqrt{-\frac{a}{3}}\right)^3 + a\sqrt{-\frac{a}{3}}+b,\tag1
\end{equation}
hence we can simply define $b$ as follows:
$$
b := -\left(\sqrt{-\frac{a}{3}}\right)^3 - a\sqrt{-\frac{a}{3}}.
$$
We immediately see that with this definition of $b$, equation (1) always holds, meaning that for all $a \leq 0$ the curve
$$
C_a := \left\{ (x,y) \in \mathbb{R}^2 : y^2 = x^3 +ax -\left(\sqrt{-\frac{a}{3}}\right)^3 - a\sqrt{-\frac{a}{3}} \right\}
$$
is not smooth. Indeed $a \leq 0$, since otherwise the square root in equation (1) were undefined. In conclusion, your curve is not smooth for all
$$
(a,b) = \left(a, -\left(\sqrt{-\frac{a}{3}}\right)^3 - a\sqrt{-\frac{a}{3}}\right),
$$
where $a \leq 0$. Here is a graphing calculator with your curve, so you can see that this solution works.
A similar argument works for the tuple $(x,y) = (-\sqrt{-a/3},0)$. I hope this is helpful!


text:
Q: How to check the NSString contains URL or string data? I am fresher to iOS, i am getting problem at checking string object contains URL or string?
NSMutableArray *Arr=[NSMutableArray alloc]initWithObject:@"Welcome", @"http://abcd.com/Images/bus.png", nil];

int i;

i++;

NSString *str=[Arr objectAtIndex:i];

Now, i want to check condition, if string contains "Welcome", have to display on label or if it is URL , i need to display that URL image in ImageView. So how can i check it? Please help me in this problem.

A: Instead of initiating both as NSStrings, try differentiating between them by making urls a NSURL (special container specifically for urls):
NSMutableArray* Arr = [NSMutableArray alloc]initWithObject:@"Welcome", [NSURL URLWithString:@"http://abcd.com/Images/bus.png"], nil];

for(id object in Arr)
{
    if([object isKindOfClass:[NSString class]])
    {
        NSString* string = object;
        NSLog(@"String: %@", string);
    }
    else if([object isKindOfClass:[NSURL class]])
    {
        NSURL* url = object;
        NSLog(@"URL: %@", url);
    }
}

A: Try like this
NSMutableArray *Arr=[[NSMutableArray alloc]initWithObjects:@"Welcome", @"http://abcd.com/Images/bus.png",nil];

    NSString *st=nil;
    for(NSString *string in Arr)
    {
     NSArray *matches = [detector
                 matchesInString:string
                                    options:0
                                      range:NSMakeRange(0,
                                     [string length])];
   for (NSTextCheckingResult *match in
          matches) {
          if ([match resultType] ==
         NSTextCheckingTypeLink) {
        NSURL *url = [match URL];
         } else
       {
        NSlog(@"it is a string");
       }
    }

}

A: To check NSString is containing a URL You can Try This code
if ([stringName hasPrefix:@"http://"] || [stringName hasPrefix:@"https://"]) {
    //show imageVivew
}

A: Try this, it will help you:
NSMutableArray *Arr=[[NSMutableArray alloc]initWithObjects:@"Welcome", @"http://abcd.com/Images/bus.png", nil];

if([Arr count])

{

for (NSString *str in Arr)

    {
        if([str isEqualToString:@"Welcome"])

        {
            NSLog(@"str is %@",str);

            //do whatever you want
        }

        if([str isEqualToString:@"http://abcd.com/Images/bus.png"])

        {
            NSLog(@"str is %@",str);

            //do whatever you want
        }
    }
}


text:
Q: How to make dynamic loader using javascript php I am working on Php, Right now i am getting data from database using multiple queries, In database there maybe be 10 records or maybe 10,000 record, So i want to use progress bar which should show how percentage (%) query complete (estimated time), Because as i said there maybe few records or maybe thousands of record,Is this possible to create dynamic loader (progress bar) ?

A: With ajax, you can get the number of rows and calculete a number to sum to the progressbar, after that you shoud call with other ajax method to a php function which has a query with limit x (this number x shoud be pass by ajax param).
After that, in the response of ajax, you can sum the % of the progressbar.
Progressbar bootstrap


text:
Q: Script for run script I have a script on vbscript
Dim WSHShell, WinDir, Value, wshProcEnv, fso, Spath

Set WSHShell = CreateObject("WScript.Shell")

Dim objFSO, objFileCopy
Dim strFilePath, strDestination

 Const OverwriteExisting = True
 Set objFSO = CreateObject("Scripting.FileSystemObject")
 Set windir = objFSO.getspecialfolder(0)
 objFSO.CopyFile "\\dv.rt.ru\SYSVOL\DV.RT.RU\scripts\shutdown.vbs", windir&"\", OverwriteExisting

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _
    & strComputer & "\root\cimv2")
JobID = "1"

Set colScheduledJobs = objWMIService.ExecQuery _
    ("Select * from Win32_ScheduledJob")
For Each objJob in colScheduledJobs
 objJob.Delete
Next

Set objNewJob = objWMIService.Get("Win32_ScheduledJob")
errJobCreate = objNewJob.Create _
    (windir & "\shutdown.vbs", "********093000.000000+660", _
        True, 1 OR 2 OR 4 OR 8 OR 16 OR 32 OR 64, ,True, JobId)

How make that shutdown.vbs not run once at 9:30 but run for 9:30 to 12:00

A: *

*Modify your shutdown.vbs script to check the time - if it's between 9:30 and 12:00, shutdown

*Schedule two tasks to execute the shutdown script: one that runs at 9:30 and one that runs on system startup.


text:
Q: Learning the Faraday Http Library I've been interested lately in the Faraday Http client library. I don't see much in the area of documentation or tutorials and wanted to know if anyone knows of any tutorials, blog posts or talks that go into Faraday?

A: This article gives some nice background: https://mislav.net/2011/07/faraday-advanced-http/

A: I would say Faraday on Github answers all your questions!


text:
Q: Excel FILTER() returning 0 for blank cells I suspect this has been asked previously, but I can't find it.
FILTER() will often return a 0 for blank rows, even when a return string is specified.
Using filter() I am often getting a 0 return value for empty cells. Assume these 6 rows of data in column A:
abc
xyz
abc

xyz
abc

If I use
FILTER(A10:A15, A10:A15 <> "xyz", "")

I get back the following (sometimes):
abc
abc
  0
abc

This seems to be somewhat unpredictable. Having 0s show up where I don't want is a problem and requires extra logic or filtering. Is this a known issue? Other than explicitly filtering out blank cells, is there another way to solve this problem?
This seems to work to get rid of 0 returning for empty cells:
FILTER(A10:A15, (A10:A15 <> "xyz") * (A10:A15 <> ""), "")

This is returned:
abc
abc
abc

I can live with this solution but it should be unnecessary. I also end up explaining why I'm filtering empty cells to people over and over.
btw, filtering out 0 doesn't work. FILTER() seems to see the cell as a blank string when reading it, but not when outputting the result.
FILTER(A10:A15, (A10:A15 <> "xyz") * (A10:A15 <> 0), "")

This will return the original results with the 0.
If there is no better solution, is there an explanation?

A: You may add &"" in front of your array argument.
For example,
FILTER(A10:A15 &"", (A10:A15 <> "xyz") * (A10:A15 <> ""), "")

This will work fine with text values but it will convert your numeric data to text, in which case, you may convert it back to numeric using the VALUE function.
Suppose if A10:A15 was numeric data, you may use:
VALUE(FILTER(A10:A15 &"", (A10:A15 > 1000) * (A10:A15 <> ""), ""))

A: As explained here, the third argument (If_empty) is not for cases when there is a blank.

FILTER(array, include, [if_empty])

Where:
Array (required) - the range or array of values that you want to filter.
Include (required) - the criteria supplied as a Boolean array (TRUE and FALSE values).
Its height (when data is in columns) or width (when data is in rows) must be equal to that of the array argument.
If_empty (optional) - the value to return when no entries meet the criteria.
Your function would return the string specified in If_empty if all the values in Array were "xyz". I.e., the criteria in Include would not evaluate to TRUE for any non-blank value in the range Array.
Also, it seems that your last formula does not anymore return zeros:

A: I figured out what seems to be a different generic solution: replace empty stings in the first argument to single quotes, so generically:
=FILTER(SUBSTITUTE($X:$Z,"","'"),*whatever*,*whatever*)

or in the case of this question:
=FILTER(SUBSTITUTE($A10:A15,"","'"),A10:A15 <> "xyz", "")

I simply makes use of how Excel handles the single quote, I haven't found any downsides yet, though I didn't test it thoroughly.

A: Another, less elegant solution, is to replace empty cells in your source array with a space character " ".
I found this thread while looking for a quick answer while reformatting data.  So adding a space was quicker that the other solutions.  I really like that
VALUE(FILTER(   &"", answer as well!


text:
Q: Should I use bigint or varchar(20) as primary key, performance-wise, for Postgres? I have 18 character long IDs I get from an API, and I currently store them as varchar(20). They are used as primary and foreign keys. Is it better in my case, to use bigint instead of a string type, performance-wise?
Since JavaScript cannot deal with bigints, they are converted by default to string, but I could set columns to be bigint, if that will help.

A: Definitely store as a bigint: this uses 8 bytes, while an 18 character string uses 19 bytes.


text:
Q: Azure Application Insights doesn't show custom events created in Azure function I have a function app written in C# created in Azure that is triggered by HttpTrigger.
I am trying to log several custom events to log the interesting time point for analyzing performance.
What I have done is to create TelemetryClient in the construct function.
  static ThumbnailGenerator()
    {
        telemetryClient = new TelemetryClient(TelemetryConfiguration.CreateDefault());
    }

And then in the function:
    [FunctionName("Upload")]
    [StorageAccount("AzureWebJobsStorage")]
    public static async Task<IActionResult> Upload(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "upload/{name}")] HttpRequest req,
        string name,
        ILogger log,
        ExecutionContext context)
    {
        var evt = new EventTelemetry("Upload function called");
        evt.Context.User.Id = name;
        telemetryClient.TrackEvent(evt);
        telemetryClient.Flush();

        ....

        DateTime start = DateTime.UtcNow;

        // Log a custom dependency in the dependencies table.
        var dependency = new DependencyTelemetry
        {
            Name = "Upload-Image-Operation",
            Timestamp = start,
            Duration = DateTime.UtcNow - start,
            Success = true
        };

        telemetryClient.TrackDependency(dependency);
        telemetryClient.Flush();

        return new OkObjectResult(name + "Uploaded successfully.");
    }

The application insights for this can correctly show the default RequestTelemetry and traces for the function all the time. However, it is very unstable for the custom event and DependencyTelemetry which sometimes shows in application insight and sometimes not at all.

I did many research and has added something like:
    telemetryClient.Flush();

But the instability is still more or less the same.
The libariries I am using are:
 <Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.9.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.14.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.0-beta.2" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.25" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
    <PackageReference Include="SixLabors.ImageSharp" Version="1.0.3" />
    <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="5.0.1" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

Does anyone know why? It seems Azure is really unstable and buggy in this part. Please give me some tips.

A: Make sure your telemetry configuration has the proper instrumentation key set. I am not sure that TelemetryConfiguration.CreateDefault() gets the right value.
Also, I suggest injecting the TelemetryClient in the constructor using Dependency Injection. It is already availble out of the box. That way you do not have to create the instance yourself and you do not have to worry about the right way to set the instrumentation key:
    [FunctionName("Upload")]
    [StorageAccount("AzureWebJobsStorage")]
    public static async Task<IActionResult> Upload(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "upload/{name}")] HttpRequest req,
        string name,
        ILogger log,
        TelemetryClient telemetryClient,
        ExecutionContext context)
    {
        telemetryClient.XXX();
        ...
    }

Flushing the client should not be necessary, only needed upon termination and even then you should wait a while as it is an async process.

A: It's possible that you are running into the Sampling feature of Application Insights.

[Sampling] is the recommended way to reduce telemetry traffic, data costs, and storage costs, while preserving a statistically correct analysis of application data.

This page also has some more details that are specific to Azure Functions:

When the rate of incoming executions exceeds a specified threshold, Application Insights starts to randomly ignore some of the incoming executions.

This sounds like the behavior that you're experiencing. You can use the host.json file to configure which types of telemetry are excluded from sampling; try adding Event to excludedTypes:
{
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "maxTelemetryItemsPerSecond" : 20,
        "excludedTypes": "Request;Exception;Event"
      }
    }
  }
}


text:
Q: Cenros 6.3 install php-imap cross-repo fails I am trying to install php-imap support on Centos 6.3
yum install php-imap

Installation failed due to repos has different php versions:
Resolving Dependencies
--> Running transaction check
---> Package php-imap.x86_64 0:5.3.3-14.el6_3 will be installed
--> Processing Dependency: php-common = 5.3.3-14.el6_3 for package: php-imap-5.3.3-14.el6_3.x86_64
--> Processing Dependency: libc-client.so.2007()(64bit) for package: php-imap-5.3.3-14.el6_3.x86_64
--> Running transaction check
---> Package libc-client.x86_64 0:2007e-11.el6 will be installed
---> Package php-imap.x86_64 0:5.3.3-14.el6_3 will be installed
--> Processing Dependency: php-common = 5.3.3-14.el6_3 for package: php-imap-5.3.3-14.el6_3.x86_64
--> Finished Dependency Resolution
Error: Package: php-imap-5.3.3-14.el6_3.x86_64 (updates)
           Requires: php-common = 5.3.3-14.el6_3
           Installed: php-common-5.3.18-1.el6.remi.x86_64 (@remi)
               php-common = 5.3.18-1.el6.remi
           Available: php-common-5.3.3-3.el6_2.8.x86_64 (base)
               php-common = 5.3.3-3.el6_2.8
           Available: php-common-5.3.3-14.el6_3.x86_64 (updates)
               php-common = 5.3.3-14.el6_3
 You could try using --skip-broken to work around the problem

Trying to installed it with --skip-broken key have this result:
Packages skipped because of dependency problems:
    libc-client-2007e-11.el6.x86_64 from base
    php-imap-5.3.3-14.el6_3.x86_64 from updates

My question is: How could I install it from the remi repo directly without checking any versions.
Thank you in advance!

A: You need to enable the remi repository in order to install the matching packages from it. I presume you had previously enabled it by some means, in order to get its version of PHP in the first place.
Edit /etc/yum.repos.d/remi.repo and make sure that enabled=1 is set in the [remi] section.
(If it isn't present, make sure you installed remi-release RPM first.)


text:
Q: Error while persisting a JPA model I have an error while persisting my data and I have no idea what is the problem there !!
Here is the content of the Persistence.xml
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

    <persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">

        <properties>

            <!--PostgreSQL-->
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/postgres"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            <property name="hibernate.connection.username" value="postgres"/>
            <property name="hibernate.connection.password" value="postgres"/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.id.new_generator_mappings" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.ejb.metamodel.generation" value="disabled"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultComponentSafeNamingStrategy"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>

    </persistence-unit>

</persistence>

Here is the Rest webservice call:
@GET
@Path("/")
public Response test() {

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");
    EntityManager em = emf.createEntityManager();

    Member member = new Member("doux");
    em.persist(member);

    em.close();
    emf.close();

    return Response.status(Response.Status.OK).build();
}

and here is the error i've got !! :
message Unknown entity: ca.products.jpa_models.Member

    description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête.

    exception

    java.lang.IllegalArgumentException: Unknown entity: ca.products.jpa_models.Member
        org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1149)
        ca.products.services.RestServices.test(RestServices.java:41)
        sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        java.lang.reflect.Method.invoke(Method.java:497)
        com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
        com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
        com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
        com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
        com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
        com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
        com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
        com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
        com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
        com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
        com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

A: I found the solution :
I should declare the link to the class in my persistence.xml since it is not belonging to the same package !!
<class>ca.products.jpa_models.Member</class>

Here is the source :

class : The class element specifies a fully qualified class name that
  you will map. By default all properly annotated classes and all
  hbm.xml files found inside the archive are added to the persistence
  unit configuration. You can add some external entity through the class
  element though. As an extension to the specification, you can add a
  package name in the  element (eg
  org.hibernate.eg). Caution, the package will include
  the metadata defined at the package level (ie in package-info.java),
  it will not include all the classes of a given package.


text:
Q: Can I assume all valid HTML entities will display correctly in all modern browers and devices? I sometimes like to use unusual symbols in my web pages, such as ⁙ (which should display as a 5-dot symbol like the 5 on a die) and ⚛ (which should display as a pictogram of an atom). I also like to use whitespace characters like   (hair space) and   (narrow nonbreaking space).
Can I just take it for granted that all modern browsers (and not-so-modern like IE-8) and various phones and tablets can display these properly?
Or is there some code I can use to check and then substitute something more standard if that character is not displayable?  What I have in mind would be "If this character isn't available, use this instead."
I tried to write that in PHP like this:
$symbol = ("⁙") ? "⁙" : "::";

But of course that won't work, because any such string in quotes is truthy. Without the quotes it throws an error.
Any ideas?


text:
Q: WiFi/BT on Realtek 8723 - Is FCC, CE certification needed for WiFi if we disable WiFi and use only Bluetooth? I'm planning on importing a generic mini pc that comes with an onboard Realtek 8723 for WiFi and Bluetooth. We will need to get it FCC, CE, and IC certified before we sell it in North America/EU.
Getting tested for WiFi and BT in a lab costs a several thousand dollars for each system (WiFi and BT). Since we do not intend to use WiFi at all, can I disable the WiFi in firmware and get certified for Bluetooth only?
The firmware in the commercial product will also have the wireless disabled with no way for user to turn it on.

A: Compliance with WLAN and Bluetooth product standards are not part of CE/FCC/IC compliance. The latter are only concerned with radio immunity/emissions and not about product conformance to industry standards.
Tests against product standards are probably already carried out by whoever made the radio module, and if you haven't changed anything there, you shouldn't need to carry out new product tests. Meaning: be careful with which antennas that are used and only use those that have been used in product testing.
Tests against CE or FCC or IC is something else. For example for CE marking, you need to test against EN/ETSI 300 328, which only cares about the radio being a 2.4GHz wideband "thing", be it Wi-Fi or Bluetooth. The nice thing here is that if your product has Wi-Fi and Bluetooth active at the same time, you get both tested under the same standard, given that they both use 2.4GHz.
If you can ensure that the Wi-Fi radio is electrically disabled and will never be active, then you shouldn't need to test it. That is, if you can ensure that it never emits a carrier wave and never acts as a receiver. In that case it can be regarded as a 'chunk of electronics' and will be covered by the immunity/emission tests of the rest of the product.

A:
Getting tested for WiFi and BT in a lab costs a several thousand
dollars for each system (WiFi and BT). Since we do not intend to use
WiFi at all, can I disable the WiFi in firmware and get certified for
Bluetooth only?

You still have to go though FCC intentional radiators test. I wouldn't think that the cost of testing wifi would be all that much more. If you want to get certified for wifi that's a different story. Getting the wifi certification allows you to use that seal for marketing and tests for interoperability
Is talk with the testing lab and see what the costs are.


text:
Q: Webbrowser component - manipulation with source html Friend of mine is playing some internet game. It's mainly text game. No animations, no videos, just text and couple of images.
He would like to have some more possibilities like enhanced ingame notepad etc.
My question is, what webbrowser (IE based/chrome/...) component should I use, if I need easy manipulation with source code of the webbrowser, meaning simple access to source html code, reading and mainly inserting a bits of my own html code to existing?
Example
When user navigates to this page

blahblah

I want to remove table from page, insert my own enhanced table and than refresh page using same css style like origin page.

A: Awesomium would allow you to do it, and it's a fast and very functional embed-able component.


text:
Q: How can I adapt a 3-pin PC fan connector to a 4-pin connector? My computer's motherboard uses all four pin fan connectors with no support for speed controlling the older three pin fan connector. The problem is, all the PC fans that I have use a three pin connector. As fan as I know there are no premade solutions available, so I was thinking of building an adapter that sits in an unused drive bay.
I can't seem to find much information on how the four pin fan connecter works. Apparently, it looks something like this:

*

*12 V

*0V

*Tachometer

*PWM

The three pin header is numbered similarly:

*

*Vcc

*0V

*Tachometer
Could I simply use a logic level MOSFET to do the following?

A: This solved my problem:
Cited from 3pin to 4pin fan adapter(Chinese)

Explanation:

*

*two fast-switch triodes (2N-2907 and 13003) utilize PWM control over 12v power.

*diode protects the fan from voltage higher than 12v

*1K R gives a 12/1000=12mA ceiling to the current from 12v to ground, just in case 2N-2907 is damaged.

*0.5K R does the same thing for 13003, limiting the max current approximately to 2.5/500=5mA

All these stuffs are easy and cheap to buy, enjoy..

A: You can just plug it in, the connectors are designed to be compatible.
the fan will only run at full speed, that may or may not be a problem.
if you want variable speed that's obviously not a suitable solution.
using the PWM signal (which is is probably only 0-3.3V) to switch a mosfet probably won't work well,  and if it does work the fan will tend to stick on some harmonic of the PWM frequency instead of following the PWM ratio.
a better approach is is to use the PWM signal to control the set-point of a voltage regulator and use the regulator output to power the fan, thus controlling it speed.

simulate this circuit – Schematic created using CircuitLab
here I show the potentiometer on a typical adjustable lm2958 LM2956 buck converter module and then the same module with the potentiometer replaced with a PWM control circuit.  it works by the PWM controlling the discharge speed of C2 and thus the bias given to feedback signal.
C1-R5 compensate for the low-pass formed by the presence of C2

A: Most 3-pin fan controllers control the fan by varying a DC voltage across the fan. This basically means that there is a PWM circuit (most likely) inside that controls a (discrete) buck regulator that brings the voltage down. The fan stays on permanently and has a functional tacho output.
You CAN control a 3-pin fan with PWM on the power pins as well (but not as you have drawn - this is not how a P-MOSFET will work), but be prepared to sacrifice the tachometer function. After all, if you cut power to the fan there is no way for the fan to pull down (it's an open collector/drain output) the tachometer pin. Therefore you get the tacho signal interleaved with the PWM signal, resulting in a garbaged tacho output.
4-pin fan controllers hand off the PWM signal to the fan itself, and these fan controllers supply an uncontrolled a 12VDC. This is probably why they are not able to speed control your fan. 3-pin fans will power up at 4-pin connectors, but only at full speed.

A: This should work correctly :

source: https://www.techpowerup.com/forums/threads/so-you-want-pwm-control-of-your-3-pin-fan.115752/
12V is permanently connected, ergo, you will have correct RPM readings.
You need a 5.1V Zener Diode, different value for resistor and positioning and uses a n-Mosfet.

A: This is rather old question, so I wanted to give a brief update for the folks stumbling upon it now. Note, that this is not an answer per se, since it does not work for everybody, unlike other answers here.
While answering similar question, I've stumbled upon the notion of motherboard support for both 3-pin and 4-pin fans. So, if you have one of the newest boards, before you start soldering any adapters go check BIOS settings - it just might have everything you need already.