Programs & Examples On #Wia

Windows Image Acquisition (WIA) is the still image acquisition platform in the Windows family of operating systems starting with Windows Millennium Edition (Windows Me) and Windows XP.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

Saving binary data as file using JavaScript from a browser

To do this task download.js library can be used. Here is an example from library docs:

download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");

How does Facebook disable the browser's integrated Developer Tools?

This is not a security measure for weak code to be left unattended. Always get a permanent solution to weak code and secure your websites properly before implementing this strategy

The best tool by far according to my knowledge would be to add multiple javascript files that simply changes the integrity of the page back to normal by refreshing or replacing content. Disabling this developer tool would not be the greatest idea since bypassing is always in question since the code is part of the browser and not a server rendering, thus it could be cracked.

Should you have js file one checking for <element> changes on important elements and js file two and js file three checking that this file exists per period you will have full integrity restore on the page within the period.

Lets take an example of the 4 files and show you what I mean.

index.html

   <!DOCTYPE html>
   <html>
   <head id="mainhead">
   <script src="ks.js" id="ksjs"></script>
   <script src="mainfile.js" id="mainjs"></script>
   <link rel="stylesheet" href="style.css" id="style">
   <meta id="meta1" name="description" content="Proper mitigation against script kiddies via Javascript" >
   </head>
   <body>
   <h1 id="heading" name="dontdel" value="2">Delete this from console and it will refresh. If you change the name attribute in this it will also refresh. This is mitigating an attack on attribute change via console to exploit vulnerabilities. You can even try and change the value attribute from 2 to anything you like. If This script says it is 2 it should be 2 or it will refresh. </h1>
   <h3>Deleting this wont refresh the page due to it having no integrity check on it</h3>

   <p>You can also add this type of error checking on meta tags and add one script out of the head tag to check for changes in the head tag. You can add many js files to ensure an attacker cannot delete all in the second it takes to refresh. Be creative and make this your own as your website needs it. 
   </p>

   <p>This is not the end of it since we can still enter any tag to load anything from everywhere (Dependent on headers etc) but we want to prevent the important ones like an override in meta tags that load headers. The console is designed to edit html but that could add potential html that is dangerous. You should not be able to enter any meta tags into this document unless it is as specified by the ks.js file as permissable. <br>This is not only possible with meta tags but you can do this for important tags like input and script. This is not a replacement for headers!!! Add your headers aswell and protect them with this method.</p>
   </body>
   <script src="ps.js" id="psjs"></script>
   </html>

mainfile.js

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var ksExists = document.getElementById("ksjs"); 
   if(ksExists) {
   }else{ location.reload();};

   var psExists = document.getElementById("psjs");
   if(psExists) {
   }else{ location.reload();};

   var styleExists = document.getElementById("style");
   if(styleExists) {
   }else{ location.reload();};


   }, 1 * 1000); // 1 * 1000 milsec

ps.js

   /*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload!You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.

   */

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var mainExists = document.getElementById("mainjs"); 
   if(mainExists) {
   }else{ location.reload();};

   //check that heading with id exists and name tag is dontdel.
   var headingExists = document.getElementById("heading"); 
   if(headingExists) {
   }else{ location.reload();};
   var integrityHeading = headingExists.getAttribute('name');
   if(integrityHeading == 'dontdel') {
   }else{ location.reload();};
   var integrity2Heading = headingExists.getAttribute('value');
   if(integrity2Heading == '2') {
   }else{ location.reload();};
   //check that all meta tags stay there
   var meta1Exists = document.getElementById("meta1"); 
   if(meta1Exists) {
   }else{ location.reload();};

   var headExists = document.getElementById("mainhead"); 
   if(headExists) {
   }else{ location.reload();};

   }, 1 * 1000); // 1 * 1000 milsec

ks.js

   /*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload! You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.

   */

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var mainExists = document.getElementById("mainjs"); 
   if(mainExists) {
   }else{ location.reload();};
   //Check meta tag 1 for content changes. meta1 will always be 0. This you do for each meta on the page to ensure content credibility. No one will change a meta and get away with it. Addition of a meta in spot 10, say a meta after the id="meta10" should also be covered as below.
   var x = document.getElementsByTagName("meta")[0];
   var p = x.getAttribute("name");
   var s = x.getAttribute("content");
   if (p != 'description') {
   location.reload();
   }
   if ( s != 'Proper mitigation against script kiddies via Javascript') {
   location.reload();
   }
   // This will prevent a meta tag after this meta tag @ id="meta1". This prevents new meta tags from being added to your pages. This can be used for scripts or any tag you feel is needed to do integrity check on like inputs and scripts. (Yet again. It is not a replacement for headers to be added. Add your headers aswell!)
   var lastMeta = document.getElementsByTagName("meta")[1];
   if (lastMeta) {
   location.reload();
   }
   }, 1 * 1000); // 1 * 1000 milsec

style.css

Now this is just to show it works on all files and tags aswell

   #heading {
   background-color:red;
   }

If you put all these files together and build the example you will see the function of this measure. This will prevent some unforseen injections should you implement it correctly on all important elements in your index file especially when working with PHP.

Why I chose reload instead of change back to normal value per attribute is the fact that some attackers could have another part of the website already configured and ready and it lessens code amount. The reload will remove all the attacker's hard work and he will probably go play somewhere easier.

Another note: This could become a lot of code so keep it clean and make sure to add definitions to where they belong to make edits easy in future. Also set the seconds to your preferred amount as 1 second intervals on large pages could have drastic effects on older computers your visitors might be using

Python base64 data decode

import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)

worked for me. At the risk of pasting an offensively-long result, I got:

>>> base64.b64decode(coded_string)
2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07M\x00\x00\x00\x00C\x96\x07_\x00\x00\x00\x00C\x96\x07p\x00\x00\x00\x00C\x96\x07\x82\x00\x00\x00\x00C\x96\x07\x94\x00\x00\x00\x00C\x96\x07\xa6Cq\xf0\x7fC\x96\x07\xb8DJ\x81\xc7C\x96\x07\xcaD\xa5\x9dtC\x96\x07\xdcD\xb6\x97\x11C\x96\x07\xeeD\x8b\x8flC\x96\x07\xffD\x03\xd4\xaaC\x96\x08\x11B\x05&\xdcC\x96\x08#\x00\x00\x00\x00C\x96\x085C\x0c\xc9\xb7C\x96\x08GCy\xc0\xebC\x96\x08YC\x81\xa4xC\x96\x08kC\x0f@\x9bC\x96\x08}\x00\x00\x00\x00C\x96\x08\x8e\x00\x00\x00\x00C\x96\x08\xa0\x00\x00\x00\x00C\x96\x08\xb2\x00\x00\x00\x00C\x96\x86\xf9\x00\x00\x00\x00C\x96\x87\x0b\x00\x00\x00\x00C\x96\x87\x1d\x00\x00\x00\x00C\x96\x87/\x00\x00\x00\x00C\x96\x87AA\x0b\xe7PC\x96\x87SCI\xf5gC\x96\x87eC\xd4J\xeaC\x96\x87wD\r\x17EC\x96\x87\x89D\x00F6C\x96\x87\x9bC\x9cg\xdeC\x96\x87\xadB\xd56\x0cC\x96\x87\xbf\x00\x00\x00\x00C\x96\x87\xd1\x00\x00\x00\x00C\x96\x87\xe3\x00\x00\x00\x00C\x96\x87\xf5\x00\x00\x00\x00C\x9cY}\x00\x00\x00\x00C\x9cY\x90\x00\x00\x00\x00C\x9cY\xa4\x00\x00\x00\x00C\x9cY\xb7\x00\x00\x00\x00C\x9cY\xcbC\x1f\xbd\xa3C\x9cY\xdeCCz{C\x9cY\xf1CD\x02\xa7C\x9cZ\x05C+\x9d\x97C\x9cZ\x18C\x03R\xe3C\x9cZ,\x00\x00\x00\x00C\x9cZ?
[stuff omitted as it exceeded SO's body length limits]
\xbb\x00\x00\x00\x00D\xc5!7\x00\x00\x00\x00D\xc5!\xb2\x00\x00\x00\x00D\xc7\x14x\x00\x00\x00\x00D\xc7\x14\xf6\x00\x00\x00\x00D\xc7\x15t\x00\x00\x00\x00D\xc7\x15\xf2\x00\x00\x00\x00D\xc7\x16pC5\x9f\xf9D\xc7\x16\xeeC[\xb5\xf5D\xc7\x17lCG\x1b;D\xc7\x17\xeaB\xe3\x0b\xa6D\xc7\x18h\x00\x00\x00\x00D\xc7\x18\xe6\x00\x00\x00\x00D\xc7\x19d\x00\x00\x00\x00D\xc7\x19\xe2\x00\x00\x00\x00D\xc7\xfe\xb4\x00\x00\x00\x00D\xc7\xff3\x00\x00\x00\x00D\xc7\xff\xb2\x00\x00\x00\x00D\xc8\x001\x00\x00\x00\x00'

What problem are you having, specifically?

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

Get next / previous element using JavaScript?

Tested it and it worked for me. The element finding me change as per the document structure that you have.

<html>
    <head>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <form method="post" id = "formId" action="action.php" onsubmit="return false;">
            <table>
                <tr>
                    <td>
                        <label class="standard_text">E-mail</label>
                    </td>
                    <td><input class="textarea"  name="mail" id="mail" placeholder="E-mail"></label></td>
                    <td><input class="textarea"  name="name" id="name" placeholder="E-mail">   </label></td>
                    <td><input class="textarea"  name="myname" id="myname" placeholder="E-mail"></label></td>
                    <td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
                    <td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
                    <td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
                </tr>
            </table>
            <input class="button_submit" type="submit" name="send_form" value="Register"/>
        </form>
    </body>
</html>

 

var inputs;
document.addEventListener("DOMContentLoaded", function(event) {
    var form = document.getElementById('formId');
    inputs = form.getElementsByTagName("input");
    for(var i = 0 ; i < inputs.length;i++) {
        inputs[i].addEventListener('keydown', function(e){
            if(e.keyCode == 13) {
                var currentIndex = findElement(e.target)
                if(currentIndex > -1 && currentIndex < inputs.length) {
                    inputs[currentIndex+1].focus();
                }
            }   
        });
    }
});

function findElement(element) {
    var index = -1;
    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i] == element) {
            return i;
        }
    }
    return index;
}

What is the iOS 5.0 user agent string?

I found a more complete listing at user agent string. BTW, this site has more than just iOS user agent strings. Also, the home page will "break down" the user agent string of your current browser for you.

Interface or an Abstract Class: which one to use?

Just wanted to add an example of when you may need to use both. I am currently writing a file handler bound to a database model in a general purpose ERP solution.

  • I have multiple abstract classes which handle the standard crud and also some specialty functionality like conversion and streaming for different categories of files.
  • The file access interface defines a common set of methods which are needed to get, store and delete a file.

This way, I get to have multiple templates for different files and a common set of interface methods with clear distinction. The interface gives the correct analogy to the access methods rather than what would have been with a base abstract class.

Further down the line when I will make adapters for different file storage services, this implementation will allow the interface to be used elsewhere in totally different contexts.

Read text from response

If you http request is Post and request.Accept = "application/x-www-form-urlencoded"; then i think you can to get text of respone by code bellow:

var contentEncoding = response.Headers["content-encoding"];
                        if (contentEncoding != null && contentEncoding.Contains("gzip")) // cause httphandler only request gzip
                        {
                            // using gzip stream reader
                            using (var responseStreamReader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)))
                            {
                                strResponse = responseStreamReader.ReadToEnd();
                            }
                        }
                        else
                        {
                            // using ordinary stream reader
                            using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
                            {
                                strResponse = responseStreamReader.ReadToEnd();
                            }
                        }

Python - abs vs fabs

abs() : Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float. Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() : It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

CASCADE DELETE just once

I wrote a (recursive) function to delete any row based on its primary key. I wrote this because I did not want to create my constraints as "on delete cascade". I wanted to be able to delete complex sets of data (as a DBA) but not allow my programmers to be able to cascade delete without thinking through all of the repercussions. I'm still testing out this function, so there may be bugs in it -- but please don't try it if your DB has multi column primary (and thus foreign) keys. Also, the keys all have to be able to be represented in string form, but it could be written in a way that doesn't have that restriction. I use this function VERY SPARINGLY anyway, I value my data too much to enable the cascading constraints on everything. Basically this function is passed in the schema, table name, and primary value (in string form), and it will start by finding any foreign keys on that table and makes sure data doesn't exist-- if it does, it recursively calls itsself on the found data. It uses an array of data already marked for deletion to prevent infinite loops. Please test it out and let me know how it works for you. Note: It's a little slow. I call it like so: select delete_cascade('public','my_table','1');

create or replace function delete_cascade(p_schema varchar, p_table varchar, p_key varchar, p_recursion varchar[] default null)
 returns integer as $$
declare
    rx record;
    rd record;
    v_sql varchar;
    v_recursion_key varchar;
    recnum integer;
    v_primary_key varchar;
    v_rows integer;
begin
    recnum := 0;
    select ccu.column_name into v_primary_key
        from
        information_schema.table_constraints  tc
        join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
        and tc.constraint_type='PRIMARY KEY'
        and tc.table_name=p_table
        and tc.table_schema=p_schema;

    for rx in (
        select kcu.table_name as foreign_table_name, 
        kcu.column_name as foreign_column_name, 
        kcu.table_schema foreign_table_schema,
        kcu2.column_name as foreign_table_primary_key
        from information_schema.constraint_column_usage ccu
        join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema 
        join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
        join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
        join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
        where ccu.table_name=p_table  and ccu.table_schema=p_schema
        and TC.CONSTRAINT_TYPE='FOREIGN KEY'
        and tc2.constraint_type='PRIMARY KEY'
)
    loop
        v_sql := 'select '||rx.foreign_table_primary_key||' as key from '||rx.foreign_table_schema||'.'||rx.foreign_table_name||'
            where '||rx.foreign_column_name||'='||quote_literal(p_key)||' for update';
        --raise notice '%',v_sql;
        --found a foreign key, now find the primary keys for any data that exists in any of those tables.
        for rd in execute v_sql
        loop
            v_recursion_key=rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name||'='||rd.key;
            if (v_recursion_key = any (p_recursion)) then
                --raise notice 'Avoiding infinite loop';
            else
                --raise notice 'Recursing to %,%',rx.foreign_table_name, rd.key;
                recnum:= recnum +delete_cascade(rx.foreign_table_schema::varchar, rx.foreign_table_name::varchar, rd.key::varchar, p_recursion||v_recursion_key);
            end if;
        end loop;
    end loop;
    begin
    --actually delete original record.
    v_sql := 'delete from '||p_schema||'.'||p_table||' where '||v_primary_key||'='||quote_literal(p_key);
    execute v_sql;
    get diagnostics v_rows= row_count;
    --raise notice 'Deleting %.% %=%',p_schema,p_table,v_primary_key,p_key;
    recnum:= recnum +v_rows;
    exception when others then recnum=0;
    end;

    return recnum;
end;
$$
language PLPGSQL;

How to make tesseract to recognize only numbers, when they are mixed with letters?

For tesseract 3, the command is simpler tesseract imagename outputbase digits according to the FAQ. But it doesn't work for me very well.

