text:
Q: Google API client ID isn't authorizing I am trying to make an app to do a basic search for youtube videos. I'm using the Youtube Data API and I went to the google developer's console and created a client ID for my domain name.
I downloaded the auth.js and the search.js that Google has on their sample code section and put my client ID into where it says 'my client id' but the application isn't working. I used console.log and it seems that I'm not getting past the function 'checkAuth'.
Am I missing something?? Here is a link to the page: http://www.vidme.cassandraburnscreative.com/#search
Here is the auth.js and search.js together
var OAUTH2_CLIENT_ID = 'my client ID';
var OAUTH2_SCOPES = [
  'https://www.googleapis.com/auth/youtube'
];

googleApiClientReady = function() {
  console.log("googleApiClientReady");
  gapi.auth.init(function() {
    window.setTimeout(checkAuth, 1);
    console.log("gapi.auth.init");
  });
}

function checkAuth() {
  gapi.auth.authorize({
    client_id: OAUTH2_CLIENT_ID,
    scope: OAUTH2_SCOPES,
    immediate: true
  }, handleAuthResult);
  console.log("checkAuth");
}

function handleAuthResult(authResult) {
  if (authResult && !authResult.error) {
    // Authorization was successful. Hide authorization prompts and show
    // content that should be visible after authorization succeeds.
    $('.pre-auth').hide();
    $('.post-auth').show();
    loadAPIClientInterfaces();
    console.log("Load Interfaces");
  } else {

    $('#login-link').click(function() {
      console.log("nope");
      gapi.auth.authorize({
        client_id: OAUTH2_CLIENT_ID,
        scope: OAUTH2_SCOPES,
        immediate: false
        }, handleAuthResult);
      console.log("HandleAuthResult");
    });
  }
}

function loadAPIClientInterfaces() {
  gapi.client.load('youtube', 'v3', function() {
    handleAPILoaded();
    console.log("handleAPILoaded");
  });
}

function handleAPILoaded() {
  $('#search-button').attr('disabled', false);
}

