text:
Q: Tomcat 7 error about LeaseException querying an EMR cluster I am getting below error while connecting to the EMR cluster using Tomcat server and Hbase as the database.
I have made the changes suggested at http://www.nosql.se/2012/05/hbase-scanner-leaseexception/
and I have also rebooted the clusters suggested as here : http://mail-archives.apache.org/mod_mbox/hbase-user/201209.mbox/%3CCAOcnVr3R-LqtKhFsk8Bhrm-YW2i9O6J6Fhjz2h7q6_sxvwd2yw%40mail.gmail.com%3E

HTTP Status 500 - org.apache.hadoop.hbase.regionserver.LeaseException: org.apache.hadoop.hbase.regionserver.LeaseException: lease '5811533108977417332' does not exist at org.apache.hadoop.hbase.regionserver.Leases.removeLease(Leases.java:231) at org.apache.hadoop.hbase.regionserver.HRegionServer.next(HRegionServer.java:2136) at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Server.call(WritableRpcEngine.java:369) at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1326)
type Exception report
message org.apache.hadoop.hbase.regionserver.LeaseException: org.apache.hadoop.hbase.regionserver.LeaseException: lease '5811533108977417332' does not exist at org.apache.hadoop.hbase.regionserver.Leases.removeLease(Leases.java:231) at org.apache.hadoop.hbase.regionserver.HRegionServer.next(HRegionServer.java:2136) at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Server.call(WritableRpcEngine.java:369) at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1326)
description The server encountered an internal error (org.apache.hadoop.hbase.regionserver.LeaseException: org.apache.hadoop.hbase.regionserver.LeaseException: lease '5811533108977417332' does not exist at org.apache.hadoop.hbase.regionserver.Leases.removeLease(Leases.java:231) at org.apache.hadoop.hbase.regionserver.HRegionServer.next(HRegionServer.java:2136) at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Server.call(WritableRpcEngine.java:369) at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1326) ) that prevented it from fulfilling this request.
exception
java.lang.RuntimeException: org.apache.hadoop.hbase.regionserver.LeaseException: org.apache.hadoop.hbase.regionserver.LeaseException: lease '5811533108977417332' does not exist
    at org.apache.hadoop.hbase.regionserver.Leases.removeLease(Leases.java:231)
    at org.apache.hadoop.hbase.regionserver.HRegionServer.next(HRegionServer.java:2136)
    at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Server.call(WritableRpcEngine.java:369)
    at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1326)
org.apache.hadoop.hbase.client.AbstractClientScanner$1.hasNext(AbstractClientScanner.java:44)
    Query.doGet(Query.java:64)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
org.apache.hadoop.hbase.regionserver.LeaseException: org.apache.hadoop.hbase.regionserver.LeaseException: lease '5811533108977417332' does not exist
    at org.apache.hadoop.hbase.regionserver.Leases.removeLease(Leases.java:231)
    at org.apache.hadoop.hbase.regionserver.HRegionServer.next(HRegionServer.java:2136)
    at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Server.call(WritableRpcEngine.java:369)
    at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1326)
sun.reflect.GeneratedConstructorAccessor15.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    org.apache.hadoop.hbase.RemoteExceptionHandler.decodeRemoteException(RemoteExceptionHandler.java:96)
    org.apache.hadoop.hbase.client.ScannerCallable.call(ScannerCallable.java:149)
    org.apache.hadoop.hbase.client.ScannerCallable.call(ScannerCallable.java:42)
    org.apache.hadoop.hbase.client.ServerCallable.withRetries(ServerCallable.java:164)
    org.apache.hadoop.hbase.client.ClientScanner.next(ClientScanner.java:279)
    org.apache.hadoop.hbase.client.AbstractClientScanner$1.hasNext(AbstractClientScanner.java:41)
    Query.doGet(Query.java:64)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.28 logs.
Apache Tomcat/7.0.28

A: try improving the performance by using caching.
<property>
<name>hbase.client.scanner.caching</name>
<value>100</value>
</property>
</configuration>

Sometime the regionserver automatically hog down and cause  lease expired


text:
Q: Will there be an backport of Unity 6/compiz for Precise?
Possible Duplicate:
Is it possible to install Unity 6.x.x on Ubuntu 12.04?

In my opinion Unity 5.x in precise is not how it should be in an LTS and I would like to know, whether Unity 6.x/compiz (as in quantal) will be backported to precise for a better performance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to map domain in AWS Route53 with GCP Cloud Run app Our domain is registered in Route 53. We have 1 hosted zone, and the domain is currently used for one of our EC2 instances (I think as an elastic IP address). Our hosted zone has all of the records needed to work with our EC2 instance. We now need to use this domain instead for my an application deployed through GCP's Cloud Run. I have headed to console.cloud.google.com/run/domains and clicked Add Mapping, typed in our base url, and received a button to Verify in Webmaster Central, which I click, bringing me to this google page with this dropdown (in the images below I changed my url to the fake domain mydomain.com):

This dropdown does not have Route53 or Amazon Registrar as an option, and I'm not sure what other option to choose. At the bottom is Other, which opens up the following menu:

For step 1, I am struggling. I have logged into my AWS account, went to Route 53, and created a new hosted zone for mydomain.com:

I click on the new hosted zone for mydomain.com, click create record, choose Simple Routing for the policy (there were 6 options: Simple Routing, Weighted, Geolocation, Latency, Failover, Multivalue answer), then click Define Simple Record, and get sent to this page:

I left the record name blank, set the Record Type to TXT, selected IP address or another value depending on the record type, and copy/pasted the line from the google webmaster verification page into the input field. They I click Define Simple Record to create the record.
Unfortunately, after all of this, the verification is not successful from the Google Webmaster verification page. To confirm this, I am receiving the following error notification when I click Verify:

Perhaps moving the domain from Route 53 to Google's DNS would be easier, although to me it seems simpler to leave the domain in AWS and simply give permission to the Cloud Run app to use the domain. This seems like it would be an issue for anybody with an app in Cloud Run and a domain in AWS Route 53.
Edit
When I run dig TXT mydomain.com from the command line, I get something that looks like this (numbers edited):
MyComputer-1:Documents myname$ dig TXT mydomain.com

; <<>> DiG 9.10.6 <<>> TXT mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26912
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;cbbanalytics.com.              IN      TXT

;; AUTHORITY SECTION:
mydomain.com.       900     IN      SOA     ns-923.awsdns-18.com. awsdns-hostmaster.amazon.com. 1 5740 300 1204600 86210

;; Query time: 87 msec
;; SERVER: 6300:1004:dc40:4b00::1#53(2600:1400:dc40:4b00::1)
;; WHEN: Thu Sep 24 11:14:11 PDT 2020
;; MSG SIZE  rcvd: 123

Nicholass-MBP-5:Documents nicholas$

A: (Posted solution on behalf of the question author, to move it to the answer section).
Per suggestion in the comments, I deleted the 2nd hosted zone, created the TXT record in the 1st hosted zone (in the same way as done in the screenshot above), and the verification worked.

A: DNS records can take time to propagate, the best would be to query your domain like:
dig TXT mydomain.com

If this doesn't work, it's not Google's fault –you might be misconfiguring your nameservers on the domain name incorrectly (they might not even be pointing to Route53).
If dig returns the desired answer, check the Verification screen again and try verifying again.


text:
Q: Упоминание зарегистрированных названий Могу ли я без явного разрешения правообладателя использовать зарегистрированное им название (Facebook, Ferari, Formula 1 и т.д.) в своем ПО, предназначенном для получении прибыли мне. Или как получить это разрешение? И как трудно?
Заранее спасибо!

A: Можно. Но если это ПО, которое будет приносить большую прибыль или станет очень популярным - на него начнут обращать внимание, вот тогда и будут проблемы.
На счет торговых марок: в своей стране ты можешь зарегистрировать марку facebook если она еще не зарегистрирована, и использовать это имя. Но фейсбук может отсудить при желании.


text:
Q: Using cookies to consume other web services from server I have a backend server written in Java that contains services used by a mobile app that I have also created. I am using Appcelerator as a 3rd party push notification service and they require a user to be logged in in order to send push notifications.
Here is the flow of events that I would like to have happen:

*

*The user logs in to my app (could also log in to Appcelerator here)

*The user does something that should send a push notification

*The request gets sent to MY server to send the push notification

*My server makes the request to Appcelerator to send a push notification

Somewhere in that process, there needs to be an authentication with Appcelerator. Currently, I'm just using my credentials with Appcelerator as sort of an admin and I'm authenticating before each unique push notification is sent. However, this means authenticating before each push notification which will significant increase the time it takes.
There are two possible solutions I have identified but I am unsure if either is possible:

*

*Have each user of my mobile app authenticate with Appcelerator when first logging in and save that some how on my server so that when they make a request to my server, I use their cookie to authenticate. (This seems insecure.)