I turn to try different psm options and find -psm 6 works best for my case.

man tesseract for details.

Rules for C++ string literals escape character

\a is the bell/alert character, which on some systems triggers a sound. \nnn, represents an arbitrary ASCII character in octal base. However, \0 is special in that it represents the null character no matter what.

To answer your original question, you could escape your '0' characters as well, as:

std::string ("\060\000\060", 3);

(since an ASCII '0' is 60 in octal)

The MSDN documentation has a pretty detailed article on this, as well cppreference

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

There are a couple of parallization bugs in SQL server with abnormal input. OPTION(MAXDOP 1) will sidestep them.

EDIT: Old. My testing was done largely on SQL 2005. Most of these seem to not exist anymore, but every once in awhile we question the assumption when SQL 2014 does something dumb and we go back to the old way and it works. We never managed to demonstrate that it wasn't just a bad plan generation on more recent cases though since SQL server can be relied on to get the old way right in newer versions. Since all cases were IO bound queries MAXDOP 1 doesn't hurt.

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

navigate to C:\wamp64\alias\phpmyadmin.conf and change from:

php_admin_value upload_max_filesize 128M
php_admin_value post_max_size 128M

to

php_admin_value upload_max_filesize 2048M
php_admin_value post_max_size 2048M

or more :)

Is there a way to SELECT and UPDATE rows at the same time?

if it's inside the transaction, the database locking system will take care of concurrency issues. of course, if you use one (the mssql default is that it uses lock, so it states if you don't override that)

Why maven settings.xml file is not there?

I also underwent the same issue as Maven doesn't create the settings.xml file under .m2 folder. What I did was the following and it works smoothly without any issues.

Go to the location where you maven was unzipped.

Direct to following path,

\apache-maven-3.0.4\conf\ and copy the settings.xml file and paste it inside your .m2 folder.

Now create a maven project.

git replacing LF with CRLF

Removing the below from the ~/.gitattributes file

* text=auto

will prevent git from checking line-endings in the first-place.

What is the size of an enum in C?

While the previous answers are correct, some compilers have options to break the standard and use the smallest type that will contain all values.

Example with GCC (documentation in the GCC Manual):

enum ord {
    FIRST = 1,
    SECOND,
    THIRD
} __attribute__ ((__packed__));
STATIC_ASSERT( sizeof(enum ord) == 1 )

Show a popup/message box from a Windows batch file

You can use Zenity. Zenity allows for the execution of dialog boxes in command-line and shell scripts. More info can also be found on Wikipedia.

It is cross-platform: a Windows installer for Windows can be found here.

Resolve Javascript Promise outside function scope

Yes, you can. By using the CustomEvent API for the browser environment. And using an event emitter project in node.js environments. Since the snippet in the question is for the browser environment, here is a working example for the same.

_x000D_
_x000D_
function myPromiseReturningFunction(){_x000D_
  return new Promise(resolve => {_x000D_
    window.addEventListener("myCustomEvent", (event) => {_x000D_
       resolve(event.detail);_x000D_
    }) _x000D_
  })_x000D_
}_x000D_
_x000D_
_x000D_
myPromiseReturningFunction().then(result => {_x000D_
   alert(result)_x000D_
})_x000D_
_x000D_
document.getElementById("p").addEventListener("click", () => {_x000D_
   window.dispatchEvent(new CustomEvent("myCustomEvent", {detail : "It works!"}))_x000D_
})
_x000D_
<p id="p"> Click me </p>
_x000D_
_x000D_
_x000D_

I hope this answer is useful!

SQL Logic Operator Precedence: And and Or

Query to show a 3-variable boolean expression truth table :

;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
    CASE WHEN

(A=1) OR (B=1) AND (C=1)

    THEN 'True' ELSE 'False' END AS Result
FROM cteData

Results for (A=1) OR (B=1) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   True
1   0   1   True
1   1   0   True
1   1   1   True

Results for (A=1) OR ( (B=1) AND (C=1) ) are the same.

Results for ( (A=1) OR (B=1) ) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   False
1   0   1   True
1   1   0   False
1   1   1   True

Node package ( Grunt ) installed but not available

In my case, i need modify the file /usr/local/bin/grunt in line 1 ( don't make this ):

 #!/usr/bin/env node //remove this line
 #!/usr/bin/env nodejs // and put this line to run with nodejs

Edited:

To avoid problems, I created a link with the name of "node" because many other programs still use "node" command.

 sudo ln -s /usr/bin/nodejs /usr/sbin/node

Using Python 3 in virtualenv

virtualenv --python=/usr/local/bin/python3 <VIRTUAL ENV NAME> this will add python3 path for your virtual enviroment.

What are my options for storing data when using React Native? (iOS and Android)

Here's what I've learned as I determine the best way to move forward with a couple of my current app projects.

Async Storage (formerly "built-in" to React Native, now moved on its own)

I use AsyncStorage for an in-production app. Storage stays local to the device, is unencrypted (as mentioned in another answer), goes away if you delete the app, but should be saved as part of your device's backups and persists during upgrades (both native upgrades ala TestFlight and code upgrades via CodePush).

Conclusion: Local storage; you provide your own sync/backup solution.

SQLite

Other projects I have worked on have used sqlite3 for app storage. This gives you an SQL-like experience, with compressible databases that can also be transmitted to and from the device. I have not had any experience with syncing them to a back end, but I imagine various libraries exist. There are RN libraries for connecting to SQLite.

Data is stored in your traditional database format with databases, tables, keys, indices, etc. all saved to disk in a binary format. Direct access to the data is available via command line or apps that have SQLite drivers.

Conclusion: Local storage; you supply the sync and backup.

Firebase

Firebase offers, among other things, a real time noSQL database along with a JSON document store (like MongoDB) meant for keeping from 1 to n number of clients synchronized. The docs talk about offline persistence, but only for native code (Swift/Obj-C, Java). Google's own JavaScript option ("Web") which is used by React Native does not provide a cached storage option (see 2/18 update below). The library is written with the assumption that a web browser is going to be connecting, and so there will be a semi-persistent connection. You could probably write a local caching mechanism to supplement the Firebase storage calls, or you could write a bridge between the native libraries and React Native.

Update 2/2018 I have since found React Native Firebase which provides a compatible JavaScript interface to the native iOS and Android libraries (doing what Google probably could/should have done), giving you all the goodies of the native libraries with the bonus of React Native support. With Google's introduction of a JSON document store beside the real-time database, I'm giving Firebase a good second look for some real-time apps I plan to build.

The real-time database is stored as a JSON-like tree that you can edit on the website and import/export pretty simply.

Conclusion: With react-native-firebase, RN gets same benefits as Swift and Java. [/update] Scales well for network-connected devices. Low cost for low utilization. Combines nicely with other Google cloud offerings. Data readily visible and editable from their interface.

Realm

Update 4/2020 MongoDB has acquired Realm and is planning to combine it with MongoDB Stitch (discussed below). This looks very exciting.

Update 9/2020 Having used Realm vs. Stitch: Stitch API's essentially allowed a JS app (React Native or web) to talk directly to the Mongo database instead of going through an API server you build yourself.

Realm was meant to synchronize portions of the database whenever changes were made.

The combination of the two gets a little confusing. The formerly-known-as-Stitch API's still work like your traditional Mongo query and update calls, whereas the newer Realm stuff attaches to objects in code and handles synchronization all by itself... mostly. I'm still working through the right way to do things in one project, which is using SwiftUI, so it's a bit off-topic. But promising and neat nonetheless.


Also a real time object store with automagic network synchronization. They tout themselves as "device first" and the demo video shows how the devices handle sporadic or lossy network connectivity.

They offer a free version of the object store that you host on your own servers or in a cloud solution like AWS or Azure. You can also create in-memory stores that do not persist with the device, device-only stores that do not sync up with the server, read-only server stores, and the full read-write option for synchronization across one or more devices. They have professional and enterprise options that cost more up front per month than Firebase.

Unlike Firebase, all Realm capabilities are supported in React Native and Xamarin, just as they are in Swift/ObjC/Java (native) apps.

Your data is tied to objects in your code. Because they are defined objects, you do have a schema, and version control is a must for code sanity. Direct access is available via GUI tools Realm provides. On-device data files are cross-platform compatible.

Conclusion: Device first, optional synchronization with free and paid plans. All features supported in React Native. Horizontal scaling more expensive than Firebase.

iCloud

I honestly haven't done a lot of playing with this one, but will be doing so in the near future.

If you have a native app that uses CloudKit, you can use CloudKit JS to connect to your app's containers from a web app (or, in our case, React Native). In this scenario, you would probably have a native iOS app and a React Native Android app.

Like Realm, this stores data locally and syncs it to iCloud when possible. There are public stores for your app and private stores for each customer. Customers can even chose to share some of their stores or objects with other users.

I do not know how easy it is to access the raw data; the schemas can be set up on Apple's site.

Conclusion: Great for Apple-targeted apps.

Couchbase

Big name, lots of big companies behind it. There's a Community Edition and Enterprise Edition with the standard support costs.

They've got a tutorial on their site for hooking things up to React Native. I also haven't spent much time on this one, but it looks to be a viable alternative to Realm in terms of functionality. I don't know how easy it is to get to your data outside of your app or any APIs you build.

[Edit: Found an older link that talks about Couchbase and CouchDB, and CouchDB may be yet another option to consider. The two are historically related but presently completely different products. See this comparison.]

Conclusion: Looks to have similar capabilities as Realm. Can be device-only or synced. I need to try it out.

MongoDB

Update 4/2020

Mongo acquired Realm and plans to combine MongoDB Stitch (discussed below) with Realm (discussed above).


I'm using this server side for a piece of the app that uses AsyncStorage locally. I like that everything is stored as JSON objects, making transmission to the client devices very straightforward. In my use case, it's used as a cache between an upstream provider of TV guide data and my client devices.

There is no hard structure to the data, like a schema, so every object is stored as a "document" that is easily searchable, filterable, etc. Similar JSON objects could have additional (but different) attributes or child objects, allowing for a lot of flexibility in how you structure your objects/data.

I have not tried any client to server synchronization features, nor have I used it embedded. React Native code for MongoDB does exist.

Conclusion: Local only NoSQL solution, no obvious sync option like Realm or Firebase.

Update 2/2019

MongoDB has a "product" (or service) called Stitch. Since clients (in the sense of web browsers and phones) shouldn't be talking to MongoDB directly (that's done by code on your server), they created a serverless front-end that your apps can interface with, should you choose to use their hosted solution (Atlas). Their documentation makes it appear that there is a possible sync option.

This writeup from Dec 2018 discusses using React Native, Stitch, and MongoDB in a sample app, with other samples linked in the document (https://www.mongodb.com/blog/post/building-ios-and-android-apps-with-the-mongodb-stitch-react-native-sdk).

Twilio Sync

Another NoSQL option for synchronization is Twilio's Sync. From their site: "Sync lets you manage state across any number of devices in real time at scale without having to handle any backend infrastructure."

I looked at this as an alternative to Firebase for one of the aforementioned projects, especially after talking to both teams. I also like their other communications tools, and have used them for texting updates from a simple web app.


[Edit] I've spent some time with Realm since I originally wrote this. I like how I don't have to write an API to sync the data between the app and the server, similar to Firebase. Serverless functions also look to be really helpful with these two, limiting the amount of backend code I have to write.

I love the flexibility of the MongoDB data store, so that is becoming my choice for the server side of web-based and other connection-required apps.

I found RESTHeart, which creates a very simple, scalable RESTful API to MongoDB. It shouldn't be too hard to build a React (Native) component that reads and writes JSON objects to RESTHeart, which in turn passes them to/from MongoDB.


[Edit] I added info about how the data is stored. Sometimes it's important to know how much work you might be in for during development and testing if you've got to tweak and test the data.


Edits 2/2019 I experimented with several of these options when designing a high-concurrency project this past year (2018). Some of them mention hard and soft concurrency limits in their documentation (Firebase had a hard one at 10,000 connections, I believe, while Twilio's was a soft limit that could be bumped, according to discussions with both teams at AltConf).

If you are designing an app for tens to hundreds of thousands of users, be prepared to scale the data backend accordingly.

How to get first object out from List<Object> using Linq

I would to it like this:

//Dictionary object with Key as string and Value as List of Component type object
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>();

//from each element of the dictionary select first component if any
IEnumerable<Component> components = dic.Where(kvp => kvp.Value.Any()).Select(kvp => (kvp.Value.First() as Component).ComponentValue("Dep"));

but only if it is sure that list contains only objects of Component class or children

CMake link to external library

One more alternative, in the case you are working with the Appstore, need "Entitlements" and as such need to link with an Apple-Framework.

For Entitlements to work (e.g. GameCenter) you need to have a "Link Binary with Libraries"-buildstep and then link with "GameKit.framework". CMake "injects" the libraries on a "low level" into the commandline, hence Xcode doesn't really know about it, and as such you will not get GameKit enabled in the Capabilities screen.

One way to use CMake and have a "Link with Binaries"-buildstep is to generate the xcodeproj with CMake, and then use 'sed' to 'search & replace' and add the GameKit in the way XCode likes it...

The script looks like this (for Xcode 6.3.1).

s#\/\* Begin PBXBuildFile section \*\/#\/\* Begin PBXBuildFile section \*\/\
    26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks \*\/ = {isa = PBXBuildFile; fileRef = 26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/; };#g

s#\/\* Begin PBXFileReference section \*\/#\/\* Begin PBXFileReference section \*\/\
    26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameKit.framework; path = System\/Library\/Frameworks\/GameKit.framework; sourceTree = SDKROOT; };#g

s#\/\* End PBXFileReference section \*\/#\/\* End PBXFileReference section \*\/\
\
\/\* Begin PBXFrameworksBuildPhase section \*\/\
    26B12A9F1C10543B00A9A2BA \/\* Frameworks \*\/ = {\
        isa = PBXFrameworksBuildPhase;\
        buildActionMask = 2147483647;\
        files = (\
            26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks xxx\*\/,\
        );\
        runOnlyForDeploymentPostprocessing = 0;\
    };\
\/\* End PBXFrameworksBuildPhase section \*\/\
#g

s#\/\* CMake PostBuild Rules \*\/,#\/\* CMake PostBuild Rules \*\/,\
            26B12A9F1C10543B00A9A2BA \/\* Frameworks xxx\*\/,#g
s#\/\* Products \*\/,#\/\* Products \*\/,\
            26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/,#g

save this to "gamecenter.sed" and then "apply" it like this ( it changes your xcodeproj! )

sed -i.pbxprojbak -f gamecenter.sed myproject.xcodeproj/project.pbxproj

You might have to change the script-commands to fit your need.

Warning: it's likely to break with different Xcode-version as the project-format could change, the (hardcoded) unique number might not really by unique - and generally the solutions by other people are better - so unless you need to Support the Appstore + Entitlements (and automated builds), don't do this.

This is a CMake bug, see http://cmake.org/Bug/view.php?id=14185 and http://gitlab.kitware.com/cmake/cmake/issues/14185

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.

Here is the code - The code is in asp.net core 2.0 but should work in above versions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;

namespace UnityAssets.Website.Services
{
    public class EmailSender : IEmailSender
    {
        public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
        {
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
            email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
            email.Subject = subject;

            var body = new BodyBuilder
            {
                HtmlBody = htmlMessage
            };

            email.Body = body.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //provider specific settings
                await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
                await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);

                await client.SendAsync(email).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
    }
}

Display text on MouseOver for image in html

You can use CSS hover
Link to jsfiddle here: http://jsfiddle.net/ANKwQ/5/

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ'></a>
<div>text</div>
?

CSS:

div {
    display: none;
    border:1px solid #000;
    height:30px;
    width:290px;
    margin-left:10px;
}

a:hover + div {
    display: block;
}?

Auto-center map with multiple markers in Google Maps API v3

This work for me in Angular 9:

  import {GoogleMap, GoogleMapsModule} from "@angular/google-maps";
  @ViewChild('Map') Map: GoogleMap; /* Element Map */

  locations = [
   { lat: 7.423568, lng: 80.462287 },
   { lat: 7.532321, lng: 81.021187 },
   { lat: 6.117010, lng: 80.126269 }
  ];

  constructor() {
   var bounds = new google.maps.LatLngBounds();
    setTimeout(() => {
     for (let u in this.locations) {
      var marker = new google.maps.Marker({
       position: new google.maps.LatLng(this.locations[u].lat, 
       this.locations[u].lng),
      });
      bounds.extend(marker.getPosition());
     }

     this.Map.fitBounds(bounds)
    }, 200)
  }

And it automatically centers the map according to the indicated positions.

Result:

enter image description here

How do I use popover from Twitter Bootstrap to display an image?

Here I have an example of Bootstrap 3 popover showing an image with the tittle above it when the mouse hovers over some text. I've put in some inline styling that you may want to take out or change.....

This also works pretty well on mobile devices because the image will popup on the first tap and the link will open on the second. html:

<h5><a href="#" title="Solid Tiles Template" target="_blank" data-image-url="http://s29.postimg.org/t5pik8lyf/tiles1_preview.jpg" class="preview" rel="popover" style="color: green; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 1 <i class="fa fa-external-link"></i></a></h5>

<h5><a href="#" title="Clear Tiles Template" target="_blank" data-image-url="http://s9.postimg.org/rdonet7jj/tiles2_2_preview.jpg" class="preview" rel="popover" style="color: red; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 2 <i class="fa fa-external-link"></i></a></h5>

<h5><a href="#" title="Clear Tiles Template" target="_blank" data-image-url="http://s27.postimg.org/8scrcdu9v/tiles3_3_preview.jpg" class="preview" rel="popover" style="color: blue; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 3 <i class="fa fa-external-link"></i></a></h5>

js:

$('.preview').popover({
    'trigger':'hover',
    'html':true,
    'content':function(){
        return "<img src='"+$(this).data('imageUrl')+"'>";
    }
});

https://jsfiddle.net/pepsimax_uk/myk38781/3/

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

You can try with the below commands:

hduser@master:~$ sudo /etc/init.d/mysql stop
[ ok ] Stopping mysql (via systemctl): mysql.service.
hduser@master:~$ sudo /etc/init.d/mysql start
[ ok ] Starting mysql (via systemctl): mysql.service.

How to create a pivot query in sql server without aggregate function

Check this out as well: using xml path and pivot

SQLFIDDLE DEMO

| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
|   Asset |  205 |  142 |  421 |
|  Equity |  365 |  214 |  163 |
|  Profit |  524 |  421 |  325 |

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period) 
            FROM demo c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT account, ' + @cols + ' from 
            (
                select account
                    , value
                    , period
                from demo
           ) x
            pivot 
            (
                 max(value)
                for period in (' + @cols + ')
            ) p '


