text:
Q: Как спрятать div при нажатиии в этом исполнении? Есть такой небольшой код для обратной связи и я тут заморочился с ним.
вопрос, как же при нажатии прятать то куда нажимал и открывать другой блок(что уже работает). И так же сделать наоборот, нажимая на второй блок(прячась) что бы открывался первый.

http://jsfiddle.net/ryb4uexf/3/

A: Смотри как реализовано у меня, может натолкнёт на мысль. При нажатии на кнопку она вызывает функцию changeDiv, передавая параметр (свой айди) - что даёт тебе знать куда ты нажимаешь, ну и соответственно с этого ты можешь узнать на что ты НЕ нажал и поменять что тебе нужно.
По умолчанию в стиле элемента стоит display: none. (у того который изначально должен быть скрыт)
<button id="idHere" onclick="changeDiv(this.id)">Button</button>
function changeDiv(divID) {
    var ifclosed = document.getElementById(divID).style.display;

    if (ifclosed==='' || ifclosed==='none') {
        document.getElementById(divID).style.display = "block"; // show body div tag
    } else {
        document.getElementById(divID).style.display = "none"; // hide body div tag
    }
}

A:


text:
Q: How can I improve the speed of my Makefile? I am building a multiple binaries in C++ & CUDA with a couple of files in Fortran.  I found this question and I'm having a similar problem.  A user recently asked me to re-build a three year old version of the repository (before we had performed a massive migration and renaming) and I was shocked to see how quickly it built.  It would be impossible / incredibly time consuming to determine exactly which of changes between that version and now caused the build to take so friggin' long.
However, I noticed in an answer's comment to the aforementioned question:

In particular, remember to use := instead of =, as := does the expansion
  immediately, which saves time. – Jack Kelly Mar 23 at 22:38

Are there other suggestions that I should be aware of?
Note:

*

*I use the 'include' paradigm where each directory I want to build has a module.mk file which is directly included into the one and only Makefile.

*I do use several functions like:

(markdown..)
#
# CUDA Compilation Rules
#

define cuda-compile-rule
  $1: $(call generated-source,$2) \
    $(call source-dir-to-build-dir, $(subst .cu,.cubin, $2)) \
    $(call source-dir-to-build-dir, $(subst .cu,.ptx, $2))
    $(NVCC) $(CUBIN_ARCH_FLAG) $(NVCCFLAGS) $(INCFLAGS) $(DEFINES) -o $$@ -c $$<

  $(call source-dir-to-build-dir, $(subst .cu,.cubin, $2)): $(call generated-source,$2)
    $(NVCC) -cubin -Xptxas -v $(CUBIN_ARCH_FLAG) $(NVCCFLAGS) $(INCFLAGS) $(DEFINES) $(SMVERSIONFLAGS) -o $$@ $$<

  $(call source-dir-to-build-dir, $(subst .cu,.ptx, $2)): $(call generated-source,$2)
    $(NVCC) -ptx $(CUBIN_ARCH_FLAG) $(NVCCFLAGS) $(INCFLAGS) $(DEFINES) $(SMVERSIONFLAGS) -o $$@ $$<

  $(subst .o,.d,$1): $(call generated-source,$2)
    $(NVCC) $(CUBIN_ARCH_FLAG) $(NVCCFLAGS) $3 $(TARGET_ARCH) $(INCFLAGS) $(DEFINES) -M $$< | \
    $(SED) 's,\($$(notdir $$*)\.o\) *:,$$(dir $$@)\1 $$@: ,' > $$@.tmp
    $(MV) $$@.tmp $$@
endef

*

*But most of these functions I used in the older version...

Lastly: How can I determine if it's the compilation time or the make time which is really slowing things down?
I didn't want to append the entire Makefile.  It's 914 lines, but I'd be happy to update the question with snippets if it would help.
Update: Here is my dependency generation rule & compile rule:
#
# Dependency Generation Rules
#

define dependency-rules

  $(subst .o,.d,$1): $2
    $(CC) $(CFLAGS) $(DEFINES) $(INCFLAGS) $3 $(TARGET_ARCH) -M $$< | \
    $(SED) 's,\($$(notdir $$*)\.o\) *:,$$(dir $$@)\1 $$@: ,' > $$@.tmp
    $(MV) $$@.tmp $$@

endef

%.d: %.cpp
    $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -M $< | \
    $(SED) 's,\($(notdir $*)\.o\) *:,$(dir $@)\1 $@: ,' > $@.tmp
    $(MV) $@.tmp $@

Update 2: Using @Beta's suggestion, I was able to parcel out the dependency generation and Makefile time was roughly 14.2% of the overall compiling time.  So I'm going focus on minimizing header inclusion in my C++ code first.  Thanks to both of you for your suggestions!!

A: *

*It shouldn't be all that difficult to determine which changes slowed everything down. You have all the versions over the past three years (I hope), and you say the difference is dramatic. So try the version from two years ago. If it's taking too long, do a binary search. You could even automate this process, have it run overnight and give you a graph in the morning, build time sampled each month for the past 36 months.

*If you're using GNUMake (as I hope), `make -n` will print out the commands it would execute, without actually executing them. This will give you all of the Make time with no compilation time.