function search() {
  var q = $('#query').val();
  var request = gapi.client.youtube.search.list({
    q: q,
    part: 'snippet'
  });

  request.execute(function(response) {
    var str = JSON.stringify(response.result);
    $('#search-container').html('
' + str + '
');
  });
}

and the html

Search For an Artist:

       <input id="query" placeholder='+ Add Artist' type="text"/>
      <button id="search-button" disabled onclick="search()">Search</button>

A: You don't need to be connected or use Oauth2 to search something with the YouTube API.
You only need an api key.
A sample example :
function googleApiClientReady() {
    var apiKey = 'YOUR_API_KEY';

    gapi.client.setApiKey(apiKey);
    gapi.client.load('youtube', 'v3', function() {
        isLoad = true;
    });

    request = gapi.client.youtube.search.list({
        q: q,
        part: 'snippet'
     });
    request.execute(function(response) {
        //your code to here
    });
}

Don't forget to add this file to your index.html and add this following line after :

From doc YouTube API


text:
Q: Attach a div next to button in componentDidMount - React I want to attach a info icon div next to a button node when the page loads.
I am trying to do that in the componentDidMount but the button node is not available till that time.
I am trying a setTimeout but it depends on the data in the table sometimes it works using 3000ms but sometimes if the data is more it doesnt appear.
Is there any better/sure shot way of attaching the info node.
The button node is coming from a external lib I am using so I am not creating that node in the render/return method so cant add that time.
    componentDidMount() {

        window.setTimeout(() => {
            const actionSectionnode = document.querySelector('#main-content .action-section');
            const template = `

            </dnx-tooltip>`;
            if ($(actionSectionnode).length > 0) {
                actionSectionnode.insertAdjacentHTML('afterend', template);
            }
        }, 3000);
    }

One more thing - The button node is coming when I am using a query selector but doesnt appear when document.getElementsByClassName is used. As the queryselector is dangerous - what else can I use.

A: You shouldn't be using pure javascript, what you could do is Conditional Rendering
You should have a state that says if you should render the div
state = {
    ...
    isDivShowing = false;
}

In componentDidMount you set the state to true
componentDidMount(){
    ...
    this.setState({isDivShowing: true})
    ...
}

And in render, you check it before rendering
render() {
    return(
        ...
        {   // conditional rendering
            this.state.isDivShowing && (

...

            )
        }
    )
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding usage of not operator in :selected I just came across this FIDDLE online. The JS looks like below:
$(function() {
    $('#add').click(function() {
        return !$('#select1 option:selected').appendTo('#select2');
    });
    $('#remove').click(function() {
        return !$('#select2 option:selected').appendTo('#select1');
    });
});

HTML ::
<SELECT id="select1" name="select1" size="3"><OPTION value="1">Test 1</option><OPTION value="2">Test 2</option></select>
<SELECT id="select2" name="select2"></select>
<br><input type="button" id="add" value="Add >>"><input type="button" id="remove" value="<< Remove">

Its basically just a piece of JS interchanging a select values. But what I don't understand is the usage of the ! operator(not operator).
Now I understand that the not operator inverses the result, but in the above code what is it really doing? I am not understanding what the not operator is doing in the above fiddle and what impact it is having on the end result? Can anybody explain?

A: It's a fancy way of doing:
$('#add').click(function() {
        $('#select1 option:selected').appendTo('#select2');
         return false;
});

the return false prevents default behavior of the button by cancelling the event.
Since an object will always be truthy, !object will be false and $(selector) returns an object


text:
Q: How to use TargetField property of asp:menu control I have a table in sql server 2008 that has all the information about my option menus.
And i am using <asp:Menu> control to show option menus in my web site with data binding from that table.In that table i have a field called Target.Values in this field are

_blank , _parent , _search , _self , _top

this values describes how to open that form.This field is linked with Target property of <asp:menu> control.But it's not working.Can any one tell me how to use this property on data bind <asp:menu> control.

A: This problem is solved by changing the name of Target field in my data source.


text:
Q: Coordinate not taking effect upon compilation in Spring Cloud Pipelines I am following this tutorial and I am facing build failure in 'deploy to test' stage when this repo is compiled. The reason for failure is that sc-pipelines.yml defines eureka service with coordinate: scpipelines/github-eureka:latest, which is not getting compiled into the equivalent target\k8s\eureka.yml. The compiled yml is having image: : for container image. Could someone please help me on how to get this image value populated with scpipelines/github-eureka:latest ?
12:39:25 Logging in to Kubernetes API [kubernetes.default:443], with cluster name [gke_kubproject-210508_asia-south1-b_cluster-1] and user [default]
12:39:25 Cluster "gke_kubproject-210508_asia-south1-b_cluster-1" set.
12:39:25 User "default" set.

12:39:25 Context "gke_kubproject-210508_asia-south1-b_cluster-1" created.
12:39:25 Switched to context "gke_kubproject-210508_asia-south1-b_cluster-1".
12:39:25 CLI version
12:39:25 Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.2", GitCommit:"bb9ffb1654d4a729bb4cec18ff088eacc153c239", GitTreeState:"clean", BuildDate:"2018-08-07T23:17:28Z", GoVersion:"go1.10.3", Compiler:"gc", Platform:"linux/amd64"}
12:39:25 Server Version: version.Info{Major:"1", Minor:"9+", GitVersion:"v1.9.7-gke.5", GitCommit:"9b635efce81582e1da13b35a7aa539c0ccb32987", GitTreeState:"clean", BuildDate:"2018-08-02T23:42:40Z", GoVersion:"go1.9.3b4", Compiler:"gc", Platform:"linux/amd64"}
12:39:25 Pipeline descriptor already parsed - will not parse it again
12:39:25 Deleting all possible entries with name [rabbitmq-github-webhook]
12:39:26 Error from server (NotFound): secrets "rabbitmq-github-webhook" not found
12:39:26 Error from server (NotFound): persistentvolumeclaims "rabbitmq-github-webhook" not found
12:39:26 Error from server (NotFound): pods "rabbitmq-github-webhook" not found
12:39:26 Error from server (NotFound): deployments.extensions "rabbitmq-github-webhook" not found

12:39:26 service "rabbitmq-github-webhook" deleted
12:39:26 Will deploy service with type [rabbitmq] name [rabbitmq-github-webhook] and coordinates []
12:39:26 Waiting for RabbitMQ to start
12:39:26 replicationcontroller "rabbitmq-github-webhook" deleted
12:39:26 Error from server (NotFound): error when deleting "target/k8s/rabbitmq-service.yml": services "rabbitmq-github-webhook" not found
12:39:26 Failed to delete app by [target/k8s/rabbitmq-service.yml] file. Continuing with the script
12:39:27 replicationcontroller/rabbitmq-github-webhook replaced
12:39:27 service/rabbitmq-github-webhook replaced
12:39:27 Deleting all possible entries with name [mysql-github-webhook]

12:39:27 secret "mysql-github-webhook" deleted
12:39:27 Error from server (NotFound): persistentvolumeclaims "mysql-github-webhook" not found
12:39:27 pod "mysql-github-webhook" deleted

12:39:44 Error from server (NotFound): deployments.extensions "mysql-github-webhook" not found

12:39:44 service "mysql-github-webhook" deleted
12:39:44 Will deploy service with type [mysql] name [mysql-github-webhook] and coordinates []
12:39:44 Waiting for MySQL to start
12:39:44 Generating secret with name [mysql-github-webhook]
12:39:45 Error from server (NotFound): secrets "mysql-github-webhook" not found
12:39:45 Failed to delete secret [mysql-github-webhook]. Continuing with the script
12:39:45 secret/mysql-github-webhook created
12:39:45 Error from server (NotFound): error when deleting "target/k8s/mysql.yml": pods "mysql-github-webhook" not found
12:39:45 Failed to delete app by [target/k8s/mysql.yml] file. Continuing with the script
12:39:45 Error from server (NotFound): error when deleting "target/k8s/mysql-service.yml": services "mysql-github-webhook" not found
12:39:45 Failed to delete app by [target/k8s/mysql-service.yml] file. Continuing with the script

12:39:45 pod/mysql-github-webhook replaced
12:39:46 service/mysql-github-webhook replaced
12:39:46 Deleting all possible entries with name [eureka-github-webhook]
12:39:46 Error from server (NotFound): secrets "eureka-github-webhook" not found
12:39:46 Error from server (NotFound): persistentvolumeclaims "eureka-github-webhook" not found

12:39:46 Error from server (NotFound): pods "eureka-github-webhook" not found
12:39:47 Error from server (NotFound): deployments.extensions "eureka-github-webhook" not found
12:39:47 Error from server (NotFound): services "eureka-github-webhook" not found
12:39:47 Will deploy service with type [eureka] name [eureka-github-webhook] and coordinates []
12:39:47 Deploying Eureka. Options - image name [:], app name [eureka-github-webhook], env [TEST]
12:39:47 error: error parsing target/k8s/eureka.yml: error converting YAML to JSON: yaml: line 13: mapping values are not allowed in this context
12:39:47 Failed to delete app by [target/k8s/eureka.yml] file. Continuing with the script
12:39:47 Error from server (NotFound): error when deleting "target/k8s/eureka-service.yml": services "eureka-github-webhook" not found
12:39:47 Failed to delete app by [target/k8s/eureka-service.yml] file. Continuing with the script

12:39:47 error: error parsing target/k8s/eureka.yml: error converting YAML to JSON: yaml: line 13: mapping values are not allowed in this context
12:39:47 Build step 'Execute shell' marked build as failure
12:39:47 Archiving artifacts
12:39:48 Finished: FAILURE

sc-pipelines.yml
test:
  # list of required services
  services:
    - type: rabbitmq
      name: rabbitmq-github-webhook
    - type: mysql
      name: mysql-github-webhook
      database: example
    - type: eureka
      name: eureka-github-webhook
      coordinates: scpipelines/github-eureka:latest

eureka.yml - Please notice the empty value for image key.
1 apiVersion: extensions/v1beta1
 2 kind: Deployment
 3 metadata:
 4   name: eureka-github-webhook
 5 spec:
 6   replicas: 1 # tells deployment to run 2 pods matching the template
 7   template: # create pods using pod definition in this template
 8       metadata:
 9         labels:
10           name: eureka-github-webhook
11       spec:
12         containers:
13         - name: eureka-github-webhook
14           image: :
15           ports:
16           - containerPort: 8761
17           env:
18           - name: PORT
19             value: "8761"
20           - name: eureka_client_serviceUrl_defaultZone
21             value: "http://eureka-github-webhook.sc-pipelines-prod:8761/eureka/"
22           livenessProbe:

A: It was a bug https://github.com/spring-cloud/spring-cloud-pipelines/issues/187. Please try again using the latest commits from the master branch


text:
Q: Solving differential equation with vector magnitude. I am trying to solve a system of three coupled differential equations. I managed to simplify them using a matrix.
$$  \newcommand{\myMatrix}[1]{\bm{\mathit{#1}}} \frac{d\vec{x}}{dt}=\pmb{A}\left| \vec{x} \right|\vec{x}-\vec{d} $$
Where $\pmb{A}$ is a constant $3\times3$ matrix and $\vec{d}$ is a constant vector. I know there are ways to solve this if it weren't for the vector magnitude. Does anybody have any idea how to solve it with the vector magnitude?


text:
Q: Asymptotic expansion of the hypergeometric function Given a function of the form:
$$f(z)= \text{ }_2F_1\left(a,b ;c;\frac{1 - z}{2}\right)$$
is there a way to find to find the asymptotic form of this function in the limit $z \rightarrow 1$ ?

A: Almost by the definition.
Let $x=\frac{1-z}2$
$$\, _2F_1\left(a,b;c;\frac{1-z}{2}\right)=\, _2F_1\left(a,b;c;x\right)=1+\frac{a b }{c}x+\frac{a (a+1) b (b+1) }{2 c (c+1)}x^2+O\left(x^3\right)$$ Now, replace $x$.

A: We may use its integral representation ((16) here) which shows that:
$$
f(z) = \frac{\Gamma(c)}{\Gamma(b) \Gamma(c-b)} \int_0^1 \frac{t^{b-1} (1-t)^{c-b-1}}{(1-t\frac{1-z}{2})^a} dt
$$
As this is an integral with a positive integrand we may now interchange limit and integral sign, which yields:
$$
\lim_{z\rightarrow 1} f(z) = \frac{\Gamma(c)}{\Gamma(b) \Gamma(c-b)} \int_0^1 t^{b-1} (1-t)^{c-b-1} dt
$$
Continuing as suggested in the comments we find that the integral on the rhs is the Beta function which equals $\frac{\Gamma(b) \Gamma(c-b)}{\Gamma(c)}$ thus the result is one.


text:
Q: Rally java rest API - Cannot parse object reference I am trying to create defects using Rally REST API in java.
My code to insert the defect looks something like this:
    JsonObject newDefect = new JsonObject();

    newDefect.addProperty("Workspace", workspaceRef);
    newDefect.addProperty("Project", projectRef);

    newDefect.addProperty("Name", d.name);
    newDefect.addProperty("Description", d.description);
    newDefect.addProperty("Notes", d.notes);
    newDefect.addProperty("Owner", getUserReference(restApi, d.owner));

    System.out.println("Creating defect: " + d.qcid + " - " + d.name);
    CreateRequest createRequest = new CreateRequest("defect", newDefect);
    CreateResponse createResponse = restApi.create(createRequest);

getUserReference is implemented as follows:
private String getUserReference(RallyRestApi restApi, String name) throws Exception
{
    // Read User
    QueryRequest userRequest = new QueryRequest("User");
    userRequest.setFetch(new Fetch("UserName", "Subscription", "DisplayName"));
    userRequest.setQueryFilter(new QueryFilter("UserName", "=", name));
    QueryResponse userQueryResponse = restApi.query(userRequest);
    JsonArray userQueryResults = userQueryResponse.getResults();
    JsonElement userQueryElement = userQueryResults.get(0);
    JsonObject userQueryObject = userQueryElement.getAsJsonObject();
    String userRef = userQueryObject.get("_ref").toString();
    return userRef;
}

The problem: I get error 'Cannot parse object reference' on the user. I get it when I use the actual name (user@domain.com) or the user reference as depicted above.
the current error i get is: Cannot parse object reference from ""https://rally1.rallydev.com/slm/webservice/v2.0/user/14659049875""
what am i doing wrong?
thanks
Asaf

A: Please use getAsString methods instead of toString.
Try:
String userRef = userQueryObject.get("_ref").getAsString();

instead of
String userRef = userQueryObject.get("_ref").toString();

A: faced similar problem,
setting older version of WSAPI helped me as a workaround
restApi = new RallyRestApi(new URI(rallyUrl), rallyUser, rallyPassword);
restApi.setWsapiVersion("1.36");


text:
Q: How to move a subdirectory from a branch in one git repository to a branch in a different repository, preserving history? I've got a directory containing utility libraries that were developed in a branch in one git repository, but it turns out they really belong in a different directory in a different project. I've read through and attempted Greg Bayer's Moving Files from one Git Repository to Another, Preserving History multiple times, but I'm unable to preserve history. I'm attempting to do this all under non-master branches to be more safe as the project is not ready to merge back to master yet anyway.
Here's what I'm doing so far:
Preparing the "DirectoryName" directory to be moved from branch "SomeBranch" of "Repo1" repository:
cd ~/Desktop
git clone git@github.com:username/Repo1.git
cd Repo1
git checkout -b SomeBranch origin/SomeBranch
git remote rm origin
git filter-branch --subdirectory-filter DirectoryName
mkdir DirectoryName
git mv *.php *.txt DirectoryName
git add DirectoryName
git commit -m "Stripped everything down to just DirectoryName."

Merging the "DirectoryName" directory into the "SomeBranch" branch of the "Repo2" repository:
cd ~/Desktop
git clone git@github.com:username/Repo2.git
cd Repo2
git checkout -b SomeBranch origin/SomeBranch
git remote rm origin
git remote add Repo1 ../Repo1/
git pull Repo1 SomeBranch
git remote rm Repo1

When I do this I can successfully strip everything down to "DirectoryName" in Repo1 (and I can pull it over to Repo2 as well), but the history is lost. If I do a git log -- DirectoryName or git log -- DirectoryName/SomeFile.php, I only see the "Stripped everything down to just DirectoryName." commit). So, clearly something is wrong with my git filter-branch command, but I'm not familiar enough with it to figure out what.
Any suggestions would be greatly appreciated as we're undergoing some fundamental changes to our codebase, so I'll need to be doing this relatively frequently for a while as stuff moves around (but we want to preserve the history).
Update: As I mentioned git log -- DirectoryName (or git log -- DirectoryName/SomeFile.php; either in Repo1 or Repo2) does not show any commits other that the "Stripped everything down to just DirectoryName." commit, but if I do git log I see the correct commit history. Am I just using git log incorrectly or is there some corruption that's causing the commits to not show up correctly?
Another Update: git log -- DirectoryName does show the correct commits in my original, unmodified Repo1, but it does not show the correct commits after the git filter-branch (and I've tried git filter-branch --subdirectory-filter DirectoryName -- --all but that mucks with the "master" branch as well and doesn't appear to be necessary... same result). That said, the commit history is there after running git filter-branch, I can see it all with git log master.. it just no longer seems to pertain to the directory or the files. Any ideas?

A: It sounds as if what you've done is fine, it's just a misunderstanding about git log that's causing problems.
git just stores the state of the tree at each commit, rather than recording the changes that took the tree from the state in one commit to the next.  If you're using git log to find the history of a particular file or directory, however, you can tell it to try to look for renames when the history of the file appears to run out.  You can do that with:
git log --follow -- DirectoryName

Or if that doesn't work, try it for just a single file, e.g.
git log --follow -- DirectoryName/whatever.txt

A: Here's how I'd do it:

*

*Create patches for all the commits that touch the files in the subdir:
$ c=1; git log --format=%h -- subdir/*|tac|while read commit; do
git format-patch --stdout -1 $commit > $(printf '%04d' $c).patch
c=$((c+1))
done

Note that if there are single commits that touches both files in the subdir and outside of subdir then the patch will also include the diff on the other file so you'll have to prune those hunks, or do a filter branch to remove those files once you done step two below:

*Use git am to apply the patches on the branch in the other repo:
$ git am *.patch


text:
Q: How to Continously Refresh a timer to Check a Background object value & Perform some Action depending on object state I Need a Continously Refreshing timer to Check a Background object value (after say every 10 seconds) & Perform some Action depending on object state in a C# Winforms application.
I'm a little confused between using System.Timers.Timer and System.Threading.Timer.
Also , I would appreciate if there is any other better solution available.
The first problem that I am facing is that I cant create the timer in the Initialize function block - it throws a run-time object reference exception.
So , i had to move it to the part where the LoadData() is being carried out.
(See Below).
So far , here is what I am Doing  :
//This function gets called only at initialize time
void Initialize()
{
//Initializing Commands , Context ,  base. ()_stuff etc goes here
}

//This function is called both when page is initialized first time
// as well as whenever Refresh button on the page is hit to reload the data
private void LoadData()
   {

    //Data Load Stuff Here

// My Timer goes Here

_poller = new System.Threading.Timer(o => RefreshStatus(), null, 10000, 10000);

       }  //End LoadData()

I have 4 questions that I would like answered :-
1) Which timer should i be using ?
(System.Timers.Timer OR System.Threading.Timer OR System.Windows.Forms.Timer OR Any Other).
2) Why am I not able to justify the same code in the Initialize() part that I am able to use in the LoadData() part?
Just FYI , I am using a loose interpretation of the MVP pattern
3) Since I am creating a new Instance of the Timer every time the page is loaded or reloaded or refreshed , do I need to worry about GC , by calling the dispose or deleting the previous instance of the timer or setting it to null ?
FYI, The _poller is a Class/Form level object.
I don't want a scenario where multiple timers start running in the same Form/page.
4) Wherever I have read about the Timer Best Practice usage , they have all advocated using an Infinite Timeout in the beginning and later updating it to a user desired value.
What is the specific advantage of this ?
Also , once I am done loading the data , I don't have a fixed place from where I can set the timeout. What should I do in such a case ?


text:
Q: Not able to register a tap on the screen using tapGestureRecognizer I am trying to build a chat app using Firebase. I am trying to implement a tap gesture in order to dismiss the keyboard when it's on. Unfortunately, nothing happen when you tap on the screen. I tried different things, same result. I will appreciate it if someone knows the reason why it's not working. I tried with the parameter numberOfTouches as well, same result.
class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
    // Declare instance variables here

    // We've pre-linked the IBOutlets
    @IBOutlet var heightConstraint: NSLayoutConstraint!
    @IBOutlet var sendButton: UIButton!
    @IBOutlet var messageTextfield: UITextField!
    @IBOutlet var messageTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        messageTableView.delegate = self
        messageTableView.dataSource = self

        //TODO: Set yourself as the delegate of the text field here:
        messageTextfield.delegate = self

        //TODO: Set the tapGesture here:
        //messageTableView.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewTapped))
        messageTableView.addGestureRecognizer(tapGesture)

        //TODO: Register your MessageCell.xib file here:
        messageTableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "customMessageCell")
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell

        let messageArray = ["1","2","3"]
        cell.messageBody.text = messageArray[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.estimatedRowHeight = 100.0
        tableView.rowHeight = UITableViewAutomaticDimension
        return 3
    }

    @objc func tableViewTapped (){
        messageTableView.endEditing(true)
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        UIView.animate(withDuration: 0.5) {
            self.heightConstraint.constant = 380
            self.view.layoutIfNeeded()
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        UIView.animate(withDuration: 0.5) {
        self.heightConstraint.constant = 50
        self.view.layoutIfNeeded()
    }
}

A: Try to set endEditing of the whole view true by updating your selector method:
@objc func tableViewTapped (){
    view.endEditing(true)
}

Also you might want to add the gestureRecognizer to view itself instead of tableView, because it might cause further problems by overlapping with didSelectRowAt method.
If that doesnt work try to add following in your viewDidLoad (In this case you wont need a gestureRecognizer):
messageTableView.keyboardDismissMode = .interactive


text:
Q: 400 Bad request when posting json array to spring controller on azure I am getting 400 bad request when I am trying to pass a json array to spring controller on azure app service. However I am not getting any error when I try to run the service from my local environment. My request is as follows,
$http.post(appPath + '/app/temp/saveTempData?tempData=' + JSON.stringify(row.data)).success(function(result) {

            if (result.result) {

                toaster.pop("successful", "Updated successfully");
            } else {
                toaster.pop("warning", "Something went wrong please try again later.");
            }
        })

Where row.data is an json array.On the spring controller I have the following,
@RequestMapping(value = "/saveTempData", method = RequestMethod.POST)
@ResponseBody
public String saveTempData(@RequestParam JSONArray tempData) {

}

This code is working in my local machine, but on the azure app service it gives me 400 bad request. Thank you.

A: We have to encode the request parameter when sending json array to the app service controller using encodeURIComponent like follows,
$http.post(appPath + '/app/temp/saveTempData?tempData=' + encodeURIComponent(JSON.stringify(row.data))).success(function(result) {

            if (result.result) {

                toaster.pop("successful", "Updated successfully");
            } else {
                toaster.pop("warning", "Something went wrong please try again later.");
            }
        })


text:
Q: Compiling tar files without configure or readme files How to open and compile tar files that doesn't contain a configure or readme file such as
http://git.infradead.org/users/dwmw2/openconnect.git/snapshot/292eb3e0176f9259594902d619981a1131c0f17c.tar.gz ?

A: In this particular case, the software does use the GNU Autoconf build system that results in the ./configure, make, make install recipe - but starts one step back by providing a configure.ac Autoconf input file rather than a ready-made configure script.
In general, configure is made from configure.ac using the autoconf program, sometimes using autoreconf to run additional configuration tools. In this case, that should be done by executing the provided autogen.sh script, so the recipe becomes
./autogen.sh
./configure
make

(and possibly)
sudo make install

For additional information about the Autotools build system, see A brief introduction to the GNU Autotools


text:
Q: IOS App Build issue: Command CodeSign failed with a nonzero exit code I am trying to build my IOS app (developed using capacitor and ionic frameworks).
Just after integrating Google Firebase and adding Resources/GoogleService-Info.plist file I am having followng error while building my app in XCode.
Command CodeSign failed with a nonzero exit code
CodeSign /Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Products/Debug-iphonesimulator/App.app (in target 'App' from project 'App')
    cd /Users/piyush/Downloads/ncsmobileapp/ios/App
    export CODESIGN_ALLOCATE\=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate

    Signing Identity:     "-"

    /usr/bin/codesign --force --sign - --entitlements /Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Intermediates.noindex/App.build/Debug-iphonesimulator/App.build/App.app.xcent --timestamp\=none --generate-entitlement-der /Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Products/Debug-iphonesimulator/App.app

/Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Products/Debug-iphonesimulator/App.app: code object is not signed at all
In subcomponent: /Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Products/Debug-iphonesimulator/App.app/AppIcon60x60@2x.png
Command CodeSign failed with a nonzero exit code

I tried cleaning the build cahce, restarting the xcode.
re-building the app through capacitor, but nothig solved this issue yet.
Can anyone help in solving this issue?
Update
While archiving the app following error occurs:
CodeSign /Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Intermediates.noindex/ArchiveIntermediates/App/InstallationBuildProductsLocation/Applications/App.app (in target 'App' from project 'App')
    cd /Users/piyush/Downloads/ncsmobileapp/ios/App
    export CODESIGN_ALLOCATE\=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate

    Signing Identity:     "Apple Development: Piyush Aggarwal (ZWHGYV6A62)"
    Provisioning Profile: "iOS Team Provisioning Profile: app.neo.school"
                          (d2353688-03d7-47ff-942f-4f34fd4c6a93)

    /usr/bin/codesign --force --sign 5FE6CDFE4B615D56B70C5DAEB7A151005A1122AE --entitlements /Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Intermediates.noindex/ArchiveIntermediates/App/IntermediateBuildFilesPath/App.build/Release-iphoneos/App.build/App.app.xcent --generate-entitlement-der /Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Intermediates.noindex/ArchiveIntermediates/App/InstallationBuildProductsLocation/Applications/App.app

/Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Intermediates.noindex/ArchiveIntermediates/App/InstallationBuildProductsLocation/Applications/App.app: code object is not signed at all
In subcomponent: /Users/piyush/Library/Developer/Xcode/DerivedData/App-cfgpruswvcmgvpcxuzeyccwfgdyx/Build/Intermediates.noindex/ArchiveIntermediates/App/InstallationBuildProductsLocation/Applications/App.app/AppIcon60x60@2x.png
Command CodeSign failed with a nonzero exit code

A: Please try to delete the derived data and clean the build.
Steps to delete derived data:-
1.Open your project,Go to files -> Workspace Settings
Then you will find a derived data location with an arrow:-
Just click on that arrow,after that you will find a folder named derived data,
delete all the files inside derived data folder.
Then it will working fine.

A: The issue was due to resources folder.
I created that folder to add my GoogleServices-Info.plist file.
I renamed my resources folder and changaed the path to my GoogleServices-Info.pllist file by following code in build phrases of the app in xcode:
PATH_TO_GOOGLE_PLISTS="${PROJECT_DIR}/App/[FOLDER NAME]"

        cp -r "$PATH_TO_GOOGLE_PLISTS/GoogleService-Info.plist" "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/GoogleService-Info.plist" ;

A: I have the same (random) issue when Archiving project where OneSignal (specifically OneSignalNotificationServiceExtension) framework is included. What I have to do to make it work (w00t) is to change KeyChain Trust setting on Apple Worldwide Developer Relations Certification Authority (Expires: Tuesday, 7 February 2023 at 22:48:47 Central European ) certificate back to Use System Defaults and then again back to Always Trust. I have no idea why this works, but it works.


text:
Q: Ruby On Rails Excel Import Issue Hello I am working on ruby on rails platform. I am doing excel import with Roo package with following code
def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
      when '.xls' then
        Roo::Excel.new(file.path, nil, :ignore)
      when '.xlsx' then
        Roo::Excelx.new(file.path, nil, :ignore)
      else
        raise "Unknown file type: #{file.original_filename}"
    end
  end

The code is working fine on production until I did bundle update command on production and after this I get error for importing Excel with above code is
Wrong number of arguments ( 3 for 1..2) for Roo::Excelx.new(file.path, nil, :ignore) please suggest how the working code gets such a error.

A: Try This
 Roo::Excelx.new(file.path,options={})


text:
Q: How to find distribution of kth highest of n iid's? For example, suppose there are five people whose heights are independent and exponentially distributed with mean 5.5 feet.
I want to be able to solve problems like
1) Find the expected height of the second tallest guy.
2) Find the probability that the third tallest guy is more than twice as tall as the shortest guy.
I think I should be able to find the solutions to problems like these if I know how to find the height distributions of each of the people.

A: Let's note $\mathbf{X}_{î:n}$ the random variable of the $i^{th}$ smallest measure out of a sample having a total of $n$ measures. As an example, the smallest person is noted $\mathbf{X}_{1:n}$ and the tallest is noted $\mathbf{X}_{n:n}$.
We need the distribution of the measures (you said exponential in the problem, but the following can be for any distribution). Let's note $F_{\mathbf{X}}(x)$ the probability that a measure  is x or smaller ($P(\mathbf{X} \le x$). Then what is needed is $F_{\mathbf{X}_{i:n}}(x)$.
The problem of the density of $i^{th}$ smallest can be conceived as the distribution of a sample in which $i-1$ observations are smaller than $x$, $n-1$ observations are larger than $x$, and finally, one observation is precisely $x$. Thus, the density if based on $F_{\mathbf{X}}$ raised to the power of $i-1$, based on $1-F_{\mathbf{X}}$ raised to the power of $n-i$, and finally, based on $f_{\mathbf{X}}$. The only difficulty is that we don't know which observations in the sample will be smaller than x, which will be larger, and which one will be equal. So we need to consider all the possible arrangements of the dataset, which is achieved by weighting the result with $$\frac{n!}{(i-1)!(n-k)!}.$$ Hence, the distribution is
$$
F_{\mathbf{X}_{i:n}}(x) = \frac{n!}{(i-1)!(n-k)!} \left(F_{\mathbf{X}}(x) \right)^{i-1} \times
\left(1-F_{\mathbf{X}}(x) \right)^{n-i}
\times
f_{\mathbf{X}}(x).
$$
Once you have the distribution, you can integrate this to get the density, and find expected value as usual with
$$
\int_A x f_{\mathbf{X}_{i:n}}(x) \, \mathbf{d}x
$$
where $A$ is the domain of the random variable $\mathbf{X}$.

A: Hint: condition on height of the shortest, and use the "lack of memory" property of the exponential distribution.


text:
Q: Google Sheets: json into columns I'm completely new to this and would appreciate your help.
I am trying to import GraphQL prices into Google Sheets and display the information in columns.
So far, I have this:
function graphData(query,url){
  var options = {"headers": {"Content-Type": "application/json"
                            },
                 "payload": JSON.stringify({query}),
                 "method": "POST"
                };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
  return response;
};

function Prices () {
  var ss = SpreadsheetApp.openById('1uEpj8gWdHJCVXN2fTgGBCzoi5ZOnkIq0leoGWDB1s-g');
  var sheet = ss.getSheetByName('Test');
  //sheet.appendRow(["a man", "a plan", "panama"]);
  var url = 'https://api.thegraph.com/subgraphs/name/openpredict/chainlink-prices-subgraph' ;

  var query = 'query{prices(first:2 where:{assetPair_in:["USDC/ETH","DAI/ETH "]} orderBy:timestamp orderDirection:desc) {assetPair{id}timestamp price}}';
  var a=graphData(query,url);
  var code= a.getContent();
  var json = a.getContentText(); // get the response content as text

  var mae = JSON.parse(json); //parse text into json

Variable mae contains the following:

I am stuck at this point, not succeeding to properly access and display assetPair, timestamp and price in columnns.
I have tried this, which is not quite right:
  var data;

    for (i = 0; i < mae.length; i++) {
      data = mae["data"]["prices"][i];
      var rows = [];
      for (j in data) rows.push(data[j]);
      sheet.appendRow(rows);
    }

Any help would be most welcome!

A: The following script works for me:
function graphData(query,url){
  var options = {"headers": {"Content-Type": "application/json"
                            },
                 "payload": JSON.stringify({query}),
                 "method": "POST"
                };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
  return response;
};

async function Prices () {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1');
  //sheet.appendRow(["a man", "a plan", "panama"]);
  var url = 'https://api.thegraph.com/subgraphs/name/openpredict/chainlink-prices-subgraph';

  var query = 'query{prices(first:2 where:{assetPair_in:["USDC/ETH","DAI/ETH "]} orderBy:timestamp orderDirection:desc) {assetPair{id}timestamp price}}';
  var a = graphData(query,url);
  var code= a.getContent();
  var json = a.getContentText(); // get the response content as text

  var mae = JSON.parse(json);

  var data;
  for (i = 0; i < mae.data.prices.length; i++) {
    data = mae.data.prices[i];
    var rows = [];
    for (j in data) rows.push(data[j]);
    sheet.appendRow(rows);
  }
}

You had
 data = mae["data"]["prices"][i];

I changed this to
data = mae.data.prices[i];

I also changed
for (i = 0; i < mae.length; i++) {

to
for (i = 0; i < mae.data.prices.length; i++) {

If you would like to get just the ID in the first column, you could change the FOR loop to include this:
  var data;
  for (i = 0; i < mae.data.prices.length; i++) {
    data = mae.data.prices[i];
    var rows = [];

    for (j in data) {
      if(j == 'assetPair') rows.push(data[j].id)
      else rows.push(data[j])
    };
    sheet.appendRow(rows);
  }

A: Function for you
function graphData(query,url){
  var options = {"headers": {"Content-Type": "application/json"
                            },
                 "payload": JSON.stringify({query}),
                 "method": "POST"
                };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
  return response;
};

function Prices () {
  var ss = SpreadsheetApp.openById('1uEpj8gWdHJCVXN2fTgGBCzoi5ZOnkIq0leoGWDB1s-g');
  var sheet = ss.getSheetByName('Test');
  sheet.appendRow(["a man", "a plan", "panama"]);
  var url = 'https://api.thegraph.com/subgraphs/name/openpredict/chainlink-prices-subgraph' ;

  var query = 'query{prices(first:2 where:{assetPair_in:["USDC/ETH","DAI/ETH "]} orderBy:timestamp orderDirection:desc) {assetPair{id}timestamp price}}';
  var a=graphData(query,url);
  var code= a.getContent();
  var json = a.getContentText(); // get the response content as text

  var mae = JSON.parse(json); //parse text into json

  var rows = [],dat,lastR=sheet.getLastRow()+1;
  mae.data.prices.forEach(x => {rows[rows.length]=[x.assetPair.id,x.timestamp,x.price];});
  sheet.getRange('A'+lastR+':C'+(lastR+rows.length-1)).setValues(rows);
  }


text:
Q: Как обнаруживать заданное место/область на камеру/видео? С очевидными объектами(котики, собачки) всё понятно, но как обнаруживать ни чем не выделяющиеся объекты?
Как обнаружить в режиме реального времени заданное место на камеру, например в комнате с белыми стенами?


text:
Q: Scroll to top and refresh page at same time ok, I have a code which smooth scrolls to the top of the page, but I also need it to reload (refresh) the page as well. Here is the code I have to scroll but I don't know how to implement the reload into it. Any thoughts most welcome.
var x = document.getElementById('title1');

function myFunction() {
   if (x.style.display === 'block') {
       x.style.display = 'block';
   } else {
       x.style.display = 'block';
   }
   $("html, body").animate({ scrollTop: 0 }, "slow");
}

A: Yeah, here is a simple solution. Jquery animate method provides us a callback method which run after animation finished, so you can try
var x = document.getElementById('title1');
function myFunction() {
   if (x.style.display === 'block') {
       x.style.display = 'block';
   } else {
       x.style.display = 'block';
   }
   $("html, body").animate({ scrollTop: 0 }, "slow", function(){
      window.location.reload()
   });
}

A: You can detect if scroll reaches top of page and refresh it by:
$(window).scroll(function(){
   if($(window).scrollTop() == 0){
      console.log('top');
      window.location.reload(false);
   }
});

$(window).scroll(function(){
       if($(window).scrollTop() == 0){
detect if window scroll reach top of page.
Refresh page: window.location.reload(false);
Update:
To prevent detecting from manually scrolled you could add a flag whether it was manually scrolled or by animation: var animate= false; then you could update when animate was triggered: animate=true;
See snippet:

var x = document.getElementById('title1');
var animate= false;

function myFunction() {
   if (x.style.display === 'block') {
       x.style.display = 'block';
   } else {
       x.style.display = 'block';
   }
   $("html, body").animate({ scrollTop: 0 }, "slow");
   animate=true;
}

$(window).scroll(function(){
   if($(window).scrollTop() == 0 && animate==true){
      console.log('top');
      window.location.reload(false);
   }
});
body{
height:1000px;
}
#title1{
position:relative;
top:900px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<button id="title1" onclick="myFunction()">test</button>
</body>

A: you can reload using reload function in the Location class
location.reload();

A: Be careful of the location.reload function as it will re-post the previous request if there is one. Browsers also try to be friendly and reload the page at the same scroll position, so you would have to scroll to the top, then reload.
A better bet is to use the location.search function. That will also give you the opportunity to pass extra parameters in the querystring to instruct the page to scroll to wherever you want.
Here's a handy js function you might find useful
/**
 * reloads a document without triggering the previous POST
 * @param {obj} document
 * @param {string} queryString optional overwrite of current qs
 */
function documentReload(document, queryString){
var loc = document.location;
//passing a queryString to container
if (queryString) {
    loc.search = queryString; //will cause it to reload
    return;
}
//refresh page
//loc.reload(true); - can cause the POST data warning
loc.href = loc.protocol +'//'+ loc.host + loc.pathname + loc.search;
}


text:
Q: Not inherit some (chosen) methods from derived classes Say that, for example, I have two (python (3.3)) classes a and b with their own methods:
class a:
    def m1(self):
        print("Hi 1")
    def m2(self):
        print("Hi 2")
        ##...other methods...
class b(a):
    def k1(self):
        print("Other hi")

How do I make it so that class b inherits all methods from a except (for example) m2? (besides copy/paste, that doesn't count.) So the expression a.m2() would be legitimate, but b.m2() would throw an AttributeError.

A: Why would you want to do that? The whole point of class inheritance is to be able to test that instances of b are also instances of a; isinstance(b(), a) is True for a reason. By removing methods from b you are breaking that model badly.
Instead make a have fewer methods, and add c to have those that b doesn't need:
class a:
    def m1(self):
        print("Hi 1")
        ##...other methods...

class b(a):
    def k1(self):
        print("Other hi")

class c(a):
    def m2(self):
        print("Hi 2")

Or, you could not inherit from a and just copy methods from a as needed:
class b:
    # copied methods
    m1 = a.m1

    def k1(self):
        print("Other hi")

Now b isa a is no longer true, the expectation that all of a's methods are implemented won't be there anymore.
If a is entirely out of your control and there are too many methods to copy, perhaps use proxying with __getattr__ and passing through anything but m2. A last ditch method could be to implement m2 and raise AttributeError, but that should be a last resort only.

A: You can get the effect that you want by making 'a' and 'b' siblings rather than parent and child. This might work for you:
class p:
    def m1(self):
        print("Hi 1")

class a(p):
    def m2(self):
        print("Hi 2")

class b(a):
    def k1(self):
        print("Other hi")

So these methods are now all valid, the others will throw AttributeErrors:
a.m1()
a.m2()
b.m1()
b.k1()

A: If b inherits from a, it's supposed to inherit every method. That's inheritance about. But if it's necessary to do this (note that is not recommended) you could override the m2() method, so it raises an Exception when called.
class b(a):
    def m2(self):
        raise Exception("...")

A: That does not really make sense. The point of inheritance is so that the inheriting object is exactly compatible to the base type. This is the Liskov substitution principle: Wherever an object of the original type is acceptable, an object of the derived type also will be.
If you change your derived type to not have some members of the base type, then you are violating this principle. With the dynamic typing in Python, it wouldn't be that much of a problem but it's still violating the idea behind it.
So you really just shouldn't do that.


text:
Q: How to detect Bluetooth adapter with Electron? Is it possible to detect in Electron, if PC (Mac or Linux) has Bluetooth adapter connected? I'm using "bluetooth-serial-port" library for Bluetooth communication. If BT adapter is not connected to PC the application keeps reloading.
This is how the app is trying to find devices.
var btSerial = new (require('bluetooth-serial-port')).BluetoothSerialPort();

try {
    btSerial.inquire();
}
catch (e) {
    callback(new Error('something bad happened ' + e));
}
btSerial.on('failure', function(error){console.log(error);});

A: According to this issue on GitHub the bluetooth-serial-port will crash when the computer doesn't have any bluetooth device installed.
As far as I know, Electron doesn't have any API for bluetooth. Depending on your use case, you can use web bluetooth to use bluetooth (or just check if the computer has bluetooth). Check out electron-web-bluetooth on GitHub to see a working example.

A: You can use inquireSync() to avoid a crash
try {
    btSerial.inquireSync();
}
catch (e){
    callback(new Error('something bad happened ' + e));
}


text:
Q: How do I disconnect a user in Voximplant from logged_in status? The client state is logged_in. How can I disconnect a user state from voximplant side because I want to login again loginwithpassword() function

A: You can use client.disconnect() method
https://voximplant.com/docs/references/reactnative/voximplant/client#disconnect


text:
Q: C# Simple Web Server Image Read-In So I'm back with another question about my web server. I've added several new features to it since my last question, but now I've ran into another problem.
I'm trying to allow the server to serve out an image that is called through HTML. However, the image isn't displaying on the webpage for some reason. I've stepped through the code and it does seem to be sending through the file, but it's just not displaying on the other end. Here is my code:
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;

namespace miniWebServer_csc360
{
    public partial class Form1 : Form
    {
        public static int requestCount = 0;
        public static Boolean singleUse = true;

        public static HttpListener listener = new HttpListener();

        //public static HttpListenerContext context;
        //public static HttpListenerResponse response;

        static Form1 thisform;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            thisform = this;
        }

        private void start_button_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(serverThread);
            t.Start();
        }

        public static void serverThread()
        {
            if (singleUse)
            {
                listener.Prefixes.Add("http://10.211.55.4:69/");
                listener.Prefixes.Add("http://localhost:69/");

                singleUse = false;
            }

            if (listener.IsListening)
                listener.Stop();

            else
                listener.Start();

            if (listener.IsListening)
            {
                thisform.Invoke((MethodInvoker)delegate { thisform.status_label.Text
                   = "Listening..."; });
                thisform.Invoke((MethodInvoker)delegate { thisform.start_button.Text
                   = "Stop Server"; });
            }

            else
            {
                thisform.Invoke((MethodInvoker)delegate { thisform.status_label.Text
                   = "Not listening..."; });
                thisform.Invoke((MethodInvoker)delegate { thisform.start_button.Text
                   = "Start Server"; });
            }

            while (listener.IsListening)
            {
                try
                {
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerResponse response = context.Response;

                    requestCount++;

                    thisform.Invoke((MethodInvoker)delegate { thisform.counter.Text
                       = requestCount.ToString(); });

                    string page = Directory.GetCurrentDirectory()
                        + context.Request.Url.LocalPath;

                    if (context.Request.Url.LocalPath != "/HEAD.html"
                         && context.Request.Url.LocalPath != "/favicon.ico")
                    {
                        if (context.Request.Url.LocalPath == "/")
                        {
                            string path = context.Request.Url.LocalPath + "index.html";
                                 thisform.Invoke((MethodInvoker)delegate
                            {
                                thisform.request_Box.AppendText(path + "\r\n");
                            });
                        }

                        else
                        {
                            thisform.Invoke((MethodInvoker)delegate
                            {
                                thisform.request_Box.AppendText
                                  (context.Request.Url.LocalPath + "\r\n");
                            });
                        }
                    }

                    if (context.Request.Url.LocalPath == "/")
                        page += "index.html";

                    TextReader tr = new StreamReader(page);
                    string msg = tr.ReadToEnd();

                    byte[] buffer = Encoding.UTF8.GetBytes(msg);

                    if (context.Request.Url.LocalPath == "/header.html")
                    {
                        File.WriteAllText(Directory.GetCurrentDirectory() + "/HEAD.html",
                            context.Request.HttpMethod + " " +
                            context.Request.RawUrl + " HTTP/"
                            + context.Request.ProtocolVersion + "\n"
                            + context.Request.Headers.ToString());
                    }

                    response.ContentLength64 = buffer.Length;
                    Stream st = response.OutputStream;
                    st.Write(buffer, 0, buffer.Length);

                    context.Response.Close();
                }
                catch (Exception error)
                {

                }
            }
        }
    }
}

Thanks in advance!

A: You have to set HttpListenerResponse.ContentType to the appropriate MIME type for the image, such as "image/gif".
In addition, the example code is reading the image through a TextReader and converting it to a UTF8 byte array.  That's not going to work for binary files; it'll mangle the bytes.  You need to read those files with a FileStream or any other approach that will return the binary file contents unmodified.


text:
Q: SAS - Excel Import DateTime not retaining enough significant digits As the title states, I'm having issues importing datetimes from Excel to SAS. The issue seems to be with seconds:
here's sample data from excel:
My DateTime:

Here's the raw excel numbers:

Edit2:
43417.58657407
43417.58656250

When I'm import these into SAS, this is how SAS is displaying them:
13NOV2018:14:04:39
13NOV2018:14:04:39

and the numeric values:
1857737079
1857737079

I'm trying to figure out how to get SAS to read the seconds correctly. I'm using proc import and here's my code:
proc import
out = MyDSOutput
datafile= MyDSInput
dbms     = EXCEL replace;
sheet    = "page";
getnames = yes;
mixed    = yes;
scantext = yes;
usedate  = no;
scantime = yes;
textsize = 32767;
;
run;

EDIT: I should have added that converting this to a CSV really isn't an option because I have numeric IDs that are  >15 digits and excel will convert anything >15 digits to 0s.
EDIT2: Added an expanded version of the raw excel numbers

A: Excel stores time as a fraction of a day.  It is impossible to represent a specific number of seconds exactly when you do that.  That particular time, 14:04:40 (second number 50,680), is particularly hard to represent as a floating point fraction. If you represent it as 0.58657407  and multiple by the number of seconds in a day you get seconds of 50,679.999648, so slightly less that what you want.
Try splitting your DATETIME field into separate DATE and TIME fields. That way SAS will have more binary digits to represent just the time of day (since it doesn't also have to have the 40K or 20K seconds for the day of the year).  Perhaps that will get close?  Or store the value as a character string in Excel and then use INPUT() function in SAS to convert the string to a datetime value.
For your ID issue, do not store ID values as numbers, in any system if you can avoid it. If you can store the ID in your EXCEL file then EXCEL can write it the the CSV file. But when you read the CSV file make sure to read that column into a character variable and not a numeric one.


text:
Q: Getting dynamically created ion-input value in IONIC2 I  have  the  following  HTML  part  in  which ion-item  is  created  dynamically based  on *ngFor
<ion-list *ngIf="Label_view">

  <ion-item style="Float:Right;margin-left: 4%;" *ngFor="let bil of arr_label;let i=index ">
    <ion-label floating>{{bil}}</ion-label>
    <ion-input [(ngModel)]="array" id={{i}}  type="text"  maxlength="5"></ion-input>
  </ion-item>

Register

I  have  to  get values  of ion-input  into  component .I  have  used [(ngModel)] value  to  bind  to  array.
My  component side
array:any[]=[];

Blr_regis()
{
    console.log( array);
  //  console.log(document.getElementById("1").Value);
    var x=document.getElementById("1").Value;
   console.log(x);
}

I'm getting  UNDEFINED as  console  Output.
Is  there something  am  missing?

A: The issue is because you're trying to bind an Array with the input element. It should be bound to a string or a number (or a single position of the array).
Instead of doing something like this:
  <ion-item style="Float:Right;margin-left: 4%;" *ngFor="let bil of arr_label;let i=index ">
    <ion-label floating>{{bil}}</ion-label>
    <ion-input [(ngModel)]="array" id={{i}}  type="text"  maxlength="5"></ion-input>
  </ion-item>

And having those two let in the *ngFor, why don't you put everything together in the same array like this:
this.newArray : Array<{id: number, value: string}> = [];

// Assuming the `arr_label` exists and it has been properly initialized
for(let i=0; i < arr_label.length; i++) {
    this.newArray.push({ id: i, value: arr_label[i] });
}

And then in your view:
  // We only iterate over the newArray because all the information we need is there
  <ion-item style="Float:Right;margin-left: 4%;" *ngFor="let bill of newArray">

    <ion-label floating>{{bill.value}}</ion-label>
    <ion-input [(ngModel)]="array[bill.id]" type="text" maxlength="5"></ion-input>

  </ion-item>

Notice we're now binding the input to a single position of the array, using the id (which would be 0, 1, and so on).
You can find a working plunker here. Take a look at the code in Page1.ts and Page1.html


text:
Q: Most efficient way to place hundreds of array formulas? I am new to VBA and advanced formulas for that matter and would deeply appreciate some guidance here.
I have a workbook that acts as a GUI for a database in another workbook. I use the following array formula to act as a search function:
{=IF(ISERROR(INDEX('Client Contact Database.xlsx'!Data.ContactsFull,SMALL(IF('Client Contact Database.xlsx'!Data.ContactClients=$L$1,ROW('Client Contact Database.xlsx'!Data.ContactClients)),ROW(1:1)),2)),"",INDEX('Client Contact Database.xlsx'!Data.ContactsFull,SMALL(IF('Client Contact Database.xlsx'!Data.ContactClients=$L$1,ROW('Client Contact Database.xlsx'!Data.ContactClients)-1),ROW(1:1)),1))}

Although very sloppy, this works fine. However, I now need to add option buttons to toggle between searching for two different things. This means I have to replace the array formula from A3:L104 through VBA. My question is twofold:

*

*How can I shorten this formula to under 255 chars to use with .FormulaArray? I tried putting it in two halves but my understanding of syntax is not sufficient.

*Even if I got that to work, I imagine it would be extremely slow and inefficient. Is there a better way to go about this task?
Any help is greatly appreciated, I'm in way over my head with this. Thanks in advance.

A: First off, swap out your IF(ISERROR(<formula>), "", <formula>) for something that uses the IFERROR function. This will effectively cut your formula in half as IFERROR takes care of error control and default value without duplicating the formula.
=iferror(INDEX('Client Contact Database.xlsx'!Data.ContactsFull,SMALL(IF('Client Contact Database.xlsx'!Data.ContactClients=$L$1,ROW('Client Contact Database.xlsx'!Data.ContactClients)-1),ROW(1:1)),1), "")

I did not build all of the external references and named ranges for a full build environment, but I believe I transcribed that correctly.


text:
Q: Expected breaker temperature on a 208V 30A circuit with continuous 80% load I have several cabinets of servers in a datacenter and each of these cabinets is on a dedicated 208V 30A circuit. The load on each of these circuits is 24A and one circuit is slightly higher (~24.6A).
Recently, a datacenter technician (not an electrician) got in touch with me and said that my breakers in the panel were hot and that I should reduce the load on the circuits.
He took measurements using an infrared gun on three circuits. He said that the temperature was 117F for two of them and 110F for the other. He said that the maximum temp should be 104F. The ambient temperature in the room is roughly 72F.
A couple questions:

*

*Is it normal that my breaker temps are reaching 117F on a circuit that's at 80% load or slightly higher?

*Is the max temp for a breaker really only 104F? If humans and sensitive electronics can handle 104F, then surely a breaker could handle much higher temperatures...
I understand that it's impossible to give an exact answer to these questions when I'm unable to provide specifics on the breaker panel -- I'm just trying to get a general idea of what's 'reasonable' before I start pushing back on this request.

A: The breakers are likely rated for 40C (104F) ambient.That would be the meaning of 40C marked on the breaker. They are likely rated for connection to wire that has a 60/75C insulation temperature rating. That would also be marked on the breaker. The surface temperature of the breaker can be expected to be higher than the ambient temperature. A surface temperature of 47C should not be a problem if the ambient temperature is 40C, but 47C surface temperature in a 20C ambient could be a problem. That would mean the surface temperature has a 27C rise and would reach 67C in a 40C ambient. However the following information seems to indicate that the breaker is allowed to get hotter than the wire.
UL Surface Temperature Rise Limits
Non-metallic 60 deg. C
Metallic 35 deg. C
UL Terminal Temperature Rise
80% Rated CB 50 deg. C
100% Rated CB 60 deg. C
The above information was found in another forum, not directly from UL.


text:
Q: Ubuntu, how to detach process in a server that opens a window? Can you help me with this problem?
I want to detach a process I start in a server. This process is an application with one window/widget (similar to gedit, kate...). I access to the server by means of ssh -X, and run the binary process in a terminal. I have used screen and tmux, but the problem is that once I run the process, the window is oppened remotely from the server to my computer. Then, I would like to let the process openned, so I close the screen/tmux, and once I exit the ssh connection, the terminal waits till I close the process window, thus killing the process in the server.
Is there any way to let the process detached even with the process X windows?

A: I don't think it is possible over ssh. When you have such process, it needs to communicate with the X server (which is running on your client). You can't just take it away from the process.
If you need to run processes with X detached, you need to use X server on that remote machine. For this use case, VNC is probably better solution, since it can create virtual displays that are available even after disconnect.


text:
Q: Exception has been thrown by the target of an invocation. System.ArgumentNullException : text cannot be null Parameter name: text (Selenium) I have a test case automation selenium C# language to test login multiple users from excel file.
But, I have a problem to test with code. When I run this code, it still login completely the data from excel file. However, the system displayed failure my code test. It shown the reason fail:
Message: System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
----> System.ArgumentNullException : text cannot be null
Parameter name: text
Here my test code selenium C#:
using excel = Microsoft.Office.Interop.Excel;

using NUnit.Framework;

using System;

using OpenQA.Selenium.Support.PageObjects;

using LoginPage.Objects;

namespace NUnit.Tests1.TestCases

{
[TestFixture]
public class Data_Driven : Login_Page
{
    [Test]
    public void Test_Login_Excel()
    {
        try
        {
            excel.Application x = new excel.Application(); //
            excel.Workbook y = x.Workbooks.Open(@"D:\NUnit.Tests1\Test_Login.xlsx");
            excel._Worksheet x1WorkSheet = y.Sheets[1];
            excel.Range datarange = x1WorkSheet.UsedRange;
            int sw = datarange.Count;
            Console.WriteLine(sw);

                for (int i = 2; i <= datarange.Count; i++)
                {
                    if (datarange != null)
                    {
                        string Username = Convert.ToString(datarange.Cells[1][i].value2);
                        string Password = Convert.ToString(datarange.Cells[2][i].value2);
                        waitfunction();
                        var LoginPage = new Login_Page();
                        PageFactory.InitElements(driver, LoginPage);
                        LoginPage.Username.SendKeys(Username);
                        LoginPage.Password.SendKeys(Password);
                        LoginPage.Login.Click();
                        sleepfunction();
                        LoginPage.Username.Clear();
                        sleepfunction();
                        LoginPage.Password.Clear();
                    }
                    else
                    {
                        return;
                    }

                }

        } catch (Exception e)
            {
                throw (e);
            }
     }
}

}
Please help me to fix this problem to the system pass test case.
Thanks every one!


text:
Q: Check entry exists in sqlite3 python I checked some similar posts, but don't get my answer.
I want to check if specific username is in database or not.
import sqlite3
con = sqlite3.connect("session.db")
c = con.cursor()
a1 = 'jack'
c.execute("SELECT EXISTS(SELECT username FROM User WHERE username=?)", (a1))
if c.fetchone():
    print("Found!")

else:
    print("Not found...")

A: Your script has one obvious problem with it, namely that you are not actually passing a valid Python tuple to the call to execute().  Instead, you are passing a single string variable.  You should be passing (a,), with a trailing comma, to tell Python that you intend this to mean a tuple.
import sqlite3
con = sqlite3.connect("session.db")
c = con.cursor()
a1 = 'jack'
c.execute("SELECT EXISTS (SELECT 1 FROM User WHERE username = ?)", (a1,))
if c.fetchone():
    print("Found!")
else:
    print("Not found...")

To be clear here, ('jack') will be interpreted as a string, while ('jack',) will be interpreted as a tuple.

A: You should change your code a bit like this-
c.execute("SELECT EXISTS(SELECT username FROM User WHERE username=?)", (a1,))

Notice the comma after a1. Without this change the code should throw an error like Incorrect number of bindings supplied as only a1 (in your case value jack) will be treated as 4 different parameter provided to c.execute(). Turning it to tuple will bind the whole string jack to the appropriate placeholder.
After that check the result like -
found, = c.fetchone()
# found will be 1 in case the entry is present
if found:
    print("Found")
else:
    print("Not found")

c.fetchone() returns a tuple. In your case tuple with one element indicating whether the entry exists or not (1 if present, 0 otherwise)


text:
Q: Compare two Excel-files in Powershell I need help comparing two Excel files in Powershell.
I have an Excel-file which contains 6 000 rows and 4-5 columns with headers:
"Number" "Name" "Mobile data".
Let's call it: $Services
Now, I want to compare that file with other Excel-files. For example:
one file containing 50 rows with header columns: "Number", "Name", etc.
Let's call it $Department
The important thing is that in $Services, it contains more important columns like "Mobile data",
so my mission is to compare column: "Number" from $Services with column "Number" from each other Excel file.
Then if they match, write "the whole row" from $Services
I'm not that familiar with Excel, so I thought, this should be possible to do in Powershell.
I'm novice in Powershell, so I only know basic stuff. I'm not that familiar with pscustomobject and param.
Anyway, what I tried to do was to first declare them in variables with ImportExcel:
$Services = Import-Excel -Path 'C:\Users\*.xlsx'
$Department = Import-Excel -Path 'C:\Users\*.xlsx'

Then I made a foreach statement:
foreach ($Service in $Services) {
   if (($Service).Number -like ($Department).Number)
   {Write-Output "$Service"}
}

The problem with this is that it is collecting all empty columns from ($Services).Number and writing the output of each row in $Services.
I tried to add a nullorEmpty to $Department, if the .Number is empty, but it didn't make any difference. I also tried to add that if the row is empty in .Number, add "1234", but still it collects all .Number that is empty in $Services.
I also tried to do a: $Services | ForEach-Object -Process {if (($_).Number -match ($Department).Number)
{Write-Output $_}} But it didn't match any. When I tried -notmatch it took all.
I don't know but it seems that I have to convert the files to objects, like the columns to object so each string becomes an object. But right now my head is just spinning and I need some hints on where I can start with this.

A: I would recommend downloading the Module ImportExcel from the PSGallery.
Import-Excel can easily import your Excel sheet(s) to rows of objects, especially if your sheets are 'clean', i.e., only contain (optional) headers and data rows.
Simply import the cells to PowerShell objects and use Compare-Object to discover differences.
EDIT (after reading the additional questions by poster in the comments):
To compare using specific properties you'll need to add these to the Compare-Object parameters.
Using a trivial "PSCustomObject" to create a simple set of objects to show this idea it might look like this:
$l = 1..4 | ForEach-Object { [pscustomobject]@{a=$_;b=$_+1} }
$r = 1,2,4,5 | ForEach-Object { [pscustomobject]@{a=$_;b=$_+1} }
compare-object $l $r -Property B

B SideIndicator
- -------------
6 =>
4 <=

You may also compare multiple properties this way:
compare-object $l $r -Property A,B

A B SideIndicator
- - -------------
5 6 =>
3 4 <=

FYI: I find myself typing "Get-Command -Syntax SomeCommand" so often every day that I just made a function "Get-Syntax" (which also expands aliases) and then aliased this to simply "syn".
90% of the time once you understand the structure of PowerShell cmdlets (at least well-written ones) there is no need to even look at the full help -- the "syntax" blocks are sufficient.
Until then, type HELP (Get-Help) a lot -- 100+ times per day. :)

A: So the solution for my whole problem was to add -PassThru.
Because my mission was to compare the numbers of the two Excel-files, select the numbers that equals and then take all the properties from one file. So my script became like this:
    $Compare = Compare-Object $Services $Department -Property Numbers -IncludeEqual -ExcludeDifferent -PassThru
        $Compare | Export-Excel -Path 'C:\Users\*

But I wonder, -PassThru sends all the objects from ReferenceObject, how can I send all the objects from DifferenceObject?


text:
Q: Uncheck rows in Repeater DataTable in ASP.NET C# I have a data table filled using a Repetear. Also one column contains a checkbox property to select rows and, with a button, insert the checked rows into another table. After that, I use Response.Redirect("Page.aspx") to restart everything.
Is there a way to uncheck all the rows and clean the search result of the table without reload the page??
The table fills with 30,000 records and the page takes to much to load.
aspx:

        Data Table #1

                        Seleccionar
                        Id_Parte
                        Stock
                        Planta

                    <asp:Repeater ID="rptStockAlmacen" runat="server">
                        <ItemTemplate>

                                    <asp:CheckBox ID="chkSeleccionar" runat="server" />

                                    <asp:Label ID="lblId_Parte" runat="server" Text='<%# Eval("Id_Parte") %>' />

                                    <asp:Label ID="lblStock" runat="server" Text='<%# Eval("Stock") %>' />

                                <asp:HiddenField ID="hiddenSeleccionar" runat="server" Value='<%#Eval("Id_Parte") %>' />

                        </ItemTemplate>
                    </asp:Repeater>

aspx.cs:
protected void btnInsertar_Click(object sender, EventArgs e)
    {
        foreach (RepeaterItem i in rptStockAlmacen.Items)
        {
            CheckBox cb = (CheckBox)i.FindControl("chkSeleccionar");
            if (cb.Checked)
            {
                HiddenField hiddenSeleccionar = (HiddenField)i.FindControl("hiddenSeleccionar");
                SqlComm.SqlExecuteQueryInsert("insert into PartesSupervisadas (Id_Parte) values ('" + Int32.Parse(hiddenSeleccionar.Value) + "');");
            }
        }

        Response.Redirect("StockAlmacen.aspx");

    }

A: Ouch you need to implement paging first and foremost. After that you could either call a js function to look for all checkboxes and clear them, you can do it on load or create a button that the user can click which fires the event. E.g. below
 function uncheckMe()
 {
    var checkBox = document.getElementsByTagName('input');
    for(var i = 0; i < checkBox.length; i++)
    {
      if(checkBox[i].type =='checkbox')
      {
        checkBox[i].checked = false;
      }
    }
 }


text:
Q: Change background color of DialogButton in Flutter I am using rflutter_alert and I currently want to Change background color of DialogButton in my Flutter app and I am not getting it. Where should I modify my code with the color chosen for the button?
 // Showing Alert Dialog with Response JSON Message.
    Alert(
      context: context,
      type: AlertType.error,
      title: "",
      desc: "Usuario/Correo o contraseña incorrecta",
      buttons: [
        DialogButton(
          child: Text(
            "Cerrar",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          width: 120,
        )
      ],
    ).show();
  }
} on TimeoutException catch (e) {
  setState(() {
    visible = false;
  });

A: Alert provides style parameter that can be used to customize the default behavior.
Alert(
    style: AlertStyle(backgroundColor: Colors.amber),

More about rflutter_alert


text:
Q: Form submit not working for the React Food App I am trying to build this React Food App using Edamam API. React App is fetching by default data which I set state to "Chicken" but when I submit value through form ,its not fetching data. I am using useEffect to render my page when form submitted.
State and useEffect
import React,{useEffect, useState} from 'react'
import './App.css';
import Recipe from "./Recipe"

function App() {

  const APP_ID = "personalId";
  const APP_KEY = "personalKey";

  const [recipeData, setrecipeData] = useState([])

  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("Chicken");

  useEffect( () => {
    getRecipe();
  },[] )

Fetching API
  const getRecipe = async () => {
    const response = await fetch(`https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`)
    const data = await response.json();
    setrecipeData(data.hits)
    console.log(data.hits);
  }

Event Handling

  function handleChange(event){

    console.log(event.target.value);
    setSearch(event.target.value);

  }

  function handleSubmit(event){
    event.preventDefault();
    setQuery(search);

  }

Components
  return (

Recipe App

      <form onSubmit={handleSubmit} className="search-form">
        <input className="search-bar" type='text' onChange={handleChange} value={search}/>
        <button className="search-button" type="submit">Search</button>
      </form>
      {recipeData.map( eachRecipe =>(
        <Recipe
          key = {eachRecipe.recipe.label}
          title = {eachRecipe.recipe.label}
          calorie = {eachRecipe.recipe.calories}
        /> ))
        }

  );
}

export default App;

A: Your uesEffect's dependency array is empty, so it only renders on the very first render since that never changes. I think you meant to put [query] in it. Alternatively you could just call the getRecipe() directly in the handleSubmit()

A: I think it's probably because your useEffect function isn't listening to the query state's chages.
Try adding your state query into the useEffect's dependency array, like so:

useEffect( () => {
    getRecipe();
  },[query])


text:
Q: EF4: OfType filter for GetObjectStateEntries I override the SaveChanges method in my datacontext and have the following code:
IEnumerable<BaseEntity> newEntries = ObjectStateManager.GetObjectStateEntries(EntityState.Added).OfType<BaseEntity>();

In my model all businessobjects derive from BaseEntity. When I add a new 'Investment' (also derived from BaseEntity!) to my datacontext the code above will not show this entity in the resultset.
GetObjectStateEntries(EntityState.Added) however returns one entity which is of type Investment.
Why doesn't OfType<> recognize if an object is derived?

A: That because this query returns objects of type ObjectStateEntry and instance of this object has a property Entity which holds your entity object.
Try this:
var IEnumerable<BaseEntity> newEntries = ObjectStateManager
    .GetObjectStateEntries(EntityState.Added)
    .Select(e => e.Entity)
    .OfType<BaseEntity>();


text:
Q: python serial port code is working in windows but not in linux i have wrote some python code that is working fine in windows but it is not working in linux (ubuntu 12.04).
Im getting this message:
File "mygui.py", line 50, in sendPacket
returnpacket = str(length) + str(com3.read(ord(length)-1))
TypeError: ord() expected a character, but string of length 0 found

here is my code:
import serial
import crc16pure
import time

def main():
#works for 115200, 250000, 500000, 1000000
com3 = serial.Serial('/dev/ttyUSB0',baudrate=1000000,dsrdtr=False)
com3.timeout = 10
time.sleep(5) #MUST wait this long before writing, otherwise the serial
#p = '{"aaaaaaaaaaaaaaaa",{"  ",{"iget",{null}}}}'
p = '{"SensorNodeUUID":"aaaaaaaaaaaaaaaa","SlaveUUID":"  ","Command":"iget","Args":null}'
#discard first byte
com3.read()
timesum = 0
lstart = time.clock()

for i in range(3):
#print("writing packet")
start = time.clock()
#print(preparepacket(p))
com3.write(preparepacket(p))

length = com3.read()

returnpacket = str(length) + str(com3.read(ord(length)-1))
print(returnpacket)
com3.close()

A: I've not done serial in years, and I've since written bufsock...  You might try bufsock to see if it helps your situation:
http://stromberg.dnsalias.org/~dstromberg/bufsock.html
It'll deal with things like waiting until a byte is ready, before giving up on a read.  I've used on Cygwin, but never native Windows Python.  But it's known to work on CPython 2.x, CPython 3.x, Jython and Pypy on *ix.
Don't let the name fool you - I wrote it for buffering sockets, but it works fine for file handles too.


text:
Q: Repeat alarm every 20 minutes in android I'd like to repeat an alarm every 20 minutes.
So I tried:
manifest:
<receiver android:name=".AlarmReceiver" />

AlarmReceiver.class
    public class AlarmReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent intent2 = new Intent(context, MainActivity.class);
                showNotification(context, "text", "text", intent2);

                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(context, notification);
                r.play();
        }

@TargetApi(Build.VERSION_CODES.N)
    public void showNotification(Context context, String title, String body, Intent intent) {

...

}

   }

and in my main activity:
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(System.currentTimeMillis());
        time.add(Calendar.SECOND, 1200);
        alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);

It is working only the first time. I'd like to keep it repeating even when the app is not opening, any ideas?

A: Starting with KitKat (API 19), alarms are all inexact, meaning the system will batch alarms around similar times together.  If you need exact timing, there are different APIs to call.  Further complicating things, starting with Marshmallow, Android introduced the concept of Doze, which further restricts the when/how things can wake up the device.  You can still use exact alarms, but need to use the API which allows it during idle (Doze) time: setAndAllowWhileIdle().  Bear in mind that when your alarm fires, you could be in a Doze window and your app will be restricted on what kinds of operations it can perform.

A: Try below for Repeating alarm on every 20 minutes interval
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),1000 * 60 * 20, pendingIntent);