execute(@query)

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

Though it is an old question, I am adding my answer in it, because the solution that worked for me on Windows 7 as an admin user, is missing in the answers' list. Though my solution is for installed MySQL, I am putting it for those who search for a solution for this error message. Here it is:

  1. Click on the Windows 7 start button and type taskmgr in the search bar
  2. Right click on the taskmgr program icon and select Run as administrator
  3. In the Task Manager window, go to the Services tab
  4. Right click on the MySQL service and click Start Service
Step 1 and 2Step 3 and 4

Get content uri from file path in android

U can try below code snippet

    public Uri getUri(ContentResolver cr, String path){
    Uri mediaUri = MediaStore.Files.getContentUri(VOLUME_NAME);
    Cursor ca = cr.query(mediaUri, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null);
    if (ca != null && ca.moveToFirst()) {
        int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
        ca.close();
        return  MediaStore.Files.getContentUri(VOLUME_NAME,id);
    }
    if(ca != null) {
        ca.close();
    }
    return null;
}

Accessing JPEG EXIF rotation data in JavaScript on the client side

Firefox 26 supports image-orientation: from-image: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)

There is also a bug to implement this in Chrome.

Beware that this property is only supported by Firefox and is likely to be deprecated.

SQLite add Primary Key

According to the sqlite docs about table creation, using the create table as select produces a new table without constraints and without primary key.

However, the documentation also says that primary keys and unique indexes are logically equivalent (see constraints section):

In most cases, UNIQUE and PRIMARY KEY constraints are implemented by creating a unique index in the database. (The exceptions are INTEGER PRIMARY KEY and PRIMARY KEYs on WITHOUT ROWID tables.) Hence, the following schemas are logically equivalent:

CREATE TABLE t1(a, b UNIQUE);

CREATE TABLE t1(a, b PRIMARY KEY);

CREATE TABLE t1(a, b);
CREATE UNIQUE INDEX t1b ON t1(b); 

So, even if you cannot alter your table definition through SQL alter syntax, you can get the same primary key effect through the use an unique index.

Also, any table (except those created without the rowid syntax) have an inner integer column known as "rowid". According to the docs, you can use this inner column to retrieve/modify record tables.

How to override equals method in Java

Here is the solution that I recently used:

public class Test {
    public String a;
    public long b;
    public Date c;
    public String d;
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Test)) {
            return false;
        }
        Test testOther = (Test) obj;
        return (a != null ? a.equals(testOther.a) : testOther.a == null)
                && (b == testOther.b)
                && (c != null ? c.equals(testOther.c) : testOther.c == null)
                && (d != null ? d.equals(testOther.d) : testOther.d == null);
    }

}

How to create a .gitignore file

If you're using Windows it will not let you create a file without a filename in Windows Explorer. It will give you the error "You must type a file name" if you try to rename a text file as .gitignore

enter image description here

To get around this I used the following steps

  1. Create the text file gitignore.txt
  2. Open it in a text editor and add your rules, then save and close
  3. Hold SHIFT, right click the folder you're in, then select Open command window here
  4. Then rename the file in the command line, with ren gitignore.txt .gitignore

Alternatively @HenningCash suggests in the comments

You can get around this Windows Explorer error by appending a dot to the filename without extension: .gitignore. will be automatically changed to .gitignore

wget command to download a file and save as a different filename

wget -O yourfilename.zip remote-storage.url/theirfilename.zip

will do the trick for you.

Note:

a) its a capital O.

b) wget -O filename url will only work. Putting -O last will not.

Is there a way to detect if an image is blurry?

Matlab code of two methods that have been published in highly regarded journals (IEEE Transactions on Image Processing) are available here: https://ivulab.asu.edu/software

check the CPBDM and JNBM algorithms. If you check the code it's not very hard to be ported and incidentally it is based on the Marzialiano's method as basic feature.

How can I dynamically add items to a Java array?

This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.

    int [] test = {12,22,33};
    int [] test2= new int[test.length+1];
    int m=5;int mz=0;
    for ( int test3: test)        
    {          
    test2[mz]=test3; mz++;        
    } 
    test2[mz++]=m;
    test=test2;

    for ( int test3: test)

    {
      System.out.println(test3);
    }

fast way to copy formatting in excel

Does:

Set Sheets("Output").Range("$A$1:$A$500") =  Sheets(sheet_).Range("$A$1:$A$500")

...work? (I don't have Excel in front of me, so can't test.)

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

Go to Start > Programs > Microsoft SQL Server > Enterprise Manager

Right-click the SQL Server instance name > Select Properties from the context menu > Select Security node in left navigation bar

Under Authentication section, select SQL Server and Windows Authentication

Note: The server must be stopped and re-started before this will take effect

Error 18452 (not associated with a trusted sql server connection)

In log4j, does checking isDebugEnabled before logging improve performance?

Since Log4j version 2.4 (orslf4j-api 2.0.0-alpha1) it's much better to use fluent API (or Java 8 lambda support for lazy logging), supporting Supplier<?> for log message argument, that can be given by lambda:

log.debug("Debug message with expensive data : {}", 
           () -> doExpensiveCalculation());

OR with slf4j API:

log.atDebug()
            .addArgument(() -> doExpensiveCalculation())
            .log("Debug message with expensive data : {}");

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

Git: How configure KDiff3 as merge tool and diff tool

For Mac users

Here is @Joseph's accepted answer, but with the default Mac install path location of kdiff3

(Note that you can copy and paste this and run it in one go)

git config --global --add merge.tool kdiff3 
git config --global --add mergetool.kdiff3.path  "/Applications/kdiff3.app/Contents/MacOS/kdiff3" 
git config --global --add mergetool.kdiff3.trustExitCode false

git config --global --add diff.guitool kdiff3
git config --global --add difftool.kdiff3.path "/Applications/kdiff3.app/Contents/MacOS/kdiff3"
git config --global --add difftool.kdiff3.trustExitCode false

Converting a generic list to a CSV string

The problem with String.Join is that you are not handling the case of a comma already existing in the value. When a comma exists then you surround the value in Quotes and replace all existing Quotes with double Quotes.

String.Join(",",{"this value has a , in it","This one doesn't", "This one , does"});

See CSV Module

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

Building executable jar with maven?

The answer of Pascal Thivent helped me out, too. But if you manage your plugins within the <pluginManagement>element, you have to define the assembly again outside of the plugin management, or else the dependencies are not packed in the jar if you run mvn install.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>


    <build>
        <pluginManagement>
            <plugins>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>main.App</mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                    <executions>
                        <execution>
                            <id>make-assembly</id>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

            </plugins>

        </pluginManagement>

        <plugins> <!-- did NOT work without this  -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
            </plugin>
        </plugins>

    </build>


    <dependencies>
       <!--  dependencies commented out to shorten example -->
    </dependencies>

</project>

Spring 3 MVC resources and tag <mvc:resources />

I also met this problem before. My situation was I didn't put all the 62 spring framework jars into the lib file (spring-framework-4.1.2.RELEASE edition), it did work. And then I also changed the 3.0.xsd into 2.5 or 3.1 for test, it all worked out. Of course, there are also other factors to affect your result.

How to pass url arguments (query string) to a HTTP request on Angular?

If you plan on sending more than one parameter.

Component

private options = {
  sort:   '-id',
  select: null,
  limit:  1000,
  skip:   0,
  from:   null,
  to:     null
};

constructor(private service: Service) { }

ngOnInit() {
  this.service.getAllItems(this.options)
    .subscribe((item: Item[]) => {
      this.item = item;
    });
}

Service

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
constructor(private http: Http) { }

