text:
Q: How can I detect whether a user control is running in the IDE, in debug mode, or in the released EXE? I have a user control that I'm building.  It's purpose is to display the status of a class to the user.  Obviously, this does not matter, and will slow things down when the control runs in the IDE, as it does as soon as you add it to a form.
One way to work around this would be to have the control created and added to the controls collection of the form at run-time.  But this seems less than perfect.
Is there a way to set a flag in the control so that it can skip certain sections of code based on how it is running?
p.s. I'm using C# and VS 2008

A: I found this answer on another post and it seems to be easier and working better for my situation.
Detecting design mode from a Control's constructor
using System.ComponentModel;

if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
}

A: public static bool IsInRuntimeMode( IComponent component ) {
    bool ret = IsInDesignMode( component );
    return !ret;
}

public static bool IsInDesignMode( IComponent component ) {
    bool ret = false;
    if ( null != component ) {
        ISite site = component.Site;
        if ( null != site ) {
            ret = site.DesignMode;
        }
        else if ( component is System.Windows.Forms.Control ) {
            IComponent parent = ( (System.Windows.Forms.Control)component ).Parent;
            ret = IsInDesignMode( parent );
        }
    }

    return ret;
}

A: This is the method I used in my project:
//use a Property or Field for keeping the info to avoid runtime computation
public static bool NotInDesignMode { get; } = IsNotInDesignMode();
private static bool IsNotInDesignMode()
{
    /*
    File.WriteAllLines(@"D:\1.log", new[]
    {
        LicenseManager.UsageMode.ToString(), //not always reliable, e.g. WPF app in Blend this will return RunTime
        Process.GetCurrentProcess().ProcessName, //filename without extension
        Process.GetCurrentProcess().MainModule.FileName, //full path
        Process.GetCurrentProcess().MainModule.ModuleName, //filename
        Assembly.GetEntryAssembly()?.Location, //null for WinForms app in VS IDE
        Assembly.GetEntryAssembly()?.ToString(), //null for WinForms app in VS IDE
        Assembly.GetExecutingAssembly().Location, //always return your project's output assembly info
        Assembly.GetExecutingAssembly().ToString(), //always return your project's output assembly info
    });
    //*/

    //LicenseManager.UsageMode will return RunTime if LicenseManager.context is not present.
    //So you can not return true by judging it's value is RunTime.
    if (LicenseUsageMode.Designtime == LicenseManager.UsageMode) return false;
    var procName = Process.GetCurrentProcess().ProcessName.ToLower();
    return "devenv" != procName //WinForms app in VS IDE
        && "xdesproc" != procName //WPF app in VS IDE/Blend
        && "blend" != procName //WinForms app in Blend
        //other IDE's process name if you detected by log from above
        ;
}

Attention!!!: The code returned bool is indicating NOT in design mode!


text:
Q: How is quality factor affected when combining inductors? Lets say I have an inductor, L1 = 22 nH, with a quality factor (Q) of 50. I need an inductor of 44 nH, so I put two L1s in series. Will the Q of "the combined inductor" be 50?
What if I want half the inductance, and place two L1s in parallel?
Best regards
-paw

A: The value of Q relates the impedance of the inductor to its resistance:
Q = X(L)/R, so for a frequency f,
Q = 2 pi f L / R.
For a series connection both L and R sum, so
Q' = 2 pi f (2L) / 2R
The factors of 2 cancel, and the Q of the composite inductor (Q') is identical to the Q of the component inductors (for the case identical Qs).
The same calculation can be made for any number of inductors, in series or in parallel. In all cases, the composite Q will lie somewhere between the highest and lowest Qs of the individual components.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get text from Input field in Unity3D with C# I'm trying to get a text inside an inputField in Unity3D with C#.
I've placed an inputField in my editor, renamed and tagged in: Username_field.
My question is: How i can get the text inside the InputField Username_field in a C# script?

A: Attach below monobehaviour script to your InputField gameObject:
public class test : MonoBehaviour {
    void Start ()
    {
        var input = gameObject.GetComponent<InputField>();
        var se= new InputField.SubmitEvent();
        se.AddListener(SubmitName);
        input.onEndEdit = se;

        //or simply use the line below,
        //input.onEndEdit.AddListener(SubmitName);  // This also works
    }

    private void SubmitName(string arg0)
    {
        Debug.Log(arg0);
    }
}

See also below animation:

A: You can use the "On Value Change" or "End Edit" event of the InputField.
The Unity3D documentation provides more detail on how to use a UnityEvent: http://docs.unity3d.com/Manual/UnityEvents.html
Alternatively, you should also be able to access the Text using the Text property of the Text control that your InputField is attached to.

A: using UnityEngine.UI;
public InputField betInput;
void Start () {
    betInput.onEndEdit.AddListener(delegate { inputBetValue(betInput); });
}
public void inputBetValue(InputField userInput)
{
    betValue = int.Parse(userInput.text);
    Debug.Log(userInput.text);
}

https://i.stack.imgur.com/CeF1a.png //This is unity Picture where you select method.
Also worth checking out https://unity3d.com/learn/tutorials/topics/scripting/text-input


text:
Q: How to fix Scanner throws NoSuchElementException but won't wait for input? I am trying to read input from the console using the Scanner class but no matter what I've tried so far it always errors on my computer with
"Exception in thread "main" java.util.NoSuchElementException: No line found"
public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");
    String userName = myObj.nextLine();
    System.out.println("Username is: " + userName);
}

I tried this with an online code site Repl.it and it works fine there but not on my computer. I am running Debian Buster with the latest OpenJDK and JRE with the latest version NetBeans IDE.
This is my system info from NetBeans
Product Version: Apache NetBeans IDE 11.1
Java: 11.0.4; OpenJDK 64-Bit Server VM 11.0.4+11-post-Debian-1deb10u1
Runtime: OpenJDK Runtime Environment 11.0.4+11-post-Debian-1deb10u1
System: Linux version 4.19.0-5-amd64 running on amd64; ANSI_X3.4-1968;        en_US (nb)

I have tried checking for the next element using hasNext() like this
public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");
    if(myObj.hasNext()){
        String userName = myObj.nextLine();
        System.out.println("Username is: " + userName);
    }
}

The console never waits for user input so hasNext() always returns false. This code works okay on repl.it but not on my computer. I have tried purging and reinstalling the JDK, JRE, and reinstalling NetBeans but the issue persists and I'm not sure what the issue is now.
How can I fix this problem?

A: Just write
run.standardInput = System.in;
In your gradle.build file


text:
Q: How To incorporate TurboParser Instead of MaltParser for improved results like from online demo? I have successfully installed Semafor on Linux Mint 18.1 and I can run it. But the results I get from my version differs drastically from the online demo. I realized that online demo uses TurboParser, not MaltPraser. I tried A LOT to download TurboParser's model, but the remote host is sending data on 100 KB/s which is so lousy while I can download from other web sites at about 1 MB/s! But I kept on downloading and finally received a corrupted file. Now I have a request and a question:

*

*Can any one upload the model on a better host? Maybe a Google drive or so?

*How can TurboParser be incorporated in Semafor? I could not figure it out because I failed to download the model.


text:
Q: Why Apache doesn't gzip css or js files which have parameters? Some CSS & JS files are not compressed by apache with mod_deflate enabled. This files looks like this "[domain.name]/aggregator.css?..." or "[domain.name]/misc/jquery.js?..." in YSlow. The other CSS & JS without the "?" gets compressed. Kindly explain me how do I make apache compress this files also.
I added the following line on the .htaccess file
  <IfModule mod_deflate.c>
        <FilesMatch "\.(css|js|x?html?|php)$">
           SetOutputFilter DEFLATE
        </FilesMatch>
  </IfModule>

Thanks

A: Hrm, interesting. I can't reproduce this:
[root@dev ~]# cat /etc/httpd/conf.d/test.conf
<FilesMatch "\.txt$">
  SetOutputFilter DEFLATE
  Header set X-Ping "Pong"
</FilesMatch>

[root@dev ~]# GET -SedH 'Accept-Encoding: gzip, deflate' 'http://localhost/test.txt'
GET http://localhost/test.txt --> 200 OK
Content-Encoding: gzip
Content-Length: 2449
X-Ping: Pong

[root@dev ~]# GET -SedH 'Accept-Encoding: gzip, deflate' 'http://localhost/test.txt?foo'
GET http://localhost/test.txt?foo --> 200 OK
Content-Encoding: gzip
Content-Length: 2449
X-Ping: Pong

(unrelated headers removed)
As mentioned above, FilesMatch matches filesystem paths, not URIs. Are the resources that aren't being compressed files on the filesystem or are they generated on the fly, or proxied, or redirected or something else that breaks direct URI-to-filesystem mapping? You could try using LocationMatch instead, which is probably a better bet anyway if any part of your app isn't static files.
<IfModule mod_deflate.c>
  <LocationMatch "\.(css|js|x?html?|php)$">
     SetOutputFilter DEFLATE
  </LocationMatch>
</IfModule>

A: The $ at the end of your regular expression will match the end of the URL, so if there is anything after the file extension, it won't match. You could omit the $ but then it would match if there was a ".css" etc. anywhere in the URL. Something like the example below might be safer. This should match either ".css" at the end of URL, or ".css" followed by ?, some parameters, and then the end of the URL.
   <IfModule mod_deflate.c>
        <FilesMatch "\.(css|js|x?html?|php)($|\?.*$)">
           SetOutputFilter DEFLATE
        </FilesMatch>
   </IfModule>


text:
Q: Make a custom button invisible based on a field value How can we make a custom button visible based an the status of a field on a standard layout ( not a visualforce page) in a custom object.

A: Here's a tutorial by Tehnrd:
http://www.tehnrd.com/show-and-hide-buttons-on-page-layouts/

A: This is possible leveraging record types and a unique page layout for each. The jQuery solution posted by Matthew looks really cool though.


text:
Q: Two power sources into appliance (12Vdc) I am creating powering board for LED strips inside the cacti glass house. It consume 12V DC around 2 amps. I would like to power them up from battery (charged by solar, lead-acid battery 20Ah), but if there is no energy left, switch to DC power supply (12vdc).
I found the answers that it is possibly made by diodes here. But I do not fully understand, I am a programmer with no electro background, so I am a beginner (and I love it :)). I do not understand how to wire the diodes to do the job.
I understand that it will choose higher voltage, so when the battery drops down below some limit, it will take power from the power source. But how to do it, please?

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. Diode connection.
There will be a small voltage drop (0.7 to 1.0 V) across the diodes but it shouldn't cause any problems.