A: Try to use android worker manager since it is working with doze mode as well. https://developer.android.com/reference/androidx/work/PeriodicWorkRequest#min_periodic_interval_millis
https://developer.android.com/reference/androidx/work/PeriodicWorkRequest


text:
Q: Permanently hide form page after being submitted using Wordpress & Contact Form 7 I am using Wordpress and am using Contact Form 7 to create "Questionaire" page.
This is the case that am trying to achieve:

*

*User logged in.

*Redirect user to "Questionaire page".

*User succesfully submitted their answer.

*User logout.

*User logged in again, they won't see "Questionaire page" anymore because they already submitted their answer in Step 2. Instead redirect them to another page.

Am not quite sure whether this will be helpful or not. This is the sample code for Questionaire in using contact form 7:

1. Which secondary school did you attend?

[text* q1]

2. What do you plan to do immediately after secondary school?

[text* q2]

[submit "Send"]

A: <?php
    $user = wp_get_current_user();
    if ($user->ID != 0) {
        $status = get_user_meta($user->ID, 'FORM_STATUS', 'FORM_STATUS_VALUE');
        if ($status != 'SOMETHING') {
            //Do stuff
        }
        else {
            //Do stuff
        }
    }

?>

then after form submit you can redirect user to another page, and in this page change get_user_meta($user->ID, 'FORM_STATUS', 'FORM_STATUS_VALUE_NEW')
to redirect after form submit http://contactform7.com/redirecting-to-another-url-after-submissions/