getAllItems(query: any) {
  let params: URLSearchParams = new URLSearchParams();
  for(let key in query){
    params.set(key.toString(), query[key]);
  }
  this.options.search = params;
  this.header = this.headers();

And continue with your http request just how @ethemsulan did.

Server side route

router.get('/api/items', (req, res) => {
  let q = {};
  let skip = req.query.skip;
  let limit = req.query.limit;
  let sort  = req.query.sort;
  q.from = req.query.from;
  q.to = req.query.to;

  Items.find(q)
    .skip(skip)
    .limit(limit)
    .sort(sort)
    .exec((err, items) => {
      if(err) {
        return res.status(500).json({
          title: "An error occurred",
          error: err
        });
      }
      res.status(200).json({
        message: "Success",
        obj:  items
      });
    });
});

Where do I put my php files to have Xampp parse them?

I created my project folder 'phpproj' in

...\xampp\htdocs

ex:...\xampp\htdocs\phpproj

and it worked for me. I am using Win 7 & and using xampp-win32-1.8.1

I added a php file with the following code

<?php

// Show all information, defaults to INFO_ALL
phpinfo();

?>

was able to access the file using the following URL

http://localhost/phpproj/copy.php

Make sure you restart your Apache server using the control panel before accessing it using the above URL

How can I initialize C++ object member variables in the constructor?

Regarding the first (and great) answer from chris who proposed a solution to the situation where the class members are held as a "true composite" members (i.e.- not as pointers nor references):

The note is a bit large, so I will demonstrate it here with some sample code.

When you chose to hold the members as I mentioned, you have to keep in mind also these two things:

  1. For every "composed object" that does not have a default constructor - you must initialize it in the initialization list of all the constructor's of the "father" class (i.e.- BigMommaClass or MyClass in the original examples and MyClass in the code below), in case there are several (see InnerClass1 in the example below). Meaning, you can "comment out" the m_innerClass1(a) and m_innerClass1(15) only if you enable the InnerClass1 default constructor.

  2. For every "composed object" that does have a default constructor - you may initialize it within the initialization list, but it will work also if you chose not to (see InnerClass2 in the example below).

See sample code (compiled under Ubuntu 18.04 (Bionic Beaver) with g++ version 7.3.0):

#include <iostream>

using namespace std;

class InnerClass1
{
    public:
        InnerClass1(int a) : m_a(a)
        {
            cout << "InnerClass1::InnerClass1 - set m_a:" << m_a << endl;
        }

        /* No default constructor
        InnerClass1() : m_a(15)
        {
            cout << "InnerClass1::InnerClass1() - set m_a:" << m_a << endl;
        }
        */

        ~InnerClass1()
        {
            cout << "InnerClass1::~InnerClass1" << endl;
        }

    private:
        int m_a;
};

class InnerClass2
{
    public:
        InnerClass2(int a) : m_a(a)
        {
            cout << "InnerClass2::InnerClass2 - set m_a:" << m_a << endl;
        }

        InnerClass2() : m_a(15)
        {
            cout << "InnerClass2::InnerClass2() - set m_a:" << m_a << endl;
        }

        ~InnerClass2()
        {
            cout << "InnerClass2::~InnerClass2" << endl;
        }

    private:
        int m_a;
};

class MyClass
{
    public:
        MyClass(int a, int b) : m_innerClass1(a), /* m_innerClass2(a),*/ m_b(b)
        {
            cout << "MyClass::MyClass(int b) - set m_b to:" << m_b << endl;
        }

         MyClass() : m_innerClass1(15), /*m_innerClass2(15),*/ m_b(17)
        {
            cout << "MyClass::MyClass() - m_b:" << m_b << endl;
        }

        ~MyClass()
        {
            cout << "MyClass::~MyClass" << endl;
        }

    private:
        InnerClass1 m_innerClass1;
        InnerClass2 m_innerClass2;
        int m_b;
};

int main(int argc, char** argv)
{
    cout << "main - start" << endl;

    MyClass obj;

    cout << "main - end" << endl;
    return 0;
}

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

I had same problem. Solution was simple, I've set HTTPBody, but haven't set HTTPMethod to POST. After fixing this, everything was fine.

How to change default timezone for Active Record in Rails?

In Ruby on Rails 6.0.1 go to config > locales > application.rb y agrega lo siguiente:

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module CrudRubyOnRails6
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    config.active_record.default_timezone = :local
    config.time_zone = 'Lima'

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end
end

You can see that I am configuring the time zone with 2 lines:

config.active_record.default_timezone =: local
config.time_zone = 'Lima'

I hope it helps those who are working with Ruby on Rails 6.0.1

SQL Server 2012 can't start because of a login failure

The answer to this may be identical to the problem with full blown SQL Server (NTService\MSSQLSERVER) and this is to reset the password. The ironic thing is, there is no password.

Steps are:

  • Right click on the Service in the Services mmc
  • Click Properties
  • Click on the Log On tab
  • The password fields will appear to have entries in them...
  • Blank out both Password fields
  • Click "OK"

This should re-grant access to the service and it should start up again. Weird?

NOTE: if the problem comes back after a few hours or days, then you probably have a group policy which is overriding your settings and it's coming and taking the right away again.

Difference between session affinity and sticky session?

As I've always heard the terms used in a load-balancing scenario, they are interchangeable. Both mean that once a session is started, the same server serves all requests for that session.

iterating quickly through list of tuples

I wonder whether the below method is what you want.

You can use defaultdict.

>>> from collections import defaultdict
>>> s = [('red',1), ('blue',2), ('red',3), ('blue',4), ('red',1), ('blue',4)]
>>> d = defaultdict(list)
>>> for k, v in s:
       d[k].append(v)    
>>> sorted(d.items())
[('blue', [2, 4, 4]), ('red', [1, 3, 1])]

How to find if element with specific id exists or not

 var myEle = document.getElementById("myElement");
    if(myEle){
        var myEleValue= myEle.value;
    }

the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value

Cannot make file java.io.IOException: No such file or directory

I got the same problem when using rest-easy. After searching while i figured that this error occured when there is no place to keep temporary files. So in tomcat you can just create tomcat-root/temp folder.

Changing project port number in Visual Studio 2013

To specify a port for the ASP.NET Development Server

  • In Solution Explorer, click the name of the application.

  • In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.

  • This will enable editing of the Port number property.

  • In the Properties pane, click the text box beside Port number and
    type in a port number. Click outside of the Properties pane. This
    saves the property settings.

  • Each time you run a file-system Web site within Visual Web Developer, the ASP.NET Development Server will listen on the specified port.

Hope this helps.

Sending cookies with postman

I used postman chrome extension until it became deprecated. Chrome extension also less usable and powerful then native postman application. So, it became not very convenient to use chrome extension. I have found next approach:

  1. copy any request in chrome/any other browser as CURL request (image 1)
  2. import to postman copied request (image 2)
  3. save imported request in postman's list

copy curl request image 1

enter image description here image 2

SQL Server - find nth occurrence in a string

I was toying with a faster way to do this than simply iterating through the string.

CREATE FUNCTION [ssf_GetNthSeparatorPosition] ( @TargetString VARCHAR(MAX)
                                              , @Sep VARCHAR(25)
                                              , @n INTEGER )
RETURNS INTEGER
/****************************************************************************************
--#############################################################################
-- Returns the position of the Nth Charactor sequence
--                                     1234567890123456789
-- Declare @thatString varchar(max) = 'hi,there,jay,yo'
  Select dbo.ssf_GetNthSeparatorPosition(@thatString, ',', 3) --would return 13
--############################################################################ 


****************************************************************************************/
AS
    BEGIN
        DECLARE @Retval INTEGER = 0
        DECLARE @CurPos INTEGER = 0
        DECLARE @LenSep INTEGER = LEN(@Sep)

        SELECT @CurPos = CHARINDEX(@Sep, @TargetString)

        IF ISNULL(@LenSep, 0) > 0
            AND @CurPos > 0
            BEGIN

               SELECT @CurPos = 0
              ;with lv0 AS (SELECT 0 g UNION ALL SELECT 0)
                            ,lv1 AS (SELECT 0 g FROM lv0 a CROSS JOIN lv0 b) -- 4
                            ,lv2 AS (SELECT 0 g FROM lv1 a CROSS JOIN lv1 b) -- 16
                            ,lv3 AS (SELECT 0 g FROM lv2 a CROSS JOIN lv2 b) -- 256
                            ,lv4 AS (SELECT 0 g FROM lv3 a CROSS JOIN lv3 b) -- 65,536
                            ,lv5 AS (SELECT 0 g FROM lv4 a CROSS JOIN lv4 b) -- 4,294,967,296
                            ,Tally (n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM lv5),
                        results
                          AS ( SELECT n - LEN(@Sep) AS Nth
                                ,   row_number() OVER ( ORDER BY n ) - 1 AS Position
                                FROM Tally t
                                WHERE n BETWEEN 1
                                        AND     DATALENGTH(@TargetString) + DATALENGTH(@Sep)
                                    AND SUBSTRING(@Sep + @TargetString, n, LEN(@Sep)) = @Sep)
                    SELECT @CurPos = Nth
                        FROM results
                        WHERE results.Position = @n


            END
        RETURN @CurPos

    END

GO

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

Convert columns to string in Pandas

One way to convert to string is to use astype:

total_rows['ColumnID'] = total_rows['ColumnID'].astype(str)

However, perhaps you are looking for the to_json function, which will convert keys to valid json (and therefore your keys to strings):

In [11]: df = pd.DataFrame([['A', 2], ['A', 4], ['B', 6]])

In [12]: df.to_json()
Out[12]: '{"0":{"0":"A","1":"A","2":"B"},"1":{"0":2,"1":4,"2":6}}'

In [13]: df[0].to_json()
Out[13]: '{"0":"A","1":"A","2":"B"}'

Note: you can pass in a buffer/file to save this to, along with some other options...

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

I used Adobe's detection kit, originally suggested by justpassinby. Their system is nice because it detects the version number and compares it for you against your 'required version'

One bad thing is it does an alert showing the detected version of flash, which isn't very user friendly. All of a sudden a box pops up with some seemingly random numbers.

Some modifications you might want to consider:

  • remove the alert
  • change it so it returns an object (or array) --- first element is boolean true/false for "was the required version found on user's machine" --- second element is the actual version number found on user's machine

Loop through list with both content and index

Like everyone else:

for i, val in enumerate(data):
    print i, val

but also

for i, val in enumerate(data, 1):
    print i, val

In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don't want your index to start with the default value of zero.

I was printing out lines in a file the other day and specified the starting value as 1 for enumerate(), which made more sense than 0 when displaying information about a specific line to the user.

How to get an object's methods?

You can use console.dir(object) to write that objects properties to the console.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"

example of adding (compile 'io.reactivex:rxjava:1.1.0'):

hit refresh

If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

If you're using IntelliJ & Mac just go to Project structure -> SDK and make sure that there is Java listed but it points to sth like

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

Rather than user home...

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

I had a similar problem, but I was using initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil explicitly using the name of the class as the string passed (yes bad form!).

I ended up deleting and re-creating the view controller using a slightly different name but neglected to change the string specified in the method, thus my old version was still used - even though it was in the trash!

I will likely use this structure going forward as suggested in: Is passing two nil paramters to initWithNibName:bundle: method bad practice (i.e. unsafe or slower)?

- (id)init
{
    [super initWithNibName:@"MyNib" bundle:nil];
    ... typical initialization ...
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    return [self init];
}

Hopefully this helps someone!

How do I change the font size and color in an Excel Drop Down List?

I work on 60-70% zoom vue and my dropdown are unreadable so I made this simple code to overcome the issue

Note that I selected first all my dropdown lsts (CTRL+mouse click), went on formula tab, clicked "define name" and called them "ProduktSelection"

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("ProduktSelection")
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

ActiveWindow.Zoom = 100

End If

End Sub

I then have another sub

Private Sub Worksheet_Change(ByVal Target As Range) 

where I come back to 65% when value is changed.

Checking if a variable is defined?

It should be mentioned that using defined to check if a specific field is set in a hash might behave unexpected:

var = {}
if defined? var['unknown']
  puts 'this is unexpected'
end
# will output "this is unexpected"

The syntax is correct here, but defined? var['unknown'] will be evaluated to the string "method", so the if block will be executed

edit: The correct notation for checking if a key exists in a hash would be:

if var.key?('unknown')

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

Javascript isnull

return results == null ? 0 : (results[1] || 0);

How to check if a file exists before creating a new file

Try

ifstream my_file("test.txt");
if (my_file)
{
 // do stuff
}

From: How to check if a file exists and is readable in C++?

or you could use boost functions.

SQL Server - NOT IN

You're probably better off comparing the fields individually, rather than concatenating the strings.

SELECT t1.*
    FROM Table1 t1
        LEFT JOIN Table2 t2
            ON t1.MAKE = t2.MAKE
                AND t1.MODEL = t2.MODEL
                AND t1.[serial number] = t2.[serial number]
    WHERE t2.MAKE IS NULL

android get all contacts

This is the Method to get contact list Name and Number

 private void getAllContacts() {
    ContentResolver contentResolver = getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            if (hasPhoneNumber > 0) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Cursor phoneCursor = contentResolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
                        null);
                if (phoneCursor != null) {
                    if (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

   //At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
                        phoneCursor.close();
                    }


                }
            }
        }
    }
}

Serialize JavaScript object into JSON string

It's just JSON? You can stringify() JSON:

var obj = {
    cons: [[String, 'some', 'somemore']],
    func: function(param, param2){
        param2.some = 'bla';
    }
};

var text = JSON.stringify(obj);

And parse back to JSON again with parse():

var myVar = JSON.parse(text);

If you have functions in the object, use this to serialize:

function objToString(obj, ndeep) {
  switch(typeof obj){
    case "string": return '"'+obj+'"';
    case "function": return obj.name || obj.toString();
    case "object":
      var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
      return ('{['[+isArray] + Object.keys(obj).map(function(key){
           return '\n\t' + indent +(isArray?'': key + ': ' )+ objToString(obj[key], (ndeep||1)+1);
         }).join(',') + '\n' + indent + '}]'[+isArray]).replace(/[\s\t\n]+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)/g,'');
    default: return obj.toString();
  }
}

Examples:

Serialize:

var text = objToString(obj); //To Serialize Object

Result:

"{cons:[[String,"some","somemore"]],func:function(param,param2){param2.some='bla';}}"

Deserialize:

Var myObj = eval('('+text+')');//To UnSerialize 

Result:

Object {cons: Array[1], func: function, spoof: function}

Clicking a checkbox with ng-click does not update the model

How about changing

<input type='checkbox' ng-click='onCompleteTodo(todo)' ng-model="todo.done">

to

<input type='checkbox' ng-change='onCompleteTodo(todo)' ng-model="todo.done">

From docs:

Evaluate given expression when user changes the input. The expression is not evaluated when the value change is coming from the model.

Note, this directive requires ngModel to be present.

Regarding Java switch statements - using return and omitting breaks in each case

Why not just

private double translateSlider(int sliderval) {
if(sliderval > 4 || sliderval < 0)
    return 1.0d;
return (1.0d - ((double)sliderval/10.0d));
}

Or similar?

How to create a label inside an <input> element?

Please use PlaceHolder.JS its works in all browsers and very easy for non html5 compliant browsers http://jamesallardice.github.io/Placeholders.js/

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

If you are using homebrew and homebrew services, you can probably just do:

brew services stop postgresql
brew upgrade postgresql
brew postgresql-upgrade-database
brew services start postgresql

I think this might not work completely if you are using advanced postgres features, but it worked perfectly for me.

Android read text raw resource file

Well with Kotlin u can do it just in one line of code:

resources.openRawResource(R.raw.rawtextsample).bufferedReader().use { it.readText() }

Or even declare extension function:

fun Resources.getRawTextFile(@RawRes id: Int) =
        openRawResource(id).bufferedReader().use { it.readText() }

And then just use it straightaway:

val txtFile = resources.getRawTextFile(R.raw.rawtextsample)

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

Storing sex (gender) in database

CREATE TABLE Admission (
    Rno INT PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(25) NOT NULL,
    Gender ENUM('M','F'),
    Boolean_Valu boolean,
    Dob Date,
    Fees numeric(7,2) NOT NULL
);




insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Raj','M',true,'1990-07-12',50000);
insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Rani','F',false,'1994-05-10',15000);
select * from admission;

enter link description here

How do I set the version information for an existing .exe, .dll?

the above answer from @DannyBeckett helped me a lot,

I put the following in a batch file & I place it in the same folder where ResourceHacker.exe & the EXE I work on is located & it works excellent. [you may edit it to fit your needs]

    @echo off
    :start1
    set /p newVersion=Enter version number [?.?.?.?]:
    if "%newVersion%" == "" goto start1
    :start2
    set /p file=Enter EXE name [for 'program.exe' enter 'program']:
    if "%file%" == "" goto start2
    for /f "tokens=1-4 delims=." %%a in ('echo %newVersion%') do (set ResVersion=%%a,%%b,%%c,%%d)
    (
    echo:VS_VERSION_INFO VERSIONINFO
    echo:    FILEVERSION    %ResVersion%
    echo:    PRODUCTVERSION %ResVersion%
    echo:{
    echo:    BLOCK "StringFileInfo"
    echo:    {
    echo:        BLOCK "040904b0"
    echo:        {
    echo:            VALUE "CompanyName",        "MyCompany\0"
    echo:            VALUE "FileDescription",    "TestFile\0"
    echo:            VALUE "FileVersion",        "%newVersion%\0"
    echo:            VALUE "LegalCopyright",     "COPYRIGHT © 2019 MyCompany\0"
    echo:            VALUE "OriginalFilename",   "%file%.exe\0"
    echo:            VALUE "ProductName",        "Test\0"
    echo:            VALUE "ProductVersion",     "%newVersion%\0"
    echo:        }
    echo:    }
    echo:    BLOCK "VarFileInfo"
    echo:    {
    echo:        VALUE "Translation", 0x409, 1200
    echo:    }
    echo:}
    ) >Resources.rc     &&      echo setting Resources.rc
    ResourceHacker.exe -open resources.rc -save resources.res -action compile -log CONSOLE
    ResourceHacker -open "%file%.exe" -save "%file%Res.exe" -action addoverwrite -resource "resources.res"  -log CONSOLE
    ResourceHacker.exe -open "%file%Res.exe" -save "%file%Ico.exe" -action addskip -res "%file%.ico" -mask ICONGROUP,MAINICON, -log CONSOLE
    xCopy /y /f "%file%Ico.exe" "%file%.exe"
    echo.
    echo.
    echo your compiled file %file%.exe is ready
    pause

[as a side note i used resource hacker also to compile the res file, not GoRC]

Best way to "push" into C# array

As per comment "That is not pushing to an array. It is merely assigning to it"

If you looking for the best practice to assign value to array then its only way that you can assign value.

Array[index]= value;

there is only way to assign value when you do not want to use List.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