text:
Q: Nginx - Can't Upload file larger than 10Kb I built a file upload form using AJAX code that runs perfectly on my localhost.
However, when I upload this code to my nginx server. I get a net::ERR_CONNECTION_RESET when trying to upload any file larger the 10KB (yes that is a K). I'm using HTTPS.
Below is my ajax code :
$("#save-button").click(function(){
    console.log("max_execution_time = <?php echo(ini_get('max_execution_time')); ?>");
    console.log("max_input_time = <?php echo ini_get('max_input_time'); ?>");
    console.log("memory_limit = <?php echo ini_get('memory_limit'); ?>");
    console.log("post_max_size = <?php echo ini_get('post_max_size'); ?>");
    console.log("file_uploads = <?php echo ini_get('file_uploads'); ?>");
    console.log("upload_max_filesize = <?php echo ini_get('upload_max_filesize'); ?>");
    console.log("max_file_uploads = <?php echo ini_get('max_file_uploads'); ?>");
    console.log("default_socket_timeout = <?php echo ini_get('default_socket_timeout'); ?>");

    var formData = new FormData();

    var formRawData = $('#info-form-container').serializeArray();

    formRawData.forEach(function(element) {
        if(element.value!=""){
            formData.append(element.name, element.value);
        }
    });

    formData.append('data[ID]',id);
    formData.append('data[FLAG]', myData.CURRENT_FLAG)
    if (myData.CURRENT_FLAG == 1 || myData.CURRENT_FLAG == 6) {
        console.log($("#file")[0].files[0])
        formData.append('FILE', $("#file").prop('files')[0])
    }

    var xhr = new XMLHttpRequest();

    xhr.open('POST', '/mrk/Csr_mkt/save/', true);

    var onerror = function(event) {
        toastr.error("Error");
    }

    xhr.onload = function () {
        if (xhr.status === 200) {
            response = JSON.parse(xhr.responseText);

            if(response.errorId == 0) {
                notifsuccess(response.message);
            } else {
                swal('', response.message, 'error')
            }
        }
    };

    xhr.send(formData);

    return false;
});

Result
Below is the result from my browser console :

NGinx Conf
Below is my nginx conf :
#NGINX CodeIgniter CONFIG
#=========================================================
#
# The default server
#
server {
    listen 80 default_server;
#   listen [::]:80 default_server;
#   listen 443 https;
    client_max_body_size 100M;
#    ssl on;
#    ssl_certificate /etc/ssl/certs/ca-bundle.crt;
#    ssl_certificate_key /etc/ssl/privatekey3.key;

    server_name mydomain.id www.mydomain.id;
#   server_name mydomain.id www.mydomain.id localhost;
#   return 301 https://ganeshaoperation.id$request_uri;
#   rewrite ^/(.+) https://mydomain.id/$1 permanent;
        root  /var/www/html/go-erp;
#       dev02 /var/www/html/go-erp;
        index  index.php index.htm index.html;
    #charset koi8-r;

    access_log  /var/log/nginx/appsvr1_acces.log  main;
    error_log  /var/log/nginx/appsvr1_error.log;

    location / {
        #try_files $uri $uri/ /index.php;
        try_files $uri $uri/ /index.php?$uri; # CI

        }

   location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
        expires max;
        log_not_found off;
    }

 # redirect server error pages to the static page /50x.html
 #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    error_page  404              /404.html;
    location = /404.html {
        root   /usr/share/nginx/html;
    }

    location  /pmd {
        auth_basic "Admin Login";
        auth_basic_user_file /etc/nginx/pma_pass;
        index index.php;
    }

  location ~ \.php$ {
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(.*)$;
    include /etc/nginx/fastcgi_params;
    fastcgi_read_timeout 150;
    fastcgi_pass 127.0.0.1:9000;
    #fastcgi_pass 127.0.0.1:80;
    #fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    #fastcgi_param HTTP_PROXY "";
  }

  location /uploads/ {
    internal;
    alias /var/www/html/go.erp_ori/uploads/;
    try_files $uri /$uri none.png / none.png;
        client_max_body_size 100M;
  }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny  all;
    }
}

Please help me, thank you very much

A: Please try to put the line below in your nginx conf file in server, http or location context:
client_max_body_size 1024m;

and remember to reload or restart your nginx.

A: Be sure about allowed maximum upload size on server side. If it is the case, increase the value.
https://www.tecmint.com/limit-file-upload-size-in-nginx/


text:
Q: Prioritization of pthread_rwlock? Considering this example code:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

void *func1(void *);
void *func2(void *);

static pthread_rwlock_t rwLock = PTHREAD_RWLOCK_INITIALIZER;

int main() {

    pthread_t thread1;
    pthread_t thread2;

    pthread_create(&thread1, NULL, func1, NULL);
    sleep(1);
    int i;
    for (i = 0; i < 3; i++) {
        pthread_create(&thread2, NULL, func2, (void *)(i + 1));
    }

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    return 0;
}

void *func1(void *arg) {

    int j;
    for(j = 0; j < 10; j++) {

        printf("func 1: trying lock\n");
        pthread_rwlock_wrlock(&rwLock);
        printf("func 1: lock aquired, sleep 1 sec...\n");

        sleep(1);

        pthread_rwlock_unlock(&rwLock);
    }
}

void *func2(void *arg) {

    int true = 1;
    while(true) {

        pthread_rwlock_rdlock(&rwLock);

        printf("func 2: thread %i: lock aquired, sleep 1 sec... \n", (int)arg);
        sleep(1);

        pthread_rwlock_unlock(&rwLock);
    }
}

I have one thread looping over in func1 in which write lock is asked for 1 second, and 3 others looping over in func 2 in which read lock is asked for 1 second.
On the pthread_rwlock_rdlock man page it says "The calling thread acquires the read lock if a writer does not hold the lock and there are no writers blocked on the lock. ". From my output paste on line 5 you can see on "func 1: trying lock" a writer is clearly on block there, so why do my readers will get the lock anyway? After line 5, 3 lines are printed each second. Reducing my reader threads increases writer's chance to get the lock.
func 1: trying lock
func 1: lock aquired, sleep 1 sec...
func 1: trying lock
func 1: lock aquired, sleep 1 sec...
func 1: trying lock
func 2: thread 1: lock aquired, sleep 1 sec...
func 2: thread 3: lock aquired, sleep 1 sec...
func 2: thread 2: lock aquired, sleep 1 sec...
func 2: thread 2: lock aquired, sleep 1 sec...
func 2: thread 3: lock aquired, sleep 1 sec...
func 2: thread 1: lock aquired, sleep 1 sec...
func 2: thread 2: lock aquired, sleep 1 sec...
func 2: thread 3: lock aquired, sleep 1 sec...
func 2: thread 1: lock aquired, sleep 1 sec...
func 2: thread 3: lock aquired, sleep 1 sec...
func 2: thread 1: lock aquired, sleep 1 sec...
func 2: thread 2: lock aquired, sleep 1 sec...
func 2: thread 3: lock aquired, sleep 1 sec...
func 2: thread 2: lock aquired, sleep 1 sec...
func 2: thread 1: lock aquired, sleep 1 sec...
func 2: thread 3: lock aquired, sleep 1 sec...
func 2: thread 1: lock aquired, sleep 1 sec...
func 2: thread 2: lock aquired, sleep 1 sec...
...

Added another example
#define _GNU_SOURCE

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#define SIZE 10000

void *writerFunc(void *);
void *readerFunc1(void *);
void *readerFunc2(void *);
int setSchedulePolicyTo2(void);

static pthread_rwlock_t rwLock = PTHREAD_RWLOCK_INITIALIZER;

int main() {

    pthread_t readerThread1;
    pthread_t readerThread2;
    pthread_t writerThread;

    pthread_create(&readerThread1, NULL, readerFunc1, NULL);
    sleep(1);
    pthread_create(&readerThread1, NULL, writerFunc, NULL);
    sleep(1);
    pthread_create(&readerThread2, NULL, readerFunc2, NULL);

    pthread_join(readerThread1, NULL);
    pthread_join(readerThread2, NULL);
    pthread_join(writerThread, NULL);

    return 0;
}

void *writerFunc(void *arg) {
    printf("                writer's scheduling policy: %d\n", setSchedulePolicyTo2());

    printf("writer 1: trying to acquire rw lock...(on hold)\n");
    pthread_rwlock_wrlock(&rwLock); // Note ..._wrlock
    printf("writer 1: rw lock acquired \n");
    pthread_rwlock_unlock(&rwLock);
}

void *readerFunc1(void *arg) {
    printf("                reader1's scheduling policy: %d\n", setSchedulePolicyTo2());

    printf("reader 1: trying to acquire rw lock...(on hold)\n");
    pthread_rwlock_rdlock(&rwLock);
    printf("reader 1: rw lock acquired \n");
    sleep(3); // enough time to let reader 2 to acquire rw lock before this reader releases it.
    pthread_rwlock_unlock(&rwLock);
    printf("reader 1: rw lock released \n");
}

void *readerFunc2(void *arg) {
    printf("                reader2's scheduling policy: %d\n", setSchedulePolicyTo2());

    printf("reader 2: trying to acquire rw lock...(on hold)\n");
    pthread_rwlock_rdlock(&rwLock);
    printf("reader 2: rw lock acquired \n");
    sleep(2);
    pthread_rwlock_unlock(&rwLock);
    printf("reader 2: rw lock released \n");
}

int setSchedulePolicyTo2() {
    struct sched_param sp;
        sp.sched_priority = 10;
    int policy;
    int j;
    if((j = pthread_setschedparam(pthread_self(), SCHED_RR, &sp)) != 0) {
        printf("error: %s \n", strerror(errno));
    }
    if((j = pthread_getschedparam(pthread_self(), &policy, &sp)) != 0) {
        printf("error: %s \n", strerror(errno));
    }
    return policy;
}

output:
$ gcc main.c -pthread
$ sudo ./a.out
                reader1's scheduling policy: 2
reader 1: trying to acquire rw lock...(on hold)
reader 1: rw lock acquired
                writer's scheduling policy: 2
writer 1: trying to acquire rw lock...(on hold)
                reader2's scheduling policy: 2
reader 2: trying to acquire rw lock...(on hold)
reader 2: rw lock acquired
reader 1: rw lock released
reader 2: rw lock released
writer 1: rw lock acquired
Segmentation fault (end of program)

As per the manpage of pthread_rwlock_rdlock, reader 2 should not acquire the lock because there is writer on hold with same priority and all threads' scheduling policy is set to SCHED_RR (2).

If the Thread Execution Scheduling option is supported, and the
  threads involved in the lock are executing with the scheduling
  policies SCHED_FIFO or SCHED_RR, the calling thread shall not acquire
  the lock if a writer holds the lock or if writers of higher or equal
  priority are blocked on the lock; otherwise, the calling thread shall
  acquire the lock.

The writer acquires the lock only when both readers have released the rw lock.

A: Read the manpage carefully.
Note that the sentence you quoted

The calling thread acquires the read lock if a writer does not hold the lock and there are no writers blocked on the lock