text:
Q: How to unit test a controller with XUnit, Moq and AutoFixture? I have a controller with the following signature:
public CustomerTypeController(
    IHttpContextAccessor accessor,
    IPrincipalProvider provider,
    IMapper mapper,
    ILogger<CustomerTypeController> logger,
    ICustomerTypeService customerTypeService)
{ }

I also set up an AutoDataAttribute:
public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute()
        : base(() =>
        {
            var fixture = new Fixture().Customize(new CompositeCustomization(
                new AutoMoqCustomization(),
                new SupportMutableValueTypesCustomization()));

            fixture.Behaviors.OfType<ThrowingRecursionBehavior>()
                .ToList()
                .ForEach(x => fixture.Behaviors.Remove(x));

            fixture.Behaviors.Add(new OmitOnRecursionBehavior());

            return fixture;
        })
    { }
}

For now my Theory looks like this:
[Theory, AutoMoqData]
public void GetWhenHasCustomerTypesShouldReturnOneCustomerType(
    IFixture fixture,
    [Frozen] Mock<ICustomerTypeService> service,
    CustomerTypeController sut)
{
    //Arrange
    var items = fixture.CreateMany<Model.CustomerType>(3).ToList();

    //Act
    var result = sut.Get(1);

    //Assert
    Assert.IsType<OkResult>(result);
}