setTimeout(() => { // your code here }, 0);

I wrapped my code in setTimeout and it worked

Regex Last occurrence?

A negative look ahead is a correct answer, but it can be written more cleanly like:

(\\)(?!.*\\)

This looks for an occurrence of \ and then in a check that does not get matched, it looks for any number of characters followed by the character you don't want to see after it. Because it's negative, it only matches if it does not find a match.

How to convert string to boolean php

function stringToBool($string){
    return ( mb_strtoupper( trim( $string)) === mb_strtoupper ("true")) ? TRUE : FALSE;
}

or

function stringToBool($string) {
    return filter_var($string, FILTER_VALIDATE_BOOLEAN);
}

How can I zoom an HTML element in Firefox and Opera?

It does not work in uniform way in all browsers. I went to to: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_pulpitimage and added style for zoom and -moz-transform. I ran the same code on firefox, IE and chrome and got 3 different results.

<html>
<style>
body{zoom:3;-moz-transform: scale(3);}
</style>
<body>

<h2>Norwegian Mountain Trip</h2>
<img border="0" src="/images/pulpit.jpg" alt="Pulpit rock"  />

</body>
</html>

Calling class staticmethod within the class body?

What about injecting the class attribute after the class definition?

class Klass(object):

    @staticmethod  # use as decorator
    def stat_func():
        return 42

    def method(self):
        ret = Klass.stat_func()
        return ret

Klass._ANS = Klass.stat_func()  # inject the class attribute with static method value

Can't import org.apache.http.HttpResponse in Android Studio

HttpClient was deprecated in Android 5.1 and is removed from the Android SDK in Android 6.0. While there is a workaround to continue using HttpClient in Android 6.0 with Android Studio, you really need to move to something else. That "something else" could be:

Or, depending upon the nature of your HTTP work, you might choose a library that supports higher-order operations (e.g., Retrofit for Web service APIs).

In a pinch, you could enable the legacy APIs, by having useLibrary 'org.apache.http.legacy' in your android closure in your module's build.gradle file. However, Google has been advising people for years to stop using Android's built-in HttpClient, and so at most, this should be a stop-gap move, while you work on a more permanent shift to another API.

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

Difference between $.ajax() and $.get() and $.load()

Important note : jQuery.load() method can do not only GET but also POST requests, if data parameter is supplied (see: http://api.jquery.com/load/)

data Type: PlainObject or String A plain object or string that is sent to the server with the request.

Request Method The POST method is used if data is provided as an object; otherwise, GET is assumed.

Example: pass arrays of data to the server (POST request)
$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

Defining a `required` field in Bootstrap

Form validation can be enabled in markup via the data-api or via JavaScript. Automatically enable form validation by adding data-toggle="validator" to your form element.

<form role="form" data-toggle="validator">
   ...
</form>

Or activate validation via JavaScript:

$('#myForm').validator()

and you need to use required flag in input field

For more details Click Here

Map and Reduce in .NET

Linq equivalents of Map and Reduce: If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.

  • Map is Select:

    Enumerable.Range(1, 10).Select(x => x + 2);
    
  • Reduce is Aggregate:

    Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
    
  • Filter is Where:

    Enumerable.Range(1, 10).Where(x => x % 2 == 0);
    

https://www.justinshield.com/2011/06/mapreduce-in-c/

Select multiple columns by labels in pandas

How do I select multiple columns by labels in pandas?

Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:

loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]

          A         B         C         E         G         H         I
0 -1.666330  0.321260 -1.768185 -0.034774  0.023294  0.533451 -0.241990
1  0.911498  3.408758  0.419618 -0.462590  0.739092  1.103940  0.116119
2  1.243001 -0.867370  1.058194  0.314196  0.887469  0.471137 -1.361059
3 -0.525165  0.676371  0.325831 -1.152202  0.606079  1.002880  2.032663
4  0.706609 -0.424726  0.308808  1.994626  0.626522 -0.033057  1.725315
5  0.879802 -1.961398  0.131694 -0.931951 -0.242822 -1.056038  0.550346
6  0.199072  0.969283  0.347008 -2.611489  0.282920 -0.334618  0.243583
7  1.234059  1.000687  0.863572  0.412544  0.569687 -0.684413 -0.357968
8 -0.299185  0.566009 -0.859453 -0.564557 -0.562524  0.233489 -0.039145
9  0.937637 -2.171174 -1.940916 -1.553634  0.619965 -0.664284 -0.151388

Note that the +1 is added because when using iloc the rightmost index is exclusive.


Comments on Other Solutions

  • filter is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.

  • The "location-based" solution with loc is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.

  • Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.

Click in OK button inside an Alert (Selenium IDE)

This is an answer from 2012, the question if from 2009, but people still look at it and there's only one correct (use WebDriver) and one almost useful (but not good enough) answer.


If you're using Selenium RC and can actually see an alert dialog, then it can't be done. Selenium should handle it for you. But, as stated in Selenium documentation:

Selenium tries to conceal those dialogs from you (by replacing window.alert, window.confirm and window.prompt) so they won’t stop the execution of your page. If you’re seeing an alert pop-up, it’s probably because it fired during the page load process, which is usually too early for us to protect the page.

It is a known limitation of Selenium RC (and, therefore, Selenium IDE, too) and one of the reasons why Selenium 2 (WebDriver) was developed. If you want to handle onload JS alerts, you need to use WebDriver alert handling.

That said, you can use Robot or selenium.keyPressNative() to fill in any text and press Enter and confirm the dialog blindly. It's not the cleanest way, but it could work. You won't be able to get the alert message, however.

Robot has all the useful keys mapped to constants, so that will be easy. With keyPressNative(), you want to use 10 as value for pressing Enter or 27 for Esc since it works with ASCII codes.

How to send a JSON object over Request with Android?

public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
    JSONArray array;
    @Override
    protected JSONArray doInBackground(Void... params) {

        try {
            commonurl cu = new commonurl();
            String u = cu.geturl("tempshowusermain.php");
            URL url =new URL(u);
          //  URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("lid",lid);


            DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            outputStream.write(jsonObject.toString().getBytes("UTF-8"));

            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                StringBuffer stringBuffer = new StringBuffer();
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                object =  new JSONObject(stringBuffer.toString());
             //   array = new JSONArray(stringBuffer.toString());
                array = object.getJSONArray("response");

            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return array;


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();



    }

    @Override
    protected void onPostExecute(JSONArray array) {
        super.onPostExecute(array);
        try {
            for (int x = 0; x < array.length(); x++) {

                object = array.getJSONObject(x);
                ComonUserView commUserView=new ComonUserView();//  commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
                //pidArray.add(jsonObject2.getString("pid").toString());

                commUserView.setLid(object.get("lid").toString());
                commUserView.setUname(object.get("uname").toString());
                commUserView.setAboutme(object.get("aboutme").toString());
                commUserView.setHeight(object.get("height").toString());
                commUserView.setAge(object.get("age").toString());
                commUserView.setWeight(object.get("weight").toString());
                commUserView.setBodytype(object.get("bodytype").toString());
                commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
                commUserView.setImagepath(object.get("imagepath").toString());
                commUserView.setDistance(object.get("distance").toString());
                commUserView.setLookingfor(object.get("lookingfor").toString());
                commUserView.setStatus(object.get("status").toString());

                cm.add(commUserView);
            }
            custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
          gridusername.setAdapter(custuserprof);
            //  listusername.setAdapter(custuserprof);
            } catch (Exception e) {

                e.printStackTrace();
        }
    }

C# How do I click a button by hitting Enter whilst textbox has focus?

Most beginner friendly solution is:

  1. In your Designer, click on the text field you want this to happen. At the properties Window (default: bottom-right) click on the thunderbolt (Events). This icon is next to the alphabetical sort icon and the properties icon.

  2. Scroll down to keyDown. Click on the Dropdown field right to it. You'll notice there's nothing in there so simply press enter. Visual Studio will write you the following code:

    private void yourNameOfTextbox_KeyDown(object sender, KeyEventArgs e)
    {
    
    }
    
  3. Then simply paste this between the brackets:

    if (e.KeyCode == Keys.Enter)
    {
         yourNameOfButton.PerformClick();
    }
    

This will act as you would have clicked it.

How to install SimpleJson Package for Python

Really simple way is:

pip install simplejson

Unrecognized escape sequence for path string containing backslashes

You can either use a double backslash each time

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

or use the @ symbol

string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

How can I make sticky headers in RecyclerView? (Without external lib)

you can get sticky header functionality by copying these 2 files into your project. i had no issues with this implementation:

  • can interact with the sticy header (tap/long press/swipe)
  • the sticky header hides and reveals itself properly...even if each view holder has a different height (some other answers here don't handle that properly, causing the wrong headers to show, or the headers to jump up and down)

see an example of the 2 files being used in this small github project i whipped up

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Why does this AttributeError in python occur?

The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

Get div to take up 100% body height, minus fixed-height header and footer

Trying to calculate the header and footer is bad :( A design should be simple, self explanatory. Plain easy. Calculations are just...not easy. Not easy for human and a bit hard on machines.

What you're looking for is a subset of the Holy Grail design.

Here's an implementation using the flex display. It includes side bars in addition to the footer and header. Enjoy:

<!DOCTYPE html>
<html style="height: 100%">
  <head>
    <meta charset=utf-8 />
    <title>Holy Grail</title>
    <!-- Reset browser defaults -->
    <link rel="stylesheet" href="reset.css">
  </head>
  <body style="display: flex; height: 100%; flex-direction: column">
    <div>HEADER<br/>------------
    </div>
    <!-- No need for 'flex-direction: row' because it's the default value -->
    <div style="display: flex; flex: 1">
      <div>NAV|</div>
      <div style="flex: 1; overflow: auto">
        CONTENT - START<br/>
        <script>
        for (var i=0 ; i<1000 ; ++i) {
          document.write(" Very long content!");
        }
        </script>
        <br/>CONTENT - END
      </div>
      <div>|SIDE</div>
    </div>
    <div>------------<br/>FOOTER</div>
  </body>
</html>

Solve error javax.mail.AuthenticationFailedException

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendMail1 {

    public static void main(String[] args) {
        // Recipient's email ID needs to be mentioned.
          String to = "valid email to address";

          // Sender's email ID needs to be mentioned
          String from = "valid email from address";


          // Get system properties
          Properties properties = System.getProperties();

          properties.put("mail.smtp.starttls.enable", "true"); 
          properties.put("mail.smtp.host", "smtp.gmail.com");

          properties.put("mail.smtp.port", "587");
          properties.put("mail.smtp.auth", "true");
          Authenticator authenticator = new Authenticator () {
                public PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication("userid","password");//userid and password for "from" email address 
                }
            };

            Session session = Session.getDefaultInstance( properties , authenticator);  
          try{
             // Create a default MimeMessage object.
             MimeMessage message = new MimeMessage(session);

             // Set From: header field of the header.
             message.setFrom(new InternetAddress(from));

             // Set To: header field of the header.
             message.addRecipient(Message.RecipientType.TO,
                                      new InternetAddress(to));

             // Set Subject: header field
             message.setSubject("This is the Subject Line!");

             // Now set the actual message
             message.setText("This is actual message");

             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");
          }catch (MessagingException mex) {
             mex.printStackTrace();
          }
    }

}

How to set selected value of jquery select2?

For Ajax, use $(".select2").val("").trigger("change"). That should solve the problem.

Jenkins pipeline how to change to another folder

The dir wrapper can wrap, any other step, and it all works inside a steps block, for example:

steps {
    sh "pwd"
    dir('your-sub-directory') {
      sh "pwd"
    }
    sh "pwd"
} 

Duplicate symbols for architecture x86_64 under Xcode

In Xcode 6.3.2. I have checked all possibility like as belowed

1: I have not import .m file in my project.

2: Removed -ObjC from Other linker flag.

3: Removed all my derive Data.

still i am getting same error. I have removed this error by removing any variable declaration from .pch file. in my case, i have declared AppDelegate object in .pch file. finally i found reason that cause error. so i remove declaration of any variable from .pch file and my project working charm.

What is a mutex?

Mutex: Mutex stands for Mutual Exclusion. It means only one process/thread can enter into critical section at a given time. In concurrent programming multiple threads/process updating the shared resource (any variable, shared memory etc.) may lead to some unexpected result. ( As the result depends upon the which thread/process gets the first access).

In order to avoid such an unexpected result we need some synchronization mechanism, which ensures that only one thread/process gets access to such a resource at a time.

pthread library provides support for Mutex.

typedef union
{
  struct __pthread_mutex_s
  {
    ***int __lock;***
    unsigned int __count;
    int __owner;
#ifdef __x86_64__
    unsigned int __nusers;
#endif
int __kind;
#ifdef __x86_64__
    short __spins;
    short __elision;
    __pthread_list_t __list;
# define __PTHREAD_MUTEX_HAVE_PREV      1
# define __PTHREAD_SPINS             0, 0
#else
    unsigned int __nusers;
    __extension__ union
    {
      struct
      {
        short __espins;
        short __elision;
# define __spins __elision_data.__espins
# define __elision __elision_data.__elision
# define __PTHREAD_SPINS         { 0, 0 }
      } __elision_data;
      __pthread_slist_t __list;
    };
#endif

This is the structure for mutex data type i.e pthread_mutex_t. When mutex is locked, __lock set to 1. When it is unlocked __lock set to 0.

This ensure that no two processes/threads can access the critical section at same time.

Renaming files in a folder to sequential numbers

The majority of the other solutions will overwrite existing files already named as a number. This is particularly a problem if running the script, adding more files, and then running the script again.

This script renames existing numerical files first:

#!/usr/bin/perl

use strict;
use warnings;

use File::Temp qw/tempfile/;

my $dir = $ARGV[0]
    or die "Please specify directory as first argument";

opendir(my $dh, $dir) or die "can't opendir $dir: $!";

# First rename any files that are already numeric
while (my @files = grep { /^[0-9]+(\..*)?$/ } readdir($dh))
{
    for my $old (@files) {
        my $ext = $old =~ /(\.[^.]+)$/ ? $1 : '';
        my ($fh, $new) = tempfile(DIR => $dir, SUFFIX => $ext);
        close $fh;
        rename "$dir/$old", $new;
    }
}

rewinddir $dh;
my $i;
while (my $file = readdir($dh))
{
    next if $file =~ /\A\.\.?\z/;
    my $ext = $file =~ /(\.[^.]+)$/ ? $1 : '';
    rename "$dir/$file", sprintf("%s/%04d%s", $dir, ++$i, $ext); 
}

Check if cookies are enabled

You can make an Ajax Call (Note: This solution requires JQuery):

example.php

<?php
    setcookie('CookieEnabledTest', 'check', time()+3600);
?>

<script type="text/javascript">

    CookieCheck();

    function CookieCheck()
    {
        $.post
        (
            'ajax.php',
            {
                cmd: 'cookieCheck'
            },
            function (returned_data, status)
            {
                if (status === "success")
                {
                    if (returned_data === "enabled")
                    {
                        alert ("Cookies are activated.");
                    }
                    else
                    {
                        alert ("Cookies are not activated.");
                    }
                }
            }
        );
    }
</script>

ajax.php

$cmd = filter_input(INPUT_POST, "cmd");

if ( isset( $cmd ) && $cmd == "cookieCheck" )
{
    echo (isset($_COOKIE['CookieEnabledTest']) && $_COOKIE['CookieEnabledTest']=='check') ? 'enabled' : 'disabled';
}

As result an alert box appears which shows wheter cookies are enabled or not. Of course you don't have to show an alert box, from here you can take other steps to deal with deactivated cookies.

Relay access denied on sending mail, Other domain outside of network

Set your SMTP auth to true if using the PHPmailer class:

$mail->SMTPAuth = true;

How do I trim whitespace from a string?

How do I remove leading and trailing whitespace from a string in Python?

So below solution will remove leading and trailing whitespaces as well as intermediate whitespaces too. Like if you need to get a clear string values without multiple whitespaces.

>>> str_1 = '     Hello World'
>>> print(' '.join(str_1.split()))
Hello World
>>>
>>>
>>> str_2 = '     Hello      World'
>>> print(' '.join(str_2.split()))
Hello World
>>>
>>>
>>> str_3 = 'Hello World     '
>>> print(' '.join(str_3.split()))
Hello World
>>>
>>>
>>> str_4 = 'Hello      World     '
>>> print(' '.join(str_4.split()))
Hello World
>>>
>>>
>>> str_5 = '     Hello World     '
>>> print(' '.join(str_5.split()))
Hello World
>>>
>>>
>>> str_6 = '     Hello      World     '
>>> print(' '.join(str_6.split()))
Hello World
>>>
>>>
>>> str_7 = 'Hello World'
>>> print(' '.join(str_7.split()))
Hello World

As you can see this will remove all the multiple whitespace in the string(output is Hello World for all). Location doesn't matter. But if you really need leading and trailing whitespaces, then strip() would be find.

ValueError : I/O operation on closed file

Indent correctly; your for statement should be inside the with block:

import csv    

with open('v.csv', 'w') as csvfile:
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    for w, c in p.items():
        cwriter.writerow(w + c)

Outside the with block, the file is closed.

>>> with open('/tmp/1', 'w') as f:
...     print(f.closed)
... 
False
>>> print(f.closed)
True

How can I disable all views inside the layout?

In Kotlin, you can use isDuplicateParentStateEnabled = true before the View is added to the ViewGroup.

As documented in the setDuplicateParentStateEnabled method, if the child view has additional states (like checked state for a checkbox), these won't be affected by the parent.

The xml analogue is android:duplicateParentState="true".

How to get Locale from its String representation in Java?

  1. Java provides lot of things with proper implementation lot of complexity can be avoided. This returns ms_MY.

    String key = "ms-MY";
    Locale locale = new Locale.Builder().setLanguageTag(key).build();
    
  2. Apache Commons has LocaleUtils to help parse a string representation. This will return en_US

    String str = "en-US";
    Locale locale =  LocaleUtils.toLocale(str);
    System.out.println(locale.toString());
    
  3. You can also use locale constructors.

    // Construct a locale from a language code.(eg: en)
    new Locale(String language)
    // Construct a locale from language and country.(eg: en and US)
    new Locale(String language, String country)
    // Construct a locale from language, country and variant.
    new Locale(String language, String country, String variant)
    

Please check this LocaleUtils and this Locale to explore more methods.

What is the equivalent of Select Case in Access SQL?

You could do below:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

How do I read a resource file from a Java jar file?

I'd like to point out that one issues is what if the same resources are in multiple jar files. Let's say you want to read /org/node/foo.txt, but not from one file, but from each and every jar file.

I have run into this same issue several times before. I was hoping in JDK 7 that someone would write a classpath filesystem, but alas not yet.

Spring has the Resource class which allows you to load classpath resources quite nicely.

I wrote a little prototype to solve this very problem of reading resources form multiple jar files. The prototype does not handle every edge case, but it does handle looking for resources in directories that are in the jar files.

I have used Stack Overflow for quite sometime. This is the second answer that I remember answering a question so forgive me if I go too long (it is my nature).

This is a prototype resource reader. The prototype is devoid of robust error checking.

I have two prototype jar files that I have setup.

 &lt;pre>
         &lt;dependency>
              &lt;groupId>invoke&lt;/groupId>
              &lt;artifactId>invoke&lt;/artifactId>
              &lt;version>1.0-SNAPSHOT&lt;/version>
          &lt;/dependency>

          &lt;dependency>
               &lt;groupId>node&lt;/groupId>
               &lt;artifactId>node&lt;/artifactId>
               &lt;version>1.0-SNAPSHOT&lt;/version>
          &lt;/dependency>

The jar files each have a file under /org/node/ called resource.txt.

This is just a prototype of what a handler would look like with classpath:// I also have a resource.foo.txt in my local resources for this project.

It picks them all up and prints them out.

   

    package com.foo;

    import java.io.File;
    import java.io.FileReader;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.URI;
    import java.net.URL;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;

    /**
    * Prototype resource reader.
    * This prototype is devoid of error checking.
    *
    *
    * I have two prototype jar files that I have setup.
    * <pre>
    *             <dependency>
    *                  <groupId>invoke</groupId>
    *                  <artifactId>invoke</artifactId>
    *                  <version>1.0-SNAPSHOT</version>
    *              </dependency>
    *
    *              <dependency>
    *                   <groupId>node</groupId>
    *                   <artifactId>node</artifactId>
    *                   <version>1.0-SNAPSHOT</version>
    *              </dependency>
    * </pre>
    * The jar files each have a file under /org/node/ called resource.txt.
    * <br />
    * This is just a prototype of what a handler would look like with classpath://
    * I also have a resource.foo.txt in my local resources for this project.
    * <br />
    */
    public class ClasspathReader {

        public static void main(String[] args) throws Exception {

            /* This project includes two jar files that each have a resource located
               in /org/node/ called resource.txt.
             */


            /* 
              Name space is just a device I am using to see if a file in a dir
              starts with a name space. Think of namespace like a file extension 
              but it is the start of the file not the end.
            */
            String namespace = "resource";

            //someResource is classpath.
            String someResource = args.length > 0 ? args[0] :
                    //"classpath:///org/node/resource.txt";   It works with files
                    "classpath:///org/node/";                 //It also works with directories

            URI someResourceURI = URI.create(someResource);

            System.out.println("URI of resource = " + someResourceURI);

            someResource = someResourceURI.getPath();

            System.out.println("PATH of resource =" + someResource);

            boolean isDir = !someResource.endsWith(".txt");


            /** Classpath resource can never really start with a starting slash.
             * Logically they do, but in reality you have to strip it.
             * This is a known behavior of classpath resources.
             * It works with a slash unless the resource is in a jar file.
             * Bottom line, by stripping it, it always works.
             */
            if (someResource.startsWith("/")) {
                someResource = someResource.substring(1);
            }

              /* Use the ClassLoader to lookup all resources that have this name.
                 Look for all resources that match the location we are looking for. */
            Enumeration resources = null;

            /* Check the context classloader first. Always use this if available. */
            try {
                resources = 
                    Thread.currentThread().getContextClassLoader().getResources(someResource);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if (resources == null || !resources.hasMoreElements()) {
                resources = ClasspathReader.class.getClassLoader().getResources(someResource);
            }

            //Now iterate over the URLs of the resources from the classpath
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();


                /* if the resource is a file, it just means that we can use normal mechanism
                    to scan the directory.
                */
                if (resource.getProtocol().equals("file")) {
                    //if it is a file then we can handle it the normal way.
                    handleFile(resource, namespace);
                    continue;
                }

                System.out.println("Resource " + resource);

               /*

                 Split up the string that looks like this:
                 jar:file:/Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar!/org/node/
                 into
                    this /Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar
                 and this
                     /org/node/
                */
                String[] split = resource.toString().split(":");
                String[] split2 = split[2].split("!");
                String zipFileName = split2[0];
                String sresource = split2[1];

                System.out.printf("After split zip file name = %s," +
                        " \nresource in zip %s \n", zipFileName, sresource);


                /* Open up the zip file. */
                ZipFile zipFile = new ZipFile(zipFileName);


                /*  Iterate through the entries.  */
                Enumeration entries = zipFile.entries();

                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    /* If it is a directory, then skip it. */
                    if (entry.isDirectory()) {
                        continue;
                    }

                    String entryName = entry.getName();
                    System.out.printf("zip entry name %s \n", entryName);

                    /* If it does not start with our someResource String
                       then it is not our resource so continue.
                    */
                    if (!entryName.startsWith(someResource)) {
                        continue;
                    }


                    /* the fileName part from the entry name.
                     * where /foo/bar/foo/bee/bar.txt, bar.txt is the file
                     */
                    String fileName = entryName.substring(entryName.lastIndexOf("/") + 1);
                    System.out.printf("fileName %s \n", fileName);

                    /* See if the file starts with our namespace and ends with our extension.        
                     */
                    if (fileName.startsWith(namespace) && fileName.endsWith(".txt")) {


                        /* If you found the file, print out 
                           the contents fo the file to System.out.*/
                        try (Reader reader = new InputStreamReader(zipFile.getInputStream(entry))) {
                            StringBuilder builder = new StringBuilder();
                            int ch = 0;
                            while ((ch = reader.read()) != -1) {
                                builder.append((char) ch);

                            }
                            System.out.printf("zip fileName = %s\n\n####\n contents of file %s\n###\n", entryName, builder);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    //use the entry to see if it's the file '1.txt'
                    //Read from the byte using file.getInputStream(entry)
                }

            }


        }

        /**
         * The file was on the file system not a zip file,
         * this is here for completeness for this example.
         * otherwise.
         *
         * @param resource
         * @param namespace
         * @throws Exception
         */
        private static void handleFile(URL resource, String namespace) throws Exception {
            System.out.println("Handle this resource as a file " + resource);
            URI uri = resource.toURI();
            File file = new File(uri.getPath());


            if (file.isDirectory()) {
                for (File childFile : file.listFiles()) {
                    if (childFile.isDirectory()) {
                        continue;
                    }
                    String fileName = childFile.getName();
                    if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {

                        try (FileReader reader = new FileReader(childFile)) {
                            StringBuilder builder = new StringBuilder();
                            int ch = 0;
                            while ((ch = reader.read()) != -1) {
                                builder.append((char) ch);

                            }
                            System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", childFile, builder);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }

                }
            } else {
                String fileName = file.getName();
                if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {

                    try (FileReader reader = new FileReader(file)) {
                        StringBuilder builder = new StringBuilder();
                        int ch = 0;
                        while ((ch = reader.read()) != -1) {
                            builder.append((char) ch);

                        }
                        System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", fileName, builder);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

            }
        }

    }


   

You can see a fuller example here with the sample output.

Renaming columns in Pandas

If you've got the dataframe, df.columns dumps everything into a list you can manipulate and then reassign into your dataframe as the names of columns...

columns = df.columns
columns = [row.replace("$", "") for row in columns]
df.rename(columns=dict(zip(columns, things)), inplace=True)
df.head() # To validate the output

Best way? I don't know. A way - yes.

A better way of evaluating all the main techniques put forward in the answers to the question is below using cProfile to gage memory and execution time. @kadee, @kaitlyn, and @eumiro had the functions with the fastest execution times - though these functions are so fast we're comparing the rounding of 0.000 and 0.001 seconds for all the answers. Moral: my answer above likely isn't the 'best' way.

import pandas as pd
import cProfile, pstats, re

old_names = ['$a', '$b', '$c', '$d', '$e']
new_names = ['a', 'b', 'c', 'd', 'e']
col_dict = {'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}

df = pd.DataFrame({'$a':[1, 2], '$b': [10, 20], '$c': ['bleep', 'blorp'], '$d': [1, 2], '$e': ['texa$', '']})

df.head()

def eumiro(df, nn):
    df.columns = nn
    # This direct renaming approach is duplicated in methodology in several other answers:
    return df

def lexual1(df):
    return df.rename(columns=col_dict)

def lexual2(df, col_dict):
    return df.rename(columns=col_dict, inplace=True)

def Panda_Master_Hayden(df):
    return df.rename(columns=lambda x: x[1:], inplace=True)

def paulo1(df):
    return df.rename(columns=lambda x: x.replace('$', ''))

def paulo2(df):
    return df.rename(columns=lambda x: x.replace('$', ''), inplace=True)

def migloo(df, on, nn):
    return df.rename(columns=dict(zip(on, nn)), inplace=True)

def kadee(df):
    return df.columns.str.replace('$', '')

def awo(df):
    columns = df.columns
    columns = [row.replace("$", "") for row in columns]
    return df.rename(columns=dict(zip(columns, '')), inplace=True)

def kaitlyn(df):
    df.columns = [col.strip('$') for col in df.columns]
    return df

print 'eumiro'
cProfile.run('eumiro(df, new_names)')
print 'lexual1'
cProfile.run('lexual1(df)')
print 'lexual2'
cProfile.run('lexual2(df, col_dict)')
print 'andy hayden'
cProfile.run('Panda_Master_Hayden(df)')
print 'paulo1'
cProfile.run('paulo1(df)')
print 'paulo2'
cProfile.run('paulo2(df)')
print 'migloo'
cProfile.run('migloo(df, old_names, new_names)')
print 'kadee'
cProfile.run('kadee(df)')
print 'awo'
cProfile.run('awo(df)')
print 'kaitlyn'
cProfile.run('kaitlyn(df)')

Java Interfaces/Implementation naming convention

The name of the interface should describe the abstract concept the interface represents. Any implementation class should have some sort of specific traits that can be used to give it a more specific name.

If there is only one implementation class and you can't think of anything that makes it specific (implied by wanting to name it -Impl), then it looks like there is no justification to have an interface at all.

Spring RestTemplate GET with parameters

public static void main(String[] args) {
         HttpHeaders httpHeaders = new HttpHeaders();
         httpHeaders.set("Accept", MediaType.APPLICATION_JSON_VALUE);
         final String url = "https://host:port/contract/{code}";
         Map<String, String> params = new HashMap<String, String>();
         params.put("code", "123456");
         HttpEntity<?> httpEntity  = new HttpEntity<>(httpHeaders); 
         RestTemplate restTemplate  = new RestTemplate();
         restTemplate.exchange(url, HttpMethod.GET, httpEntity,String.class, params);
    }

How to write console output to a txt file

You need to do something like this:

PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);

The second statement is the key. It changes the value of the supposedly "final" System.out attribute to be the supplied PrintStream value.

There are analogous methods (setIn and setErr) for changing the standard input and error streams; refer to the java.lang.System javadocs for details.

A more general version of the above is this:

PrintStream out = new PrintStream(
        new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);

If append is true, the stream will append to an existing file instead of truncating it. If autoflush is true, the output buffer will be flushed whenever a byte array is written, one of the println methods is called, or a \n is written.


I'd just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.

Alternatively, if you are not "logging" then consider the following:

  • With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.

    $ java MyApp > output.txt   
    

    For more information, refer to a shell tutorial or manual entry.

  • You could change your application to use an out stream passed as a method parameter or via a singleton or dependency injection rather than writing to System.out.

Changing System.out may cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending on System.out and System.err, but you could be unlucky.)

Requery a subform from another form?

All your controls are belong to us!

Fionnuala answered this correctly but skimmers like me would find it easy to miss the point.

You don't refresh the subFORM you refresh the subform CONTROL. In fact, if you check with allforms() the subForm isn't even loaded as far as access is concerned.

On the main form look at the label the subform wizard provided or select the subform by clicking once or on the border around it and look at the "caption" in the "Other" tab in properties. That's the name you use for requerying, not the name of the form that appears in the navigation panel.

In my case I had a subform called frmInvProdSub and I tried for many hours to figure out why Access didn't think it existed. I gave up, deleted the form and re-created it. The very last step is telling it what you want to call the control so I called it frmInvProdSub and finished the wizard. Then I tried and voila, it worked!

When I looked at the form name in the navigation window I realized I'd forgotten to put "Sub" in the name! That's when it clicked. The CONTROL is called frmInvProdSub, not the form and using the control name works.

Of course if both names are identical then you didn't have this problem lol.

MySQL stored procedure return value

Add:

  • DELIMITER at the beginning and end of the SP.
  • DROP PROCEDURE IF EXISTS validar_egreso; at the beginning
  • When calling the SP, use @variableName.

This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).

DROP PROCEDURE IF EXISTS `validar_egreso`;

DELIMITER $$

CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
    IN codigo_producto VARCHAR(100),
    IN cantidad INT,
    OUT valido INT(11)
)
BEGIN

    DECLARE resta INT;
    SET resta = 0;

    SELECT (codigo_producto - cantidad) INTO resta;

    IF(resta > 1) THEN
       SET valido = 1;
    ELSE
       SET valido = -1;
    END IF;

    SELECT valido;
END $$

DELIMITER ;

-- execute the stored procedure
CALL validar_egreso(4, 1, @val);

-- display the result
select @val;

XML Error: There are multiple root elements

You need to enclose your <parent> elements in a surrounding element as XML Documents can have only one root node:

<parents> <!-- I've added this tag -->
    <parent>
        <child>
            Text
        </child>
    </parent>
    <parent>
        <child>
            <grandchild>
                Text
            </grandchild>
            <grandchild>
                Text
            </grandchild>
        </child>
        <child>
            Text
        </child>
    </parent>
</parents> <!-- I've added this tag -->

As you're receiving this markup from somewhere else, rather than generating it yourself, you may have to do this yourself by treating the response as a string and wrapping it with appropriate tags, prior to attempting to parse it as XML.

So, you've a couple of choices:

  1. Get the provider of the web service to return you actual XML that has one root node
  2. Pre-process the XML, as I've suggested above, to add a root node
  3. Pre-process the XML to split it into multiple chunks (i.e. one for each <parent> node) and process each as a distinct XML Document

error : expected unqualified-id before return in c++

You need to move " } " before the line of cout << endl; to the line before the first else .

psql: FATAL: role "postgres" does not exist

For what it is worth, i have ubuntu and many packages installed and it went in conflict with it.

For me the right answer was:

sudo -i -u postgres-xc
psql

How can I set focus on an element in an HTML form using JavaScript?

If your code is:

<input type="text" id="mytext"/>

And If you are using JQuery, You can use this too:

<script>
function setFocusToTextBox(){
    $("#mytext").focus();
}
</script>

Keep in mind that you must draw the input first $(document).ready()

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Downgrading the version of Gradle worked for me:

classpath 'com.android.tools.build:gradle:3.2.0'

In Java, how to append a string more efficiently?

- Each time you append or do any modification with it, it creates a new String object.

- So use append() method of StringBuilder(If thread safety is not important), else use StringBuffer(If thread safety is important.), that will be efficient way to do it.

Writing a string to a cell in excel

try this instead

Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")

ADDITION

Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.

Please can you try the following:

  • Save a new xlsm file and call it "MyFullyQualified.xlsm"
  • Add a sheet with no protection and call it "mySheet"
  • Add a module to the workbook and add the following procedure

Does this run?

 Sub varchanger()

 With Excel.Application
    .ScreenUpdating = True
    .Calculation = Excel.xlCalculationAutomatic
    .EnableEvents = True
 End With

 On Error GoTo Whoa:

    Dim myBook As Excel.Workbook
    Dim mySheet As Excel.Worksheet
    Dim Rng  As Excel.Range

    Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
    Set mySheet = myBook.Worksheets("mySheet")
    Set Rng = mySheet.Range("A1")

    'ActiveSheet.Unprotect


    Rng.Value = "SubTotal"

    Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"

LetsContinue:
        Exit Sub
Whoa:
        MsgBox Err.Number
        GoTo LetsContinue

End Sub

Way to go from recursion to iteration

Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.

var stack = [];
stack.push(firstObject);

// while not empty
while (stack.length) {

    // Pop off end of stack.
    obj = stack.pop();

    // Do stuff.
    // Push other objects on the stack as needed.
    ...

}

Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:

foo(first);
foo(second);

has to be replaced by

stack.push(second);
stack.push(first);

Edit: The article Stacks and Recursion Elimination (or Article Backup link) goes into more details on this subject.

.NET HttpClient. How to POST string value?

There is an article about your question on asp.net's website. I hope it can help you.

How to call an api with asp net

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Here is a small part from the POST section of the article

The following code sends a POST request that contains a Product instance in JSON format:

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}

Virtualenv Command Not Found

If you're using Linux, open your terminal and type virtualenv halfway and autocomplete with tab key. If there's no auto-completion install virtualenv on your system by running:

mycomp$sudo apt-get install virtualenv
//if you're already super user.
mycomp#apt-get install virtualenv

You can now navigate to where you want to create your project and do:

myprj$pip3 install virtualenv    
//to install python 3.5 and above  
myprj$virtualenv venv --python=python3.5  
//to activate virtualenv  
(venv)myprj$source venv/bin/activate  
(venv)myprj$deactivate

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

How to pass parameters in $ajax POST?

Jquery.ajax does not encode POST data for you automatically the way that it does for GET data. Jquery expects your data to be pre-formated to append to the request body to be sent directly across the wire.

A solution is to use the jQuery.param function to build a query string that most scripts that process POST requests expect.

$.ajax({
    url: 'superman',
    type: 'POST',
    data: jQuery.param({ field1: "hello", field2 : "hello2"}) ,
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function (response) {
        alert(response.status);
    },
    error: function () {
        alert("error");
    }
}); 

In this case the param method formats the data to:

field1=hello&field2=hello2

The Jquery.ajax documentation says that there is a flag called processData that controls whether this encoding is done automatically or not. The documentation says that it defaults to true, but that is not the behavior I observe when POST is used.

Get the full URL in PHP

Clear code, working in all webservers (Apache, nginx, IIS, ...):

$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

The CLI's webpack config can now be ejected. Check Anton Nikiforov's answer.


outdated:

You can hack the config template in angular-cli/addon/ng2/models. There's no official way to modify the webpack config as of now.

There's a closed "wont-fix" issue on github about this: https://github.com/angular/angular-cli/issues/1656

Open multiple Eclipse workspaces on the Mac

Instead of copying Eclipse.app around, create an automator that runs the shell script above.

Run automator, create Application.

choose Utilities->Run shell script, and add in the above script (need full path to eclipse)

Then you can drag this to your Dock as a normal app.

Repeat for other workspaces.

You can even simply change the icon - https://discussions.apple.com/message/699288?messageID=699288򪮘

What does "dereferencing" a pointer mean?

I think all the previous answers are wrong, as they state that dereferencing means accessing the actual value. Wikipedia gives the correct definition instead: https://en.wikipedia.org/wiki/Dereference_operator

It operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer.

That said, we can dereference the pointer without ever accessing the value it points to. For example:

char *p = NULL;
*p;

We dereferenced the NULL pointer without accessing its value. Or we could do:

p1 = &(*p);
sz = sizeof(*p);

Again, dereferencing, but never accessing the value. Such code will NOT crash: The crash happens when you actually access the data by an invalid pointer. However, unfortunately, according the the standard, dereferencing an invalid pointer is an undefined behaviour (with a few exceptions), even if you don't try to touch the actual data.

So in short: dereferencing the pointer means applying the dereference operator to it. That operator just returns an l-value for your future use.

How to add a default include path for GCC in Linux?

A gcc spec file can do the job, however all users on the machine will be affected.

See here

The type or namespace name 'System' could not be found

right click you project name then open the properties windows. downgrade your Target framework version, build Solution then upgrade your Target framework version to the latest, build Solution .

Sending simple message body + file attachment using Linux Mailx

You can try this:

(cat ./body.txt)|mailx -s "subject text" -a "attchement file" [email protected]

How to position one element relative to another with jQuery?

Something like this?

$(menu).css("top", targetE1.y + "px"); 
$(menu).css("left", targetE1.x - widthOfMenu + "px");

How does the JPA @SequenceGenerator annotation work

Now, back to your questions:

Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?

By using the GenerationType.SEQUENCE strategy on the @GeneratedValue annotation, the JPA provider will try to use a database sequence object of the underlying database that supports this feature (e.g., Oracle, SQL Server, PostgreSQL, MariaDB).

If you are using MySQL, which doesn't support database sequence objects, then Hibernate is going to fall back to using the GenerationType.TABLE instead, which is undesirable since the TABLE generation performs badly.

So, don't use the GenerationType.SEQUENCE strategy with MySQL.

Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have auto-increment feature?

I assume you are talking about the GenerationType.IDENTITY when you say database auto-increment feature.

To use an AUTO_INCREMENT or IDENTITY column, you need to use the GenerationType.IDENTITYstrategy on the @GeneratedValue annotation.

Q3. If JPA generates numeric value on its own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?

The only time when the JPA provider generates values on its own is when you are using the sequence-based optimizers, like:

These optimizers are meat to reduce the number of database sequence calls, so they multiply the number of identifier values that can be generated using a single database sequence call.

To avoid conflicts between Hibernate identifier optimizers and other 3rd-party clients, you should use pooled or pooled-lo instead of hi/lo. Even if you are using a legacy application that was designed to use hi/lo, you can migrate to the pooled or pooled-lo optimizers.

Q4. Please also shed some light on sequenceName and allocationSize properties of @SequenceGenerator annotation.

The sequenceName attribute defines the database sequence object to be used to generate the identifier values. IT's the object you created using the CREATE SEQUENCE DDL statement.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post"
)
private Long id;

Hibernate is going to use the seq_post database object to generate the identifier values:

SELECT nextval('hibernate_sequence')

The allocationSize defines the identifier value multiplier, and if you provide a value that's greater than 1, then Hibernate is going to use the pooled optimizer, to reduce the number of database sequence calls.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post",
    allocationSize = 5
)
private Long id;

Then, when you persist 5 entities:

for (int i = 1; i <= 5; i++) {
    entityManager.persist(
        new Post().setTitle(
            String.format(
                "High-Performance Java Persistence, Part %d",
                i
            )
        )
    );
}

Only 2 database sequence calls will be executed, instead of 5:

SELECT nextval('hibernate_sequence')
SELECT nextval('hibernate_sequence')
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 4', 4)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 5', 5)

POST: sending a post request in a url itself

If you are sending a request through url from browser(like consuming webservice) without using html pages by default it will be GET because GET has/needs no body. if you want to make url as POST you need html/jsp pages and you have to mention in form tag as "method=post" beacause post will have body and data will be transferred in that body for security reasons. So you need a medium (like html page) to make a POST request. You cannot make an URL as POST manually unless you specify it as POST through some medium. For example in URL (http://example.com/details?name=john&phonenumber=445566)you have attached data(name, phone number) so server will identify it as a GET data because server is receiving data is through URL but not inside a request body

MySQL - force not to use cache for testing speed of query

Try using the SQL_NO_CACHE (MySQL 5.7) option in your query. (MySQL 5.6 users click HERE )

eg.

SELECT SQL_NO_CACHE * FROM TABLE

This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.

What is the equivalent of bigint in C#?

Int64 maps directly to BigInt.

Source

How to deserialize a list using GSON or another JSON library in Java?

Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:

List<Video> = new ArrayList<>(Arrays.asList(videoArray));

Using .text() to retrieve only text not nested in child tags

isn't the code:

var text  =  $('#listItem').clone().children().remove().end().text();

just becoming jQuery for jQuery's sake? When simple operations involve that many chained commands & that much (unnecessary) processing, perhaps it is time to write a jQuery extension:

(function ($) {
    function elementText(el, separator) {
        var textContents = [];
        for(var chld = el.firstChild; chld; chld = chld.nextSibling) {
            if (chld.nodeType == 3) { 
                textContents.push(chld.nodeValue);
            }
        }
        return textContents.join(separator);
    }
    $.fn.textNotChild = function(elementSeparator, nodeSeparator) {
    if (arguments.length<2){nodeSeparator="";}
    if (arguments.length<1){elementSeparator="";}
        return $.map(this, function(el){
            return elementText(el,nodeSeparator);
        }).join(elementSeparator);
    }
} (jQuery));

to call:

var text = $('#listItem').textNotChild();

the arguments are in case a different scenario is encountered, such as

<li>some text<a>more text</a>again more</li>
<li>second text<a>more text</a>again more</li>

var text = $("li").textNotChild(".....","<break>");

text will have value:

some text<break>again more.....second text<break>again more

CSS disable text selection

You could also disable user select on all elements:

* {
    -webkit-touch-callout:none;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
}

And than enable it on the elements you do want the user to be able to select:

input, textarea /*.contenteditable?*/ {
    -webkit-touch-callout:default;
    -webkit-user-select:text;
    -moz-user-select:text;
    -ms-user-select:text;
    user-select:text;
}

Auto-increment primary key in SQL tables

  1. Presumably you are in the design of the table. If not: right click the table name - "Design".
  2. Click the required column.
  3. In "Column properties" (at the bottom), scroll to the "Identity Specification" section, expand it, then toggle "(Is Identity)" to "Yes".

enter image description here

What in the world are Spring beans?

A Bean is a POJO(Plain Old Java Object), which is managed by the spring container.

Spring containers create only one instance of the bean by default. ?This bean it is cached in memory so all requests for the bean will return a shared reference to the same bean.

The @Bean annotation returns an object that spring registers as a bean in application context.?The logic inside the method is responsible for creating the instance.

When do we use @Bean annotation?

When automatic configuration is not an option. For example when we want to wire components from a third party library, because the source code is not available so we cannot annotate the classes with @Component.

A Real time scenario could be that someone wants to connect to Amazon S3 bucket. Because the source is not available he would have to create a @bean.

@Bean
public AmazonS3 awsS3Client() {
    BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsKeyId, accessKey);
    return AmazonS3ClientBuilder.standard().withRegion(Regions.fromName(region))
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
}

Source for the code above -> https://www.devglan.com/spring-mvc/aws-s3-java

Because I mentioned @Component Annotation above.

@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and class path scanning.

Component annotation registers the class as a single bean.

How to determine the Boost version on a system?

@Vertexwahns answer, but written in bash. For the people who are lazy:

boost_version=$(cat /usr/include/boost/version.hpp | grep define | grep "BOOST_VERSION " | cut -d' ' -f3)
echo "installed boost version: $(echo "$boost_version / 100000" | bc).$(echo "$boost_version / 100 % 1000" | bc).$(echo "$boost_version % 100 " | bc)"

Gives me installed boost version: 1.71.0

How to get character for a given ascii value

Simply Try this:

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

Need to install urllib2 for Python 3.5.1

Acording to the docs:

Note The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request.

Convert column classes in data.table

This is a BAD way to do it! I'm only leaving this answer in case it solves other weird problems. These better methods are the probably partly the result of newer data.table versions... so it's worth while to document this hard way. Plus, this is a nice syntax example for eval substitute syntax.

library(data.table)
dt <- data.table(ID = c(rep("A", 5), rep("B",5)), 
                 fac1 = c(1:5, 1:5), 
                 fac2 = c(1:5, 1:5) * 2, 
                 val1 = rnorm(10),
                 val2 = rnorm(10))

names_factors = c('fac1', 'fac2')
names_values = c('val1', 'val2')

for (col in names_factors){
  e = substitute(X := as.factor(X), list(X = as.symbol(col)))
  dt[ , eval(e)]
}
for (col in names_values){
  e = substitute(X := as.numeric(X), list(X = as.symbol(col)))
  dt[ , eval(e)]
}

str(dt)

which gives you

Classes ‘data.table’ and 'data.frame':  10 obs. of  5 variables:
 $ ID  : chr  "A" "A" "A" "A" ...
 $ fac1: Factor w/ 5 levels "1","2","3","4",..: 1 2 3 4 5 1 2 3 4 5
 $ fac2: Factor w/ 5 levels "2","4","6","8",..: 1 2 3 4 5 1 2 3 4 5
 $ val1: num  0.0459 2.0113 0.5186 -0.8348 -0.2185 ...
 $ val2: num  -0.0688 0.6544 0.267 -0.1322 -0.4893 ...
 - attr(*, ".internal.selfref")=<externalptr> 

How do I run .sh or .bat files from Terminal?

I had this problem for *.sh files in Yosemite and couldn't figure out what the correct path is for a folder on my Desktop...after some gnashing of teeth, dragged the file itself into the Terminal window; hey presto!!

How do I use valgrind to find memory leaks?

You can run:

valgrind --leak-check=full --log-file="logfile.out" -v [your_program(and its arguments)]

How do I update the password for Git?

you can change password through command line in 2 places, following would edit credentials to connect the repo

git config --edit 

The credentials also can be changed at global using global parameter like below

 git config --global --add user.password "XXXX"

or set the credentials helper with

git config --global credential.helper wincred

but if you have repo level credentials set the use the first command

git config --edit

How to Insert Double or Single Quotes

To Create New Quoted Values from Unquoted Values

  • Column A contains the names.
  • Put the following formula into Column B = """" & A1 & """"
  • Copy Column B and Paste Special -> Values

Using a Custom Function

Public Function Enquote(cell As Range, Optional quoteCharacter As String = """") As Variant
    Enquote = quoteCharacter & cell.value & quoteCharacter
End Function

=OfficePersonal.xls!Enquote(A1)

=OfficePersonal.xls!Enquote(A1, "'")

To get permanent quoted strings, you will have to copy formula values and paste-special-values.

How to combine results of two queries into a single dataset

Here is an example that does a union between two completely unrelated tables: the Student and the Products table. It generates an output that is 4 columns:

select
        FirstName as Column1,
        LastName as Column2,
        email as Column3,
        null as Column4
    from
        Student
union
select
        ProductName as Column1,
        QuantityPerUnit as Column2,
        null as Column3,
        UnitsInStock as Column4
    from
        Products

Obviously you'll tweak this for your own environment...

Error: Unexpected value 'undefined' imported by the module

I met this problem at the situation: - app-module --- app-routing // app router ----- imports: [RouterModule.forRoot(routes)] --- demo-module // sub-module ----- demo-routing ------- imports: [RouterModule.forRoot(routes)] // --> should be RouterModule.forChild!

because there is only a root.

Can Mockito capture arguments of a method called multiple times?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive) - the code samples below require it to work:

import static org.mockito.Mockito.*;

In the verify() method you can pass the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<MyExampleClass> argument = ArgumentCaptor.forClass(MyExampleClass.class);
verify(yourmock, atleast(2)).myMethod(argument.capture());

List<MyExampleClass> passedArguments = argument.getAllValues();

for (MyExampleClass data : passedArguments){
    //assertSometing ...
    System.out.println(data.getFoo());
}

The list of all passed arguments during your test is accessible via the argument.getAllValues() method.

The single (last called) argument's value is accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

Firefox Developer Edition (59.0b6) has Scratchpad (Shift +F4) where you can run javascript

How can I make a ComboBox non-editable in .NET?

To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Link to the documentation for the ComboBox DropDownStyle property on MSDN.

Get list of databases from SQL Server

In SQL Server 2008 R2 this works:

select name 
from master.sys.databases 
where owner_sid > 1;

And list only databases created by user(s).

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Better way to cast object to int

Convert.ToInt32(myobject);

This will handle the case where myobject is null and return 0, instead of throwing an exception.

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

Call a stored procedure with another in Oracle

To invoke the procedure from the SQLPlus command line, try one of these:

CALL test_sp_1();
EXEC test_sp_1

ng-mouseover and leave to toggle item using mouse in angularjs

Angular solution

You can fix it like this:

$scope.hoverIn = function(){
    this.hoverEdit = true;
};

$scope.hoverOut = function(){
    this.hoverEdit = false;
};

Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.

Also you need to put ngRepeat on li:

<ul>
    <li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
        {{task.name}}
        <span ng-show="hoverEdit">
            <a>Edit</a>
        </span>
    </li>
</ul>

Demo

CSS solution

However, when possible try to do such things with CSS only, this would be the optimal solution and no JS required:

ul li span {display: none;}
ul li:hover span {display: inline;}

Changing background color of text box input not working when empty

You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property. Here is a JSFiddle for it.

  <div class="div-image-text">
    <input class="input-image-url" type="text" placeholder="Add text" name="input-image">
    <input type="button" onclick="addRemoteImage(event);" value="Submit">
  </div>
  <div class="no-image-url-error" name="input-image-error">Textbox empty</div>

addRemoteImage = function(event) {
  var textbox = document.querySelector("input[name='input-image']"),
    imageUrl = textbox.value,
    errorDiv = document.querySelector("div[name='input-image-error']");
  if (imageUrl == "") {
    errorDiv.style.display = "block";
    textbox.classList.add('text-error');
    setTimeout(function() {
      errorDiv.style.removeProperty('display');
      textbox.classList.remove('text-error');
    }, 3000);
  } else {
    textbox.classList.remove('text-error');
  }
}

How can I get screen resolution in java?

Here's some functional code (Java 8) which returns the x position of the right most edge of the right most screen. If no screens are found, then it returns 0.

  GraphicsDevice devices[];

  devices = GraphicsEnvironment.
     getLocalGraphicsEnvironment().
     getScreenDevices();

  return Stream.
     of(devices).
     map(GraphicsDevice::getDefaultConfiguration).
     map(GraphicsConfiguration::getBounds).
     mapToInt(bounds -> bounds.x + bounds.width).
     max().
     orElse(0);

Here are links to the JavaDoc.

GraphicsEnvironment.getLocalGraphicsEnvironment()
GraphicsEnvironment.getScreenDevices()
GraphicsDevice.getDefaultConfiguration()
GraphicsConfiguration.getBounds()

How do I import an SQL file using the command line in MySQL?

The following steps help to upload file.sql to the MySQL database.

Step 1: Upload file.sql.zip to any directory and unzip there
Note: sudo apt-get install unzip : sudo apt-get unzip file.sql.zip
Step 2: Now navigate to that directory. Example: cd /var/www/html

Step 3: mysql -u username -p database-name < file.sql
Enter the password and wait till uploading is completed.

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

IE8 support for CSS Media Query

css3-mediaqueries-js is probably what you are looking for: this script emulates media queries. However (from the script's site) it "doesn't work on @imported stylesheets (which you shouldn't use anyway for performance reasons). Also won't listen to the media attribute of the <link> and <style> elements".

In the same vein you have the simpler Respond.js, which enables only min-width and max-width media queries.

Is there a RegExp.escape function in JavaScript?

The functions in the other answers are overkill for escaping entire regular expressions (they may be useful for escaping parts of regular expressions that will later be concatenated into bigger regexps).

If you escape an entire regexp and are done with it, quoting the metacharacters that are either standalone (., ?, +, *, ^, $, |, \) or start something ((, [, {) is all you need:

String.prototype.regexEscape = function regexEscape() {
  return this.replace(/[.?+*^$|({[\\]/g, '\\$&');
};

And yes, it's disappointing that JavaScript doesn't have a function like this built-in.

Select all columns except one in MySQL?

You can use SQL to generate SQL if you like and evaluate the SQL it produces. This is a general solution as it extracts the column names from the information schema. Here is an example from the Unix command line.

Substituting

  • MYSQL with your mysql command
  • TABLE with the table name
  • EXCLUDEDFIELD with excluded field name
echo $(echo 'select concat("select ", group_concat(column_name) , " from TABLE") from information_schema.columns where table_name="TABLE" and column_name != "EXCLUDEDFIELD" group by "t"' | MYSQL | tail -n 1) | MYSQL

You will really only need to extract the column names in this way only once to construct the column list excluded that column, and then just use the query you have constructed.

So something like:

column_list=$(echo 'select group_concat(column_name) from information_schema.columns where table_name="TABLE" and column_name != "EXCLUDEDFIELD" group by "t"' | MYSQL | tail -n 1)

Now you can reuse the $column_list string in queries you construct.

Changing background colour of tr element on mouseover

<tr>s themselves are very hard to access with CSS, try tr:hover td {background:#000}

Read/write to file using jQuery

If you want to do this without a bunch of server-side processing within the page, it might be a feasible idea to blow the text value into a hidden field (using PHP). Then you can use jQuery to process the hidden field value.

Whatever floats your boat :)

'const string' vs. 'static readonly string' in C#

You can change the value of a static readonly string only in the static constructor of the class or a variable initializer, whereas you cannot change the value of a const string anywhere.

Disable autocomplete via CSS

You can't use CSS to disable autocomplete, but you can use HTML:

<input type="text" autocomplete="false" />

Technically you can replace false with any invalid value and it'll work. This iOS the only solution I've found which also works in Edge.

Visual Studio 2015 installer hangs during install?

I had the same issue. It would hang immediately, as soon as it said "Applying Microsoft Visual Studio 2015." There was only a small sliver in the progress bar. I even let the install run overnight. There was no disk activity or CPU usage from the installer.

What finally worked was to kill the process in Task Manager and restart the computer. As soon as I rebooted, the installer opened up automatically and completed successfully.

How to do if-else in Thymeleaf?

Thymeleaf has an equivalent to <c:choose> and <c:when>: the th:switch and th:case attributes introduced in Thymeleaf 2.0.

They work as you'd expect, using * for the default case:

<div th:switch="${user.role}"> 
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p> 
</div>

See this for a quick explanation of syntax (or the Thymeleaf tutorials).

Disclaimer: As required by StackOverflow rules, I'm the author of Thymeleaf.

Create nice column output in python

Here is a variation of the Shawn Chin's answer. The width is fixed per column, not over all columns. There is also a border below the first row and between the columns. (icontract library is used to enforce the contracts.)

@icontract.pre(
    lambda table: not table or all(len(row) == len(table[0]) for row in table))
@icontract.post(lambda table, result: result == "" if not table else True)
@icontract.post(lambda result: not result.endswith("\n"))
def format_table(table: List[List[str]]) -> str:
    """
    Format the table as equal-spaced columns.

    :param table: rows of cells
    :return: table as string
    """
    cols = len(table[0])

    col_widths = [max(len(row[i]) for row in table) for i in range(cols)]

    lines = []  # type: List[str]
    for i, row in enumerate(table):
        parts = []  # type: List[str]

        for cell, width in zip(row, col_widths):
            parts.append(cell.ljust(width))

        line = " | ".join(parts)
        lines.append(line)

        if i == 0:
            border = []  # type: List[str]

            for width in col_widths:
                border.append("-" * width)

            lines.append("-+-".join(border))

    result = "\n".join(lines)

    return result

Here is an example:

>>> table = [['column 0', 'another column 1'], ['00', '01'], ['10', '11']]
>>> result = packagery._format_table(table=table)
>>> print(result)
column 0 | another column 1
---------+-----------------
00       | 01              
10       | 11              

Formatting code in Notepad++

If you go to TextFX menu and go to TextFX Edit, you will see a menu item Reindent C++ Code.

That will also format C# code.

How do I combine 2 javascript variables into a string

if you want to concatenate the string representation of the values of two variables, use the + sign :

var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1

But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:

function Container(){
   this.variables = [];
}
Container.prototype.addVar = function(var){
   this.variables.push(var);
}
Container.prototype.toString = function(){
   var result = '';
   for(var i in this.variables)
       result += this.variables[i];
   return result;
}

var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1

the advantage is that you can get the string representation of the two variables, bit you can modify them later :

container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

Dynamically creating keys in a JavaScript associative array

JavaScript does not have associative arrays. It has objects.

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all; you're setting fields on the object.

Now that that is cleared up, here is a working solution to your example:

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.

addEventListener for keydown on Canvas

Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex attribute on the canvas element (as suggested by hobberwickey).

You can't focus a canvas element. A simple work around this, would be to make your "own" focus.

var lastDownTarget, canvas;
window.onload = function() {
    canvas = document.getElementById('canvas');

    document.addEventListener('mousedown', function(event) {
        lastDownTarget = event.target;
        alert('mousedown');
    }, false);

    document.addEventListener('keydown', function(event) {
        if(lastDownTarget == canvas) {
            alert('keydown');
        }
    }, false);
}

JSFIDDLE

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

You can use an RDLC file provided in visual studio to define your report layout. You can view the rdlc using the ReportViewer control.

Both are provided out of the box with visual studio.

How do I get the Session Object in Spring?

i made my own utils. it is handy. :)

package samples.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;


/**
 * SpringMVC????
 * 
 * @author ??([email protected])
 *
 */
public final class WebContextHolder {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);

    private static WebContextHolder INSTANCE = new WebContextHolder();

    public WebContextHolder get() {
        return INSTANCE;
    }

    private WebContextHolder() {
        super();
    }

    // --------------------------------------------------------------------------------------------------------------

    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();
    }

    public HttpSession getSession() {
        return getSession(true);
    }

    public HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    public String getSessionId() {
        return getSession().getId();
    }

    public ServletContext getServletContext() {
        return getSession().getServletContext();    // servlet2.3
    }

    public Locale getLocale() {
        return RequestContextUtils.getLocale(getRequest());
    }

    public Theme getTheme() {
        return RequestContextUtils.getTheme(getRequest());
    }

    public ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }

    public ApplicationEventPublisher getApplicationEventPublisher() {
        return (ApplicationEventPublisher) getApplicationContext();
    }

    public LocaleResolver getLocaleResolver() {
        return RequestContextUtils.getLocaleResolver(getRequest());
    }

    public ThemeResolver getThemeResolver() {
        return RequestContextUtils.getThemeResolver(getRequest());
    }

    public ResourceLoader getResourceLoader() {
        return (ResourceLoader) getApplicationContext();
    }

    public ResourcePatternResolver getResourcePatternResolver() {
        return (ResourcePatternResolver) getApplicationContext();
    }

    public MessageSource getMessageSource() {
        return (MessageSource) getApplicationContext();
    }

    public ConversionService getConversionService() {
        return getBeanFromApplicationContext(ConversionService.class);
    }

    public DataSource getDataSource() {
        return getBeanFromApplicationContext(DataSource.class);
    }

    public Collection<String> getActiveProfiles() {
        return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
    }

    public ClassLoader getBeanClassLoader() {
        return ClassUtils.getDefaultClassLoader();
    }

    private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (NoUniqueBeanDefinitionException e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        } catch (NoSuchBeanDefinitionException e) {
            LOGGER.warn(e.getMessage());
            return null;
        }
    }

}