*One of the biggest sources of unnecessary build time (even bigger than recursion, which you aren't using) is unnecessary rebuilding, recompiling/relinking/whatever when you don't really need to. This can be because your makefile doesn't handle dependencies correctly, or because your C++ files `#include` headers recklessly, or something about CUDA or FORTRAN that I wouldn't know. Run Make twice in a row, and see if it does anything on the second pass. Look over the makefile for suspiciously huge prerequisite lists. Have a skillful programmer take a look at a few of the source files, especially the newer ones, and check for unnecessary dependencies.

A: ElectricMake (emake) is a drop-in replacement for gmake that makes it really, really easy to answer questions like this.  emake can generate an annotated build log that includes detailed timing information about every job in the build, and then you can load that into ElectricInsight to generate, for example, the Job Time by Type report:

If you want to give it a try, you can get an eval copy.
(disclaimer: I'm the architect and lead developer of ElectricMake and ElectricInsight!)

A: I really doubt that make's variable assignment (immediate with := or recursive =) can make significant impact on speed in general. One specific and obvious case when it does serious impact is shell command:
VAR := $(shell ...)

There could be other hidden consuming processes which are not obvious. For example in our environment standard temporary windows directory was on network drive. Thus, when make stored/updated files on that drive (even with 1G LAN) - it was very slow.  What you need is to debug makefile(s). This maybe helpful.
According to the mentioned doc you can put debug prints in the form of $(warning Going to do bla-bla-bla) and then watch where the process freezes most of all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transfinite induction without successor of a limit ordinal. Suppose I have some statement $P(\beta)$ where $\beta$ is an ordinal.
Suppose further that

*

*$P(\emptyset)$ is true;

*$P(\beta) \implies P(\beta +1)$ for $\beta$ a successor ordinal; and

*$P(\lambda)$ is true for $\lambda$ a limit orindal.

Is this enough data to specify that $P(\beta)$ is true for all $\beta$? Essentially, can transfinite induction be done without checking the case for successors of limit ordinals?

A: Certainly not - consider the property "is not the successor of an infinite limit ordinal." $0$ has this property, as does any successor-of-a-successor ordinal and any limit ordinal, but not every ordinal has this property.
While this may seem silly, it's a perfectly valid counterexample.


text:
Q: Accepting PayPal payments using the Recurly API We use the RecurlyAPI.  Currently PayPal payments are only available with the Recurly Hosted Payment Pages and Recurly.js.  Are there any plans to make PayPal payments available through the API?

A: It's not currently something we're have plans to support, but I'll certainly note it as a request for functionality. You can read more about using PayPal with Recurly here


text:
Q: Docusign authentication timeout errors We use Selenium which brings up a fresh (i.e., clear cache) Chrome browser
(Version 81.0.4044.113 (Official Build) (64-bit)) but this happens also manually and with IE. And it is intermittent (maybe 80% of the time)
When signing in to sign a document, about 10% or 20% of the time everything works fine, but the rest of the time it just times out (spinning circle) or I get the error below:
dsPrepare is not defined.
We are inside a VPN. Not sure whether that matters or not?
Anyone know what is happening, or what this error means?
I did enter a question in the community too.
We are using Java (1.8) with Eclipse and Selenium


text:
Q: Wifi Connected but no internet after installing squid proxy I am having issues connecting to the internet after I tried to set up a proxy. I eventually deleted it as I couldn't configure my settings to have internet. But I still don't. I rebooted my network manager, tried to open a web page via another browser, do updates - unsuccessfully. In Software & Updates->Additional Drivers there were none (And as far as I know there should be).
ifconfig:
    eth0      Link encap:Ethernet  HWaddr f0:76:1c:b9:6f:0c
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:1107 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1107 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:97357 (97.3 KB)  TX bytes:97357 (97.3 KB)

wlan0     Link encap:Ethernet  HWaddr 34:e6:ad:d9:40:9f
          inet addr:192.168.1.9  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::36e6:adff:fed9:409f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:77 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:6052 (6.0 KB)  TX bytes:650 (650.0 B)

sudo lshw --c network :
Hardware Lister (lshw) - B.02.16
usage: lshw [-format] [-options ...]
       lshw -version

    -version        print program version (B.02.16)

format can be
    -html           output hardware tree as HTML
    -xml            output hardware tree as XML
    -short          output hardware paths
    -businfo        output bus information

options can be
    -class CLASS    only show a certain class of hardware
    -C CLASS        same as '-class CLASS'
    -c CLASS        same as '-class CLASS'
    -disable TEST   disable a test (like pci, isapnp, cpuid, etc. )
    -enable TEST    enable a test (like pci, isapnp, cpuid, etc. )
    -quiet          do not display status
    -sanitize       sanitise output (remove sensitive information like serial numbers, etc.)
    -numeric        output numeric IDs (for PCI, USB, etc.)

I thank you in advance and please let me know if I can prove you with additional information!


text:
Q: Null pointer exception switching to search in Pocketsphinx Demo I want to develop an speech recognizer in android. I've used this thread and this video to use speech recognition in android device.
Here is my code :
MainActivity.java:
package com.example.pocket_sphinx;

import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import android.os.Bundle;
import android.app.Activity;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.SpeechRecognizer;

public class MainActivity extends Activity implements RecognitionListener {

       private static final String KWS_SEARCH = "wakeup";
        private static final String DICTATION_SEARCH = "digits";

        private static final String KEYPHRASE = "oh mighty computer";

        private SpeechRecognizer recognizer;
        private HashMap<String, Integer> captions;

        @Override
        public void onCreate(Bundle state) {
            super.onCreate(state);

            // Prepare the data for UI
            captions = new HashMap<String, Integer>();

            setContentView(R.layout.activity_main);
            ((TextView) findViewById(R.id.caption_text))
                    .setText("Preparing the recognizer");

            // Recognizer initialization is a time-consuming and it involves IO,
            // so we execute it in async task

            new AsyncTask<Void, Void, Exception>() {
                @Override
                protected Exception doInBackground(Void... params) {
                    try {
                        Assets assets = new Assets(MainActivity.this);

                        File assetDir = assets.syncAssets();

                        setupRecognizer(assetDir);

                        recognizer.startListening(KWS_SEARCH);

                    } catch (IOException e) {
                        return e;
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Exception result) {
                    if (result != null) {
                        ((TextView) findViewById(R.id.caption_text))
                                .setText("Failed to init recognizer " + result);
                    } else {
                        switchSearch(KWS_SEARCH);
                    }
                }
            }.execute();
        }

        @Override
        public void onPartialResult(Hypothesis hypothesis) {
            String text = hypothesis.getHypstr();
            Log.d("Spoken text",text);

            if (text.equals(KEYPHRASE))
                switchSearch(DICTATION_SEARCH);

            else
                ((TextView) findViewById(R.id.result_text)).setText(text);
        }

        @Override
        public void onResult(Hypothesis hypothesis) {
            ((TextView) findViewById(R.id.result_text)).setText("");
            if (hypothesis != null) {
                String text = hypothesis.getHypstr();
                makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onBeginningOfSpeech() {
        }

        @Override
        public void onEndOfSpeech() {
            Log.d("end","In end of speech");
            if (DICTATION_SEARCH.equals(recognizer.getSearchName()))
                switchSearch(KWS_SEARCH);
        }

        private void switchSearch(String searchName) {
            recognizer.stop();
            recognizer.startListening(searchName);
            String caption = getResources().getString(captions.get(searchName));
            ((TextView) findViewById(R.id.caption_text)).setText(caption);
        }

        private void setupRecognizer(File assetsDir) {
            File modelsDir = new File(assetsDir, "models");
            recognizer = defaultSetup()
                    .setAcousticModel(new File(modelsDir, "hmm/en-us"))
                    .setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
                    .setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
                    //.setFloat("-beam", 1e-30f)
                    .getRecognizer();
            recognizer.addListener(this);

            // Create keyword-activation search.
            recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);

            // Create language model search.
            File languageModel = new File(modelsDir, "lm/weather.dmp");
            recognizer.addNgramSearch(DICTATION_SEARCH, languageModel);
        }
    }

Actually I have no idea how to use it. after running ,it is throwing a runtime exception. I've posted the logcat of my code:
03-08 14:02:53.040: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(99): 788 unique initial diphones
03-08 14:02:53.230: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(148): 0 root, 0 non-root channels, 58 single-phone words
03-08 14:02:53.250: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(186): Creating search tree
03-08 14:02:53.470: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(192): before: 0 root, 0 non-root channels, 58 single-phone words
03-08 14:02:55.630: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(326): after: max nonroot chan increased to 2230
03-08 14:02:55.630: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(339): after: 253 root, 2102 non-root channels, 13 single-phone words
03-08 14:02:55.630: I/cmusphinx(17309): INFO: ngram_search_fwdflat.c(157): fwdflat: min_ef_width = 4, max_sf_win = 25
03-08 14:02:57.130: W/dalvikvm(17309): threadid=2: spin on suspend #1 threadid=11 (pcf=0)
03-08 14:02:57.140: W/dalvikvm(17309): threadid=2: spin on suspend resolved in 1010 msec
03-08 14:02:57.150: D/-heap(17309): GC_CONCURRENT freed 417K, 8% free 7863K/8455K, paused 14ms+1015ms, total 1597ms
03-08 14:02:57.210: I/SpeechRecognizer(17309): Start recognition "wakeup"
03-08 14:02:57.390: I/cmusphinx(17309): INFO: pocketsphinx.c(863): Writing raw audio log file: /mnt/sdcard/Android/data/com.example.pocket_sphinx/files/sync/000000000.raw
03-08 14:02:57.890: I/SpeechRecognizer(17309): Stop recognition
03-08 14:02:57.890: I/SpeechRecognizer(17309): Start recognition "wakeup"
03-08 14:02:57.890: W/dalvikvm(17309): threadid=1: thread exiting with uncaught exception (group=0x41ab9450)
03-08 14:02:57.930: E/AndroidRuntime(17309): FATAL EXCEPTION: main
03-08 14:02:57.930: E/AndroidRuntime(17309): java.lang.NullPointerException
03-08 14:02:57.930: E/AndroidRuntime(17309):    at com.example.pocket_sphinx.MainActivity.switchSearch(MainActivity.java:108)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at com.example.pocket_sphinx.MainActivity.access$2(MainActivity.java:105)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at com.example.pocket_sphinx.MainActivity$1.onPostExecute(MainActivity.java:67)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at com.example.pocket_sphinx.MainActivity$1.onPostExecute(MainActivity.java:1)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at android.os.AsyncTask.finish(AsyncTask.java:631)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at android.os.Looper.loop(Looper.java:137)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at android.app.ActivityThread.main(ActivityThread.java:4802)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at java.lang.reflect.Method.invokeNative(Native Method)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at java.lang.reflect.Method.invoke(Method.java:511)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:813)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:580)
03-08 14:02:57.930: E/AndroidRuntime(17309):    at dalvik.system.NativeStart.main(Native Method)
03-08 14:02:57.940: I/cmusphinx(17309): INFO: pocketsphinx.c(863): Writing raw audio log file: /mnt/sdcard/Android/data/com.example.pocket_sphinx/files/sync/000000001.raw

A: You have two issues with your code:
1) You start search inside doInBackground and start the same search again in onPostExecute, you can just call switchSearch in onPostExecute, that would be enough
2) You do not fill captions array but you use it in switchSearch method. So you get null pointer exception. You can comment out
        String caption = getResources().getString(captions.get(searchName));
        ((TextView) findViewById(R.id.caption_text)).setText(caption);

in switchSearch if you are not going to use captions


text:
Q: Typecasting in C for each of the variables What is the difference between the following two?
// uint8_t a; uint8_t b;

uint16_t first = (uint16_t)(a * b);

uint16_t second = (uint16_t)a * (uint16_t)b;

What could be the use cases of these two kinds of implementations?

A: The mathematical product of a*b is in the range [0...65,025].
If unsigned/int is 32-bit, no difference.
If unsigned/int is 16-bit, a * b risks signed int overflow and undefined behavior (UB).  Both a, b are converted to int prior to the multiplication and a*b may exceed INT_MAX (32,767).
(uint16_t)a * (uint16_t)b; is better.


text:
Q: Downloading pdf file and saving to SD card I want to download and save pdf file to internal storage. Here is code that i am using:
I am calling my method from other class:
new Thread(new Runnable() {
    public void run() {

        new Main().downloadPdfContent("http://people.opera.com/howcome/2005/ala/sample.pdf");

    }
  }).start();

Method look like this:
public void downloadPdfContent(String urlToDownload){

    URLConnection urlConnection = null;

    try{

        URL url = new URL(urlToDownload);

        //Opening connection of currrent url

        urlConnection = url.openConnection();
        urlConnection.connect();

        //int lenghtOfFile = urlConnection.getContentLength();

    String PATH = Environment.getExternalStorageDirectory() + "/1/";

    File file = new File(PATH);
    file.mkdirs();
    File outputFile = new File(file, "test.pdf");
    FileOutputStream fos = new FileOutputStream(outputFile);

    InputStream is = url.openStream();

    byte[] buffer = new byte[1024];

    int len1 = 0;

    while ((len1 = is.read(buffer)) != -1) {
        fos.write(buffer, 0, len1);
    }

    fos.close();
    is.close();

   System.out.println("--pdf downloaded--ok--"+urlToDownload);

    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();

    }

}

I found link of pdf on the web:
http://people.opera.com/howcome/2005/ala/sample.pdf
However i get an exception on this line:
urlConnection.connect();
Exception:
java.net.UnknownHostException: people.opera.com
I can't figure out what's wrong. Maybe someone could take a look.
Thanks.

A: Put
    <uses-permission android:name="android.permission.INTERNET"/>

in your AndroidManifest.xml

A: Follow following steps :
1) Declare file name
String fileName;
    //for image
    fileName = "matchfine1.png";
    //for pdf
    fileName = "samplepdf.pdf";

2) Call method to invoke download process.
startDownload(fileName);

3) Define startDownload method:
//for download file start
    private void startDownload(String filename) {
        String filedowname = filename;
        //for image
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        //for pdf
        String url = "http://people.opera.com/howcome/2005/ala/sample.pdf";
        new DownloadFileAsync().execute(url,filedowname);
    }

4) For auto loading progressBar:
@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }

5) Define the download process extending AsyncTask
class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(final String... aurl) {

            try {

                File root = android.os.Environment.getExternalStorageDirectory();
                File dir = new File (root.getAbsolutePath() + "/Your_file_save_path/");
                if(dir.exists()==false) {
                    dir.mkdirs();
                }

                URL url = new URL(aurl[0]);
                String filename = aurl[1];
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(dir+"/"+filename);

                byte data[] = new byte[1024];

                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {}
            return null;

        }
        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC", progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    }
    //for download file end

6) Replace "Your_file_save_path" by your file path in dir. and then download and check in the specified location.

A: I have used the same code and got Network.onThreadException Error.   But then after using this piece of code in my oncreate() method, I was able to resolve the issue.
if (android.os.Build.VERSION.SDK_INT > 9)
{
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);
 }