Do I need to setup the service with the items before getting an item from the controller? If yes, how is the service set up?

A: Use the [NoAutoProperties] attribute to decorate the controller parameter in the test method.
Refer to this answer for details.


text:
Q: oracle plsql: retrieve runtime parameter values when you call a procedure I need a generalized method to get list of runtime parameters (values) when I call a procedure. I need something similar to the $$PLSQL_UNIT that returns the name of the running procedure.
(plsql Oracle 10g)
E.g. look at this sample procedure:
(it simply prints its own name and parameters )
CREATE OR REPLACE PROCEDURE  MY_PROC(ow in varchar2, tn IN varchar2)
 IS

BEGIN
     dbms_output.put_line('proc_name: '||$$PLSQL_UNIT||' parameters: '|| ow||' '||tn  );

    EXCEPTION
    WHEN OTHERS THEN
       DBMS_OUTPUT.PUT_LINE('ERRORE: ' ||SQLERRM);

END MY_PROC;
/

Running procedure produces the following output:
SQL>
  1   BEGIN
  2     IBAD_OWN.MY_PROC('first_par', 'second_par');
  3   END;
  4  /

proc_name: MY_PROC parameters: first_par second_par

PL/SQL procedure successfully completed.

I'm not satisfy because I can't copy and paste in all my procedures because I have to hard code each procedure to set their right parameter variables.
Thanks in advance for the help.