does not say that the reader will not acquire the lock if there are writers blocked (if rather than if and only if.
The following will use the POSIX documentation.
The paragraphs immediately following the quoted sentence specify how pthread_rwlock_rdlock() acts if there are writers blocked on the lock:

[TPS] [Option Start] If the Thread Execution Scheduling option is supported, and the
  threads involved in the lock are executing with the scheduling
  policies SCHED_FIFO or SCHED_RR, the calling thread shall not acquire
  the lock if a writer holds the lock or if writers of higher or equal
  priority are blocked on the lock; otherwise, the calling thread shall
  acquire the lock. [Option End]
[TPS TSP] [Option Start] If the Threads Execution Scheduling option is
  supported, and the threads involved in the lock are executing with the
  SCHED_SPORADIC scheduling policy, the calling thread shall not acquire
  the lock if a writer holds the lock or if writers of higher or equal
  priority are blocked on the lock; otherwise, the calling thread shall
  acquire the lock. [Option End]
If the Thread Execution Scheduling option is not supported, it is
  implementation-defined whether the calling thread acquires the lock
  when a writer does not hold the lock and there are writers blocked on
  the lock. If a writer holds the lock, the calling thread shall not
  acquire the read lock. If the read lock is not acquired, the calling
  thread shall block until it can acquire the lock. The calling thread
  may deadlock if at the time the call is made it holds a write lock.

To provide a complete answer would thus require you posting whether your implementation provides the Thread Execution Scheduling option and if it does, which scheduling policy was selected.
To see what the current scheduling policy is (if you're on Linux), run the following program:
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>

int main(void)
{
  printf("round-robin scheduling policy: %d\n", SCHED_RR);
  printf("fifo scheduling policy: %d\n", SCHED_FIFO);
  printf("other scheduling policy: %d\n", SCHED_OTHER);
  pthread_attr_t ta;
  pthread_getattr_np(pthread_self(), &ta);
  int ts;
  pthread_attr_getschedpolicy(&ta, &ts);
  printf("current scheduling policy: %d\n", ts);
}

Unless the current scheduling policy is Round-Robin or Fifo, the first two paragraphs of the quoted documentation do not apply. In such a case, the scheduling behavior is implementation defined. In particular, it is easily possible for a reader/writer lock to prefer readers, in which case the writer will almost certainly never get to run for your program, because the readers are serializing on the lock protecting stdout (via printf()), as per C11 draft standard n1570:

7.21 Input/output
7.21.2 Streams
7 Each stream has an associated lock that is used to prevent data races when multiple threads of execution access a stream, and to restrict the interleaving of stream operations performed by multiple threads. Only one thread may hold this lock at a time. The lock is reentrant: a single thread may hold the lock multiple times at a given time.

Since this lock is held while also holding the readlock, and the sleep() is also executed while holding the readlock, and the readers do nothing between releasing the readlock and acquiring it again, the likelihood that at any point there is no reader holding the lock is very small. Thus, the writer never has a chance.


text:
Q: Prioritizing asynchronous jquery ajax calls I have 2 asynchronous jQuery ajax call in my code. They are called one after the other from a javascript file. Now what happens is that the first call is made when the page is loaded. The first call takes around 60 seconds to complete. But depending on the user input the second call can be made even before the completion of the first call.
Now the 2nd call only takes around 4 seconds to complete. I want to set priority in the second call such that when it is made it should be treated with higher priority and it should be completed ahead of the 1st call.
Please let me know if this is possible and if yes then how.

A: Make this priority at the serverside. Once a file is beeing loaded by the client it is not a good method to try to stop it, serverside code will be ran anyway. So, do some checks in serversideocode to notice if the 60 second request is done with a specific id, if so, pause that code and push in the small one.
For instance you can have a temporary table in sql. With active requests. saving progress of files and removing when done. Use it to keep track.

A: $.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});

If you want call 2 to not wait for call 1, just put the ajax calls one after the other.  The second call will execute without waiting for the first to finish.
If you want second call to be executed after response from the first then put the second ajax call in the .done() function.


text:
Q: SharePoint 2010 - specific day before date What I would like is a calculation that would take return the value of the Thursday before my [TargetDate] value.  If it is on a Thursday, it too has to be the Thursday before.  This is to make sure that the form is submitted before the target date.
I found this, but looks like I'd have to do a WEEKDAY statement for every day of the week
How to default a date field to a particular day of the week?
Can't seem to wrap my head around this one!  Any help would be greatly appreciated!

A: This should get the job done:
=IF(WEEKDAY([TargetDate])<=5,[TargetDate]-WEEKDAY([TargetDate])-2,[TargetDate]-WEEKDAY([TargetDate])+5)


text:
Q: number of different arrangements of $n$ squares How to find the number of different arrangements of n squares with conditions that firstly every arrangement should be connected and secondly if two squares intersect they should intersect on a whole edge(not part of edge or a vertex)?
For example in the image below two arrangement on the left are allowed and the two on the right are not.

and for n=4 there are five different arrangements as shown below.

How one should study this problem in an abstract mathematical way? Is there some kind of a partition of a number to be related to this?
edit 1: symmetries (rotations and reflections) are not allowed.


text:
Q: Why is moment-timezone using a lot less space with webpack 4 and/or create react app 4? With webpack 3, I was using moment-timezone-data-webpack-plugin to reduce my bundle size and it worked well. Tests showed it reduced the bundle size dramatically. I've now upgraded to webpack 4 and create-react-app 4, and it seems like

*

*this plugin has no impact on the total bundle size

*analyzing the bundle, moment-timezone only takes about 7k

As far as I can tell moment-timezone is functioning correctly in my app, so I'm very confused.
Webpack 4 is a lot better at reducing bundle size, but there's no way it can know which timezone data my app needs are runtime, so I can't imagine how that could be part of the answer.

A: Apologies for this being a non-answer, but hopefully it saves some time.
MomentJS have been aware of their size for a while, and have taken steps to try to structure their project so it can be stripped down better. They have structured their project, so that the locales are stored separately.
However the trick here is you mentioned CreateReact4, you are not testing this in a clean room, so anything could be taking effect.
Create React 4 document that:
Troubleshooting.md - MomentJS Locales are Missing

If you use a Moment.js, you might notice that only the English locale
is available by default. This is because the locale files are large,
and you probably only need a subset of all the locales provided by
Moment.js.
To add a specific Moment.js locale to your bundle, you need to import
it explicitly.

This is because CreateReact4 is configured by default to remove the locales
react-scripts/config/webpack.config.js#L671-L678
  // Moment.js is an extremely popular library that bundles large locale files
  // by default due to how webpack interprets its code. This is a practical
  // solution that requires the user to opt into importing specific locales.
  // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  // You can remove this if you don't use Moment.js:
  new webpack.IgnorePlugin({
    resourceRegExp: /^\.\/locale$/,
    contextRegExp: /moment$/,
  }),

It's possible you could trim it further using the plugin you mentioned in the question (Have you checked if it's even being invoked / compatible anymore?), but the bulk of the gzipped data really is the locales, not the timezone data, (TZ don't compress as easily).
Moment TZ Data Plugin state on their site that depending on the config gives various savings.
Default                 1164 KiB        105 KiB
Strip locales           959 KiB (~82%)  56 KiB (~53%)
Strip tz data           265 KiB (~23%)  69 KiB (~66%)
Strip locales & tz data 60 KiB (~5%)    20 KiB (~19%)

So CreateReact4's default behaviour of stripping un-needed locales, likely gives a 53% reduction by default(gzipped).
However you state that Moment-js is using 7k... so whilst this is a good breakdown of what could be happening, there's clearly something further at play, even moment.js-min is 18kb.

A: I believe that during an upgrade of moment-timezone, you have gone from one with timezone data, to one without.
https://momentjs.com/timezone/ states that (minified) moment-timezone without data is only 2.8k
Loading the unminified version: https://momentjs.com/downloads/moment-timezone.js and looking at my browsers network tab, shows that it clocks in at around 5.2k
It's my assumption (without additional information/testing and recreating your webpack) that this is the likely culprit.
"But my web app appears to be working" I hear you cry.
moment-timezone falls back to (new) native browser API's, try testing in an older browser:
If you don't need to support old projects / browsers, consider Luxon.

A: I had same feeling when did dune to webpack2 some time ago.
In my experience the answer was: strings of localizations. Before - it took all of them, and know they somehow limited.


text:
Q: LinkConnect errors while connecting to remote kernel. Interactive commands fail For a while I have a set-up running a Mathematica front-end on a Macbook and a remote kernel on a Linux (CentOS) computer.  Recently something changed and I have issues with the remote kernel but I cannot pinpoint it.  I upgraded MacOS to 10.12.4  and also Mathematica to 11.1 on both systems.
When I start the remote kernel, I get the following message :
LinkConnect::linkc: Unable to connect to LinkObject[53745@172.16.9.115,53746@172.16.9.115,56,2].
LinkConnect::linkc: Unable to connect to LinkObject[53743@172.16.9.115,53744@172.16.9.115,57,3].
LinkObject::linkn: Argument LinkObject[53743@172.16.9.115,53744@172.16.9.115,57,3] in MathLinkAddSharingLink[LinkObject[53743@172.16.9.115,53744@172.16.9.115,57,3],MathLinkAllowPreemptive->True,MathLinkLinkSwitchPre->FrontEndPrivatePreContextSwitchIn,MathLinkLinkSwitchPost->FrontEndPrivatePreContextSwitchOut] has an invalid LinkObject number; the link may be closed.
At first everything seems to work.  I can do computations and plot graphics.  However, any dynamic or interactive (e.g. Manipulate) command fails.  So I presume the failed link is used for this.
The Macbook is effectively listening to the ports as can be seen from the output of lsof :
java      2987 peterb   62u  IPv4 0xdbd5c28e4af9a547      0t0  TCP macbook-pro.sky.lan:53743 (LISTEN)
java      2987 peterb   63u  IPv4 0xdbd5c28e519a1357      0t0  TCP macbook-pro.sky.lan:53744 (LISTEN)
java      2987 peterb   64u  IPv4 0xdbd5c28e5176186f      0t0  TCP macbook-pro.sky.lan:53745 (LISTEN)
java      2987 peterb  146u  IPv4 0xdbd5c28e46850a5f      0t0  TCP macbook-pro.sky.lan:53746 (LISTEN)
A port scan of the Macbook done on the Linux computer confirms that the ports are open.  So I does not seem to be a network or firewall issue.
So I am stuck now and out of ideas where to look (not really an expert in these link issues).
Peter

A: I had the same problem today, with exactly the same error message, of mathematica being not able to connect to the kernels, which is why I ended up on your question.
In my case it had nothing to do with the process of connecting to remote kernels as I am simply using vnc to work on that machine.
I had this problem now for several days. Today while having "top" in a shell running in the background I could see that there were still WolframKernels popping up to the top, although I had certainly closed the program.
So I used
ps -u username
in the shell to see what kind of kernels they were. I found a list of kernels and some of them had "defunct" written behind them.
Using then
ps -ef | grep defunct
will show all  processes together with two numbers, the PID and PPID.
Then type
kill -9 PID PPID
and all the processes belonging to the PPID will be killed.
It seems that due to whatever there will be zombified processes remaining in the background and then somehow they interfere with new kernels, either by blocking licenses or whatever. I don't have enough computer knowledge to exactly understand what is going on.
I just described what helped me and maybe the same procedure works for you or anybody else. It is probably not the best solution, but now my kernels run again nicely.


text:
Q: TYPO3 - inline FLUID - add a Space I am searching for a Example or Solution.
I have a inline for each and I need a Space after the Items
{items -> f:for(each: '{field.referenzTeaserCategory -> dce:explode(delimiter:\',\')}', as: 'items', iteration: 'iterator')}

The Output is "cat1cat2cat3" but i need the Output with a Space, like this: "cat1 cat2 cat3"
Thanks for a Solution.

A: Use an Partial File to solve it:
MyPartial.html
<f:spaceless>
  <f:for each="{field.referenzTeaserCategory -> dce:explode(delimiter:',')}" as="item" iteration="iterator">
    {item}
  </f:for>
</f:spaceless>

You can also use Sections within your template:
MyTemplate.html

<f:section name="MyCategories"><f:spaceless>
  <f:for each="{field.referenzTeaserCategory -> dce:explode(delimiter:',')}" as="item" iteration="iterator">
    {item}
  </f:for>
</f:spaceless></f:section>

A: I don't think that you can build this with inline notation with normal fluid.
You need to use a viewhelper which concatenates your variable items with a string ' '. You may introduce this VH or use tag notation:
<f:for each="{field.referenzTeaserCategory -> dce:explode(delimiter:',')}" as="items" iteration="iterator">{items} </f:for>

BTW: really items? it is only one item (at a time)

A: Haven't used an inline foreach yet but maybe an whitespapce after the closing curly bracket will work.
like this:
'{field.referenzTeaserCategory -> dce:explode(delimiter:\',\')} '


text:
Q: Solving the inequality $\frac{|x + 3| + x}{x + 2} > 1$ I have an inequality which is as follows

If $x\in \mathbb R$ , solve the following inequality for $x$
  $$\frac{|x+3|+x}{x+2}\gt 1$$

I rearranged and got this
$$|x+3|\gt2$$
solving for it gives me $x\in(-\infty,-5)\cup (-1,\infty)$
But putting $-6$ in original inequality is making the statement false
I told it to my friend and he got $x\in R-[-2,-1]-\{-5\}$
And he is right ,
But I want to know why am I wrong and how to approach the correct answer??
Please help!!

A: You error comes from the fact that, in your "rearranging" process, you have (maybe without noticing it) had to multiply both sides of your inequality by $(x+2)$ but, doing that, you have implicitly assumed that $x+2>0$. If, on the contrary, $x+2<0$, you have to reverse the inequality symbol, i.e., your inequality becomes
$$(x+2)\left(\frac{|x+3|+x}{x+2}\right)\lt (x+2) \ \ \iff \ \ |x+3|+x \lt x+2 \ \ \iff \ \ |x+3| \lt 2$$

A: I like to make it easy to myself by first solving:
$$f(x)=\frac{|x+3|+x}{x+2}-1=0$$
We get:
$$|x+3|+x=x+2$$
$$|x+3|=2$$
$$x=-5 \lor x=-1$$
Furthermore, $x$ cannot be $-2$ else we would divide by $0$. $f(x)$ is a continuous function except at $x=-2$. By simply choosing some values for $x$ we get:
$$
\begin{array}{c|lcr}
x & &-5 && -2 && -1 \\
\hline
f(x) & -&0&+ & \text{X}&- & 0&+\\
\end{array}
$$
Therefore: $x\in(-5,-2)\cup(-1,\infty)$

A: your inequality is equivalent to
$$\frac{|x+3|-2}{x+2}>0$$
now we do case work:
1)$$x\geq -3$$ then we get $$\frac{x+1}{x+2}>0$$
a) if $x+2>0$ then we have $x+1>x+2$ which is impossible
b) if $x+2<0$ then $x+1<x+2$ which is true.
and we get
$$-3\le x<-2$$
can you finish?
you can not multiply be $x+2$ because this can be negative