text:
Q: How to set up jdk 8 on mac m1? i have jdk 16 installed but due to certain reasons i want jdk8 now.
my jdk 16 is not installed on $JAVA_HOME
i have no documentation on how to install jdk8 since all documentation are for -bash, while my mac has -zsh and i also don't know how to set up environment variable and all(i am a complete beginner).
it would be really helpful if someone could guide me for installation


text:
Q: Socket Connection with Sub context of URL I used below code to read sub context news from bbc site,but it is throwing UnknownHostException.Any hints please.
try {
            InetAddress addr = InetAddress.getByName("bbc.co.uk/news/");
            int port = 80;

            // This constructor will block until the connection succeeds
            Socket socket = new Socket(addr, port);
        } catch (UnknownHostException e) {
            System.out.println("exception is"+e);
        } catch (IOException e) {
        }

A: From  the JavaDoc on InetAddress.getByName(...):

Determines the IP address of a host, given the host's name.

In bbc.co.uk/news/ the host is bbc.co.uk with news being a subcontext as you already stated.
So change that to InetAddress.getByName("bbc.co.uk") or alternatively use the URL class, if you don't have to use a Socket : new URL("http://bbc.co.uk/news/").openStream().

A: Your InetAddress.getByName() method is incorrect. It should specify only the host name.
InetAddress addr = InetAddress.getByName("bbc.co.uk");


text:
Q: enter space at the end of value cause error Im having following reg-ex which is working OK, the only thing is
if user type any value which is valid and press than spaces I got error,
how can I avoid the space at the end of the values?
@"^[a-z\d][\da-z-.]*[a-z\s\d]$",

A: ^[a-z\d][\da-z-.]*[a-z\s\d][\s]*$

Use this if you want to accept any amount of whitespace characters at the end (small S).
^[a-z\d][\da-z-.]*[a-z\s\d][\S]*$

Use this if you don't want to accept strings with white spaces at the end (capital S).
Or you can also use the Trim function after you matched it with the unchanged regex.

A: simply using
String.Trim();
 string foo = "   hello ";
 string bar = foo.Trim();

 Console.WriteLine(bar); // writes "hello"

See more:How to remove all white spaces from the start or end of a string?


text:
Q: how to bookmark a dynamically created aspx page? There is this site wich in the address bar only shows like "http://example.com/examplepage.aspx".
Normally if it would have parameters behind it you probably could just copy that one.
But since it doesn't, how do i bookmark this page.
It doesn't necessarily have to be a bookmark, but at least an easy way to access the page.
(fyi I know basic HTML and Java, maybe it's only possible programmatically).
thnx

A: Generally dynamic pages (taking in context with the question) are not book mark friendly.
You could probably sniff the incoming request, and create a fake form which you can then submit later.
However there may be situations where there are parameters such as session id which are valid for only small periods of time.
You should read up on sessions. In really simple terms, a session is assigned to users accessing a website. They have an expiry period. IF you stay idle beyond  set time (determined by the developer) you will not be able to get in. And every time you log back in, you may be assign a new session.
You would have noticed, that some websites automatically log you in, this is mostly done with the help of cookies. Cookies work in tandem with sessions, they store very basic information, so the next time you come back to a website, it will be able to identify you as a returning user and provide you with access.
Then again, some pages don't use sessions, they might have their own custom way of identifying users.
Bookmarks can be used in dynamic pages, if the code allows you to send GET requests, if they don't have any other extra parameters which will block you.
To Summarize:

*

*Dynamic page not very bookmark friendly.

*There may be parameters used to access a webpage which change constantly, which you cannot really save.

*You may be able to get into dynamic pages using bookmarks, if they don't use any of the dynamically changing parameters.

Since you know Java, you should probably read up on JSPs/servlets to get an understanding of what happens behind the scenes in dynamic pages.
Hope this answers your questions.


text:
Q: Is there a way to teach tesseract for iOS a new font? Im currently using tesseract for iOS using Nolan Brown's example. It works ok, but I need it to start picking up a new font (which I have in .tff format) which will always be numbers.
I have found questions on StackOverflow about tesseract learning fonts which all point to the google guides on how to teach Tesseract a new font using command line. But I'm already using a compiled copy of the lib from Nolan's example.
How can I teach tesseract a new font? Will I need to recompile the lib for iOS? How do I do this?

A: You might try training a new "traineddata" file using these instructions.


text:
Q: How to query for empty array in JSONB? Consider this example:
postgres=# CREATE TABLE emptyarray (fields jsonb);
CREATE TABLE
postgres=# INSERT INTO emptyarray VALUES ('{"key":["a","b"]}');
INSERT 0 1
postgres=# INSERT INTO emptyarray VALUES ('{"key":[]}');
INSERT 0 1
postgres=# SELECT * from emptyarray where Fields@>'{"key":["b"]}';
       fields
---------------------
 {"key": ["a", "b"]}
(1 row)

postgres=# SELECT * from emptyarray where Fields@>'{"key":[]}';
       fields
---------------------
 {"key": ["a", "b"]}
 {"key": []}
(2 rows)

In the second query I expected only one rows in the results (the one record with empty array). But as you can see there are two rows in the result. How do I query for a empty array using @> syntax?
I am using PostgreSQL 9.6

A: You could use:
SELECT * from emptyarray where Fields-> 'key' = '[]'::jsonb;

Rextester Demo


text:
Q: Angular-universal MutationObserver problem I need to add angular-universal with ssr to an existing project. I followed this tutorial, everything seemed fine except when I run the project. After I execute npm run dev:ssr I see Compiled successfully and this message:
ReferenceError: window is not defined
at Module.FARa (/home/project-path/dist/project/server/main.js:69075:26)
at __webpack_require__ (/home/project-path/dist/project/server/main.js:20:30)
at Module.JMXn (/home/project-path/dist/project/server/main.js:75830:74)
at __webpack_require__ (/home/project-path/dist/project/server/main.js:20:30)
at Module.PCNd (/home/project-path/dist/project/server/main.js:82492:109)
at __webpack_require__ (/home/project-path/dist/project/server/main.js:20:30)
at Module.ZAI4 (/home/project-path/dist/project/server/main.js:99022:79)
at __webpack_require__ (/home/project-path/dist/project/server/main.js:20:30)
at Module.24aS (/home/project-path/dist/project/server/main.js:41256:69)
at __webpack_require__ (/home/project-path/dist/project/server/main.js:20:30)

A: You can try this solution:
global['MutationObserver'] = getMockMutationObserver();

function getMockMutationObserver() {
  return class {
    observe(node, options) {}
    disconnect() {}
    takeRecords() {
      return [];
    }
  };
}

credit: https://github.com/cloudinary/cloudinary_angular/issues/298


text:
Q: How do I make Git always use "theirs/ours" for resolving conflicts in a particular file, during rebase? I've created my own dev branch from a pretty active repository. This repository (Clappr) also contains a compiled and minified file, which is updated with the source code.
Whenever I want to rebase my dev branch with the master, this file is conflicting, because it cannot be automatically merged—of course, because it's a minified JS file:
$ git checkout dev
$ git rebase master
First, rewinding head to replay your work on top of it...
Applying: dummy commit
Using index info to reconstruct a base tree...
M   dist/clappr.js
M   src/playbacks/hls/hls.js
Falling back to patching base and 3-way merge...
Auto-merging src/playbacks/hls/hls.js
Auto-merging dist/clappr.js
CONFLICT (content): Merge conflict in dist/clappr.js

I can resolve this conflict using --ours, but I have to do this for every single commit on master that I haven't rebased yet.
I know I can skip a patch entirely, but can I somehow automatically tell Git to ignore that clappr.js file and just always use whatever is in my dev branch?

A: You can define a custom merge driver (as in "Git: How to rebase many branches (with the same base commit) at once?" for a concrete example).
That merge driver "keepMine" associated with dist/clappr.js, and declare that merge driver in a .gitattributes file present in each of your branches.
See "How do I tell git to always select my local version for conflicted merges on a specific file?".
echo clappr.js merge=keepMine > dist/.gitattributes
git config merge.keepMine.name "always keep mine during merge"
git config merge.keepMine.driver "keepMine.sh %O %A %B"

With keepMine.sh put somewhere in your $PATH, not in the repository:
# I want to keep MY version when there is a conflict
# Nothing to do: %A (the second parameter) already contains my version
# Just indicate the merge has been successfully "resolved" with the exit status
exit 0

(For a KeepTheir.sh, see "How to stop a merge (yet again…)")

Even simpler, as noted by branch14 in the comments:

Linux already has a command that successfully does nothing, aptly named "true".

git config merge.keepMine.driver "true"


text:
Q: pygame.error: File is not a Windows BMP file (continuation of the problem) I have recently started using Mac for coding. Thus, I had to move all my files from my previous computer (Windows). Long story short, everything was good until this error occurred.
pygame.error: File is not a Windows BMP file
I checked Stackoverflow and found this question with the explanation of how to resolve the problem. How to uninstall pygame on mac OSX 10.9.4
But still nothing.
I use python3, however, python 2.7 was installed on my computer initially (Idk how) and I checked so that my program does not notice it.
Can anyone help me, please?

A: did you check your PIP version if not check it and if it needs to be updated u can update
than u can reinstall PyGame library
Every PC system has Python old version. In order to use Python u have to Update your Python up 3.5 version.. than hope everything will be fine :)


text:
Q: accessing variables declared outside the asp code <script ID="clientEventHandlersVBS" LANGUAGE="vbscript">

s=pass()
y=s

</script>
<%
session("password")=y
Response.write(session("password"))
Response.write(y)
%>

i have this code. but nothing is getting stored inside the session variable neither anything is getting printed. cant i access the variables declared outside the asp code or is their any syntax mistake. any help is really appreciated

A: First of all put
<% Option Explicit %>

at the top of every .asp page.
You will immediatly see that you are trying to access non declared variabels s and y.
So of course nothing is stored in the session variables.
Can you not use
<%
   s = pass
   y = s
%>

and so on ?
What is the purpose of the <script ... line if you are using vbscript any how ?