*Persist my authentication with Appcelerator past 1 request to my server. (This seems to be the easier of the two solutions but I'm unsure if it is possible/the right way to do it.)

A: Since I am doing user management on my server, it does not make sense to also do it through Appcelerator. I previously thought that if I wanted to use Appcelerator as a push notification service, that I had to create users through their service as well.
However, I now realize that there are two sections in their Push Notification API.

*

*subscribe

*unsubscribe

*notify

and

*

*subscribeToken

*unsubscribeToken

*notifyToken

The latter group, uses the pushToken from the device, which is not related to Appcelerator in any way. With those methods, you do not need to have Appcelerator users as you can just send the push notifications to the device tokens.


text:
Q: ошибка передачи вектора в функцию C++ При написании многопоточного приложения на c++ возникла необходимость передачи в функцию, которая выполняется в многопоточном режиме (multy), некоторое количество ссылок на вектора, которые для каждого потока имеют собственное значение. В результате компиляции вылетают ошибки:

*

*Severity    Code    Description Project File    Line    Suppression State
Error   C2672   'std::invoke': no matching overloaded function found

*Severity    Code    Description Project File    Line    Suppression State
Error   C2893   Failed to specialize function template 'unknown-type
std::invoke(_Callable &&,_Types &&...) noexcept()'

Код консольного приложения ниже:
#include "pch.h"
#include "libraries.h"
#include "globalVariables.h"
//#include "multyThreadingFunc.h"

thread_local double centerOfMass = 0.0;

thread_local double templateZ;

vector<float> distanceAxis(n_bin + 1);

//here the total number of molecules in each bin is saved during the loop for the analyte molecules
vector<double> vectordensity(n_bin);

mutex mtx;

void multy(FILE &fid, int &amountOfAtoms, float &time, vector<float> &coordinates, vector<float> &changedCoord, double &centerOfMass, double &templateZ, vector<double> &vectordensity) {

    FILE *file = &fid;
    ...//some calculating
}

int main()
{
    thread_local vector<float> coordinates(3); //x,y,z coordinates
    thread_local vector<double> changedCoord;

    FILE *fid = fopen("Benzene_Simu1_0_35ns.gro","rt");
    if (fid == NULL) throw exception("Error was happend with the file");

    float time;

    for (int i = 1; i <= n_bin; i++) {
        distanceAxis[i] = (i - 0.5)*BinWidth;
    }

    int startTime = clock();
    while (true) {
        std::thread thr(multy, ref(fid), &amountOfAtoms, &time, ref(coordinates), ref(changedCoord), &centerOfMass, &templateZ, ref(vectordensity));

        if (feof(fid)) break;

        vectordensity[bin]++;   //sorts the molecules according to their bins
                                //after finishing the loop, density contains the distribution of the molecules over all bins for all time steps

        index++;
    }
    --index;

    fclose(fid);
    cout << endl << (endTime - startTime) / 1000 << endl;
    return 0;
}

A: Написана какая-то ерунда при передаче аргументов в поток. Например, в функции потока параметр
int &amountOfAtoms

это ссылка на int, а при создании потока вы передаете туда
&amountOfAtoms

т.е. указатель на int. Эта ошибка присутствует и с другими параметрами. Неудивительно что компилятор не может вызвать функцию потока. Что характерно, ссылки на векторы вы передаете правильно, а ссылки на скалярные значения почему-то нет. Откуда такое деление?
С параметром fid вообще что-то непонятное творится. Почему передается ref(fid) (то есть фактически FILE *&), когда функция потока принимает FILE &? Что вообще такое FILE & и зачем вам понадобился этот FILE &? Почему вы не передаете сразу нормальный человеческий FILE *?
Также я у вас в коде не увидел никаких попыток сделать "некоторое количество ссылок на вектора, которые для каждого потока имеют собственное значение". Для того, чтобы у каждого потока было "собственное значение" вектора, надо для каждого потока создавать отдельный экземпляр вектора. Но я у вас этого нигде не вижу. Все потоки получают ссылки на одни и те же векторы. В частности, неясно, зачем вы у себя в коде наставили этих thread_local спецификаторов, если все потоки получают ссылки на одни и те же данные из главного потока и работают именно с ними.


text:
Q: Having trouble deserialzing null Jackson node to a collection I'm testing deserializing to a collection object when my JsonNode no value. I want the object to be equal to null.
This is what I'm trying:
public class ImmutableDiscoveredUrlDeserializer extends JsonDeserializer<ImmutableDiscoveredUrl> {
String parentUrl;
Double parentUrlSentiment;
Set<String> childUrls;
Boolean isParentVendorUrl;
Map<TagClassification, Set<String>> parentUrlArticleTags;

/*
 * (non-Javadoc)
 * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
 */
@Override
public ImmutableDiscoveredUrl deserialize(JsonParser p, DeserializationContext ctx)
    throws IOException {

    JsonNode node = p.readValueAsTree();
    parentUrl = defaultIfNull(node.get("parentUrl").asText(), null);
    childUrls = defaultIfNull(parseChildUrls(node), emptySet());
    isParentVendorUrl = defaultIfNull(Boolean.valueOf(node.get("isParentVendorUrl").asText()), null);
    parentUrlArticleTags = defaultIfNull(parseArticleTags(node.get("parentUrlArticleTags")), emptyMap());

    return ImmutableDiscoveredUrl.discoveredUrl().parentUrl(parentUrl)
                .parentUrlSentiment(parentUrlSentiment).childUrls(childUrls)
            .isParentVendorUrl(isParentVendorUrl).parentUrlArticleTags(parentUrlArticleTags);
}

private Set<String> parseChildUrls(JsonNode node) throws IOException {
    ObjectMapper tagsMapper = new ObjectMapper();
    return tagsMapper.convertValue(node, new TypeReference<Set<String>>() {});
}

private Map<TagClassification, Set<String>> parseArticleTags(JsonNode node) throws IOException {
    ObjectMapper tagsMapper = new ObjectMapper();
    return tagsMapper.convertValue(node, new TypeReference<Set<String>>() {});
}

But I get a MismatchedInputException, stating that there's no content to map. How do I get the ObjectMapper to return a null?

A: Since you already have a JsonNode you can use ObjectMapper#convertValue:
@Test
public void converts_null_to_null() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree("{\"foo\":null}");
    JsonNode foo = jsonNode.get("foo");

    Set<String> result = mapper.convertValue(foo, new TypeReference<Set<String>>() {});

    assertNull(result);
}

Note that convertValue() will not work as intended if you pass in a plain Map. In your case you need to remove defaultIfNull and check for null yourself:
if (node.get("parentUrlArticleTags") !== null) {
    parentUrlArticleTags = parseArticleTags(node.get("parentUrlArticleTags"));
}

A: In my case I had a little different issue, for getting
Cannot deserialize instance of `java.util.HashSet` out of START_OBJECT token
 at [Source: (String)"{"bbc":"firstbckt","ssg":{"751fad0":"751fad0","be0eb99":"be0eb99"}}"

and here was my POJO
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@SuppressWarnings("serial")
public class BulkUploadRsp implements Serializable {
    private String bbc;
    private Map<String, String> ssgs = Maps.newHashMap();
    //..
    public void setSsgs(Set<String> ssgs) {
        this.ssgs = ssgs.stream().collect(Collectors.toMap(ssg -> ssg, ssg -> ssg));
    }
}

Issue was: I had this util method which starts with set*. Renaming it to setSsgs(Set<String> ssgs) helped resolve the issue


text:
Q: how to make tags within the custom directives go to specific place of template? I have a directive by name cngView
controller.js
//directive to include view panel
angular.module('cngFoundation', [])
                                    .directive('cngView', function() {
                                         return {
                                                  restrict : 'CAME',
                                                  templateUrl: 'templates/view.html'
                                                };

                                     });

to access directive

        <cng-view>

                 [AAA]

        </cng-view>

The templates/view.html is as  follows

View

        [BBB]

I have made the cng-view tag work but I don't know how to give contents inside the tag.
How to make contents I give at place "[AAA]" appear at "[BBB]" .
In short how to make contents I give within cng-view tag(a custom tag) go into the specific place inside the template content of the cng-view .
Please give guidance . At least please direct me to some online tutorial .
Thanks

A: You need to use ng-transclude which tells template where to place existing content

Also need to set transclude:true in directive
See section Creating a Directive that Wraps Other Elements in directive docs

A: You can use the built in ng-transclude directive. In your view.html replace [BBB] with

also be sure to define transclude on your directive
transclude: true,

For a working example see this plunkr


text:
Q: Access files below mounted volume inside docker container I have a docker container which mounts volume using -v /host/path:/docker/path
This mounts overwrites (shadows) the files inside the container. I would now like to copy the original files from inside the container into the mounted volumes. For this I need to access the shadowed files.
The common way of doing this seems to be mount --bind. But to use this, I would need the leverage my privileges inside the docker container and I would rather not do that.
Is there another way of accessing this shadows files that is doable from inside the docker container?
Update
A little bit about the background (in response to comments):
I want to initialize the mounted volume with the contents inside the docker image. That is standard behavior of docker when using named volumes. Unfortunately that does not seem to be possible in ECS (which is where I start the container).


text:
Q: Searching for instances of a string in a text area, counting the number found and printing in a text field. Java code Here is My code for a Searcher Listener class for my main class WordSearch. This Compiles but does not get me the results I need, which is to find the number of times a string shows up in a text area. Any help would be greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;

public class Searcher implements ActionListener
{
    private JTextField foundTextField;
    private JTextArea  mainTextArea;
    private JTextField searchTextField;
    private int count;

    public Searcher(JTextField field, JTextArea main, JTextField searched)
    {
    this.foundTextField = field;
    this.mainTextArea = main;
    this.searchTextField = searched;
    count = 0;
}

public void actionPerformed(ActionEvent e)
{
    if(e.getActionCommand().equals("search"))
    {
        count = 0;
        String allOfText = mainTextArea.getText();
        String searchedText = searchTextField.getText();
        int firstString = allOfText.indexOf(searchedText);
        boolean valid = false;
        while(!valid)
        {
            if(firstString !=-1)
            {
                count+=1;
                foundTextField.setText("" + count);
                firstString = allOfText.indexOf(searchedText, firstString);

            }
            else
            {
                valid = true;
            }
        }
        if(mainTextArea.getText().equals(""))
        {
            JOptionPane error = new JOptionPane();
            error.showMessageDialog(null,"target text is empty", " target text is empty", JOptionPane.ERROR_MESSAGE);
        }
        else if(searchTextField.getText().equals(""))
        {
            JOptionPane error = new JOptionPane();
            error.showMessageDialog(null,"search text is empty", "search text is empty", JOptionPane.ERROR_MESSAGE);
        }
    }
    else if(e.getActionCommand().equals("Reset All"))
    {
        mainTextArea.setText("");
        foundTextField.setText("");
        searchTextField.setText("");
    }
    else if(e.getActionCommand().equals("Reset"))
    {
        mainTextArea.setText("");
       foundTextField.setText("");
        searchTextField.setText("");
    }
    else if(e.getActionCommand().equals("Clear"))
    {
        mainTextArea.setText("");
    }
}
}


text:
Q: Regarding Playing Music via Spinner in android I have created a spinner view with some set of lists include. Now i wanted to play music while selecting those item list one by one....any idea....

A: hi raghavan you can use this...
 Intent intent = new Intent(android.content.Intent.ACTION_VIEW);

    Uri data = Uri.parse("file://"+Environment.getExternalStorageDirectory()
            .getAbsolutePath()+"/" + fileName);
    String type = "audio/mp3";
    intent.setDataAndType(data, type);
    startActivity(intent);

and in the filename variable pass the filename that you have selected in the list.
Hope this helps....
edit #1
final MediaPlayer mPlayer=MediaPlayer.create(getBaseContext(), R.raw.reload);
mPlayer.setOnCompletionListener(new OnCompletionListener() {

    @Override
    public void onCompletion(MediaPlayer mp) {
        //new Toast(getBaseContext());

        mPlayer.release();
        mPlayer = null;

    }
});

Insert this code inside your itemselect event...


text:
Q: Setting up an offset with anchor tags for a div I have made a single page which has a navbar and with links pointing to section id in the page.
However, when I click on the link the section of the page scrolls down till the top of the section and due to my sticky navbar, the top part of my section goes behind it.
How do I create an offset height which would match my navbar height so that the div is visible at the right position?
Here is my a screenshot of what is happening.

Also, is there a way to smoothly scroll till the section? What is the easiest method to achieve this?
My example code:
HTML:

Section 1

Sction 2

Section 3

Section 1

Section 2

Section 3

A: Offsetting anchor hash tag links to adjust for fixed header
HTML :
Goto Section I

Section I

Section specific content

CSS:
.offset:before {
    display: block;
    content: " ";
    height: 150px;      /* Give height of your fixed element */
        margin-top: -150px; /* Give negative margin of your fixed element */
        visibility: hidden;
}

A: Give padding-top to that section which is equal to the header height. Like if your header has a height: 40px then give padding-top: 40px to that section.
Have a look at the snippet below:

body {
  margin: 0;
  padding-top: 50px;
}

nav {
  background: #eee;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
}

li {
  padding: 15px;
}

.sec {
  height: 200px;
  margin-bottom: 30px;
  background: #ff0;
  padding-top: 48px;
}

Section 1

Section 2

Section 3

Section 1

Section 2

Section 3

Hope this helps!


text:
Q: How to count the keypress realtime in android How can you count the number of keypress realtime?? or by keypress?
Here is my code:
public class MyActivity extends Activity implements View.OnClickListener, View.OnKeyListener {
    /**
     * Called when the activity is first created.
     */
    EditText ed

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

        ed=(EditText)findViewById(R.id.editText);
       ed.setOnKeyListener(this);
       }

   @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {

            keyCounter++;
      Log.d("key","" + keyEvent.getKeyCode());

     return super.onKeyUp(i, keyEvent) ;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_B:

                keyCounter++;
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }
}

I tried both the onkeyup and on key.. But it didnt work;
I Toast the value of keyCounter but still zero. Anyone knows how to get the number of keypress in android?? Thanks.

A: Are you trying with a real keyboard or the software keyboard?

android.view.View.OnKeyListener
Class Overview
Interface definition for a callback to be invoked when a hardware key event is dispatched to this view.

see if you can use a TextChangedListener instead.
myEditText.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {}
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //do stuff
        }

    });