A: It isn't possible to dynamically retrieve the values of parameters passed to a procedure in Oracle PL/SQL. The language simply isn't designed to handle this kind of operation.
Incidentally, in a procedure that is located within a package, $$PLSQL_UNIT will only return the package's name. I find it's better to define a consistently-named constant within each procedure that contains the procedure's name.

A: When I wanted the same functionality as yours I didn't find any good built-in solution.
What I did is: wrote DB-level trigger which modifies original body of function/procedure/package.
This trigger adds immediatly after "begin" dynamically generated piece of code from "user_arguments".
Plus, after that I include into this trigger the code, that logs calls of procs when exception occures.
Plus, you can trace procs calls, and many more interisting things.
But this solution works fine only for preproduction because performance decreases dramatically.
PS. Sorry for my bad English.


text:
Q: Block outgoing connection (an IP address) in c# I would like to block an IP from c#.
I looked up MSDN, and found only firewall exception usage.
Is there any other simpler solutions? I don't want to touch my client's computer setting.

A: No, only the OS or an application that hooks into the OS can block outgoing connections. The firewall is the best place to do this.


text:
Q: My vector elements keep changing themselves after each input char* name = (char*)malloc(sizeof(char));
    char* highscore = (char*)malloc(sizeof(char));
    char* password = (char*)malloc(sizeof(char));
    player* c = new player(name, highscore, password);
    int i;
    int j = 0;
    int score = 0;
    vector <player*> players;
    vector <char*>* names = new vector <char*>;
    vector <char*>* passwords = new vector <char*>;
    vector <int> scores;
    ifstream input;
    input.open("user.csv");
    do {
        cout << "Welcome to Champion Yahtzee\n";
        cout << "Player Name            Highest Score\n";
        cout << "-----------            -------------\n";
        while (input.good())
        {
            input >> *c;
            players.emplace_back(c);
            names->push_back(name);
            score = atoi(highscore);
            scores.push_back(score);
            passwords->push_back(password);
            j++;
        }

This is my code, I know that in order to input into it we have to expand the vector? at least from what I read to fit in the new char and I genuinely don't know how to fix it. I've tried initializing the vector as  vector <player*> players; but that was of no use since after each input it overrode the previous pointers and sets all the elements to the input. How do I go about fixing this?

A: The reason you are getting the same values everywhere is because you only allocate your storage memory once, then push the same memory address in to your vectors over and over.
Basically, you always have only one object.
To fix this, you must allocate new objects inside the loop, like so:
vector <player*> players;
vector <char*> names;
vector <char*> passwords;
vector <int> scores;
ifstream input;
input.open("user.csv");

cout << "Welcome to Champion Yahtzee\n";
cout << "Player Name            Highest Score\n";
cout << "-----------            -------------\n";
while (input) { //this is the proper way in c++ 11 and up
    char* name = new char[MAX_NAME_LEN];
    char* highscore = new char[MAX_SCORE_LEN];
    char* password = new char[MAX_PASSWORD_LEN];
    player* c = new player(name, highscore, password);

    input >> *c;
    players.emplace_back(c);
    names.push_back(name);
    int score = atoi(highscore);
    scores.push_back(score);
    passwords.push_back(password);
}

Here are the explanations to changes to your code:

*

*Unless there is some weird requirement in your homework, the vectors do not need to be pointers, they only need to contain pointers.

*We allocate new objects at the beginning of every loop, so every time you read in data it will go in to a new place in memory.

*If you have to use char * you should define constants (or macros) like MAX_NAME_LEN for maximum length of the name field.
Your homework probably specifies maximum input length for all fields to make things simpler.

*The condition in the while loop is simply the stream object.
Starting with C++11 it overrides the casting to bool to return true while more data can be read.
If you are using older C++ standard use while (!input.eof()) or check the return value of input >> *c and break if it is false.

*If you are writing C++ you should use new to allocate memory.
Though malloc will work correctly, it is considered to be "the C way" and its use in C++ is discouraged.


text:
Q: Get certain substring from String java I can have this string as below :
String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";

or
String s = "chapterId=c_1&sectionId=s_24666";

I need to get the number ("24666" in the examples).
String res = s.substring(s.lastIndexOf("s_")+ 2) this returns me the number + chars till the end of the string(the second example is ok). But I need to stop after the number ends. How can I do that.? Thanks

A: You can split the string by the character & to get the parameters, and split each parameter with the = to get the parameter name and parameter value. And now look for the parameter name "sectionId", and cut the first 2 characters of its value to get the number, and you can use Integer.parseInt() if you need it as an int.
Note that this solution is flexible enough to process all parameters, not just the one you're currently interested in:
String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";

String[] params = s.split("&");
for (String param : params) {
    String[] nameValue = param.split("=");

    if ("sectionId".equals(nameValue[0])) {
        int number = Integer.parseInt(nameValue[1].substring(2));
        System.out.println(number); // Prints 24666

        // If you don't care about other parameters, this will skip the rest:
        break;
    }
}

Note:
You might want to put Integer.parseInt() into a try-catch block in case an invalid number would be passed from the client:
try {
    int number = Integer.parseInt(nameValue[1].substring(2));
} catch (Exception e) {
    // Invalid parameter value, not the expected format!
}

A: You can use regExp
    String s = "chapterId=c_1&sectionId=s_24666";
    //OR
    //String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
    s=s.replaceAll(".*?s_(\\d+).*","$1");
    System.out.println(s);

OUTPUT:
24666

Where,

*

*.*?s_ means anything before s_ (s_ inclusive)

*(\\d+) means one or more digits () used for group

*$1 means group 1 which is digits after s_
Note:Assumed that your every string follows specific format which includes s_ and number after s_.

A: Try following:
  String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
  String tok[]=s.split("&");
  for(String test:tok){
      if(test.contains("s_")){
          String next[]=test.split("s_");
            System.out.println(next[1]);

      }
  }

Output :
24666

Alternatively you can simply remove all other words if they are not required as below
String s="chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*s_(\\d+).*","$1");
System.out.println(s);