A: Here is a general method: split the problem into cases to remove the absolute value signs.
Case 1: if $x+3>0$ or $x>-3$,then $|x+3|=x+3$, so the equation can be expressed as:
$$
\frac{x+3+x}{x+2}>1
$$
Solving this inequality, we get:
$$\begin{align}
\frac{2x+3}{x+2}-1>0\\
\frac{2x+3-(x+2)}{x+2}>0\\
\frac{x+1}{x+2}>0
\end{align}$$
From the above, either $
\begin{cases}
 x+1>0\\
 x+2>0\\
\end{cases}
$ or
$
\begin{cases}
 x+1<0\\
 x+2<0\\
\end{cases}
$, which implies $x>-1$ or $x<-2$. Also because $x>-3$, obtaining their intersection, we obtain:
$$
x \in (-3,-2) \cup (-1,\infty)
$$
Scenario 2: if $x+3<0$, $x<-3$,or $|x+3|=-(x+3)$. We can write this as:
$$
\frac{-(x+3)+x}{x+2}>1
$$
and solving the inequality:
$$\begin{align}
\frac{-3}{x+2}-1>0\\
\frac{-3-(x+2)}{x+2}>0\\
\frac{-x-5}{x+2}>0\\
\frac{x+5}{x+2}<0
\end{align}$$
The above can be resolved as $
\begin{cases}
 x+5>0\\
 x+2<0\\
\end{cases}
$ or
$
\begin{cases}
 x+5<0\\
 x+2>0\\
\end{cases}
$, hence $x \in (-5,-2)$ or $x \in (- \infty,-5) \cap (-2,\infty)$ (the empty set, so discard it). Also since $x<-3$, obtaining their intersection we have:
$$
x \in (-5,-3)
$$
Finding the intersection of cases $1$ and $2$, the final answer is:
$$
x \in (-5,-2) \cup (-1,\infty)
$$

A: Shift the given function two units to the right to get:
$$\frac{|x+1| + x-2}{x} > 1 \implies \frac{|x+1| - 2}{x} > 0$$
Now we can separate the problem into cases, which makes the casework a little easier. When $x > 0 $, multiplying by $x$ gives $|x + 1| > 2 \implies$ $ |x - (-1)| > 2 \implies x < -3, 1 < x$, but only $1 < x$ is valid as both inequalities must be satisfied. Similarly, when $x < 0$, $|x + 1| < 2 \implies -3 < x < 1$, however only $-3 < x < 0$ is valid. When $x = 0$, the left-hand side is undefined, so $x \ne 0$.
To recover the original solution of the inequality, move two units back to the left, which means replacing $x$ with $x + 2$.
This results in $\boxed{x \in (-5, -2) \cup (-1, \infty)}$.


text:
Q: C++ a multiple indexes map I am implementing a simple searching systems where all the data are stored in the memory of the running process.
Originally, I plan to use a map of tuple to achieve this.
map<tuple<int, string, ...>, string> dict

However, it is only working when all the keys are known and not missing.
For example, say, I have,
map<<key1, key2, key3, key4, key5>, value> dict;
I cannot search the map without key2 or key2 is "don't care"
Is there any standard lib or function in C++ to do that?
Any help is highly appreciated.

A: std::map<int, std::map<string, std::map< ... , string > ... > > dict;

You can "not care" at any step.  You do have to check every possibility there.
You can do a combinatorial explosion to do all n! orderings, and have everything point to either a shared pointer or something similar.
This isn't cheap.
Permute the arguments in every possibility (n!), then make a map from each tuple of augmented optionals (with a min and max state) to the same shared ptr of data.  You can now do an ordering that treats either the left or the right as least significant, and use equal_range to not care about that key.
You could instead make an attack using something like a quad tree or oct tree or n-tree structure.  That does multi-dimensional "sorting".  Getting that to work with arbitrary keys will be fun.

A: This is an interesting and nontrivial problem I happen to have studied some years ago:

*

*The problem is, given n keys, to be able to efficiently  query for an arbitrary subset of those keys.

*In DB terminology, this can be solved by creating m indices so that each combination of keys is covered by some index. The problem is described here: the number of indices is C(n,floor(n/2)), where C(a,b) is the binomial coefficient a choose b. for n=5, the number of required indices is m=10.

*I devised an algorithm for determining what the actual indices are. In the case of n=5 and keys a, b, c, d, e, you can use indices (acedb),(baedc),(bdaec),(bedca),(cbaed),(cdbae),(cebad),(daceb),(decab),(eadbc). A crucial aspect here is that indices can be used for shorter combinations of keys. For instance, (acedb) covers the following (rearranged in alphabetical order): (a),(ac),(ace),(acde),(abcde). This is the reason why you can cover any combination with only 10 indices instead of 25−1=31.

*Now, Boost.MultiIndex can be used to actually specify and use these indices. There's an example with 4 keys that you can extend easily to 5 keys if so you wish.

A: You asked:

Is there any standard lib or function in C++ to do that?

The answer to that question is No.
The requirements are a little vague, because it seems you have a particular interface in mind. You should define your interfaces, and what you expect them to do.
The implementation of a find() like function with don't cares could be implemented with a multiple index data structure. Roughly:

*

*Create a container (like a set) of all your records.

*For each key field, create a map associating values in that key field to a set of iterators in the set of records.

*A find method would walk the collection of key maps, and compute intersections of the returned sets of iterators.

A: Not in std, but there is boost::multi_index, which allows you to specify arbitrary projections of you data as keys, and you can have as many as you like.
// your keys and value
struct Datum {
    key1_t key1;
    key2_t key2;
    key3_t key3;
    // etc ...
    value_t value;
};

namespace bmi = boost::multi_index;

// some unique types
struct Key1 {};
struct Key2 {};
struct Key3 {};
struct Key1Key2 {};
struct Key1Key2Key3 {};

using Dict = boost::multi_index_container<Datum, bmi::indexed_by<
    bmi::ordered_unique<bmi::tag<Key1>, bmi::key<&Datum::key1>>, // just key 1
    bmi::ordered_unique<bmi::tag<Key2>, bmi::key<&Datum::key2>>, // just key 2
    bmi::ordered_unique<bmi::tag<Key3>, bmi::key<&Datum::key3>>, // just key 3
    bmi::ordered_unique<bmi::tag<Key1Key2>, bmi::key<&Datum::key1, &Datum::key2>>, // key 1 then key 2
    bmi::ordered_unique<bmi::tag<Key1Key2Key3>, bmi::key<&Datum::key1, &Datum::key2, &Datum::key3>>, // key 1 then key 2 then key 3
>;
int main() {
    Dict dict = /* stuff */

    key1_t key1 = /* stuff */
    key2_t key2 = /* stuff */
    key3_t key3 = /* stuff */

    auto it1 = dict.get<0>().find(key1); // select which by position
    auto it2 = dict.get<Key2>().find(key2); // or by the tag types
    auto it5 = dict.get<Key1Key2Key3>().find({ key1, key2, key3 }); // multiple keys
}


text:
Q: Font line spacing in Firefox on Windows 7 vs Windows XP I am using Verdana font for text paragraph. The problem is that in Firefox v16 on Windows XP this text renders different than Firefox v16 on Windows 7. Internet Explorer 9 renders font without any issues on Windows 7. The difference is in line spacing - in Firefox / XP and IE / 7 line spacing is a bit narrower than Firefox / 7. I am using default settings for both Firefox and Internet Explorer on Windows 7.
So what I am talking about is not horizontal character spacing it is vertical line spacing.
As far as I know, Verdana is a standard font for XP and Win7 so there should be no issues with that.
Any CSS code to fix this and make the spacing identical in IE and Firefox on Windows 7?

A: Don't have an XP machine nearby but did you setup a custom line-height in your CSS? You said "I am using default settings" so that makes me think you didn't set a fixed line-height. If i misunderstood i apologize.