Other things:
1) use Log.d instead of Toast.
2) Try the keyCounter++; without conditions to see if the onKey is called.
3) change return false/true to return super.onKey(keyCode, event)


text:
Q: Are quoted dictionary keys an absolute must? Just curious, made an interesting observation that I got away with defining my dictionary keys without having to quote them. I guess this is a vulnerability in Python?
Within a sample, and not in REPL, the following does not raise an exception:
>>> {foo:'foo', bar:'bar'}
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 NameError: name 'foo' is not defined

How do Pythonistas handle their keys? Do you advocate unquoted or quoted keys, and why?

A: A dictionary's keys can be any hashable object (a string, an integer, a tuple, etc.):
>>> dct = {'a': 1, 1: 'a'}
>>> dct['a']
1
>>> dct[1]
'a'
>>>

Quoting a key simply means that the key is a string, as with 'a' above.

As far as your claim that:

I got away with defining my keys without having to quote them

I assume that you mean you did something like this:
dct = {key1: 1, key2: 'a'}

There is really nothing special about the code above.  It just means that the names key1 and key2 refer to hashable objects, which now become the keys of the dictionary. An example is below:
>>> key1 = 'a'
>>> key2 = 1
>>> dct = {key1: 1, key2: 'a'}
>>> dct[key1]
1
>>> dct[key2]
'a'
>>> dct['a']
1
>>> dct[1]
'a'
>>>

On the other hand, if you mean that you used the dict built-in to make a dictionary:
dct = dict(key1='a', key2=1)