A: As implied by the ID of the script (clientEventHandlersVBS) the code contained in there refers to the client (the browser, IE in this case since it is the only one that supports VB client-side)
the <% %> tags though refer to server side ASP code..
These two can never communicate as they happen at different times/computers...


text:
Q: linux kernel scheduler CFS How does linux kernel's  CFS scheduler schedule all the process within sched_latency_ns time.
Is it by traversing though the red black tree or re balancing after every process switch.

A: Start with the Wikipedia article...

In contrast to the previous O(1) scheduler used in older Linux 2.6 kernels, the CFS scheduler implementation is not based on run queues. Instead, a red-black tree implements a "timeline" of future task execution. Additionally, the scheduler uses nanosecond granularity accounting, the atomic units by which an individual process' share of the CPU was allocated (thus making redundant the previous notion of timeslices). This precise knowledge also means that no specific heuristics are required to determine the interactivity of a process, for example.[2]

A: here describe CFS in details together with snippet source code.


text:
Q: Pre-populate Form Field With The Internal Millisecond Clock From Javascript I have a form on my website that I need to pre-populate with the current unix millisecond timestamp.
I do have another form field (in the same form) which successfully pre-populates the Date (Month, Day, Year) with the following code:

DATE
<input name="date" id="date">

However... I'm not having the same luck when attempting to pre-populate a second form field with the Unix Millisecond timestamp using this code:

TIMESTAMP URL
<input name="timeStampURL" id="timeStampURL">

I don't understand why the two codes behave differently that way, but any advice as to how to get that script to pre-populate the field would be appreciated.

A: Input elements don't have any content, so setting their innerHTML property does nothing. Your first function is setting the value attribute, so should your second:

function showTimeValue() {
  document.getElementById('timeValue').value = Date.now();
}

window.onload = showTimeValue;
<input id="timeValue">
<button onclick="showTimeValue()">Update time value</button>

Each time you run the code, you'll get an updated value.


text:
Q: How to probe into the internal signals and registers in FPGA without using JTAG? I am using a Xilinx Spartan 3E FPGA kit in my academic project to synthesize a design comprising of a couple of 32 bit internal registers (eg few counters, shifters and some configuration registers) . There is no direct access to the registers using the input/output ports of the design.
My design is in Verilog. Is there any way to probe the values written in the registers through Xilinx ISE tool?
Should I use chipscope for this purpose? For verification, I want to check the internal values in the registers.
I do not have JTAG cable, I am using USB connector to interface the kit with Xilinx ISE.

A: One of the most useful ways to gain access to the internal register contents is to design it in!!
First you have to decide the most convenient mechanism with which to access the FPGA. You could use a SPI interface, UART, I2C ... what ever suits connection to your monitoring device.
I one instance I decided to design in monitoring through the use of LEDs connected to the FPGA. I had registers up to 16-bits wide in the FPGA so I connected 16 LEDs up to output pins in the FPGA design. I also equipped the design with a set of four jumpers that were inputs into the FPGA design. In the logical design of the FPGA the LED outputs were connected to an internal MUX that was 16-bits wide. The inputs to the MUX were connected to all of the various registers and counters that I wanted to be able to monitor. The selector controls for the mux channel came from the four jumper pin inputs. This allowed me to monitor up to 16 different internal sources of information (although I only needed to use 11 or 12 for that particular design).
I could easily watch the internal state machines and counters operate by viewing the LEDs. During the debug phase I needed to be able to monitor more closely than what you can view on an LED and so each of the 16 outputs also had a test point attached where I could connect my USB logic analyzer to capture the selected outputs in real time.
In your case most general purpose FPGA evaluation board provide for switches that connect to the FPGA as inputs and a set of LEDs driven by outputs of the FPGA. You can leverage these existing resources to implement exactly what I did (in my case I had made my own board). If your kit support only 8 LEDs and you have larger registers you can design the MUX to show the upper and lower halves of the register via two separate MUX selections from the switches.


text:
Q: does it make sense to use shareReplay where i want to replay the value but do not want it to share with multiple observer I have one scenario where I need to fetch the mapping for status and priority from backend, as it is static values so once the application loads I do not want to get those values multiple time from backend so for that I need a way which can give me values again without calling the backend here is the snippet for that which I am using.
    ngOnInit() {
        const status  = this.http.get('https://my-json-server.typicode.com/darpankumar/Fakedb/status').pipe(
          shareReplay(1)
        );

        const priority = this.http.get('https://my-json-server.typicode.com/darpankumar/Fakedb/priority').pipe(
          shareReplay(1)
       );
        this.statusPriority$ = combineLatest(status,priority)
      }

and the place where I need to use it I use it like this
    btnClick() {
        this.task$ = this.statusPriority$.pipe(flatMap((data :Array<any>) => {
          const [status, priority] = [...data];
          return this.http.get('https://my-json-server.typicode.com/darpankumar/Fakedb/data').pipe(
          map((data : any) =>{
            // this is the place where i do the mapping.
            data.status = status[data.statusCode];
            data.priority = priority[data.priorityCode];
            return data;
          })
        );
        }))
      }

So my question in brief is, is it a right way to implement this behaviour, as one thing which is bothering me is shareReplay gives a multicast observable and I am not using it multiple places.
but apart from this, I can not find any way which can achieve the same functionality for me.
And another question is is there any way I can make this status and priority observable hot so that it fetches the values on load time, not on the button click.
I know I can use behavioursubject(withsomeinitialValue) and then can do the backend call and subscribe to those values in ts and can do the next on behavioursubject but i do not want to do the subscription in the component.
fiddle

A: Interesting problem, short answers, it's ok. I'm not sure if it is possible to achieve the same behavior in another way without using Subjects while keeping the status and priority as observables.
Why is it ok, if you use a multicast observable with a single subscriber it is the same as using unicast observable. You can picture it as
let unicast = (x) => x

unicast('something')

let multicast = [(x)=>x]

multicast.map(fn => fn('something'))

so there isn't that much of a difference.
Anyways my approach will be a bit different for this problem, I will create some kind of service and inside of it will do the following
...
loadStaticVariables(){
const status  = this.http.get('https://my-json-server.typicode.com/darpankumar/Fakedb/status');

const priority = this.http.get('https://my-json-server.typicode.com/darpankumar/Fakedb/priority');

combineLatest(status,priority)
.subscribe(staticValueFromTheserver =>{
this.statusPriority = staticValueFromTheserver;
})
}

(And of course, this function should be called at some point before showing the button)
And after that, I would use the variable wherever I need.
Pros

*

*On load of the app you will get this static values (Which solves your problem)

Cons

*

*I don't find such

A:
And another question is is there any way I can make this status and priority observable hot so that it fetches the values on load time, not on the button click.

I think there is a way. You can use any of the publish* operators, because they return a ConnectableObservable, which has a connect() method that will allow you to subscribe to the source.
const status$  = this.http.get('https://my-json-server.typicode.com/darpankumar/Fakedb/status');

const priority$ = this.http.get('https://my-json-server.typicode.com/darpankumar/Fakedb/priority');

const connectableObs = combineLatest(status$,priority$).pipe(
  publishReplay(1),
) as ConnectableObservable<any>;

this.statusPriority$ = connectableObs;

// Load data on load times
// You can add it to an `ngOnInit` hook or in a service's constructor
this.subscription = connectableObs.connect();

And then you can statusPriority$ the same way as you did before.
connectableObs.connect() will subscribe to the source; in this case, it will get the data from those endpoints. Because you're using publishReplay, there will be a ReplaySubject which will get the data from the source and when a new subscriber is registered(e.g in btnClick), that subscriber will get the data cached by the subject.


text:
Q: How to 'insert' data into database via VB Stuggling a bit here. Trying to develop the code to link user input into my database, in the form of a book record. for example the user would be asked to enter their name address etc. But the code I have used does not seem to execute because I continually get the same error.
Line 12:         Dim con As New SqlConnection
Line 13:         Dim inscmd As New SqlCommand
Line 14:         con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database.My.MySettings.Database1ConnectionString1").ConnectionString
Line 15:         con.Open()
Line 16:         inscmd.CommandText = ("insert into booking values('" + txtfirstname.Text + "', " + txtSurname.Text + "', " + txtAddressline1.Text + "', " + txtAddressline2.Text + "', " + txtPostcode.Text + "', " + txtTime.Text + "', " + txtPeople.Text + "', " + txtDropoff1.Text + "', " + txtDropoff2.Text + "', " + txtDropoffpost.Text + "")

It is line 14 that contains the error but I dont know why. This is my code;
Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles  btnsubmit.Click
    Dim con As New SqlConnection
    Dim inscmd As New SqlCommand
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database.My.MySettings.Database1ConnectionString1").ConnectionString
    con.Open()
    inscmd.CommandText = ("insert into booking values('" + txtfirstname.Text + "', " + txtSurname.Text + "', " + txtAddressline1.Text + "', " + txtAddressline2.Text + "', " + txtPostcode.Text + "', " + txtTime.Text + "', " + txtPeople.Text + "', " + txtDropoff1.Text + "', " + txtDropoff2.Text + "', " + txtDropoffpost.Text + "")
    Print(inscmd.CommandText)
    inscmd.Connection = con
    inscmd.ExecuteNonQuery()
    con.Close()
    inscmd.Parameters.Clear()

    MsgBox("Your booking has been successfully")
    con.Close()

End Sub

A: Hopefully this will help you ( insert your code where need to  )
        Dim con As New SqlConnection
        Dim myConString As String = getSQLString() ' GET YOUR CON String

' my function looks like this when returned
"Server=ServerExactLocationPath;Database=DataBase;User Id=UserName;Password=Password;"
        Dim objcommand As SqlCommand = New SqlCommand
        'con.ConnectionString = myConString

        With objcommand
            .Connection = con
            Dim cmdText As String = ""
            cmdText = "Insert into SitesStatus (SiteNumber,StatusName,Date,ByUser) values ('" & site & "','" & status & "','" & System.DateTime.Today.ToString("MM/dd/yyyy") & "','" & dbUiInitials & "')"
        'PUT YOUR INSERT ABOVE

         .CommandText = cmdText
        End With
        con.ConnectionString = myConString
        con.Open()
        objcommand.ExecuteNonQuery()
        con.Close()

    Catch ex As Exception
      End Try
 Return Nothing