text:
Q: 'Could not find file hibernate.cfg.xml' when running after publish my application I've 2 problem.
My application is WPF c# app that us MS Access as a database (.dbm file) and NHibernate for connecting.
The first problem is after publishing my app, getting exe file and installing my app, I tried to run the application by I got an exception that it could not find file hibernate.cfg.xml. However, the app worked fine if I run through Visual Studio. That config file is in the same folder of class that call configuration.
In addition, I'm not sure whether my publish method is correct. To publish my WPF app, at the solution explorer I right clicked main project > publish > then follow several steps and end by click 'finish. I haven't seen any config file appear in the publish floder which I expect to see because I want to allow the user to be able to config the path of his database (.dbm file) later. Then this is the second problem.

A: One option is to move your nHibernate configuration into the app.config
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    ...
  </session-factory>
</hibernate-configuration>

In your configsections section add
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" requirePermission="false" />
    ...
  <configSections>
<configuration>

Or
var cfg = new Configuration();
cfg.Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"hibernate.cfg.xml"));

A: there's a another place to check.
Open your project properties, go to 'Publish' then click in 'Application Properites'. In this interface you have to check if the file Hibernate.cfg.xml is 'Include' in Publish Status.

A: After Publishing, do you see the hibernate.cfg.xml in the output directory?
If you added this file in Visual Studio, it may not copy it by default.
Make sure in the file's properties, its type is set to 'Content' and Output as 'Copy'.


text:
Q: Qt multiple QSlider control at same time I have two QSlider widgets at same window. I cannot control both of them with my two fingers at the same time.
For example, one of sliders is used for throttle and other is used for steering in a car game.
How can I handle this ?


text:
Q: Hide touch keyboard Is it possible to not show system keyboard, when you tap textbox? Ive created custom keyboard and can work with textblock only, because of this i cant delete just parts of sentence.

A: If you set IsReadOnly to true then the user can still select the text in a TextBox to copy paste and the OS doesn't show the software input keyboard when selected. You can still alter the contents of the TextBox through code though. Eg;
<TextBox x:Name="ExampleTextBox"
         IsReadOnly="True"
         Text="Initial Content"
         GotFocus="ExampleTextBox_GotFocus"
         />

And in your code behind;
private void ExampleTextBox_GotFocus(object sender, System.Windows.RoutedEventArgs e) {
  ExampleTextBox.Text += " ... focused!";
}

Would prevent the user from entering text via the software keyboard but will append "... focused" everytime they give focus to the TextBox. Contrived example, but you get the idea.
The only other thing I'd suggest is to re-style the TextBox. By default when IsReadOnly is set the TextBox will provide visual cues that it can't be modified by the user. Which isn't the case here.

A: if the user touches the keyboard, the keyboard will get focus.
the only option you as a developer have is to catch it and call this.focus moving focus away from textbox.
This will however mean that there will be a flicker where default keyboard pops up and is hidden.
I know this because i have a keyboard app. There is no other way.


text:
Q: How to use kafka-node under typescript? I need to use kafka-node under typescript:
const kafkaHost = 'localhost:9092';
const client = new Client({ kafkaHost });

After launching index.ts I get this error:
 Property '_write' in type 'ProducerStream' is not assignable to the same property in base type 'Writable'.
  Type '(message: ProduceRequest, encoding: "utf8" | "buffer", cb: (error: any, data: any) => any) => void' is not assignable to type '(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null | undefined) => void) => void'.
    Types of parameters 'encoding' and 'encoding' are incompatible.
      Type 'BufferEncoding' is not assignable to type '"utf8" | "buffer"'.
        Type '"ascii"' is not assignable to type '"utf8" | "buffer"'.

143   _write (message: ProduceRequest, encoding: 'buffer' | 'utf8', cb: (error: any, data: any) => any): void;

I think problem is in types, so I dont have installed @types/kafka-node, nevertheless it is deprecated.
How to fix it?

A: kafka-node now comes with it's own pre-defined types for Typescript. You can refer them from here
Regarding your problem, you need the import proper types before using it:
import { KafkaClient as Client } from 'kafka-node';

const kafkaHost = 'localhost:9092';
const client = new Client({ kafkaHost });

A: This is a reported bug in kafka-node with no official solution yet. The best answer for this so far is... don't let typescript check kafka-node source code.
Add "skipLibCheck": true to tsconfig.json
see here:
https://github.com/SOHU-Co/kafka-node/issues/1412


text:
Q: Qt opengGL implementation How Qt's Opengl widget works? Is it a software-only implementation or it relies on the configuration of the platform

A: It's a Qt widget that embeds an OpenGL context of the native platform - i.e. You're using the OpenGL libraries/setup on your platform - which doesn't have a lot to do with Qt


text:
Q: How to improve the throughput of request_logs on Google App Engine Downloading logs from App Engine is nontrivial. Requests are batched; appcfg.py does not use normal file IO but rather a temporary file (in reverse chronological order) which it ultimately appends to the local log file; when appending, the need to find the "sentinel" makes log rotation difficult since one must leave enough old logs for appcfg.py to remember where it left off. Finally, Google deletes old logs after some time (20 minutes for the app I use).
As an app scales, and the log generation rate grows, how can one increase the speed of fetching the logs so that appcfg.py does not fall behind?

A: You can increase the per-request batch size of logs. In the latest SDK (1.3.1), check out google_appengine/google/appengine/tools/appcfg.py around like 861 (RequestLogLines method of LogsRequester class). You can modify the "limit" parameter.
I am using 1000 and it works pretty well.


text:
Q: Firebase equivalent of MySQL in operator Assume my data looks something like this :
{
  "key_data" : {
    "1qwqwqwqwq" : {
      "map_id" : "9010",
    },
    "1212wdwdw" : {
      "map_id" : "098",
    },
    "1212dfefe" : {
      "map_id" : "5612",
    },
    "1212eerer" : {
      "map_id" : "987",
    }
  }
}

In Firebase iOS Swift Library how do I get all key_data where map_id in ['9010','098']?
Currently I am running this piece of code in a loop and appending the result into an array:
// for map_id in map_ids---
ref.queryOrderedByChild("map_id").queryEqualToValue(map_id)
                                 .observeEventType(.Value) { snapshot in
                                     //append into array
                                 }


text:
Q: Meaning of using commas and underscores with Python assignment operator? Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
def f():
    return 1,2

a, b = f()

But what is the meaning of each of the following?
d2, = values[s]  ## values[s] is a string and at this point len(values[s]) is 1

If len(values[s]) == 1, then how is this statement different than d2 = values[s]?
Another question about using an underscore in the assignment here:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)

Does the underscore have the effect of basically discarding the first value returned in the list?

A: The _ in the Python shell also refers to the value of the last operation. Hence
>>> 1
1
>>> _
1

The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.

A: You can use the trailing comma in a tuple like this:
>>> (2,)*2
(2, 2)

>>> (2)*2
4

A: d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>

a is tuple, b is an integer.

A: _ is like any other variable name but usually it means "I don't care about this variable".
The second question:  it is "value unpacking". When a function returns a tuple, you can unpack its elements.
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2


text:
Q: Using curl for scraping large pages I'm trying to scrape comments from a popular news site for an academic study using curl. It works fine for articles with <300 comments but after that it struggles.
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($handle);
curl_close($handle);
echo $html; //just to see what's been scraped

At the moment this page works fine: http://www.guardian.co.uk/commentisfree/2012/aug/22/letter-from-india-women-drink?commentpage=all#start-of-comments
But this one only returns 36 comments despite there being 700+ in total: http://www.guardian.co.uk/commentisfree/2012/aug/21/everyones-talking-about-rape?commentpage=all#start-of-comments
Why is it struggling for articles with a ton of comments?

A: You comments page is pageinated.  Each page contains differerent comments.  You will have to request all comment pagination links.
The parameter page=x is appended to the url for a different page.
It might be good to get base page then search for all links with page paarameter and request each of those in turn?
As Mike Christensen pointed out if you could use python and scrapy that functionality is built in.  You just have to specify the element the comment is located in and python will crawl all links on the page for you:)


text:
Q: MKAnnotationView images are not changing
I am trying to show images in MKAnnotationView. The images are loading initially but when I am trying to change the images for a few on a button click the images are not changing rather they are overlapping. Below is the code I have used.
MapView Delegate
extension MapViewController: MKMapViewDelegate {

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "MapAnnotation") as? MapAnnotationView

    if annotationView != nil {
        annotationView?.annotation = annotation
    }
    else {

        annotationView = MapAnnotationView(annotation: annotation, reuseIdentifier: "MapAnnotation")
    }

    annotationView?.canShowCallout = true

    return annotationView
}

MKAnnotationView
class MapAnnotationView: MKAnnotationView {

// Required for MKAnnotationView
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override init(annotation: MKAnnotation?, reuseIdentifier: String?) {

    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
    //super.prepareForReuse()
  guard let attractionAnnotation = self.annotation as? MapAnnotation else { return }
    if attractionAnnotation.type == PinType.hospital {
    image = UIImage.init(named: "hospital_green")

}
}

Button Action
@IBAction func btnGreen_Click(_ sender: Any) {
    for annotation in (policyMapView?.annotations)! {
        let mapAnnotationView = policyMapView?.view(for: annotation) as? AssistMapAnnotationView

        //if !(mapAnnotationView?.annotation is MKUserLocation) {
        if !(mapAnnotationView?.annotation is MKUserLocation) {

            let mapAnnotation = annotation as? AssistMapAnnotation

            if mapAnnotation?.type == PinType.hospital {
                if (mapAnnotation?.insurer_id == selectedInsurer1) {
                    mapAnnotationView?.image = UIImage.init(named: "hospital_purple")
                }else{
                    mapAnnotationView?.image = UIImage.init(named: "hospital_green")
                }
            }

        } else {

        }
    }
}
}


text:
Q: User friendly site structure Introduction
I am trying to learn to create websites that aren't just static, and this is probably a 'noob' question but I can't seem to find an answer anywhere.
What I want to achieve
Let's say I want to make a forum/social media type website, I want url structure like this:
home:        www.website.com
userpage:    www.website.com/user/username
post:        www.website.com/post/postid
What I can make right now
I've only played around in PHP and nothing like ASP.net but all I can do at the moment is this:
home:        www.website.com
userpage:    www.website.com/user/?user=username
post:        www.website.com/post/?post=postid
How can I create site structure without the ?var=id like you see on almost every website?
Examples:
www.reddit.com/r/subreddit
www.medium.com/user/post

A: You should learn to make RESTful apis (REST wikipedia)

REST works almost exactly like a website in a browser. A resource is
  exposed to a program via a URL. The program can access that URL and
  receive data about the resource, not unlike when you type in a URL to
  your browser and get a web page back.

Quote from: http://www.mashery.com/blog/what-restful-api


text:
Q: MYSQL - How to save a value without removing the right zero I have a table to register vehicles.
One of the columns is to save the price (type double) in that format 90.000 for example. But when I enter the values in the bank it saves and removes the last zero and becomes 90.
How do I make the value equal to the original 90.000?

A: Try using the field type DECIMAL.
https://dev.mysql.com/doc/refman/5.7/en/fixed-point-types.html