Then you should know that the keys are still normal strings:
>>> dct = dict(key1='a', key2=1)
>>> dct
{'key2': 1, 'key1': 'a'}
>>> dct[key1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'key1' is not defined
>>> dct['key1']
'a'
>>>

Finally, regarding your question of whether or not you should always use string keys, the answer is it depends.  If you need your keys to hold data that can only be represented as a string (such as a person's name), use strings.  If you need the keys to hold numerical data (such as id numbers), use integers or floats or whatever is appropriate.
Simply put, do whatever makes the most sense for your program.


text:
Q: AltBeacon Not Finding Beacons I am trying to implement the AltBeacon library to range beacons similarly to the way iOS does. However I am having trouble getting my app to recognize any beacons.
Here is my code:
onCreate:

 beaconManager = BeaconManager.getInstanceForApplication(this)
        beaconManager.bind(this)

        var region = Region(route.route.uuid, null, null, null)
        beaconManager.startMonitoringBeaconsInRegion(region)

onBeaconServiceConnect
override fun onBeaconServiceConnect() {
        beaconManager.removeAllRangeNotifiers()
        beaconManager.addRangeNotifier(object : RangeNotifier {
            override fun didRangeBeaconsInRegion(
                beacons: Collection<Beacon>,
                region: Region?
            ) {
                if (beacons.size > 0) {
                    println("I see ${beacons.size} beacons")
                    log += "The first beacon I see is about " + beacons.iterator().next().getDistance()
                     .toString() + " meters away."
                    log += "I see ${beacons.size} beacons.\n"
                    debugLog()
                }
                else
                {
                    println("I see 0 beacons")
                    log += "I see 0 beacons\n"
                    debugLog()
                }
            }
        })
        try {
            beaconManager.startRangingBeaconsInRegion(Region("myRangingUniqueId", null, null, null))
        } catch (e: RemoteException) {
        }

    }

Am I missing an element for it to range standard iBeacon BLE packets? Any help is appreciated.
Thanks

A: The most likely reasons are:

*

*Your route.route.uuid does not match the UUID of the transmitter.

*You didn't set the BeaconLayout if you are using iBeacon. (By default, the library only detects AltBeacon)

*You didn't obtain the required location permission from the user to be able to look for bluetooth beacons, causing the operating system to block detections.

I wrote a checklist to help troubleshoot problems like this.


text:
Q: Process unknown number of observables in RxJS pipe I make thousands of calls to my server but in order to avoid overloading, I have put in place a concurrency limit of 10 with RxJS:
const calls = new Subject();
calls.pipe(
    mergeAll(10)
).subscribe();

while(int < unknown_number){
    calls.next(new Observable((observer) => {
        // Call the server here
    }))
}

The problem is that I don't know how many calls will be made and I need to know when the job is done. One approach is to get when nothing is left in the queue for 5 seconds or so.
How can I do that?

A: After reading your comment, I think the answer lays in issuing a complete command against the Subject as soon as we know there is no more data to be read from the DB.
So, is a sort of pseudo-code, this could be the draft for the solution
// callToServer is a function that calls the server and returns an Observable
const callToServer: Observable<any> = (input) => httpClient.post(url, input);

const calls = new Subject<any>();
calls.pipe(
    // margeMap allows to set concurrency level as second parameter
    mergeMap(input => callToServer(input), 10)
).subscribe(
   {
      next: response => {
        // do something with the response
      },
      error: err => {
        // manage error occurrences
      },
      complete: () => {
        // here you come when the Subject completes
      }
   }
);

const cursor = db.readFromMyTable();

while(cursor has still data){
    const data = cursor.getNext(100);
    // for each record issue a next against the calls Subject
    data.forEach(d => calls.next(d));
}

// when there are no more records completes the calls Subject

A: After i read trough you comment of the flow, I think that you don't need merge map, as each new request will be after the previous one is completed, so i will suggest the following approach;

let {
  of,
  Subject
} = rxjs;
let {
  switchMap,
  delay,
  scan
} = rxjs.operators;

const db = [1, 2, 3, 4, 5, 6, 7];

const requester = new Subject();

const mockRequest = ({ page, items }) =>
  of(db.slice(page * items, (page + 1) * items)).pipe(delay(500));

const ITEMS_PER_PAGE = 2;
requester
  .pipe(
    switchMap(pageData => mockRequest(pageData)),
    scan(
      (acc, x) => {
        const newIdx = +acc[0] + 1;
        return [newIdx, x];
      },
      [0, []]
    )
  )
  .subscribe(([i, x]) => {
    if (x.length !== 0) {
      requester.next({ page: i, items: ITEMS_PER_PAGE });
      console.log(x);
    } else {
      console.log("Done and ready to unsubscribe");
    }
  });
requester.next({ page: 0, items: ITEMS_PER_PAGE });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>

(You can run the code snippet directly here or here stackBlitz)
The thing I'm doing here is calling the db while there items inside of it. In your case you should just call each time for 100 elements, while there are elements returned from the db.

A: Your don't really need to create your own streams, just:
Start with a subject that will call once:
const call$ = new BehaviorSubject(0);

call$.pipe(
    concatMap(call => {
        return callYourDatabase(call); // Pagination or whatever
    }),
    tap(res => {
        if (res) {
            call$.next(db); // Call again after completion if the previous has values
        }
    })
)


text:
Q: Operator overloading template parameter So I have a little class that implements a matrix. Everything works well, except whatever gave me the reason to post here. I've explained more about the problem in the actual code, using comments. Thanks in advance to anyone that can help! This is not the entire program, but it is big enough so that it can compile on its own.
#include <iostream>
#include <initializer_list>

template<class type_t, unsigned Rows, unsigned Columns>
class matrix
{
private:
    std::initializer_list<std::initializer_list<type_t>> elements;

public:
    type_t contents[Rows][Columns];

    matrix() {}

    matrix(const std::initializer_list<std::initializer_list<type_t>> &container)
        : elements(container)
    {
        unsigned i = 0;
        for (const auto &el : elements)
        {
            unsigned j = 0;
            for (const auto &num : el)
            {
                contents[i][j] = num;
                j++;
            }
            i++;
        }
    }

    unsigned rows() { return Rows; }
    unsigned columns() { return Columns; }

    type_t &operator()(const unsigned &i, const unsigned &j)
    {
        return contents[i][j];
    }

    template<unsigned rws, unsigned cls>
    auto operator*(matrix<type_t, rws, cls> &mat)
    {
        matrix<type_t, Rows, 3> ret_mat;  //OK, but only in case the return matrix has 3 columns
    matrix<type_t, Rows, mat.columns()> ret_mat; //Error. This is the desired result
                                //The error message tells me it needs to be a compile-time constant
                                //it's pretty obvious why the first works and what the problem is
                                //but i still have no idea how to get past this

        for (unsigned i = 0; i < this->rows(); ++i)
        {
            for (unsigned j = 0; j < mat.columns(); ++j)
            {
                for (unsigned in = 0; in < 2; ++in)
                    ret_mat.contents[i][j] += this->contents[i][in] * mat.contents[in][j];
            }
        }

        return ret_mat;
    }
};

int main()
{
    matrix<int, 4, 2> mat = { { 7, 3 },{ 2, 5 },{ 6, 8 },{ 9, 0 } };
    matrix<int, 2, 3> mat2 = { { 7, 4, 9 },{ 8, 1, 5 } };

    auto mat3 = mat * mat2;

    for (unsigned i = 0; i < mat3.rows(); ++i)
    {
        for (unsigned j = 0; j < mat3.columns(); ++j)
            std::cout << mat3(i, j) << " ";
        std::cout << std::endl;
    }
    std::cin.get();
}

A: template<unsigned rws, unsigned cls>

You already have desired expressions!
matrix<type_t, Rows, cls> ret;

Edit: as mentioned by @juanchopanza, why are you allowing multiplication of N*M on K*L with M != K? Should be
template<unsigned cls>

auto operator*(matrix<type_t, columns, cls> &mat)
{
    matrix<type_t, Rows, cls> ret_mat;


text:
Q: Write a pseudo code for a Graph algorithm Given a DAG  and a function  which maps every vertex to a unique number from 1 to , I need to write a pseudo code for an algorithm that finds for every  the minimal value of , among all vertices u that are reachable from v, and save it a an attribute of v. The time complexity of the algorithm needs to be  (assuming that time complexity of  is ).
I thought about using DFS (or a variation of it) and/or topological sort, but I don't know how to use it in order to solve this problem.
In addition, I need to think about an algorithm that gets an undirected graph and the function , and calculate the same thing for every vertex, and I don't know how to do it either.

A: Your idea of using DFS is right. Actually the function f(v) is only given for saying that each node can be uniquely identified from a number between 1 and |V|.
Just a hint for solving, you would have to modify DFS so that it returns the minimum value of f(v) of the vertex v reachable from this node and save it another array, let's say minReach and the index would be given by the function f(v). The visited array vis would similarly be identified using f(v).
I am also giving the pseudocode if you are not able to solve but try on your own first.
The pseudocode is similar to python and assuming the graph and function f(v) are available. And 0-based indexing is assumed.
vis=[0, 0, 0, .. |V| times]  # visited array for dfs
minReach= [1, 2, 3, .. |V| times] #  array for storing no. reachable nodes from a node

function dfs(node):
   vis[f(node)-1]=1                             ### mark unvisited node as visited
   for v in graph[node]:
       if vis[v]!=1:                            ## check whether adjacent node is visited
           minReach[f(node)-1]=min(minReach[f(node)-1],dfs(v)        ## if not visited apply dfs again
       else:
           minReach[f(node)-1]=min(minReach[f(node)-1],countReach[f(v)-1])   ## else store the minimum node that can be reached from this node.
   return countReach[f(node)-1]

for vertex in graph:         ### each vertex is checked in graph
   if vis[f(vertex)-1]!=1:   ### if vertex is not visited dfs is applied
      dfs(vertex)


text:
Q: Append characters to a string in multiple rows in Oracle SQL I'm trying to update a single column in multiple rows by appending the string '999':
UPDATE integration.ol_orders
SET order_id = ((SELECT order_id
             FROM   integration.ol_orders
             WHERE  status = 2) || '999')
WHERE status = 2

but for whatever reason, I keep getting the error of "ORA-01427: single-row subquery returns more than one row tips".
So, as I iterate my n rows, I'm trying to do:
a1 = a1 || '999'
a2 = a2 || '999'
a3 = a3 || '999'
an = an || '999'

Any suggestions how to go about this?
edit: changed '+' to '||', still no luck

A: The subquery looks unnecessary, just doing this should work:
UPDATE integration.ol_orders
SET order_id = order_id || '999'
WHERE status = 2

If I remember right Oracle uses || for concatenation. It might be necessary to cast the order_id to a character type if it's an integer, I'm not sure about that and can't test it at the moment. (The conversion should be implicit as stated in a comment, otherwise you can use TO_CHAR() to cast it explicitly).
Make sure to have a backup or copy of the table before running though...

A: We could use CONCAT function in Oracle SQL to tackle the issue and it seems cleaner.
UPDATE integration.ol_orders
SET order_id = CONCAT (order_id,'999')
WHERE status = 2;

Just for information:
There are two ways to concatenate Strings in Oracle SQL. Either using CONCAT function or || operator.
CONCAT function allows you to concatenate two strings together
SELECT CONCAT( string1, string2 ) FROM dual;

Since CONCAT function will only allow you to concatenate two values together. If you want to concatenate more values than two, you can nest multiple CONCAT function calls.
SELECT CONCAT(CONCAT('A', 'B'),'C') FROM dual;

An alternative to using the CONCAT function would be to use the || operator
SELECT 'My Name' || 'My Age' FROM dual;


text:
Q: 'Sqlite' Could not be found in windows phone 8 I am working on windows phone 8
Thy type or namespace name 'SqLite' could not be found (are you missing a using directive or an assembly reference?)
My process was

*

*I cloned git repo into my local.

*I added that c++ project (Sqlite) into my existing project.

*Than i added Sqlite-net ( SQLite.cs and SQLiteAsync.cs) into my project.

*Than created USE_WP8_NATIVE_SQLITE compilation symbol successfully.

But than i build my project it shows same error for three lines in "SQLite.cs" which are following.
using Sqlite3 = Sqlite.Sqlite3;
using Sqlite3DatabaseHandle = Sqlite.Database;
using Sqlite3Statement = Sqlite.Statement;

Please help me to solve this problem, my VS2012 is well configured and fulfilling the requirment for creation Sqlite DB into WP8.
Need Help, Thanks in advance.

A: I have successfully done, i was missing the one step that was adding sqlite existing project as a reference. So after completion all steps me have to add SQLite existing project as reference in my existing project.
it worked fine.
Thank you all.


text:
Q: R Regex for identifying UK postcodes My question is similar to this, but I'm looking for something R specific. I've got a data.frame of tens of thousands of addresses and need to pull out the postcodes. Postcodes are in the UK and formatted {LETTER_LETTER_DIGIT LETTER_LETTER_DIGIT}. Similar to the following:
"8, Longbow Close,\r\nHarlescott Lane,\r\nShrewsbury,\r\nEngland,\r\nSY1 3GZ"
I've used variations of this code with stringr to no avail:
str_extract('^(\\[Gg]\\[Ii]\\[Rr] 0\\[Aa]{2})|(((\\[A-Za-z]\\[0-9]{1,2})|((\\
[A-Za-z]\\[A-Ha-hJ-Yj-y]\\[0-9]{1,2})|((\\[AZa-z]\\[0-9]\\[A-Za-z])|(\\[A-Za-
z]\\[A-Ha-hJ-Yj-y]\\[0-9]?\\[A-Za-z]))))\\[0-9]\\[A-Za-z]{2})$',alfa$Address)

A: The ^ and $ anchors require the pattern to match the whole string. You may wrap the pattern with \b(?:<pattern>)\b to match those codes as whole words (\b is a word boundary). Besides, the character classes are "ruined" since you escaped their [ starting bracket (\[ matches literal [ chars). Also, swap the arguments, the first one is input, the second one is the regex. Also, to get all matches, you need to use str_extract_all rather than str_extract.
You may fix the code like this:
library(stringr)
txt <- "8, Longbow Close,\r\nHarlescott Lane,\r\nShrewsbury,\r\nEngland,\r\nSY1 3GZ"
pattern <- "\\b(?:([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2}))\\b"
str_extract_all(txt, pattern)
# => [[1]]
#   [1] "SY1 3GZ"

A: Here is a more readable way:
            if ($e{locate} =~ /\b([A-Z])([A-Z])([0-9])([A-Z]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6.$7;
                    $e{zips} = $1.$2.$3.$4.' ' .$5.$6.$7;
            } elsif ($e{locate} =~ /\b([A-Z])([0-9])([A-Z]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6;
                    $e{zips} = $1.$2.$3.' '.$4.$5.$6;
            } elsif ($e{locate} =~ /\b([A-Z])([0-9]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5;
                    $e{zips} = $1.$2.' '.$3.$4.$5;
            } elsif ($e{locate} =~ /\b([A-Z])([0-9])([0-9]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6;
                    $e{zips} = $1.$2.$3.' '.$4.$5.$6;
            } elsif ($e{locate} =~ /\b([A-Z])([A-Z])([0-9]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6;
                    $e{zips} = $1.$2.$3.' ' .$4.$5.$6;
            } elsif ($e{locate} =~ /\b([A-Z])([A-Z])([0-9])([0-9]) ([0-9])([A-Z])([A-Z])\b/) {
                    $e{zip} = $1.$2.$3.$4.$5.$6.$7;
                    $e{zips} = $1.$2.$3.$4.' '.$5.$6.$7;
            }


text: Q: How to copy HeaderFooterPolicy from one docx to another docx using Apache Poi I have to copy header footer from one docx to another docx without changing its format and page number. can anyone help? Thanks in advance


text:
Q: So I found and marked some bad clusters—now what? I don't know exactly why, but hard drive failure happens to me quite often. This time around, three out of my eight drives failed almost at the same time (two HDDs and one SSD).
I still don't know what the hell is wrong with the SSD, but CrystalDiskInfo showed the dreaded "Reallocated Sectors Count," "Current Pending Sector Count," and "Uncorrectable Sector Count" values as above threshold for both HDDs.
Sure enough, running chkdsk x: /b on one of the drives has resulted in 170 clusters being added to the Bad Clusters File. I'm scanning the other other right now (both drives are 3TB Seagates and it is taking forever).
My question is simply this: once I find and mark all the bad clusters with either chkdsk or SpinRite...what happens next? Do I happily go on using the drive, marking new clusters as they become bad? How do I find out the actual threshold for clusters that can be added to the Bad Clusters File for my drive? ...or should I just toss both (and the SSD) in the garbage right now?
I really don't understand why this is happening to me. I bought six identical 3TB drives at the same time. They have been powered on for roughly the same number of hours. They were all mostly used for storage...and yet only two out of the six developed bad clusters.

A: Generally once modern spinning HDD's start to show errors, they're on the way out and should be expected to die soon.
Only exception really is if you did something specific like drop a spinning HDD, and then bad sectors show up, the cause of the bad sectors is that specific event and not the drive "going bad."
If you are running eight drives in one system, you're drawing a lot of power.  Your bad luck could be caused by things like bad power supply or issues with the power reaching your system.  Try replacing your system's power supply with a new one of known good brand and higher wattage, and hook this computer up to a UPS or other power conditioner.  If your system is poorly ventilated or placed in a poorly ventilated area, that isn't helping.
Also, I'm sure with the advent of SSD's and fall in HDD prices they are not "making drives like they used to."
Regarding your SSD, try updating the firmware on it.


text:
Q: Parsing Values + removing garbage just started with a new project, and i need to extract the first value from a bunch of sequences like these
710:0:0:0:60:recym.wav
0:0:0:60:kick-1.wav
0:0:0:60:cymbal.wav
0:0:0:0:
1094:0:0:0:0:
1383:0:0:0:0:
1575:0:0:0:0:
1863:0:0:0:0:
2056:0:0:0:0:
2152:0:0:0:0:

i just need the first value of every row so i would want an output like 710, 0, 0, 0, 1094, 1383, 1575, 1863, 2056, 2152
first i tried to parse like this
int value = int.Parse(line);
which obviusly didn't work but i dont know how to remove the last bit. thanks for help!

A: looks like your lines are delimeted by :.  If this is always the case, split on :, then grab the first one and try to get an int out of it:
 foreach(var line  in lines)
 {
    var first = line.Split(':').FirstOrDefault();
    if(int.TryParse(first, out var number))
    {
        //do something with valid number
    }
 }


text:
Q: Are Apache Camel Mbeans extendable? I would like to add few more attributes to the existent JMX Apache Camel route attributes. Is there a way of doing this either using Spring or Java code?

A: And to answer your question. No the routes mbean are not extensible.
Though if you build custom components you can annotate your component with JMX annotations to have JMX operations and attributes enlisted out of the box. But this is only for components, and not the standard route, camelcontext, mbeans etc.
See details at: http://camel.apache.org/camel-jmx.html


text:
Q: PHP form image attachment not being recognized in if $_FILES['image'] is set I am trying to save the selected image's path after uploading to the database but it looks like on the if else code check it goes straight to else. but I need it to run the code inside the if
How can I get it to work?
Here's the code:
<form action="" method="POST" class="order">
                <fieldset id="field2">
                    <legend>Booking Details</legend>
                    <input type="text" name="full-name" placeholder="Your Full Name" class="input-responsive" required>
                    <input type="number" name="contact" placeholder="Your Phone Number" class="input-responsive" required>
                    <input type="email" name="email" placeholder="Email address" class="input-responsive" required>
                    <input type="text" name="address" placeholder="E.g. E.g. Erf 123, Abc St, Dorado Park, Windhoek" class="input-responsive" required>
                    Booking (Date and Time):
                    <input type="datetime-local" name="bdate">
                    Attach Proof of Payment (Image):
                    <input type="file" name="image">

                    <input type="submit" name="submit" value="Submit Booking" class="btn btn-primary">
                </fieldset>

</form>

<?php

                //CHeck whether submit button is clicked or not
                if(isset($_POST['submit']))
                {
                    // Get all the details from the form

                    $customer_name = $_POST['full-name'];
                    $customer_contact = $_POST['contact'];
                    $customer_email = $_POST['email'];
                    $customer_address = $_POST['address'];
                    $booking_date = $_POST['bdate'];

                    //2. Upload the Image if selected
                    //Check whether the select image is clicked or not and upload the image only if the image is selected
                    if(isset($_FILES['image']['name']))
                    {

                        //Get the details of the selected image
                        $pimage_name = $_FILES['image']['name'];

                        //Check Whether the Image is Selected or not and upload image only if selected
                        if($pimage_name !="")
                        {
                            // Image is SElected
                            //A. REnamge the Image
                            //Get the extension of selected image (jpg, png, gif, etc.)
                            $ext = end(explode('.', $pimage_name));

                            // Create New Name for Image
                            $pimage_name = "Payment-Proof-".rand(0000,9999).".".$ext; //New Image Name May Be "Payment-Proof-657.jpg"

                            //B. Upload the Image
                            //Get the Src Path and DEstinaton path

                            // Source path is the current location of the image
                            $src = $_FILES['image']['tmp_name'];

                            //Destination Path for the image to be uploaded
                            $dst = "../payments/".$pimage_name;

                            //Finally Uppload the food image
                            $upload = move_uploaded_file($src, $dst);

                            //check whether image uploaded of not
                            if($upload==false)
                            {
                                //Failed to Upload the image
                                //REdirect to Add Food Page with Error Message
                                $_SESSION['upload'] = "
Failed to Upload Image.
";
                                header('location:'.SITEURL.'mua.php');
                                //STop the process
                                die();
                            }

                        }

                    }
                    else
                    {
                        $pimage_name = ""; //SEtting DEfault Value as blank
                    }

                    //Save the Order in Databaase
                    //Create SQL to save the data
                    $sql2 = "INSERT INTO tbl_bookings SET
                        mua = '$title',
                        price = $price,
                        customer_name = '$customer_name',
                        customer_contact = '$customer_contact',
                        customer_email = '$customer_email',
                        customer_address = '$customer_address',
                        booking_date = '$booking_date',
                        payproof_name = '$pimage_name'
                    ";


text:
Q: Applying theme to site collection and all subsite underneath Issue using Powershell in SharePoint 2013 Getting error while applying theme to site collection and all subsite underneath Issue using Powershell in SharePoint 2013
Below is the code
$themeName = "PaletteTheme"
$SPSite = Get-SPSite "http://SP2013"
$i=0;
$r =  $SPSite.Url + "/_catalogs/theme/15/PaletteThemeVal.spcolor"

foreach ($SPWeb in $SPSite.AllWebs)
{
        Write-Host "SP--Web" + $SPWeb.Url
    $colorfile = $SPWeb.GetFile($r)
    Write-Host $colorfile
        $theme=[Microsoft.SharePoint.Utilities.SPTheme]::Open($themeName, $colorfile);
        Write-Host $theme
        Write-Host $theme.Name "to" $SPWeb.Title;
        $theme.ApplyTo($SPWeb, $false);
}

The theme is getting appied to the root site collection but not to the subsites under neath it.
Below is the error i am getting

A: In the below line of code, you are trying to fetch the colorfile from the sub web but it's not in the sub web; it's in the root web, that's why it works fine in the root web, but fails in other webs.
 $colorfile = $SPWeb.GetFile($r)

Try using the below code and logic,
Add-PSSnapin Microsoft.SharePoint.PowerShell

$themeName = "PaletteTheme"
$SPSite = Get-SPSite "http://SP2013"
$r =  $SPSite.Url + "/_catalogs/theme/15/palette005.spcolor"
$rootwebFile = $SPSite.rootweb.GetFile($r)

foreach ($SPWeb in $SPSite.AllWebs)
{
    Write-Host "SP--Web" + $SPWeb.Url
    Write-Host $colorfile
    $theme=[Microsoft.SharePoint.Utilities.SPTheme]::Open($themeName, $rootwebFile);
    Write-Host $theme
    Write-Host $theme.Name "to" $SPWeb.Title;
    $theme.ApplyTo($SPWeb, $false);
}

Remove-PSSnapin Microsoft.SharePoint.PowerShell


text:
Q: TypeScript - wait for the function to complete until executing the next function I have two functions: doAsyncStuff and doNextStep.
How can I secure doNextStep to be executed only after doAsyncStuff is finished?
I tried something like that but it didn't help: doAsyncStuff().then(_ => doNextStep());
async function doAsyncStuff() {
    if (vscode.workspace.workspaceFolders) {
        vscode.workspace.workspaceFolders.forEach(async (e) => {
            for (const [name, type] of await vscode.workspace.fs.readDirectory(e.uri)) {
                console.log(name);
            }
        });

    }
    return true;
}

function doNextStep() {
    console.log('next step');
}

A: Thanks a lot for your replies, the solution of hotcakedev works out of the box.
Promise.all(vscode.workspace.workspaceFolders.map(async ... await))
And this is how it looks like (resulting scenario uses async recursive function 'readFolders', which is also working well):
        await Promise.all(vscode.workspace.workspaceFolders.map(async x => {

            for (const [name, type] of await vscode.workspace.fs.readDirectory(x.uri)) {
               console.log(name);
            }
            // await readFolders(x.uri,x.uri.path);

        }));

        console.log('fin');


text:
Q: Copy column details from DataGridViewSelectedRowCollection I've got a DataGridView which is bound to a DataSet being returned by an unknown-at-design-time SQL query (well, I know what the queries are, I just don't know which one the user has selected).
I allow the user to select a set of rows from the table and hit an OK button, and I would then like to copy those rows to a new DataGridView.
Naively, I used code along the lines of:
DataGridView_New.DataSource = DataGridView_Old.SelectedRows

This gives me a number of rows in my new DataGridView equal to the number of rows in SelectedRows, but the columns are not the columns from the SQL query (as they were in DataGridView_Old); they are, instead, the Row properties of each of the individual rows (DefaultCellStyle, Resizable, ReadOnly, etc.).
Is there any quick and easy way to simply grab the column data from DataGridView_Old and copy the selected rows into DataGridView_New?

A: Here's a simple method that might do what you need:
private void CopySelectedRows(DataGridView sourceDGV, DataGridView destDGV) {
    // Clean up any previous runs.
    destDGV.DataSource = null;
    destDGV.Columns.Clear();

    // Populate the destination DGV with the same columns found in the source DGV.
    foreach (DataGridViewColumn col in sourceDGV.Columns) {
        destDGV.Columns.Add(col.Clone() as DataGridViewColumn);
    }

    // Create a DataTable that has the same structure as the source DGV's DataSource DataTable.
    DataTable table = ((DataTable)sourceDGV.DataSource).Clone();
    // Use the data bound to the selected rows in the source DGV to create rows in your DataTable.
    foreach (DataGridViewRow row in sourceDGV.Rows) {
        if (row.Selected) {
            table.Rows.Add(((DataRowView)row.DataBoundItem).Row.ItemArray);
        }
    }

    destDGV.DataSource = table;
}

My first impulse was to loop through the source DGV's SelectedRows collection but these are ordered as the user selected the rows, not necessarily the same as the displayed order.
foreach (DataGridViewRow row in sourceDGV.SelectedRows) {
    table.Rows.Add(((DataRowView)row.DataBoundItem).Row.ItemArray);
}

A: I'm not sure if it will work with DataSets, but you could try using the DataBoundItem property of each selected row to populate the new grid, something like:
public void Populate()
    {
        var selectedRows = GetRows(DataGridView_Old.SelectedRows);
        DataGridView_New.DataSource = selectedRows
                                      .Select(r => r.DataBoundItem).ToList();
    }

    public IEnumerable<DataGridViewRow> GetRows(DataGridViewSelectedRowCollection rows)
    {
        foreach (DataGridViewRow row in rows)
        {
            yield return row;
        }
    }


text:
Q: Why is my '+' operator considered as a new line character? The following code is for a modular calculator problem. The input data is:

 5
+3
* 7
+10
* 2
* 3
+1
% 11

#include <stdio.h>

int main(void) {
    char oper;
    int number,result;
    scanf("%d",&number);
    result=number;
    do
    {
        oper=getchar();
        fflush(stdin);
        scanf("%d",&number);
        if(oper=='+')
        {
            result=result+number;
        }
        else if(oper=='*')
        {
            result=result*number;
        }
        printf("%c %d %d ",oper,number,result);
    }while(oper!='%');
    result=result%number;
    printf("%d",result);
    return 0;
}

The output I get is as follows:
3 5
 3 5 * 7 35
 10 35
 10 35 * 2 70
 2 70 * 3 210
 1 210
 1 210 % 11 210 1

I can't seem to figure out why?

A: replace
oper=getchar();
fflush(stdin);
scanf("%d",&number);

with
scanf(" %c", &oper);
scanf("%d", &number);

A: If you write scanf(" %c", &operator), the space before the %c in " %c" will consume any number of whitespace characters before reading a single character.
Also, scanf will return EOF on a matching failure. You can use that as the condition for your while loop.
One more suggestion: before performing an operation, store the result in a previous variable so that you can print the value before and after the operation. This will result in user-friendly output.
#include <stdio.h>

int main(void) {
  char operator;
  int number, previous, result;
  scanf("%d", &number);
  result = number;
  while (scanf(" %c", &operator) != EOF) {
    previous = result;
    scanf("%d", &number);
    if (operator == '+') {
      result += number;
    } else if (operator == '-') {
      result -= number;
    } else if (operator == '*') {
      result *= number;
    } else if (operator == '/') {
      result /= number;
    } else if (operator == '%') {
      result %= number;
    }
    printf("%d %c %d = %d\n", previous, operator, number, result);
  }
  return 0;
}

A: In general, I find it better to use fgets() than scanf()/getchar() (alternatively, if you are using C99, gets_s() -- although I still prefer fgets() for maximum portability to older compiler environments) for all user-based input, then if necessary use sscanf(), strtol() (and the like) to convert the string into other data types, as this will read data by line in a way that is buffer-safe and you won't have to worry about things left in the input buffer. This is especially true for user-based input which is never well-formed (due to typos, etc). scanf() really only works well when reading from well-formed input files.
With that in mind, I'd would write the code more like this:
#include <stdio.h>

int main(void) {
  char buf[80];
  char oper;
  int number,result;
  fgets(buf, sizeof(buf), stdin);
  sscanf(buf, "%d",&number);
  printf("   saw input: %d\n", number );
  result=number;
  do
  {
    fgets(buf, sizeof(buf), stdin);
    sscanf(buf, "%c %d",&oper, &number);
    printf("   saw input: %c %d\n", oper, number );
    printf("   computing: %d %c %d\n", result, oper, number );
    if(oper=='+') {
      result=result+number;
    }
    else if(oper=='*') {
      result=result*number;
    }
    else if(oper=='%') {
      result=result%number;
    }
    printf("   result   : %d\n", result );
  } while( oper!='%' );
return 0;
}


text:
Q: Is there a way to save a Treeview's items and data so it can be accessed in a thread? A TreeView item and data holds a filename and the data holds a TBitmap.  My question pertains to somehow saving the items and the data in the treeview so the items and data can be accessed in a thread.   If this is possible, after saving items and data, I could access the items and data in the thread rather than accessing it in Synchronize. As the code written now is too slow because of accessing the GUI TreeItems and Data in Synchronize.
if not Terminated then
begin
   Synchronize(
   procedure
   var
     i: integer;
   begin
     for i := 1 to Form1.TreeView1.Items.Count - 1 do
     begin
        { get the bitmap }
        iImageEnIO.WIAParams.ProcessingBitmap := iImageEnIO.IEBitmap;
        { The following line prevents me from accessing the TreeView data in a thread }
        iImageEnIO.WIAParams.Transfer(TIEWiaItem(Form1.TreeView1.Items[i].Data), False);
        { Set the filename }
        iFilename := Form1.TreeView1.Items[i].Text + '.jpg';
        { Add the image to the iIEImageList }
        iIndex := iIEImageList.AppendImageRef(TIEBitmap.Create(iImageEnIO.IEBitmap), iFileName);
        iIEImageList.Filename[iIndex] := iFileName;
     end;
end);

The threads code to access the bitmaps in the thread itself works very well, but if I can move the code that gets the bitmap to the thread rather than in Synchronize would be much better.  So my question is "Is there ay way to save a treeview items and data in Synchronize so it can be accessed in the thread outside of Synchronize"?
    iImageEnIO.OnProgress := ImageEnProcProgress;
    iImageEnIO.OnFinishWork := ImageEnProcFinishWork;

    { Get the bitmap from the imagelist and save the image in the thread }
    iCount := iIEImageList.ImageCount;
    for j := 0 to iCount-1 do
       begin
         { get the filename from the string list }
         iFilename := iIEImageList.Filename[j];
         { attach the iIEBitmap2 to iImageEnIO }
         iImageEnIO.AttachedIEBitmap := iIEImageList.Image[j];
         iPath := IncludeTrailingPathDelimiter(iFolder) + iFilename;
         iImageEnIO.SaveToFile(iPath);
      end;

I hope I have asked my question correctly and it is clear what I would like to try to do.

A: I would like to turn this on its head. You want to know how to read the data from the GUI control when executing your thread method. That is a fundamental design flaw. The solution to your problem will involve not attempting to do that at all.
The tree view should not be the owner of the data. It is a GUI control and should merely present a view of the data. The data should be held in a structure that is not bound to the VCL threading rules. Once you have the data structure separated from the GUI, your problem becomes trivial. Once you reach that point, there is no problem to be solved.
So, what kind of a structure do you need? Although it is stored in a tree view, it appears to be a flat list. Store it in a TList<T> container. What do you use for T? Well, that's just the information needed for each item. That could be a record. Or it could be a class. If you are holding non-value type objects in the item type, then a class is probably better. In which case TObjectList<T> is a better fit. So, it would look like this:
type
  TItem = class
  private
    FFileName: string;
    FBitmap: TBitmap;
  end;

Then your container is simply TObjectList<TItem>. Instantiate it like this:
FItems := TObjectList<TItem>.Create(True);

The True is for the OwnsObjects parameter. This means that when you delete items from the container, or delete the container, the items are destroyed.
At this point you are able to populate the tree view by iterating over the container, and creating nodes to represent the items.
Then when your thread needs to operate on the data, it can refer to FItems which is separated from the GUI control.
The moral of the story is that you should not use your GUI controls as your primary data containers.


text:
Q: How to create a mysql "sha-256" column? For a password column, is there a mysql feature to store password hashed with "sha-256"? Or should I hash it from java code (like How to hash some string with sha256 in Java? ) before I store it in database and then hash the password input every time and compare with the database column value to authenticate?
TIA.

A: You can convert the value to hex and use a char(n) column with the appropriate length - 64 in this case. The conversion can be done in MySQL by using the sha2 function with hash_length set to 256.
But for security reasons you should not store passwords hashed using SHA-256.
Instead use bcrypt or PBKDF2.
Related

*

*How can I hash a password in Java?


text:
Q: WordPress: Cron locking and Queue I have some CPU intensive scripts that I don't want to run concurrently. Every now and again the scripts will overlap and crash the server. Already at 2GB and the mysql container still crashes.
I have a crontab setup to hit example.com/cron.php?do_cron=randstr every 15 minutes.
Is there any way to place a lock and only execute one cron task at a time? When it's done, the next one would then run.
I know this can be accomplished using PHP's file locking mechanism (but then it doesn't queue the next task). Not sure if WP does this on its own.
All help appreciated!

A: Simple Cronjob Walker

*

*Create a CPT cronjob for your cronjobs.

*Add the relevant post meta data (action, last_executed,… and whatever you need)

*Create a walker function
function my_cronjob_walker() {
    $args= array(
        'post_type' => 'cronjob',
        'posts_per_page' => 1,
        'meta_key' => 'last_executed'
        'orderby' => 'meta_value',
    );
    $cronjob = new WP_Query($args);
    if ($cronjob->have_posts()) while ($cronjob->have_posts()) {
        $cronjob->the_post();
        // do your cronjob stuff here
        do_action(get_post_meta(get_the_ID(), 'action', true);
        update_post_meta(get_the_ID(), 'last_executed', date('c'));
    }
}
if ( ! wp_next_scheduled( 'do_cronjob_walker' ) ) {
    wp_schedule_event( time(), 'hourly', 'do_cronjob_walker' );
}

add_action( 'do_cronjob_walker', 'my_cronjob_walker' );


text:
Q: Magento 2 : Why my module is on the vendor and app folder? I use these commands to install my dependencies today:
composer config repositories.myvendor_cli vcs git@github.com:myvendor/my-cli.git
composer require myvendor/cli:dev-master

To work well I ever need to add the parameter "no-api": true,
The result in my composer it's like that:
...
    "magento/module-offline-shipping-sample-data": "100.1.*",
    "myvendor/cli": "dev-master"
},
...
"repositories": {
    "0": {
        "type": "composer",
        "url": "https://repo.magento.com/"
    },
    "myvendor_cli": {
        "type": "vcs",
        "url": "https://github.com/myvendor/extension-cli.git",
        "no-api": true
    }
},
...

When I run the composer update I see the module installed in two folders:
app/code/MyVendor/CLI/
vendor/MyVendor/CLI/

The Magento doesn't permit the same installation on both folders, how can I set to install just to vendor folder?


text:
Q: How to place file in app directory via USB I'm writing an app that reads from a local file
...
    File fXmlFile = new File(file);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
...

I want to place the file into the app's directory so I can commence testing. Outputting the exception I find out that java.io.FileNotFoundException /data/data/com.blablabla.myApp/files/sample_file.xml: open failed. ENOENT (no such file or directory).
I'm confused as to where to find the directory /data/data/... I've connected the phone via USB and did find the /Android and /data directories. I've created my directory com.blablabla.myApp/files/ and added my sample_file.xml there but I continue getting the error.
What am I doing wrong? Any help is appreciated.

A: I tried looking for the file on internal storgage. Turns out that anything I can see when connected via USB/MTP protocol is the external storage. As such, I was unable to place the file where my read statement would find it. Making an adjustment where the app looks for the file made the difference.


text:
Q: MySQL query with DATE() function on LocalDateTime field I have a query like this:
@Query("SELECT rhwp.pk.reservation FROM ReservationHasWorkingPlace rhwp WHERE rhwp.pk.workingPlace.idWorkingPlace = ?1 AND NOT (DATE(rhwp.pk.reservation.endDateTime) < ?2 OR DATE(rhwp.pk.reservation.startDateTime) > ?3)")
List<Reservation> getReservationsForWPAndDateInterval(Integer idWorkingPlace, LocalDate startDate, LocalDate endDate);

where I compare a DateTime stored into database with the localDate passed through the java method.
I receive this exception:
Caused by: java.lang.IllegalArgumentException: Parameter value [2018-04-20] did not match expected type [java.util.Date (n/a)]

There is a way to configure hibernate/jpa to make this conversion automatically or I have to pass a Date object instead LocalDate?
I have tried importing even hibernate-java8 but no changed
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>${hibernate.version}</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-java8</artifactId>
    <version>${hibernate.version}</version>
</dependency>

A: You can simply use @Converter. Example with converting LocalDateTime to Timestamp:
@Converter
public class SomeConverterName implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(final LocalDateTime locDateTime) {
        return Timestamp.valueOf(locDateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(final Timestamp sqlTimestamp) {
        return sqlTimestamp.toLocalDateTime();
    }
}

And then on the entity field use:
@Column(name = "somefield")
@Convert(converter = SomeConverterName.class)
private LocalDateTime someDate;

A: converting with Using java.sql.Date.valueOf(start) works


text:
Q: @Url.Action and JavaScript I want @Url.Action() to redirect to a method of a controller with parameters that will be used in a JavaScript function.
The parameters are two, id = item.LevelId, that I take it from the foreach of the table, and the second one is annoLectivoId = "parm1". I need that annoLectivoId have the value of the variable Anno, from JavaScript.
I've tried this.href = this.href.replace(3, Anno); but it doesn't worked.
 <a href="@Url.Action("ChangeStatus", "Enroll_Student", new { id = item.LevelId, annoLectivoId = 3 })"
    title="ver detalle" style="color:red"
    onclick="FunctionCall()">
   detalle
 </a>

JavaScript:
function FunctionCall() {
    var Anno = document.getElementById("AnnoLectivoId").value;

    this.href = this.href.replace(3, Anno);
}


text:
Q: Android: Creating options menu before it's called I'm having trouble creating an options menu before I press the menu button. From what I can tell, onCreateOptionsMenu() is called when I press my menu button and the menu is then created. I need to access the menu before my menu button is pressed.
I got the usual so far. An onCreateOptionsMenu() below.
public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

A: You're really thinking about this the wrong way. If you need to "call a certain menu item in the Activity", just perform the function that the menu item would perform, don't try to programmatically "press" the menu item.
That is, if the menu option calls finish() on the Activity when pressed, simply call finish() instead of trying to virtually "press" a menu item.


text:
Q: Comparing non null-terminated char arrays I have a compressed unsigned char array of a known size. Due to compression considiration I don't store the null-terminator at the end. I want to compare it to another array of the same format.  What
would be the best way to do so?
I thought duplicating the comparessed arrays to a new array, add the null-terminator, and then compare them using strcmp().
Any better suggestions?

A: you can use strncmp() function from string.h
strncmp(str1, str2, size_of_your_string);

Here you can manually give the size of string(or the number of characters that you want to compare). strlen() may not work to get the length of your string because your strings are not terminated with the NUL character.
UPDATE:
see the code for comparison of unsigned char array
#include<stdio.h>
#include<string.h>
main()
{

unsigned char str[]="gangadhar", str1[]="ganga";
if(!strncmp(str,str1,5))
printf("first five charcters of str and str1 are same\n");
else
printf("Not same\n");

}

A: Since you know the size of the array, you could use strncmp():
int strncmp (char *string1, char *string2, int n)

with n being the number of characters to compare.
Deets: http://www.tutorialspoint.com/ansi_c/c_strncmp.htm

A: two years later, but...
I believe 'memcmp' is the function you want to use, since 'strncmp' may stop if it found a zero byte inside the compression string.


text:
Q: Stop a form load based on the return data from an ajax callback Hello I am working with an ajax post function, where I send data and my callback from PHP returns some data back. Based on the data returned I make the decision, either to go forward or allow the user to stay on the page and make changes.
        if (validateStep(step))
        {
        if(step==1)
        {
            var data = document.getElementById('hiddenContact').value;
            $.post('/app/controller/action', {'data':data}, function(returndata){if(returndata.match('not Unique'))alert('Contact source already exists'); else if(returndata.match('not posted')){alert("Not posted to the database");return false;}});
        }
        step = step + 1;
        form[0].action = '/app/controller/index/step:'+step;
        document.getElementById('step').value = step;
        form[0].submit();
        }

Here I am trying to stop the application going ahead when the return data is matched to "not posted", and I am throwing an alert and then a return false to stop the operation. I am unable to stop the application from going to next step though. Though it is returned false, the operation continues to the next step, but when I comment the last 4 lines which increment the step, set the action and submit, it stays on the page and the alert is thrown.
Does anybody know what I should do in order halt my process from submission??

A: AJAX calls are asynchronous. The "false" you are returning is on the success callback, not on the handler you have shown there. So the last four steps always execute, before the AJAX call even reaches the server. You can fix this by changing ajax response callback to deal with this, like so:
if (validateStep(step))
{
    var next_step = function() {
        step = step + 1;
        form[0].action = '/app/controller/index/step:'+step;
        document.getElementById('step').value = step;
        form[0].submit();
    }

    if(step==1)
    {
        var data = document.getElementById('hiddenContact').value;
        $.post('/app/controller/action', { 'data':data }, function(returndata) {
            if (returndata.match('not Unique')) alert('Contact source already exists');
            else if (returndata.match('not posted')) alert("Not posted to the database");
            else next_step();
        });
    }
    else next_step();
}

A: your process to continue to the next step is outside of your IF statement and will always run.
can you not do this:
    if (validateStep(step))
    {
        if(step==1)
        {
            var data = document.getElementById('hiddenContact').value;
            $.post('/app/controller/action', {'data':data}, function(returndata){
                if(returndata.match('not Unique')) {
                    alert('Contact source already exists');

                    step = step + 1;
                    form[0].action = '/app/controller/index/step:'+step;
                    document.getElementById('step').value = step;
                    form[0].submit();

                } else if (returndata.match('not posted')){
                    alert("Not posted to the database");
                    return false;
                }
            });
        }
    }


text:
Q: Unable to configure Sendmail to use Gmail I gave configured sendmail to use gmail. This is the output which I get but i am not getting the mail. what may be the problem
prashanth@prashanth-laptop:~$ sendmail -v *********.*******@gmail.com < test.mail
WARNING: local host name (prashanth-laptop) is not qualified; see cf/README: WHO AM I?
*********.*******@gmail.com... Connecting to [127.0.0.1] via relay...
220 prashanth-laptop ESMTP Sendmail 8.14.3/8.14.3/Debian-9.1ubuntu1; Fri, 2 Sep 2011 12:31:15 +0530; (No UCE/UBE) logging access from: localhost(OK)-localhost [127.0.0.1]
>>> EHLO prashanth-laptop
250-prashanth-laptop Hello localhost [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-EXPN
250-VERB
250-8BITMIME
250-SIZE
250-DSN
2    50-ETRN
250-DELIVERBY
250 HELP
>>> VERB
250 2.0.0 Verbose mode
>>> MAIL From:<prashanth@prashanth-laptop> SIZE=45
250 2.1.0 <prashanth@prashanth-laptop>... Sender ok
>>> RCPT To:<*********.*******@gmail.com>
>>> DATA
250 2.1.5 <*********.*******@gmail.com>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
050 <*********.*******@gmail.com>... Connecting to smtp.gmail.com port 587 via relay...
050 220 mx.google.com ESMTP e3sm8203378pbi.7
050 >>> EHLO prashanth-laptop
050 250-mx.google.com at your service, [117.197.206.85]
050 250-SIZE 35882577
050 250-8BITMIME
050 250-STARTTLS
050 250 ENHANCEDSTATUSCODES
050 >>> STARTTLS
050 220 2.0.0 Ready to start TLS
050 >>> EHLO prashanth-laptop
050 250-mx.google.com at your service, [117.197.206.85]
0    50 250-SIZE 35882577
050 250-8BITMIME
050 250-AUTH LOGIN PLAIN XOAUTH
050 250 ENHANCEDSTATUSCODES
050 >>> MAIL From:<prashanth@prashanth-laptop> SIZE=353
050 530-5.5.1 Authentication Required. Learn more at
050 530 5.5.1 http://mail.google.com/support/bin/answer.py?answer=14257 e3sm8203378pbi.7
050 <prashanth@prashanth-laptop>... Connecting to local...
050 <prashanth@prashanth-laptop>... Sent
250 2.0.0 p8271FSG017551 Message accepted for delivery
*********.*******@gmail.com... Sent (p8271FSG017551 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 prashanth-laptop closing connection

A: You are attempting to use port 587 but you are not authenticating.
Do you understand the warning and error messages? You will also need to have the FQDN added to your outgoing mail.
Is there a particular reason you are using Sendmail? I would recommend Postfix if you do not have strong reasons to stick with Sendmail.


text:
Q: Is there a .NET class for hotkeys that can be matched against incoming KeyEventArgs? Basically I have run-time loaded class that looks like this:
[Plugin("Plugin name")]
class PluginActions
{
  [Action("Flip Normals")
  public void FlipNormals()
  {
    // code ....
  }

  [Action("Export .X object")
  public void ExportX()
  {
    // code ....
  }
}

This basically adds buttons to the form with the onClick eventhandlers set up.
Now I would like to specify HOTKEYs in the same style using attributes:
[Plugin("Plugin name")]
class PluginActions
{
  [Action("Flip Normals", Hotkey = "Ctrl+N")
  public void FlipNormals()
  {
    // code ....
  }

  [Action("Export .X object", Hotkey = "Ctrl+E")
  public void ExportX()
  {
    // code ....
  }
}

The question is, how to represent and capture the hotkeys? As strings? Is there perhaps a class for that?
void Form_KeyDown(object sender, KeyEventArgs e)
{
  // reflection magic ...

  foreach(var action in actionAttributes)
  {
    string action_hotkey = action.hotkey;

    /**** How to match KeyEventArgs against action_hotkey? ****/
  }
}

Is there a .net helper class for dealing with hotkeys?
Or do i have to roll out my own hotkey class of some kind?
What is the correct approach here?

A: KeyEventArgs contains KeyData property, which is of value Keys, which is a flag, meaning that it can be this:
Keys keys = Keys.Control | Keys.F; (your hotkey)
If you define your hotkeys (atribute) this way (not with string) you can then compare the Keys instead of strings.

A: There is the Keys enumeration in the System.Windows.Forms namespace. Then for hotkey Ctrl+A  you can write something like this:
public class Action : Attribute {
  public Keys HotKey {get;set;}
}

[Action(HotKey = (Keys.Control | Keys.A))]
public void MyMethod() {
  ...
}


text:
Q: Jquery Accodion Expand All & Collapse All I have a Jquery Accodion and i need toggle button for Exapnd all accodion & collapse all accodion.When i try like this but it's not working.. i have tried several possible options while search the internet ..
HTML

    Expand all

    1st accodion

    2 nd accodion

Jquery
$(document).ready(function () {

// Expand/Collapse all

    $('.accordion-expand-all a').click(function () {
        $('#accordion .ui-accordion-header:not(.ui-state-active)').next().slideToggle();
        $(this).text($(this).text() == 'Expand all' ? 'Collapse all' : 'Expand all');
        $(this).toggleClass('collapse');
        return false;

});

can anyone give me solution for this.


text:
Q: Transform sparse matrix to tensor I have a pandas dataframe Object, containing a column with a bag of words representation of text stored as 29881x23947 sparse matrix of type ''. The column was processed by using sklearn and the fit_transform() function.
I now want to tranform this Colum into a 2D Tensor with the convert_to_tensor() function.
x_train_tensor = tf.convert_to_tensor(x_train)

Getting the error Message:

TypeError: Expected binary or unicode string

Which Format is required to Transform my Matrix into a Tensor?
Edit:
printing out the type of the column it says:
<class 'scipy.sparse.csr.csr_matrix'>

Example of the dataframe as output:
0          (0, 6276)\t1\n  (0, 8209)\t1\n  (0, 14299)\t...
1          (0, 6276)\t1\n  (0, 8209)\t1\n  (0, 14299)\t...
2          (0, 6276)\t1\n  (0, 8209)\t1\n  (0, 14299)\t...
3          (0, 6276)\t1\n  (0, 8209)\t1\n  (0, 14299)\t...

A: Here is an example of converting a sparse scipy matrix to tensorflow dense format.
Input sparse scipy matrix
A = np.array([[1,2,0],[0,0,3],[4,0,0]])
sA = sparse.csr_matrix(A)

print (sA)
# (0, 0)    1
# (0, 1)    2
# (1, 2)    3
# (2, 0)    4

idx, idy, val = sparse.find(sA)

print(idx, idy, val)
#[0 2 0 1] [0 0 1 2] [1 4 2 3]

To tensorflow
#merge idx and idy array to convert to [idx, idy] matrix
full_indices = tf.stack([idx, idy], axis=1)

#Output matrix size
depth_x = 3
depth_y = 3

# sparse to dense matrix
dense = tf.sparse_to_dense(full_indices,tf.constant([depth_x,depth_y]), val, validate_indices=False)

with tf.Session() as sess:
   print(sess.run(dense))
#[[1 2 0]
# [0 0 3]
# [4 0 0]]


text:
Q: How can I hide a hard coded username and password from a savvy user with a decompiler? I want to create a simple C# application that uploads a text file to my web server. But to do this I need to have my username and password included in the code. I've tried using the obfuscator that's included in Visual Studio, but after decompiling with a free decompiler I was still able to find them.
Is this possible?
Thanks!

A: Perhaps you need to rethink the fundamentals here

*

*You can never secure a platform that attackers have physical access to

*You want to achieve a situation, whereby your users, on their own platform, can submit a text file to your server, but only using your application. Even using SSL, this gets tricky since they can always monitor the HTTP communication

*You can never trust anything that comes from the internet. Yes, that includes your text file too.

What you should do instead, is configuring the server so that regardless on what is being sent to it, it does not affect your business case.
What are you using that username/password for?

A: Put it this way - if the username and password reside on the user's computer, and some program has to operate on that data in unencrypted form at some point, it is logically impossible to guarantee they are unable to view it. So the answer is no. It's a logical impossibility.
Perhaps you could create a separate user on your web server with very restricted permissions and use that instead? Then you'd have less to worry about if the user was able to retrieve the credentials from your application.

A: No.
The only way to prevent users from decompiling your code, and seeing everything in it, is not to give them your code, i.e., put the code on a server (under your control) instead of the client.
Consider writing something server-side (WCF endpoint, REST service, or something similar) that lets them send the content via something like an HTTP POST, with no authentication required. Then there's no password to crack, but your server-side code is in full control of what happens to the content that gets sent.

A: No.  You could encrypt them, but you'll need to get a decryption key from somewhere, and its likely that someone determined enough will be able to decompile your code and figure out where that key is.
I suppose you might be able to have a web request that returns a one time username and password.. so your application would call that, get the user / pwd and use it to upload.  Once used, you'd need a way to disable / delete that account.
More details might lead to an answer that's more likely to work for you, as maybe my solution is too much for what your concerns are.

A: Does it need to be in the source code?  If this only needs to run on your computer when you're logged in you could store the password in a file and protect it with file permissions.

A: What kind of access are you talking about ?
If user and password is required to make the upload, then it will ultimately be accessible in the code, and even easier, using a proxy / network listening tool.
Would it be possible to create a specific user for your application that has only upload capability (not reading any other's files, etc.) ?

A: You cant rely on code to safely and securely store credentials. You should consider passing the user name and password into your program as parameters and rely on the appropriate operating system security (e.g. windows security) to prevent users from accessing them.
If you are in an environment where you cannot control the windows credentials, you should consider a server side authorization over a secure connection like SSL.


text:
Q: Python script running from SCONS cannot access environment variables Inside of my scons script I execute another python script:
fs = env.Command('fs', None, 'python updatefs.py')
AlwaysBuild(fs)
Depends(fs,  main)

In python script I am trying to access an environment variable:
import os
mode = os.environ['PROC_MODE']

The variable was previously set up in the shell:
export PROC_MODE='some_mode'

Python complain:
KeyError: 'PROC_MODE'

What is the proper way to propagate environment to an external script?

A: This is covered in lightly in the FAQ:
FAQ
Basically SCons constructs a clean reproducible set of environment variables so that differences in any user's environment won't break a build.
So if you want to propagate a particular variable from your shell you can explicitly do it as such:
env['ENV']['MY_VARIABLE']=os.environ['MY_VARIABLE']

If you wanted to progagate all environment variables you'd do this:
env['ENV'] = os.environ

Where env is your Environment()


text:
Q: Python syntax checkers (Pylint, Prospector...) crashing with KeyError: 'repoze.who' when run from inside Vim I'm having a problem with running pylint from inside vim (which you need to do if you are using the syntastic plugin).
For example :!pylint --version crashes with this traceback:
Traceback (most recent call last):
  File "/home/seanh/.virtualenvs/ckan/bin/pylint", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/home/seanh/.virtualenvs/ckan/lib/python2.7/site-packages/pkg_resources.py", line 2736, in <module>
    add_activation_listener(lambda dist: dist.activate())
  File "/home/seanh/.virtualenvs/ckan/lib/python2.7/site-packages/pkg_resources.py", line 698, in subscribe
    callback(dist)
  File "/home/seanh/.virtualenvs/ckan/lib/python2.7/site-packages/pkg_resources.py", line 2736, in <lambda>
    add_activation_listener(lambda dist: dist.activate())
  File "/home/seanh/.virtualenvs/ckan/lib/python2.7/site-packages/pkg_resources.py", line 2274, in activate
    list(map(declare_namespace, self._get_metadata('namespace_packages.txt')))
  File "/home/seanh/.virtualenvs/ckan/lib/python2.7/site-packages/pkg_resources.py", line 1870, in declare_namespace
    path = sys.modules[parent].__path__
KeyError: 'repoze.who'

I've also seen the same error prospector running inside Vim.
But I cannot reproduce the error from outside of Vim. In a shell. If I activate my Python virtual environment in a shell then run pylint --version I get:
$ pylint --version
Warning: option include-ids is deprecated and ignored.
Warning: option symbols is deprecated and ignored.
pylint 1.3.1,
astroid 1.2.1, common 0.62.1
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2]

If I then run vim in the same shell and do :!pylint --version in Vim I get the traceback above. Quit Vim and run pylint --version in the shell again and it's fine.
There must be something different between the environment that vim runs the command in and my shell environment, that is triggering the crash. But I don't know how to investigate this, hence this question with the vim tag.
repoze.who is also implicated here. If I destroy my virtualenv and create a new virtualenv with nothing but pylint and other syntax checkers installed in it, then everything works fine both inside and outside of vim. But if I then pip install repoze.who==1.0.19 in the virtualenv then the pylint crash above reappears when running :!pylint --version in vim (but not when running it in my shell).
Vim version 7.4 installed from package on Ubuntu 14.04.

A: This seems to be a problem with repoze.who 1.0.19. pip install -U repoze.who==2.2 in the virtualenv gets rid of the problem. Weirdly you can then do pip install -U repoze.who==1.0.19 and downgrade it, and the pylint crash is still gone. I never got to the bottom of what exactly is causing it, but I suspect it may be something to do with this item from the repoze.who 2.0a1 changelog: Remove ez_setup.py and dependency on it in setup.py (support distribute).


text:
Q: C# Tree Node Removal and Memory Management I am working on a C# application that has a tree structure. The structure is made up of a list of Component objects and each Component can have a list of subcomponents. My question is if I remove the root of the tree (or subtree), does the garbage collector know to delete all the subcomponents and sub-subcomponents?

A: If there is no reference to any of those noted through any rooted object, then they are eligible for collection.
Put another way, if it's possible for any code to execute that would attempt to reference that object, then it cannot be collected; if the program can determine that it's impossible for any code executed in the future to attempt to access that object, then they are eligible for collection.
That the objects are referenced by other objects that aren't accessible isn't relevant.