Output :
24666

The dig over here is splitting your string using a Regular Expression to further divide the string into parts and get what is required. For more on Regular Expressions visit this link.

A: Try this:
I use a check in the substring() method - if there is no "&isHL" in the string (meaning its type 2 you showed us), it will just read until the string ends. otherwise, it will cut the string before the "&isHL". Hope this helps.
Code:
    String s = "chapterId=c_1&sectionId=s_**24666**";
    int endIndex = s.indexOf("&isHL");
    String answer = s.substring(s.lastIndexOf("s_") + 2,    endIndex == -1 ? s.length() : endIndex);

A: You could sue this regex : (?<=sectionId=s_)(\\d+) This uses positive look-behind.
demo here

A: Following code will work even if there is multiple occurrence of integer in given string
   String inputString = "chapterId=c_a&sectionId=s_24666&isHL=1&cssFileName=haynes_45";

    String[] inputParams = inputString.split("&");
    for (String param : inputParams)
    {
        String[] nameValue = param.split("=");

        try {
            int number = Integer.parseInt(getStringInt(nameValue[1]));
            System.out.println(number);
        }
        catch(IllegalStateException illegalStateException){
        }
    }

private String getStringInt(String inputString)
{
    Pattern onlyInt = Pattern.compile("\\d+");
    Matcher matcher = onlyInt.matcher(inputString);
    matcher.find();
    String inputInt = matcher.group();
    return inputInt;
}

OUTPUT

2466
 1
 45

A: Use split method as
String []result1 = s.split("&");
String result2 = tempResult[1];
String []result3 = result2.split("s_");

Now to get your desire number you just need to do
String finalResult = result3[1];

INPUT :
String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";

OUPUT :
24666