text:
Q: How to set up normal approximation for binomial In a particular school, 25% of first grade students do not enjoy reading. 22% of second graders do not enjoy reading.
A random sample is taken of 100 first grade students, and another independent sample of 100 second graders is taken.
Part 1:
Use normal approximation to find the probability that less than 30 first grade students in the sample do not enjoy reading.
Part 2:
Use normal approximation to find the probability that 5 more second graders than first graders in the samples do not enjoy reading.
For part 1, after doing the 0.5 correction, I got
$$ O \  follows \  N(25, 18.75) $$
$$ P(O \le 29.5) = 0.851 $$
Is that right?
And for part 2, I'm not exactly sure how to set it up.
Thanks!

A: Part 1:  p = .25 of first grade students do not enjoy reading; n = 100 first grade students selected at random; X = number out of 100 who do not enjoy reading. We seek $P\{X < 30\} = P\{X \leq 29\}.$ Using R software, the exact probability is given by 'pbinom(29, 100, .25)' which returns 0.850459.
How can this probability be approximated using the normal distribution? (First n is large enough and p is far enough from 0 (and 1) that such an approximation is
feasible.) $E(X) = np = 100(.25) = 25$ and $V(X) = np(1-p) = 18.75.$ Then
$$ P\{X \le 29.5\} = P\{(X - 25)/\sqrt{18.75} < (29.5 = 25)/\sqrt{18.75} = 1.039\} \approx P\{Z \le 1.039\} = 0.8506.$$
The 'standardized' binomial random variable $(X - 25)/\sqrt{18.75}$ is approximated by the standard normal random variable $Z$. (Notice the 'approximately equal' sign $\approx$ at the appropriate point.)
Notice that for the
discrete random variable $X$ the desired probability can be express either
as $P\{X < 30\}$ or $P\{X \leq 29\}$. When approximating by the continuous
normal random variable, one generally obtains a better approximation by using a bound 29.5 halfway between.
The approximate normal probability can be found either with software or by using printed tables of the standard normal distribution. (In the latter case you would probably have to use 1.04 rather than 1.039, we used software so your answer may be slightly different.)
Notice that the result 0.8506 is not far from the exact result 0.850495. As here, normal approximations commonly give about two-place accuracy.

A: Part 2: For second grade students p = .22, n = 100, and Y is the number of sampled students who do not enjoy reading. Much as in Part 1, we obtain
$E(Y) = 22$ and $V(Y) = 17.16$.
We also need the mean and variance of $W = Y - X$, with $X$ as in Part 1.
We have $E(W) = E(Y-X) = 22 - 25 = -3$ and $V(W) = 18.75 + 17.16 = 36.91$ (notice that variances ADD), so that the SD of the difference is 5.9924. We seek
$$P\{W = 5\} = P\{4.5 \le W \le 5.5\} \approx P\{(4.5 + 3)/5.9924 \le Z \le (5.5+3)/5.9924\} = P\{1.252 \le Z \le 1.418\} = 0.027.$$
In Part 1, some authors may have ignored the "continuity correction" that uses
half integers in the bounds. Here, however this correction is essential to getting a sensible answer.
As in Part 1, you may get a slightly different answer using printed tables
of the standard normal distribution, rounding bounds to two places, than we did with software. In R, the statement 'diff(pnorm(c(1.252, 1.418))' returns 0.02719.
A simulation of a million runs of this 200-student experiment yielded
the same answer 0.027 to three places as in the approximation. A histogram of the million differences of reading averse students is closely matched by a normal curve with mean -3 and standard deviation 5.9924. (It would have been possible to get an exact answer, but we did not. You might want to ponder how many binomial probabilities would have to be computed to do that.)


text:
Q: asihttprequest: post problems on the iphone I am trying to to establish a connection between my app and an internet service and I am using asihttprequest but I'm having a small problem. Everything works great when I am on WiFi but when I turn it off and use GPRS(EDGE) or 3G nothing seems to work. Should I change something.
Here is some of my code
[self setRequest:[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"example.url.php"]]];

[request setPostValue:textString forKey:@"mytext"];
[request setData:imageData withFileName:theFinal andContentType:@"image/png" forKey:@"userfile"];
[request setPostValue:textString2 forKey:@"description"];
[request setPostValue:latitude forKey:@"latitude"];
[request setPostValue:longitude forKey:@"longitude"];
[request setPostValue:finalIdString forKey:@"city_id"];

[request setTimeOutSeconds:60];
[request setUploadProgressDelegate:progressIndicator];
[request setDelegate:self];
[request setDidFailSelector:@selector(uploadFailed:)];
[request setDidFinishSelector:@selector(uploadFinished:)];
[request startAsynchronous];

A: found it i had to use
    [ASIHTTPRequest setShouldThrottleBandwidthForWWAN];


text:
Q: Write nicely formatted list with write function I have two lists with numbers and I want them to be written out nicely, just like what I get from print item1, item2. Can anybody help?
outfile = open("tabal_t_y.dat", "w")
for item1, item2 in zip(t, y):
    outfile.write()
outfile.close()

A: print

evaluates each expression in turn and writes the resulting object… If an object is not a string, it is first converted to a string using the rules for string conversions… A space is written before each object is (converted and) written…

However, if you read a bit farther in the docs:

print also has an extended form… sometimes referred to as "print chevron." In this form, the first expression after the >> must evaluate to a "file-like" object… the subsequent expressions are printed to this file object…

So, you don't have to do this with outfile.write at all, you can just do this:
print >>outfile, item1, item2

But if you want to use outfile.write, you can do everything print does by yourself, in two different ways:
First, you can convert the outputs to strings, then join them with spaces:
outfile.write(' '.join(map(str, (item1, item2))))

outfile.write(str(item1) + ' ' + str(item2))

def write_things(f, *things):
    f.write(' '.join(map(str, things))))
write_things(outfile, item1, item2)

… or anything else you feel comfortable with.
Or you can use string formatting:
outfile.write('{} {}'.format(item1, item2))


text:
Q: Understanding map in cohomology To find $[f] \in \pi_{2n-1}(\mathbb{S}^n)$ such that $H(f) = \pm 2$, where $H(f)$ is the Hopf invariant, we define the following map $h : \mathbb{S}^n \vee \mathbb{S}^n \longmapsto \mathbb{S}^n$ defned by $h(\star,x) = h(x,\star) = x$ where $\star$ is the basepoint of $\mathbb{S}^n$.
Since $H^n(\mathbb{S}^n) \simeq \mathbb{Z}$ and $H^{n}(\mathbb{S}^n \vee \mathbb{S}^n) \simeq \mathbb{Z} \bigoplus \mathbb{Z}$, fixed $y$ a generator of $H^{n}(\mathbb{S}^n)$ I'd like to know why $$h^{*}(y) = (y,y) = (0,y)+(y,0)$$ since I'm unable to compute it directly based on the definition of $h$.
Any help or reference would be appreciated.

A: Given the fold map $h: S^n \vee S^n \to S^n$, the induced map in $H^n$ is a group homomorphism $h^*: \mathbb{Z} \to \mathbb{Z} \oplus \mathbb{Z}$, where we identify each $H^n(S^n)$ with a copy of $\mathbb{Z}$.  Write $h^*(1) = (\lambda_1, \lambda_2)$ for integers $\lambda_1, \lambda_2$.  To deduce what these integers are, consider the map induced by the composite $h \circ i_1, h \circ i_2: S^n \to S^n$, where $i_1, i_2: S^n \to S^n \vee S^n$ are inclusions into each of the wedge summands.  By functoriality, $(h \circ i_1)^*(1) = i_1^* h^*(1) = i_1^*(\lambda_1, \lambda_2) = \lambda_1$.  On the other hand, $h \circ i_1$ is the identity, so the induced map takes generators to generators, so $\lambda_1 = \pm 1$.  Similarly, $\lambda_2 = \pm 1$.  So $h^*(1) = (\pm 1, \pm 1)$.  By picking generators consistently (or by composing with a suitable isomorphism), you can arrange for $h^*(1) = (1, 1)$.


text:
Q: How to write SQL statements in succession without error I am running a CREATE VIEW statement which is perfectly self-contained and runs perfect on its own. Two lines below I run a separate SELECT statement to view the results, which works perfect on its own.
However, I run the whole script together and it doesn't work.
Code looks something like this:
--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;

--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work

The error message is "Incorrect syntax near the keyword 'SELECT'."

A: You need to put a GO between the statements.  The semicolon is insufficient to tell the parser that they are separate batches.

A: You should run this queries separetly or you have too old SQL server to run CREATE OR ALTER VIEW. Firstly create the view, and then run the select.
You can also add GO, it will separate batches:
--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;
GO
--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work

A: Add batch separator, Go, stmt between, End of create view stmt and your select from view.
also will need to add check if view exists and drop it first stmt or change to alter or create view depending on version of sql.
IF OBJECT_ID('FOO') IS NOT NULL
DROP VIEW FOO;
GO

CREATE VIEW FOO
AS
SELECT * FROM sysobjects;
GO
SELECT * FROM FOO
GO


text:
Q: Invalid command 'WSGIReloadMechanism' in my Apache site's config file I am trying to deploy a Django project and am using Apache2 with mod_wsgi.  Here are the relevant lines in my Apache conf file:
WSGIScriptReloading On
WSGIDaemonProcess myprojectcom
WSGIReloadMechanism Process
WSGIProcessGroup myprojectcom
WSGIApplicationGroup myprojectcom
WSGIPassAuthorization On

WSGIScriptAlias / /home/myproject/myproject/deploy/deploy.wsgi

I've used a very similar conf file for many other deployments, but this is the first time that I'm getting the following error:
/etc/apache2/sites-available$ sudo /etc/init.d/apache2 restart
Syntax error on line 8 of /etc/apache2/sites-enabled/myproject.com:
Invalid command 'WSGIReloadMechanism', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.
  ...fail!

I don't see any syntax error, though.  I'm on Ubuntu, using the libapache2-mod-wsgi package.  What could be wrong?

A: Remove the whole line:
WSGIReloadMechanism Process

It isn't needed any more and the directive was removed completely in mod_wsgi 3.X.
You should preferable not rely on old blog posts for how to set up mod_wsgi and use the actual mod_wsgi documentation on the mod_wsgi site instead.


text:
Q: Best way to monitor for a server on a TCP port I have a remote Music Player Daemon(MPD) server running on a linux machine. I have a client  listening to this stream on another linux machine.
When the MPD server is asked to pause or stop the stream, it disconnects all clients connected on the TCP port. Consequently, when the server starts streaming again, the clients have to be manually reconnected.
I want to write a program that will monitor the TCP port for a server accepting connections, and then automatically restart the clients. Can I do better than running connect() and sleep() in a loop? Are there any command-line utilities to do this?
I can run the client on the machine running the MPD server, if it will help. The following will tell me if a process is listening on a local port, but they do not block if a process isn't, so I still need to wrap them in a loop.

$ sudo fuser -n tcp 8000
  8000/tcp:    9677
$ sudo netstat -nlp  | grep 8000
  tcp  0      0 0.0.0.0:8000           0.0.0.0:*               LISTEN      9677/mpd

I can try any solution that does not involve changing the behaviour of the MPD server.

A: There is always the possibility of writing a relay server that proxies for MPD.
It sits there listening on a different port for your clients and makes connections to MPD in their stead.  When MPD disconnects, the relay just attempts to reconnect every few seconds without disconnecting its clients.

A: Here you go:
echo -n "" | nc -q 0 localhost 8000 && echo "made a connection" || echo "server was down"

echo -n "" puts an EOF immediately on stdin; nc -q 0 returns immediately after seeing that EOF on stdin.  nc (netcat) tries to make a connection to localhost on port 8000.  If it connects successfully, then it returns a successful error code and we echo "made a connection"; otherwise, if the connection was refused, we echo "server was down".
If you want to test it out, then in another terminal run
nc -lvvp 8000

which will start an instance of netcat listening on port 8000, with verbose output.  In your other terminal, run the first command.  The first time you run it, it will say made a connection.  Then the server/listener will close, so the next time you run it, it will say server was down.


text:
Q: How to handle null value of AggregateResult I am having a doubt while writting the code. I am using AggregateResult while writting a query.
If AggregateResult is not equal to null then I'm able to write my logic and it is working fine.
But While AggregateResult is null I am not able to do my opeartion. I checked in debug log, and I see if AggregateResult is null then I'm not able to go to that else loop.
For reference I am attaching the code.
public static string getFolderName(String objectName, String FolderName){
   String Final_Folder_Name;

   List<AggregateResult> s = (Database.query('SELECT Max(Folder_Append__c) append FROM Frup__c WHERE Object_Name__c=:objectName AND Folder_Name__c=:FolderName'));
   Integer append_num= Integer.valueOf(s[0].get('append'));
   System.debug('Apend Number---'+append_num);

   Integer final_append_num=append_num+1;

    if(s[0].get('append')!=null){
       Final_Folder_Name =  FolderName+'_'+final_append_num;
       System.debug('####'+Final_Folder_Name );
    }else{
       System.debug('%%%');
       return FolderName;
    }
    return Final_Folder_Name;

}

Code isn't coming to else part, eventhough value of s[0].get('append') is null.
Please help me out.

A: line 5:  Integer append_num= Integer.valueOf(s[0].get('append')); seems to be used before any null tests.
Your modified code might then look like this
public static string getFolderName(String objectName, String FolderName){
 String Final_Folder_Name;

 List<AggregateResult> s = Database.query('SELECT Max(Folder_Append__c) append FROM Frup__c WHERE  Object_Name__c=:objectName AND Folder_Name__c=:FolderName');

 if (s.size() > 0) {
     Integer append_num =  (s[0].get('append') != null) ? Integer.valueOf(s[0].get('append')) : 0 ;
     System.debug('Apend Number---'+append_num);

     Integer final_append_num=append_num+1;

    // this doesn't make much sense now , left in for clarity
      if(s[0].get('append')!=null){
         Final_Folder_Name =  FolderName+'_'+final_append_num;
         System.debug('####'+Final_Folder_Name );
      }else{
         System.debug('%%%');
         return FolderName;
      }
  }
  return Final_Folder_Name;

}


text:
Q: Is this a valid LGPL scenario? Suppose I have Project X under closed source. It references/links to component Y which is LGPL, we make modifications to component Y
1) We release Project X binaries with the source to the modified component Y
OR
2) We contribute component Y modifications back upstream (to the original author(s)) and release Project X binaries without component Y source.
Does any of these scenarios comply with the LGPL?

A: 1) is fine.
2) is not: you have to distribute y source (or at least a written offer to do so). Your users would have a hard time looking for your modification in depths of upstream patch repository (a bug tracker, whatever).

A: Option (1) is certainly OK. Option (2) is probably not, because there is no real way of "contributing modifications upstream".


text:
Q: How to identify a yes/no question Is there any pattern or heuristic that can be used to identify a yes/no question, with reasonable accuracy?

A: Yes/No questions in formal English have the following characteristics:

*

*A rising intonation at the end of the question; in print, the question mark.

*An inversion of the subject and the first auxiliary verb. E.g,
You have lived in New York. ~ Have you lived in New York?
If there is no auxiliary verb at hand, Do-Support provides one:
You lived on 37th Street. ~ Did you live on 37th Street?
That's it for Y/N questions; they're the simplest.
Wh-questions start off from Y/N questions and add an interrogative Wh-word.
There are of course many other ways to ask questions. Aren't there?


text:
Q: Getting EXC_BAD_ACCESS while Applying filter to CIImage [Core Image] I am Working on Imagebase Application. I want to Apply some filter on Images. For that I have used [Core Image].
I have stored some FilterName in array and to show filter effect as preview I am using UICollection view. When user tap on Preview image then Filter will be apply on Main Imageview. But when I tap on preview cell , then filter applied successfully on Main Imageview. but after that when I am dragging collection view cell to apply next preview I am getting BAD_ACCESS Error on Filter Method.
-(UIImage *) applyFilter: (UIImage*) picture withFilterName:(NSString*)Filtername
Here is my Code to apply Filter :-

Initial setup with Filter array and RegisterCollectionview cell:-
-(void)setUpDefaultUI{
    [self HideControlsAndSetupUI];

    arrFilter = @[ @"Original",
                   @"CILinearToSRGBToneCurve",
                   @"CIPhotoEffectChrome",
                   @"CIPhotoEffectFade",
                   @"CIPhotoEffectInstant",
                   @"CIPhotoEffectMono",
                   @"CIPhotoEffectNoir",
                   @"CIPhotoEffectProcess",
                   @"CIPhotoEffectTonal",
                   @"CIPhotoEffectTransfer",
                   @"CISRGBToneCurveToLinear",
                   @"CIVignette",
                   // @"CIVignetteEffect",
                   @"CISepiaTone",
                   ];

    [self.vwCollection registerClass:[ActivityCollectionViewCell class] forCellWithReuseIdentifier:@"ActivityCollectionViewCell"];
    [self.vwCollection registerNib:[UINib nibWithNibName:@"ActivityCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ActivityCollectionViewCell"];
    _imgEdit.image=_stillImage; // To apply filter on this Image
    _OriginalImage=_stillImage; // Original image if user declined to use filter

}

CollectionView Datasource:-
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"filterAvailable");

    ActivityCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"ActivityCollectionViewCell" forIndexPath:indexPath];

    if (cell == nil) {
        NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"ActivityCollectionViewCell" owner:self options:nil];
        cell = [xib objectAtIndex:0];
        [cell.imgVw setContentMode:UIViewContentModeScaleAspectFill];
    }
      if (indexPath.item==0) {
        cell.imgVw.image = _OriginalImage; //Original Image on 0 index
    }else{
         UIImage *img=[self applyFilter:_stillImage withFilterName:[arrFilter objectAtIndex:indexPath.row]]; // Apply filter on this method
        cell.imgVw.image=img;
}
    return cell;
}

Collectionview Delegate :-
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ActivityCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ActivityCollectionViewCell" forIndexPath:indexPath];
    if (cell == nil) {
        NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"ActivityCollectionViewCell" owner:self options:nil];
        cell = [xib objectAtIndex:0];
    }
 if (indexPath.item==0) {
        _imgEdit.image=_OriginalImage; // Set original image in main Imageview
    }else{
        UIImage *img=[self applyFilter:_stillImage withFilterName:[arrFilter objectAtIndex:indexPath.row]];
        _imgEdit.image = img;  // Apply filter on Main Imageview
    }
    }

Filter Apply from This Method :-
-(UIImage *) applyFilter: (UIImage*) picture withFilterName:(NSString*)Filtername
{
    UIImageOrientation originalOrientation = picture.imageOrientation;
    CGFloat originalScale = picture.scale;
    CIImage *beginImage = [CIImage imageWithCGImage:picture.CGImage];
    CIContext *context = [CIContext contextWithOptions:nil];
     CIFilter *filter = [CIFilter filterWithName:Filtername keysAndValues: kCIInputImageKey, beginImage, nil, [NSNumber numberWithFloat:0.7], nil];
    CIImage *outputImage = [filter outputImage];
    CGImageRef cgimg =
    [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage *newImg = [UIImage imageWithCGImage:cgimg scale:originalScale orientation:originalOrientation];

    //CGImageRelease(CGImageRef) method.
    CGImageRelease(cgimg);
    return newImg;

}

Image of Error:-
 - BAD_ACCESS

A: *

*Are you certain picture is a valid UIImage object? Put a breakpoint at the start of applyFilter:withFilterName:, and use Xcode's quick-look to confirm it is what you think it is.

*Also check Filtername is a valid string.

If those are both correct, this looks suspicious:
CIFilter *filter = [CIFilter filterWithName:Filtername keysAndValues: kCIInputImageKey, beginImage, nil, [NSNumber numberWithFloat:0.7], nil];

The keys & values here are a nil-terminated list. Try removing everything after the first nil:
CIFilter *filter = [CIFilter filterWithName:Filtername keysAndValues: kCIInputImageKey, beginImage, nil];

Also note that both CIVignette & CISepiaTone have additional input parameters (see Apple's Core Image Filter Reference)

A: Finally , I got the problem. Actually the problem is , I am applying filter on Still image in Both the method.
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

and
 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

So, Final solution is use different image in Both the methods .
Here is the code :-
//Initial Setup
    -(void)setUpDefaultUI{
        [self HideControlsAndSetupUI];
    arrFilter = @[ @"Original",
                   @"CILinearToSRGBToneCurve",
                   @"CIPhotoEffectChrome",
                   @"CIPhotoEffectFade",
                   @"CIPhotoEffectInstant",
                   @"CIPhotoEffectMono",
                   @"CIPhotoEffectNoir",
                   @"CIPhotoEffectProcess",
                   @"CIPhotoEffectTonal",
                   @"CIPhotoEffectTransfer",
                   @"CISRGBToneCurveToLinear",
                   @"CIVignette",
                   // @"CIVignetteEffect",
                   @"CISepiaTone",
                   ];

    [self.vwCollection registerClass:[ActivityCollectionViewCell class] forCellWithReuseIdentifier:@"ActivityCollectionViewCell"];
    [self.vwCollection registerNib:[UINib nibWithNibName:@"ActivityCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ActivityCollectionViewCell"];
    _imgEdit.image=_stillImage;
    _OriginalImage=_stillImage;
    temp=_OriginalImage;
}

//Datasource method To display image in collection view with filter
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"filterAvailable");

    ActivityCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"ActivityCollectionViewCell" forIndexPath:indexPath];

    if (cell == nil) {
        NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"ActivityCollectionViewCell" owner:self options:nil];
        cell = [xib objectAtIndex:0];
        //[cell.imgVw setContentMode:UIViewContentModeScaleAspectFill];
        cell.imgVw.clipsToBounds = YES;

        cell.imgVw.layer.cornerRadius = 5;

    }
  if (indexPath.item==0) {
        cell.imgVw.image = _OriginalImage; //Set original image of 1st index

    }else{
        UIImage *img=[self applyFilter:temp withFilterName:[arrFilter objectAtIndex:indexPath.row]];    // Set temp image in place of stilimage
        cell.imgVw.image=img;

        }
 return cell;
}

//Apply filter on Main Imageview .
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_EnumPhotos==defaultPhotos) {

    if (indexPath.item==0) {
        _imgEdit.image=_OriginalImage; //If user click on 1st index then original filter applied on main image
    }else{

         UIImage *img=[self applyFilter:_stillImage withFilterName:[arrFilter objectAtIndex:indexPath.row]]; // Use still image here .
        _imgEdit.image = img; // Apply image on main image view
    }
    }
}

//Apply filter Method
-(UIImage *) applyFilter: (UIImage*) picture withFilterName:(NSString*)Filtername
{
    UIImageOrientation originalOrientation = picture.imageOrientation;
    CGFloat originalScale = picture.scale;
    CIImage *beginImage = [CIImage imageWithCGImage:picture.CGImage];
    CIContext *context = [CIContext contextWithOptions:nil];
     CIFilter *filter = [CIFilter filterWithName:Filtername keysAndValues: kCIInputImageKey, beginImage, nil, [NSNumber numberWithFloat:0.7], nil];
    CIImage *outputImage = [filter outputImage];
    CGImageRef cgimg =
    [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage *newImg = [UIImage imageWithCGImage:cgimg scale:originalScale orientation:originalOrientation];

    //CGImageRelease(CGImageRef) method.
    CGImageRelease(cgimg);
    return newImg;

}


text:
Q: Memberwise assignment cartesian class c++ I have code for a Cartesian class and now I want to add a memberwise assignment to set the values of coord1 to coord2. I am not quite sure how to go about doing this. What is the syntax for writing a memberwise assignment for class objects? Would I make changes to the class itself, or put them in the main function?
#include <iostream>
using namespace std;

class Cartesian
{
private:
    double x;
    double y;

public:
    Cartesian( double a = 0, double b = 0) : x(a), y(b){}

    friend istream& operator>>(istream&, Cartesian&);
    friend ostream& operator<<(ostream&, const Cartesian&);
};

istream& operator>>(istream& in, Cartesian& num)
{
    cin >> num.x >> num.y;
    return in;
}

ostream& operator<<( ostream& out, const Cartesian& num)
{
    cout << "(" << num.x << ", " << num.y << ")" << endl;
    return out;
}

int main()
{
Cartesian   coord1, coord2;

    cout << "Please enter the first coordinates in the form x y" << endl;
    cin >> coord1;

    cout << "Please enter the second coordinates in the form x y" << endl;
    cin >> coord2;

    cout << coord1;
    cout << coord2;

    return 0;
}

A: Do it the simple way: Make all members public, by using a struct and leaving out access specifiers. Data hiding does not make sense if you provide full access anyway.
Also, you can then leave out all custom constructors, as you can assign all members at once without.

A: Just add get and set methods to your class
void Cartesian::SetX(double new_x)
{
    x = new_x;
}

and
double Cartesian::GetX()
{
    return x;
}

and similar functions for GetY() and SetY(double y). This will enable you to access and set the values of x and y to whatever you want as and when you need.
Alternatively, simply change the access specifier on these members to public instead of private.
Also, be aware that your class has a default operator=() that will copy members memberwise if you assign one instance of Cartesian to another.
Thus if you have
 Cartesian point1(1.0,2.0);
 Cartesian point2(4.5,4.3);

you can simply assign point1 to point2 by
 point2 = point1;


text:
Q: What is Bigquery Data Store Strategies? I have a problem related to storing data on GCP Bigquery. I have a partition table which is size 10 Terabyte and increasing day by day. How can I store this data with minimum cost and max performance?
Fisrt Option : I can store last 1 month's data on Bigquery and the rest of the data on GCS.
Second Option: Deleting after the last 1 month's data but this option is illogical to me.
What do you think about this issue?

A: BigQuery Table
The best solution is to use a BigQuery table which is partition by a usefull date column. A huge part of this table will be charged with the lower long time storage rate. Please consider for your whole project a region-zone, which has lower costs, if this is possible for your organisation, because all needed data needs to be in the same region.
For each query only the needed time and the needed columns are charged.
GCS files
There is an option for using external tables for files stored in GCS. These have some drawbacks: for each query the complete data is read and charged. There are some partition possibilities using hive partition keys (https://cloud.google.com/bigquery/docs/hive-partitioned-queries). It is also not possible to precalculate the cost of a query, which is very bad for testing and debugging.
use cases
If you need only your monthly data for daily reports, it is enough to store these data in BigQuery and the rest in gcs. If you only need to run a query over longer times once a month, you can load the data from gcs into BigQuery and delete the table after your queries.


text:
Q: CDialog not closing when two buttons mapped Visual Studio 2005, C++, Windows XP.
I have a CDialog with a single button, which calls a function like so:
BEGIN_MESSAGE_MAP(Foo, BaseDlg) //BaseDlg inherits from CDialog
    ON_BN_CLICKED(IDBAR, Bar)
END_MESSAGE_MAP()
The dialog box closes when its 'X' is clicked.
I change the above code to:
BEGIN_MESSAGE_MAP(Foo, BaseDlg) //BaseDlg inherits from CDialog
    ON_BN_CLICKED(IDBAR, Bar)
    ON_BN_CLICKED(IDBAZ, Baz)
END_MESSAGE_MAP()
My dialog window will no longer close. Whenever the X is clicked, Baz() is called. The second ON_BN_CLICKED() handler is replacing the normal dialog close behavior for some reason.
How do I close a dialog box which has two or more buttons mapped to functions?

A: What are the numeric values assigned to IDBAR and IDBAZ in the resource file? One possible explanation is that IDBAZ == IDCANCEL, which is defined in MFC by default as the ID for both the dialog's cancel and X buttons. Defining your own handler for this constant will then override the default behaviour, which is to close the window. This only applies though if you're showing the dialog modally - if it's modeless then you always have to close the dialog yourself by calling EndDialog().


text:
Q: Replace symbols not working on keypress event I have input where I need to delete non number symbols
Here is html of component
  <input
  type="text"
  tabindex="0"
  class="search__input form-control-md + {{ class }}"
  [value]="config.value"
  [required]="config.required"
  [attr.maxlength]="config.maxLength"
  [attr.minLength]="config.minLength"
  (focusout)="onFocusOut($event)"
  (input)="onValueChange($event)"
  (keypress)="onValueChange($event)"
  (keyup.enter)="onEnter($event)"
  #inputElem
/>

Here is component
    export class TextFieldComponent implements OnInit, ControlValueAccessor {
  @Input() config: FormBase<string>;
  @Input() form: FormGroup;
  @Output() onChanged = new EventEmitter<boolean>();
  @Input() class: string;
  configControl = new FormControl();
  @Input() set value(value: string) {
    this._value = value;
  }
  get value(): string {
    return this._value;
  }

  private _value: string;

  constructor() {}

  ngOnInit() {}

  onFocusOut(event) {
    this.onValueChange(event);
    this.onChanged.emit(true);
  }

  onEnter(event) {
    this.onValueChange(event);
    this.onChanged.emit(true);
  }

  onValueChange(event) {
    this.changeValue(event.target.value);
  }

  writeValue(value) {
    this.value = value;
  }

  changeValue(value) {
    if (this.value === value) {
      return;
    }
    this.value = value;
    let result;
    switch (this.config.isNumber) {
      case true:
        result = value != null ? value.toString().replace(/[^0-9]/g, "") : null;
        console.log(result);
        this.onChange(result);
        break;
      default:
        this.onChange(value);
    }
  }

  onChange: any = () => {};

  onTouched: any = () => {};

  registerOnChange(fn) {
    this.onChange = fn;
  }

  registerOnTouched(fn) {
    this.onTouched = fn;
  }
}

My problem, that on focusout for example, this method changeValue is working well and it delete non number symbols, but on keypress event I see that on console I have replaced value, but on input, I still see letters. How I can solve this issue?

A: You need to understand what exactly keypress is doing here. The keypress event is fired when a key that produces a character value is pressed down and examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.
Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.
In the above case the keypress event won't invoke and will only be called when the character values are produced.
You should use keyUp or keyDown event to track things more effectively.
Note: check this link for the difference b/w keyup, keydown and keypress.

A: In your component access input element using ViewChild
@ViewChild('inputElem') inputEl: ElementRef;

Then to set result after replace
result = value != null ? value.toString().replace(/[^0-9]/g, '') : null;

// update input value
this.inputEl.nativeElement.value = result;

console.log(result);

Demo


text:
Q: can't install any gem using Aptana I have installed the latest Aptana Studio 3, build: 3.6.0.201407100658 and when I try to install gems, I get the same error message.
For example, from terminal window: gem install bundler
The error message:
Couldn't find a valid gem 'bundler' (>=0), here is why:
Unable to download data from https://rubygems.org - SSL_Connect returned=1 state=SSLv3 read server certificate B: certificate verify failed
(https://api.rubygems.org/latest_spec.4.8.gz)

Any help with this since I am stuck with this error.

A: This error,
Unable to download data from https://rubygems.org - SSL_Connect returned=1
state=SSLv3 read server certificate B: certificate verify failed
(https://api.rubygems.org/latest_spec.4.8.gz)

is because you are using the https version of the rubygems source. Try this
gem install bundler -s http://rubygems.org

By using the http source, you can work around this
Method 2
Change your gem sources by entering the following two commands
gem sources -r https://rubygems.org/
gem sources -a http://rubygems.org/

The first command will remove the secure connection
The second command will add the insecure connection, allowing you to bypass this warning
Then you can run
gem install bundler

A: I had a problem like this when starting to use Ruby on Rails with Aptana. Didn't get exactly the same error message, but it was an issue with the installation of the bundles.
Another person might find this helpful, so I thought that I would add that for me, all it took was running:
gem update --system

And then, as answered in the previous answer:
gem install bundler

=)


text:
Q: In Apex, how do you add in an edit column? In order to edit a row in APEX, what is the procedure?
I found this link, from 2009 , but it appears to be outdated , because I don't see any pencil & paper icon to the left of the EDIT_LINK columns :
How do you add an edit button to each row in a report in Oracle APEX?

A: 1- Create a Classic report with a normal query (including a key column, like empno in this case):
select  empno,
        name,
        job,
        hiredate
from emp

2- Select the column that will serve as a button:

3- Go to Column Formatting -> HTML Expression on the attributes display region:
and paste this code:
<button class="t-Button  " id="#EMPNO#" onclick="showRow(#EMPNO#);" type="button"><span class="t-Button-label"> + </span></button>

4- This will generate a button associated to each "empno", notice that I'm setting the id of the button to #EMPNO# (being the value of empno to that row) and I'm setting an onclick call to a javascript function called showRow(empno). In this function is where you'd call either a new page passing the parameters needed or show a modal popup whit the fetched data to beeing modified.
Here's a working example


text:
Q: how can we get number of refresh of a webpage through javascript or jquery cookies? I want to count the number of refresh of a webpage through jquery or javascript. I made research on it but did not get the perfect answer.
Can anyone help me, Please?

A: var _hash = window.location.hash;
if( _hash ){
var x = parseInt( window.location.hash.replace("#", ""));
x = x+1;
window.location.hash=x;
}else{
  window.location.hash = "1"
}

A: You can count with the help of local storage:
$(document).ready(function(){

   localStorage.refresh=localStorage.refresh!=null ? localStorage.refresh : 0;
   localStorage.setItem("refresh", parseInt(localStorage.refresh)+1);
   alert(localStorage.refresh);
});

A: You can't, because you can't write to files with pure JS.
However, using $('body').bind('beforeunload',function(){}) you can detect a reload, wich you could save in a cookie. But you can't count the total number of reloads on you page from all users. Also the cookie approach obviously won't work for browsers with cookies disabled.