A: insert into booking values('" + txtfirstname.Text + "', " + txtSurname.Text + "', " + txtAddressline1.Text + "', " + txtAddressline2.Text + "', " + txtPostcode.Text + "', " + txtTime.Text + "', " + txtPeople.Text + "', " + txtDropoff1.Text + "', " + txtDropoff2.Text + "', " + txtDropoffpost.Text + "

should be
insert into booking values('" + txtfirstname.Text + "', '" + txtSurname.Text + "', '" + txtAddressline1.Text + "', '" + txtAddressline2.Text + "', '" + txtPostcode.Text + "', " + txtTime.Text + "', '" + txtPeople.Text + "', '" + txtDropoff1.Text + "', '" + txtDropoff2.Text + "', '" + txtDropoffpost.Text + "')"

A: You should use the connection string wizard in the Project Settings window. Then try the test connection button, Make sure the type of the setting is ConnectionString
You should be able to get the connection string using this syntax if things are set up right.
con.ConnectionString = my.Settings.Database1ConnectionString1

A: strSQL = "INSERT INTO user_account_details" & _
                "(lastname,firstname,middlename,usertype,reg_date_time,status)" & _
                " VALUES ( " & _
                " '" & txtLName.Text & "', " & _
                " '" & txtFName.Text & "' , " & _
                " '" & txtMName.Text & "' , " & _
                " '" & cboUserType.Text & "' , " & _
                " '#" & Now & "#', " & _
                " 'Inactive' " & _
                ")"


text:
Q: ASP.NET MVC Master Detail Entry Form I'm trying to implement an order entry form using ASP.NET MVC but facing a lot of difficulties.  All the samples that I found are related to viewing master detail forms, and none for adding or editing.
Suppose I have two tables: Order and OrderLines that are related to each others with one-to-many relationship. In the main view I had a "New" button when clicked it should show a new order view composed of the order fields, a grid that shows the order lines, and a "Save" button that when clicked will persist the whole order along with its lines into a database. The grid should have three buttons: "Add Line", "Edit Line", and "Delete Line". When the "Add Line" is clicked a new view should be shown that allows the user to add the line to the order view grid lines –at this stage the database is not affected-. When the user clicks "Edit Line" a view will be shown that allows the user to edit the selected line and when done update the order grid lines.
The most difficult problems are:
How to pass the order and its lines collection between the order view and the order line views?
How to update the order view based on changes in the order line view?
And how to persist changes between views without the database being involved?
Is there a concrete example that shows how to implement this using MVC?

Your help and feedback is appreciated.

A: Pleas have a look at my blog post on creating master detail form in asp.net mvc. it also contains demo project that you can download

A: Unlike WebForms, ASP.NET MVC does not try to hide the stateless nature of HTTP. To work with a complex object across multiple forms you have a couple of options:

*

*Save the object on the server with each change so that the updated object is available using only an id

*Use jquery to populate the order line form and save details to the main form

I usually go with the client side option myself, with the main form having hidden fields for the data that will be edited in the subform. You may find the server side option easier though - if you really don't want to involve the database you can keep your partially updated object in the session.

A: Step 1: Create view model
public class OrderVM
{
    public string OrderNo { get; set; }
    public DateTime OrderDate { get; set; }
    public string Description { get; set; }
    public List<OrderDetail> OrderDetails {get;set;}
}

Step 2: Add javascript for add order lines

    $(function () {
        $('#orderDate').datepicker({
            dateFormat : 'mm-dd-yy'
        });
    });

    $(document).ready(function () {
        var orderItems = [];
        //Add button click function
        $('#add').click(function () {
            //Check validation of order item
            var isValidItem = true;
            if ($('#itemName').val().trim() == '') {
                isValidItem = false;
                $('#itemName').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#itemName').siblings('span.error').css('visibility', 'hidden');
            }

            if (!($('#quantity').val().trim() != '' && !isNaN($('#quantity').val().trim()))) {
                isValidItem = false;
                $('#quantity').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#quantity').siblings('span.error').css('visibility', 'hidden');
            }

            if (!($('#rate').val().trim() != '' && !isNaN($('#rate').val().trim()))) {
                isValidItem = false;
                $('#rate').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#rate').siblings('span.error').css('visibility', 'hidden');
            }

            //Add item to list if valid
            if (isValidItem) {
                orderItems.push({
                    ItemName: $('#itemName').val().trim(),
                    Quantity: parseInt($('#quantity').val().trim()),
                    Rate: parseFloat($('#rate').val().trim()),
                    TotalAmount: parseInt($('#quantity').val().trim()) * parseFloat($('#rate').val().trim())
                });

                //Clear fields
                $('#itemName').val('').focus();
                $('#quantity,#rate').val('');

            }
            //populate order items
            GeneratedItemsTable();

        });
        //Save button click function
        $('#submit').click(function () {
            //validation of order
            var isAllValid = true;
            if (orderItems.length == 0) {
                $('#orderItems').html('Please add order items');
                isAllValid = false;
            }

            if ($('#orderNo').val().trim() == '') {
                $('#orderNo').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#orderNo').siblings('span.error').css('visibility', 'hidden');
            }

            if ($('#orderDate').val().trim() == '') {
                $('#orderDate').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#orderDate').siblings('span.error').css('visibility', 'hidden');
            }

            //Save if valid
            if (isAllValid) {
                var data = {
                    OrderNo: $('#orderNo').val().trim(),
                    OrderDate: $('#orderDate').val().trim(),
                    //Sorry forgot to add Description Field
                    Description : $('#description').val().trim(),
                    OrderDetails : orderItems
                }

                $(this).val('Please wait...');

                $.ajax({
                    url: '/Home/SaveOrder',
                    type: "POST",
                    data: JSON.stringify(data),
                    dataType: "JSON",
                    contentType: "application/json",
                    success: function (d) {
                        //check is successfully save to database
                        if (d.status == true) {
                            //will send status from server side
                            alert('Successfully done.');
                            //clear form
                            orderItems = [];
                            $('#orderNo').val('');
                            $('#orderDate').val('');
                            $('#orderItems').empty();
                        }
                        else {
                            alert('Failed');
                        }
                        $('#submit').val('Save');
                    },
                    error: function () {
                        alert('Error. Please try again.');
                        $('#submit').val('Save');
                    }
                });
            }

        });
        //function for show added items in table
        function GeneratedItemsTable() {
            if (orderItems.length > 0) {
                var $table = $('
');
                $table.append('

Item	Quantity	Rate	Total

');
                var $tbody = $('
');
                $.each(orderItems, function (i, val) {
                    var $row = $('
');
                    $row.append($('').html(val.ItemName));
                    $row.append($('').html(val.Quantity));
                    $row.append($('').html(val.Rate));
                    $row.append($('').html(val.TotalAmount));
                    $tbody.append($row);
                });
                $table.append($tbody);
                $('#orderItems').html($table);
            }
        }
    });

</script>

Step 3: Create an action for save data
[HttpPost]
    public JsonResult SaveOrder(OrderVM O)
    {
        bool status = false;
        if (ModelState.IsValid)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                Order order = new Order { OrderNo = O.OrderNo, OrderDate = O.OrderDate, Description = O.Description };
                foreach (var i in O.OrderDetails)
                {
                    //
                   // i.TotalAmount =
                    order.OrderDetails.Add(i);
                }
                dc.Orders.Add(order);
                dc.SaveChanges();
                status = true;
            }
        }
        else
        {
            status = false;
        }
        return new JsonResult { Data = new { status = status} };
    }

you can download source code and video tutorial

A: You could try Telericks free MVC grid control...
http://demos.telerik.com/aspnet-mvc/grid/hierarchyserverside

A: Just off the top of my head (a kind of brain dump)...

*

*You could have a main grid part of the form. This would be full view loaded from an action (either with an order number or not depending on loading an existing one or not).

*When clicking an event (new or edit) this could open a partial view in a "lightbox" style. This would then pass back a json object back to the main form.

*The passed json object would then be rendered using templating to the bottom of the table (for a new one) or update an existing record. This could also be saved back to the server in the same ajax call. Or just update the client side and need the user to click a save button.

*An isDirty flag will be needed so any changes set it to true and the when the browser tries to leave or close etc. then you can prompt the user to save or not.
Hope this helps.
edit
Not tried this but could be interesting with the none db aspect of your question click

A: Step 3: Create an action for save data.
[HttpPost]
    public JsonResult SaveOrder(OrderVM O)

    {

        bool status = false;

        if (ModelState.IsValid)

        {

            using (ManageMobileStoreWebContext dc = new ManageMobileStoreWebContext())

            {

                //Random rnd = new Random();

                //OrderID = rnd.Next(),

                Order order = new Order { OrderNo = O.OrderNo, OrderDate = O.OrderDate, Description = O.Description };

                foreach (var i in O.OrderDetails)

                {

                    if(order.OrderDetails == null)

                    {

                        order.OrderDetails = new List<OrderDetail>();

                    }

                    // i.TotalAmount =

                    order.OrderDetails.Add(i);

                   //dc.OrderDetails.Add(i);

                }

                dc.Orders.Add(order);

                dc.SaveChanges();

                status = true;

            }

        }

        else

        {

            status = false;

        }

        return new JsonResult { Data = new { status = status } };

    }


text:
Q: Background process is waiting and not continuing process I have a program that has to call the sqlmap API and run it in the background, if you've ever used sqlmap you would know that the sqlmap API process starts and continues running until exited. It appears that the program is waiting for sqlmap's API to stop running before continuing the process:
Output:
[11:02:10 INFO] creating arguments for sqlmap...
[11:02:10 INFO] attempting to find sqlmap on your system...
[11:02:10 INFO] attempting to call sqlmap API...
------------------------------
[11:02:12] [INFO] Running REST-JSON API server at '127.0.0.1:8775'..
[11:02:12] [INFO] Admin ID: 7e8f2de3647ff14d8cd777f3fddabca8
[11:02:12] [DEBUG] IPC database: '/tmp/sqlmapipc-mH6At_'
[11:02:12] [DEBUG] REST-JSON API server connected to IPC database
[11:02:13] [DEBUG] Using adapter 'wsgiref' to run bottle
# just hangs here

Code:
try:
    path = find_sqlmap("sqlmap", verbose=verbose)
    lib.core.settings.logger.info(lib.core.settings.set_color(
        "attempting to call sqlmap API..."
    ))
    called = subprocess.Popen(
        "python {}/sqlmapapi.py -s".format("".join(path)),
        shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
        close_fds=True
    )
    print("-" * 30)
    for line in iter(called.stdout.readline, ""):
        print(line.strip())
    print("-" * 30)
    lib.core.settings.logger.info(lib.core.settings.set_color(
        "API started with PID {}, continuing process...".format(
            called.pid
        )
    ))
except Exception as e:
    lib.core.settings.logger.exception("test")
    print e
    lib.core.settings.logger.error(lib.core.settings.set_color(
        "ran into an error while trying to start the sqlmap API, please do it manually...", level=50
    ))

As you can see it will start the API, but then it will just hang at that point and will not continue (I've let it sit for about five minutes). So my question being, is there a way I can fork the system call into the background and continue moving along? I've been under the impression the subprocess.Popen will create a background process, that does not appear to be the truth here though. Any help would be greatly appreciated, thank you.


text:
Q: Neural Networks Overfitting with Python I am trying to model a network that takes in 90 parameters and give an integer between 1 and 6 inclusive.
Below is my scaled model that i intend to begin with and I appreciate any corrections or directions
self.model = keras.Sequential()
self.model.add(BatchNormalization(input_shape=(None, 90)))
self.model.add(Activation(activation="relu"))
self.model.add(LSTM(50))
self.model.add(Activation(activation="relu"))
self.model.add(Dropout(0.01))
self.model.add(Dense(7,  activation="softmax"))

self.train_epoch = 6000
opt = keras.optimizers.Adam(lr=0.000002)
self.model.compile(optimizer=opt, loss=keras.losses.sparse_categorical_crossentropy,  metrics=['accuracy'])
info = self.model.fit(self.x, self.y, epochs=self.train_epoch, validation_data=(self.m, self.n),  shuffle=True )

The issue comes in that my validation loss keeps increasing after some time.
I have tried small learning rates, high dropout value and even increased number of layers.
Can Someone please advise me on what I'm doing wrong.
I'm also not sure how many layers to use or nodes per each layer to achieve accuracy values greater than 0.5.
If someone can help I will give a link to the data and see if they can achieve better results.
Heres my current graph.enter image description here

A: Of course if you keep training for a long time, validation error will eventually increase.
As you mentioned in the title, it's a common result of over-fitting. And that's why you are checking validation error (to detect over-fitting and terminate the training), as well as training error.
You can monitor validation loss yourself, but also you can use early stopping.
The way to apply early stopping in Keras is introduced at:
https://machinelearningmastery.com/how-to-stop-training-deep-neural-networks-at-the-right-time-using-early-stopping/
And please note that LSTM is used for time-series data (keras.**Sequential**()).

A: Your statement and the graph are contradicting. When you experience overfitting always decrease the number of parameters of the model(i.e layers/kernels). Try training fewer epochs. You seem to be increasing them. Besides your chance-level is 1/7 and not 1/2. I believe its a 7 class problem.


text:
Q: Jenkins - Update / Edit the left panel label I have configured Jenkins in my system and running fine. But I need to configure the jenkins UI.
a) I want to remove the "Jenkins" logo in header and instead of that I need to add "some text title".
b) I want to edit the left panel labels.
Ex. Build history to Workflow history, My View to Workflow View and Build Executor Status to Workflow Executor Status
Do we have any option to edit the html/config file directly or need to install any plugin to edit these labels. Thanks for your valuable time.

A: You can use the Jenkin's plugin simple theme:
https://wiki.jenkins.io/display/JENKINS/Simple+Theme+Plugin
You can personalize the CSS, the home page, the favicon. Pretty much everything that you need.
If you just need to do minor changes, you can have a look at https://github.com/jenkinsci/jenkins/tree/master/src/site (site.xml). And the resources folder where the logo is stored.


text:
Q: Semantic issue, when trying to integrate SneakyJoystick into cocos2d-iphone 2.0 I am using cocos2d-iphone 2.0 (because Tiled does't work with last cocos2d-iphone version properly), and get this in the SneakyJoystick.h :
@interface SneakyJoystick : CCNode <CCTargetedTouchDelegate>
// semantic issue: Can't fine protocol declaration for 'CCTargetedTouchDelegate'

Someone faced the problem?

A: The protocol's name are changed
CCTargetedTouchDelegate now is CCTouchOneByOneDelegate
try this
@interface SneakyJoystick : CCNode <CCTouchOneByOneDelegate>


text:
Q: Negative margin on table row How do I give a
 a negative margin to move it up? I'm trying to move .small-item-block

  Caprese
  Fresh mozzarella, tomato, fresh basil and balsamic vinegar on a bed of spinach.
  $4.00
  $20.00

  Add Bacon
  $1.00
  $3.00

CSS
tr.small-item-block  {
   margin-top: -10px;
   border-spacing: -10px;
}

Here is the JS Fiddle.

A: You can't really move a row any higher than the row above it, so I think your best bet would be to remove margin/padding from the s inside that
. Example:
tr.small-item-block td {
  margin-top: 0;
  padding-top: 0;
}

A: You can't move a tr, but you can set the td's to position: relative, and then set a negative top property, like:
tr.small-item-block td {
    position: relative;
    top: -10px;
}

Here's your fiddle updated: http://jsfiddle.net/L4gLM/2/


text:
Q: Django view: get_context_data() vs get() We can do this in Django:
class LoginView(generic.FormView):

    def get_context_data(self, **kwargs):
        common = CommonView(self, **kwargs)
        context = super(LoginView, self).get_context_data(**kwargs)
        context['common'] = common.infos

or:
class LoginView(generic.FormView):

    def get(self, request, *args, **kwargs):
        common = CommonView(self, **kwargs)
        return render(request, self.template_name, {'common': common.infos })

Which one is better and why?

A: Using get_context_data() is interesting since it has only one goal (do one thing and do it well): pass data to the template.
On the other hand, get() has many tasks to do in order to return an HttpResponse in the end. get() should rather be a skeleton of method calls, delegating tasks. Among them, you have get_context_data(), and others according to the class you are inheriting.
As long as it is possible, I think it is better to let the parent class(es) handle the get(), post(), ... methods and use the convenience methods they provide.
As far as I'm concerned, the only case for which I had to handle the get() method myself is when writing generic views.

A: None of them is "better". I'd say it depends on the scenario what you need to do. get_context_data() is called for all the request methods (post, get), so if you need to have there some data available every time, use get_context_data(). If you need the data only for a specific request method (eg. in get), then put it in get.


text:
Q: How to retrieve flashvars of a GET request content? I want to add custom button to rails_admin new/edit page of specific model.
This button should parse the content of a get request to a custom URL.
The current problem I found using JQuery approach like this:
$('#your_button_id').click(function () {
  $.get('your_url', function(data) {
    //$('.result').html(data); - sample
    //Do whatever you want
    alert('Load was performed.');
  });
});

Is that it don't load the flashvars attribute.
I was wondering if there is any other alternative to retrieve the whole content with the flashvars included.

A: I'm not sure if you want to get just the URL or the response to a get request, so:
If you want the URL:
$('#your_button_id').click(function () {
  var sPageURL = window.location.search.substring(1);
  //manipulate the url in sPageURL
});

If you want the content of the url:
$('#your_button_id').click(function () {
  $.get('your_url', function(data) {
    //$('.result').html(data); - sample
    //Do whatever you want
    alert('Load was performed.');
  });
});

References:

*

*JQuery Load

*JQuery Get


text:
Q: Quantificando valores negativos em um array Estou tentando fazer um exercício, porém não foi da maneira como a plataforma queria, estou sem ideias de como resolver, estou no meu primeiro dia de javascript.... Segue o enunciado, o erro e minha tentativa.

Uma empresa mandou uma lista contendo os números mensais de tudo o que
ela faturou, e nosso trabalho é ajudá-los a criar um relatório que
exiba em quantos meses eles tiveram o saldo negativo.
var listaDeGanhos = [10, 30, -10, -5, -1, 40]
Com base no array acima, que está disponível no código, faça um loop
que verifique quantos meses tiveram valores negativos e armazene a
contagem uma variável chamada totalNegativos que também está
disponível no código.

No Código tem isso ja escrito
var listaDeGanhos = [10, 30, -10, -5, -1, 40]

var totalNegativos = 0

//minha tentativa

for ( var i = 0;  i < listaDeGanhos.length; i++){
    numeros = listaDeGanhos[i]
    if ( numeros < 0 ){
        console.log(totalNegativos++)
    }

}

Erro que recebo : Você deve verificar se o valor atual do array é negativo com um if

A: Existem várias soluções possíveis, se o enunciado pede apenas a quantidade de números negativos, a solução abaixo é simples e faz o que se pede, sem exibir um console com o número que é negativo.
var listaDeGanhos = [10, 30, -10, -5, -1, 40]
var totalNegativos = 0

//seu loop aqui:
for(var i = 0; i < listaDeGanhos.length; i++){
    if(listaDeGanhos[i] < 0)
     totalNegativos++
}
console.log(totalNegativos);

agora a solução mais bonita seria esta, mas que talvez o analisador de códigos não aceite:
var listaDeGanhos = [10, 30, -10, -5, -1, 40];

const negativos = listaDeGanhos.filter(number => number < 0 );

console.log(negativos.length);

A: let listaDeGanhos = [10, 30, -10, -5, -1, 40]

let totalNegativos = 0

listaDeGanhos.forEach(function (valor) {

    if(valor < 0){
        totalNegativos++
    }
})

console.log(totalNegativos) // 3

Agora se a plataforma exige realmente desta forma
var listaDeGanhos = [10, 30, -10, -5, -1, 40]

var totalNegativos = 0

for ( var i = 0;  i < listaDeGanhos.length; i++){

    if ( listaDeGanhos[i] < 0 ){
        totalNegativos++ // Acrescentando no total
        console.log(listaDeGanhos[i]) // Mostrando quanto foi
    }
}

// Mostre após o loop
console.log(totalNegativos)

A: Passa aí como ficou seu código por favor! estou tentando seguir a sua estrutura modificando aqui mas não está retornando corretamente. Segue o código:
var listaDeGanhos = [10, 30, -10, -5, -1, 40]

var totalNegativos = 0
//seu loop aqui:
for(var i = 0; i < listaDeGanhos.length; i++){
totalNegativos = listaDeGanhos[i]
if(listaDeGanhos[i] < 0){
console.log(totalNegativos++)
}
}

var listaDeGanhos = [10, 30, -10, -5, -1, 40]
var totalNegativos = 0

//seu loop aqui:
for(var i = 0; i < listaDeGanhos.length; i++){
    totalNegativos = listaDeGanhos[i]
if(listaDeGanhos[i] < 0){
   console.log(totalNegativos++)
}

}

A: var listaDeGanhos = [10, 30, -10, -5, -1, 40]
var totalNegativos = 0
for ( var i = 0;  i < listaDeGanhos.length; i++){
        if ( listaDeGanhos[i] < 0 )
        totalNegativos++
    }

A:

var listaDeGanhos = [10, 30, -10, -5, -1, 40]
var totalNegativos = 0

for (var i = 0; i < listaDeGanhos.length; i++){
  if(listaDeGanhos[i] < 0){
    totalNegativos ++;
  }

}
console.log(totalNegativos)

A: para mim, funcionou assim:
var listaDeGanhos = [10, 30, -10, -5, -1, 40]
var totalNegativos = 0
for (i = 0; i < listaDeGanhos.length; i++) {
console.log // aqui eu mandei apenas correr a contagem sem somar para validar a array
if (listaDeGanhos[i] < 0) {
console.log(totalNegativos++)  //o if valida os negativos e soma
}
}


text:
Q: RFB reference implementation? I'm writing an RFB server. I was wondering if anybody knows of an RFB reference client.
Currently, I run RealVNC and ask it to connect to my RFB server, and it works fine. However, RealVNC is intended to give a good end-user experience. It is not intended to test every possible valid combination of protocol features. So I know that the features which RealVNC uses are implemented correctly, but I have no idea whether the features that RealVNC doesn't use are working at all. But it would be really useful if I could check somehow.
Any suggestions?
(I could, of course, write my own RFB client as well. But that wouldn't really prove anything. If something doesn't work, I can't tell if it's the client or the server that's broken. And if everything does work, that still doesn't mean that both ends implement RFB correctly, just that each has the same bugs as the other.)

A: This  may help you  out a bit. I use  to use TCP/IP builder to make various hexcode messages(pointer event, key event, cut text)  store  them in a text  file. Now  i Used to  connect the tcp/ip builder with my rfb/vnc server.
The RFB server  you wrote will now  respond to this  TCP/IP builder  like  any RFB Client  and  you can now  verify  each and  every  scenario (  incomplete payload, wrong message number, extra  payload, message  out of  sequence etc)

Make  sure  you select "Parse Ascii" option  if  your  server  doesnt
  respond  with  rfb version number info  once  you  connect to  your
  server.

In  order  to make the  the intial message  you can  record  wireshark logs  for a successful  proper  rfb  session  between  your  rfb server and  real vnc and  then  use those  messages  to  test  your  RFB server  with TCP/IP builder.

The  RFB version  info can  be send  like this "RFB 003.008" , but
  for the  rest of the message  you  will have to  use hex symbol like
  it is  seen  network logs (pcap/wireshark)
example : this is  how to send  Framebuffer  request message to  your
  server (non-incremental  for  800 x 480)
0x030x000x000x000x000x000x030x200x010xe0


text:
Q: Gridlayout and color border I would like to create a Gridlayout with EditText inside and fill some boder with a color.
This GridLayout should "match_parent" and resize each items inside.
here is what i want :
Click Here
Here is what i have :
Click Here
Is it possible to do that ?
 <GridLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/profile_fragment_line_under_time"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="49dp"
    android:columnCount="6"
    android:numColumns="auto_fit"
    android:rowCount="4"
    android:stretchMode="columnWidth">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="0"
        android:layout_columnSpan="1"
        android:layout_row="0"
        android:layout_rowSpan="1"
        android:ems="10"
        android:focusable="false"
        android:gravity="center"
        android:hint="@string/add_new_dive_text_hint_time_in"
        android:inputType="time"
        android:textColor="@color/text_color_dark" />

    <View
        android:layout_width="wrap_content"
        android:layout_height="@dimen/line_size"
        android:layout_column="0"
        android:layout_columnSpan="1"
        android:layout_row="1"
        android:layout_rowSpan="1"
        android:background="@color/color_dark" />

    <View
        android:layout_width="wrap_content"
        android:layout_height="@dimen/line_size"
        android:layout_column="4"
        android:layout_columnSpan="1"
        android:layout_row="1"
        android:layout_rowSpan="1"
        android:background="@color/color_dark" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="0"
        android:layout_columnSpan="1"
        android:layout_row="2"
        android:layout_rowSpan="1"
        android:ems="10"
        android:focusable="false"
        android:gravity="center"
        android:hint="@string/add_new_dive_text_hint_deep"
        android:inputType="numberDecimal"
        android:textColor="@color/text_color_dark" />

    <View
        android:layout_width="@dimen/line_size"
        android:layout_height="match_parent"
        android:layout_column="1"
        android:layout_columnSpan="1"
        android:layout_row="2"
        android:layout_rowSpan="1"
        android:background="@color/color_dark" />

    <View
        android:layout_width="wrap_content"
        android:layout_height="@dimen/line_size"
        android:layout_column="2"
        android:layout_columnSpan="1"
        android:layout_row="3"
        android:layout_rowSpan="1"
        android:background="@color/color_dark" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="1"
        android:layout_columnSpan="1"
        android:layout_row="2"
        android:layout_rowSpan="1"
        android:ems="10"
        android:focusable="false"
        android:gravity="center"
        android:hint="@string/add_new_dive_text_hint_time"
        android:inputType="number"
        android:textColor="@color/text_color_dark" />

    <View
        android:layout_width="@dimen/line_size"
        android:layout_height="match_parent"
        android:layout_column="3"
        android:layout_columnSpan="1"
        android:layout_row="2"
        android:layout_rowSpan="1"
        android:background="@color/color_dark" />

    <ImageButton
        android:id="@+id/mybuttun"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="5"
        android:layout_columnSpan="1"
        android:layout_row="1"
        android:layout_rowSpan="1"
        android:background="@android:color/transparent"
        android:contentDescription="@string/desc" />

</GridLayout>

Thanks

A: I continued to investigate about this feature.
The result is not fully what i want but it's better then my previous version.
I just need to write code to resize the buttons in my GridLayout
Here is a pic :
Click Here
Here is the result :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/fragment_dive_profile_title_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="@dimen/layout_margin"
    android:background="@color/background_header_color"
    android:gravity="center"
    android:text="@string/add_new_dive_title_profile"
    android:textSize="@dimen/title_size" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/fragment_dive_profile_title_text_view"
    android:orientation="horizontal">

    <GridLayout
        android:id="@+id/fragment_dive_profile_gridLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="@dimen/layout_margin"
        android:layout_weight="2"
        android:alignmentMode="alignMargins"
        android:columnCount="5"
        android:rowCount="4"
        android:useDefaultMargins="false">

        <EditText
            android:id="@+id/fragment_dive_profile_time_in_edit_text"
            android:layout_width="@dimen/fragment_dive_profile_edit_text_size"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_columnSpan="1"
            android:layout_row="0"
            android:layout_rowSpan="1"
            android:focusable="false"
            android:gravity="center_horizontal"
            android:hint="@string/add_new_dive_text_hint_time"
            android:inputType="number"
            android:textColor="@color/text_color_dark" />

        <EditText
            android:id="@+id/fragment_dive_profile_time_out_edit_text"
            android:layout_width="@dimen/fragment_dive_profile_edit_text_size"
            android:layout_height="wrap_content"
            android:layout_column="4"
            android:layout_columnSpan="1"
            android:layout_row="0"
            android:layout_rowSpan="1"
            android:focusable="false"
            android:gravity="center_horizontal"
            android:hint="@string/add_new_dive_text_hint_time_in"
            android:inputType="number"
            android:textColor="@color/text_color_dark" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="@dimen/line_size"
            android:layout_column="0"
            android:layout_gravity="fill_horizontal"
            android:layout_row="1"
            android:contentDescription="@string/desc"
            android:src="@color/blue_color_dark" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="@dimen/line_size"
            android:layout_column="4"
            android:layout_gravity="fill_horizontal"
            android:layout_row="1"
            android:contentDescription="@string/desc"
            android:src="@color/blue_color_dark" />

        <ImageView
            android:layout_width="@dimen/line_size"
            android:layout_height="match_parent"
            android:layout_column="1"
            android:layout_gravity="fill_vertical"
            android:layout_row="1"
            android:layout_rowSpan="2"
            android:contentDescription="@string/desc"
            android:src="@color/blue_color_dark" />

        <EditText
            android:id="@+id/fragment_dive_profile_depth_editText"
            android:layout_width="@dimen/fragment_dive_profile_edit_text_size"
            android:layout_height="wrap_content"
            android:layout_column="2"
            android:layout_columnSpan="1"
            android:layout_row="2"
            android:layout_rowSpan="1"
            android:focusable="false"
            android:gravity="center_horizontal"
            android:hint="@string/add_new_dive_text_hint_deep"
            android:inputType="numberDecimal"
            android:textColor="@color/text_color_dark" />

        <ImageView
            android:layout_width="@dimen/line_size"
            android:layout_height="match_parent"
            android:layout_column="3"
            android:layout_gravity="fill_vertical"
            android:layout_row="1"
            android:layout_rowSpan="2"
            android:contentDescription="@string/desc"
            android:src="@color/blue_color_dark" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="@dimen/line_size"
            android:layout_column="1"
            android:layout_columnSpan="3"
            android:layout_gravity="fill_horizontal"
            android:layout_row="3"
            android:contentDescription="@string/desc"
            android:src="@color/blue_color_dark" />

    </GridLayout>

    <ImageButton
        android:id="@+id/fragment_dive_profile_add_remove_buttun"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="@dimen/layout_margin"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:contentDescription="@string/desc"
        android:src="@drawable/ic_action_remove_dark" />
</LinearLayout></RelativeLayout>

If anyone else have another idea, you're welcome !!!


text:
Q: How to declare multiple variables with specifying type using As in VBA? According to this documentation by Microsoft, the following code can be used to make sure;

a, b, and c are all Single; x and y are both Double

Dim a, b, c As Single, x, y As Double, i As Integer
> a, b, and c are all Single; x and y are both Double

The logic behind this is as follows

You can specify different data types for different variables by using a separate As clause for each variable you declare. Each variable takes the data type specified in the first As clause encountered after its variable name part.

However, when I checked with the debugger or MsgBox VarType(a)  output, this is not the case.

As you can see, it appears that As is only working for the variables right before itself, ie., c, y and i. All others are Variant/Empty and VarType returns 0.
Is this just the documentation being wrong, or am I missing something obvious?
Microsoft Visual Basic for Application 7.1.1056
Excel 2016 (Windows 10)

A: In VBA, when you declare
Dim a, b, c As Single

What it does is equivalent to this:
Dim a As Variant, b As Variant, c As Single

I believe the best practice is to always declare variable in a separate row. It prevents this bug and also allows for faster scanning of the code. So the code would look like this:
Dim a As Single
Dim b As Single
Dim c As Single

A: The documentation you've linked to isn't wrong, but it's written for VB.NET and not VBA.
In VBA, as you've observed, any variable declarations that aren't immediately followed by As <type> will be Variant.
Therefore you'd need to write:
Dim a As Single, b As Single, c As Single, x As Double, y As Double, i As Integer


text:
Q: Updating on-screen element several times in one function This has got to be easy, but has got me stumped.
How do I change an element on screen several times in one function?
I want to change a label to read something like "starting..." at the beginning of my function, then go away and do some stuff and then change the label to "finished" at the end.
As an illustration why does the following code:
        errorMessage.Text = "Three...";
        System.Threading.Thread.Sleep(1000);
        errorMessage.Text = "Two...";
        System.Threading.Thread.Sleep(1000);
        errorMessage.Text = "One...";
        System.Threading.Thread.Sleep(1000);
        errorMessage.Text = "Go!";
        System.Threading.Thread.Sleep(1000);

Just pause for 4 seconds and then change the label text to "Go!" rather than counting down?
TIA
Ben

A: If you want to time a process and put your results out to a label you should use a string in your function instead. Try something like this:
string countDownTimes = "";
countDownTimes += String.Format("One at: {0}, ",DateTime.Now.ToString());
System.Threading.Thread.Sleep(1000);
countDownTimes += String.Format("Two at: {0}, ",DateTime.Now.ToString());
//etc..
errorMessage.Text = countDownTimes;

If your looking to update the UI button in increments then you should look at a javascript solution or async updates.

A: The reason that your code only updates the screen once is that it is running inside of a single postback. At the end of the postback, HTML is rendered in returned to the browser for display.
Updating the page multiple times during a postback actually isn't easy. But for what you're doing, there is an easier solution. Use JavaScript to change the caption to "Starting..." at the beginning of the request, and then have the method return "Finished."

A: Because it is a web page, and the final value is what is sent to the browser.  All server side code executes and then sends the final values to browser.
Your code is updating the control with the new value on the server, but it won't be seen by the client. To do what you want, you either have to update the control through client side script (javascript), or you have to refresh the page and display the updated value.
Here is a link to the asp.net pages life cycle which is kinda what you are asking about.
http://msdn.microsoft.com/en-us/library/ms178472.aspx
If you notice nothing is sent to the browser until the Render method.

A: You need to learn about how the web works;

*

*A browser requests a page from the server

*The server sends the page (and might do some server-side processing such as ASP.net)

*The client shows the page and runs javascripts on the page

Then these javascripts might change the page after it has loaded, but step 2 can't go and change something that's already been sent to the client.

A: If it's ASP.NET all the code will be executed prior to send the html to the browser so only the last value will be shown. If you want to do that at client side you will have to do some javascript.


text:
Q: Most effective way to detect if a specific external exe program is currently running using vb.net code? I need a way for my VB.NET program to detect if certain external programs are running while its running however, I dont want someone to be able to circumvent this by changing the external exe program (im trying to detect) by simply change the program's title bar text or the executable's file name. I'm trying to write this detection code using vb.net. Thanks for any help you can offer.
Please include some sample code if you know how to code it.


text:
Q: Get target element from Vue directive <template>
  <div @click="onClick(target??)">click me</div>
</template>

<script>
...
onClick(t){
  console.log(t)
}
...
</script>

Can I retrieve target(DOM element) of directive event inside the directive like above?


text:
Q: Android App Will Not Open I have just created an Android app in Intellij. It works beautifully on the emulator, which is the same version of Android as I have on my phone (2.3.3) However, when i install the apk file on my phone, it installs fine, but then you can't open the app.
What I mean is that the install finishes and you have a done option but open is grayed out. There is no item in the menu, and there is no shortcut made. I have this in the manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

<application android:label="@string/app_name" android:icon="@drawable/icon" android:enabled="true">
    <activity android:name="PhlogMain"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name=".PhlogEditNotes"/>
    <service android:name=".PhlogListenerService"/>
</application>

I have the Samsung Galaxy Ace S5830 phone.

A: So after much work I rebuilt the whole thing, changed the keys and tried again and it worked. I am not really sure where it started to work but at least it is now! :-)


text:
Q: $.getJSON data not displaying in loop with ajaxSubmit I've been having a few issues trying to execute a dynamically loaded form with jquery. Here is my code:
$(this).ajaxSubmit({
    url: '/postform1.php',
    type: 'post',
    //target: '#preview',
    success: function(msg) {

        var s = msg + '<form name="sr" id="sr" action="postform.php" method="post"><input type="text" /></form>';
        $('#preview').html(s);

        $.getJSON("/postform1.php", function(data){
        var counter = 0;
        if(data) {
           $.each(data, function(i, val) {
                var newTextBoxDiv = $(document.createElement('div')).attr("id", val);
                newTextBoxDiv.after().html('<label>' + i + ' : </label>' + '<input type="text" name="' + i + '" id="' + i + '" value="' + val + '" >');
                newTextBoxDiv.appendTo("#sr");
                counter++;
            });
        }
        });
    }
 });

I was initially echoing the whole form from postform1.php but found the form was not submitting. I dont know if this is the right way of going about it either but figured i'd give it a try. If anyone has any ideas it would be great ro hear from you.

A: You missed to declare:
contentType: " ... ",
dataType: " ... "

A: thanks for looking into this, managed to sort it. I just changed this also:
var newTextBoxDiv = $(document.createElement('div')).attr("id", val);
            newTextBoxDiv.after().html('<label>' + i + ' : </label>' + '<input type="text" name="' + i + '" id="' + i + '" value="' + val + '" >');
            newTextBoxDiv.appendTo("#sr");
            counter++;

to this:
var newTextBoxDiv = $(document.createElement('div')).attr("id", val);
                newTextBoxDiv.html('<label>' + i + ' : </label>' + '<input type="text" name="' + i + '" id="' + i + '" value="' + val + '" >');
                newTextBoxDiv.appendTo(".sr");
                counter++;


text:
Q: Problems with const members of a union within a structure I wanted to declare some parts of the structure as being const as I'm passing it to a 3rd party in an API call.  I'm planning to populate the values by casting away const using a C style cast.  That allows me to set them but the user of the API knows that these are input values as they can't easily set them.
Cutting it down to a simple example, I have
struct mystruct
{
  union valuesUnion
  {
    const int32_t integer;
    const double real;
    valuesUnion() : integer(0), real(0.0) {}
  } values;
  mystruct() : values(valuesUnion())
  {
  }
};

int main()
{
  mystruct a;
}

Note that I had to add a constructor for "mystruct" or you get a compilation error due to uninistalised const variables.
But I get an error -
g++     Z.cpp   -o Z
Z.cpp: In constructor âmystruct::valuesUnion::valuesUnion()â:
Z.cpp:11:5: error: initializations for multiple members of âmystruct::valuesUnionâ
make: * [Z] Error 1
I can fix this if I change the union constructor to read -
valuesUnion() : integer(0) {}

I then don't get an error from g++ but it fails to compile on Visual Studio 2012 -
valuesUnion::real' : must be initialized in constructor base/member initializer list
Am I going about this the wrong way?
Thanks.

A: Union isn't like class or struct as the two "attributes" reference the same memory unit.
You can only initialize this memory once you are giving two initializations for the same memory area.
If you change
union valuesUnion

for
struct valuesUnion

Then you can check that your initialization list is right for different memory areas.


text:
Q: Can Lua send extended function Keys? ex F13-F24 I tried sending F13 with kb.stroke("F13");
Well it doesn't work, works fine with anything F12 and below.
I'm trying to use this in a custom remote in Unified Remote app, so my only workaround for know is using os.start to run an ahk script that does the key sending but it's a very slow approach.
Any help will be appreciated.

A: local ffi = require"ffi"

ffi.cdef[[
typedef struct {
   uintptr_t type;
   uint16_t  wVk;
   uint16_t  wScan;
   uint32_t  dwFlags;
   uint32_t  time;
   uintptr_t dwExtraInfo;
   uint32_t  x[2];
} INP;
int SendInput(int, void*, int);
]]

local inp_t = ffi.typeof"INP[2]"

local function PressAndReleaseKey(vkey)
   local inp = inp_t()
   for j = 0, 1 do
      inp[j].type = 1
      inp[j].wVk = vkey
      inp[j].dwFlags = j * 2
   end
   ffi.C.SendInput(2, inp, ffi.sizeof"INP")
end

PressAndReleaseKey(0x57)  -- W
PressAndReleaseKey(0x7C)  -- F13

VKeys:
https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes