Programs & Examples On #Ntruencrypt

Amazon S3 boto - how to create a folder?

Tried many method above and adding forward slash / to the end of key name, to create directory didn't work for me:

client.put_object(Bucket="foo-bucket", Key="test-folder/")

You have to supply Body parameter in order to create directory:

client.put_object(Bucket='foo-bucket',Body='', Key='test-folder/')

Source: ryantuck in boto3 issue

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

android.view.InflateException: Binary XML file: Error inflating class fragment

It might not be needed for you anymore, but if further readers find it helpful. I have exact same android.view.InflateException:...Error inflating class fragment. I had all right libraries included. Solved by adding one more user permission in the AndroidManifest.xml file i.e. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Btw I was running Android Studio 0.8.9 on Ubuntu 12.04.

How to check if an app is installed from a web-page on an iPhone?

To further the accepted answer, you sometimes need to add extra code to handle people returning the browser after launching the app- that setTimeout function will run whenever they do. So, I do something like this:

var now = new Date().valueOf();
setTimeout(function () {
    if (new Date().valueOf() - now > 100) return;
    window.location = "https://itunes.apple.com/appdir";
}, 25);
window.location = "appname://";

That way, if there has been a freeze in code execution (i.e., app switching), it won't run.

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

What does

$ git config --get-regexp '^(remote|branch)\.'

returns (executed within your git repository) ?

Origin is just a default naming convention for referring to a remote Git repository.

If it does not refer to GitHub (but rather a path to your teammate repository, path which may no longer be valid or available), just add another origin, like in this Bloggitation entry

$ git remote add origin2 [email protected]:myLogin/myProject.git
$ git push origin2 master

(I would actually use the name 'github' rather than 'origin' or 'origin2')


Permission denied (publickey).
fatal: The remote end hung up unexpectedly

Check if your gitHub identity is correctly declared in your local Git repository, as mentioned in the GitHub Help guide. (both user.name and github.name -- and github.token)

Then, stonean blog suggests (as does Marcio Garcia):

$ cd ~/.ssh
$ ssh-add id_rsa

Aral Balkan adds: create a config file

The solution was to create a config file under ~/.ssh/ as outlined at the bottom of the OS X section of this page.

Here's the file I added, as per the instructions on the page, and my pushes started working again:

Host github.com
User git
Port 22
Hostname github.com
IdentityFile ~/.ssh/id_rsa
TCPKeepAlive yes
IdentitiesOnly yes

You can also post the result of

ssh -v [email protected]

to have more information as to why GitHub ssh connection rejects you.

Check also you did enter correctly your public key (it needs to end with '==').
Do not paste your private key, but your public one. A public key would look something like:

ssh-rsa AAAAB3<big string here>== [email protected] 

(Note: did you use a passphrase for your ssh keys ? It would be easier without a passphrase)

Check also the url used when pushing ([email protected]/..., not git://github.com/...)

Check that you do have a SSH Agent to use and cache your key.

Try this:

 $ ssh -i path/to/public/key [email protected]

If that works, then it means your key is not being sent to GitHub by your ssh client.

C# testing to see if a string is an integer?

Maybe this can be another solution

try
{
    Console.Write("write your number : ");
    Console.WriteLine("Your number is : " + int.Parse(Console.ReadLine()));
}
catch (Exception x)
{
    Console.WriteLine(x.Message);
}
Console.ReadLine();

Position Absolute + Scrolling

So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/

and the relevant code:

html:

<div class="container">
  <div class="inner">
    Lorem ipsum ...
  </div>
  <div class="full-height"></div>
</div>

css:

.container{
  height: 256px;
  position: relative;
}
.inner{
  height: 100%;
  overflow: scroll;
}
.full-height{
  position: absolute;
  left: 0;
  width: 20%;
  top: 0;
  height: 100%;
}

Random number generator only generating one random number

1) As Marc Gravell said, try to use ONE random-generator. It's always cool to add this to the constructor: System.Environment.TickCount.

2) One tip. Let's say you want to create 100 objects and suppose each of them should have its-own random-generator (handy if you calculate LOADS of random numbers in a very short period of time). If you would do this in a loop (generation of 100 objects), you could do this like that (to assure fully-randomness):

int inMyRandSeed;

for(int i=0;i<100;i++)
{
   inMyRandSeed = System.Environment.TickCount + i;
   .
   .
   .
   myNewObject = new MyNewObject(inMyRandSeed);  
   .
   .
   .
}

// Usage: Random m_rndGen = new Random(inMyRandSeed);

Cheers.

R - argument is of length zero in if statement

I spent an entire day bashing my head against this, the solution turned out to be simple..

R isn't zero-index.

Every programming language that I've used before has it's data start at 0, R starts at 1. The result is an off-by-one error but in the opposite direction of the usual. going out of bounds on a data structure returns null and comparing null in an if statement gives the argument is of length zero error. The confusion started because the dataset doesn't contain any null, and starting at position [0] like any other pgramming language turned out to be out of bounds.

Perhaps starting at 1 makes more sense to people with no programming experience (the target market for R?) but for a programmer is a real head scratcher if you're unaware of this.

How to force a web browser NOT to cache images

Add a time stamp <img src="picture.jpg?t=<?php echo time();?>">

will always give your file a random number at the end and stop it caching

Convert Java string to Time, NOT Date

try...

 java.sql.Time.valueOf("10:30:54");

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

The size of a structure is greater than the sum of its parts because of what is called packing. A particular processor has a preferred data size that it works with. Most modern processors' preferred size if 32-bits (4 bytes). Accessing the memory when data is on this kind of boundary is more efficient than things that straddle that size boundary.

For example. Consider the simple structure:

struct myStruct
{
   int a;
   char b;
   int c;
} data;

If the machine is a 32-bit machine and data is aligned on a 32-bit boundary, we see an immediate problem (assuming no structure alignment). In this example, let us assume that the structure data starts at address 1024 (0x400 - note that the lowest 2 bits are zero, so the data is aligned to a 32-bit boundary). The access to data.a will work fine because it starts on a boundary - 0x400. The access to data.b will also work fine, because it is at address 0x404 - another 32-bit boundary. But an unaligned structure would put data.c at address 0x405. The 4 bytes of data.c are at 0x405, 0x406, 0x407, 0x408. On a 32-bit machine, the system would read data.c during one memory cycle, but would only get 3 of the 4 bytes (the 4th byte is on the next boundary). So, the system would have to do a second memory access to get the 4th byte,

Now, if instead of putting data.c at address 0x405, the compiler padded the structure by 3 bytes and put data.c at address 0x408, then the system would only need 1 cycle to read the data, cutting access time to that data element by 50%. Padding swaps memory efficiency for processing efficiency. Given that computers can have huge amounts of memory (many gigabytes), the compilers feel that the swap (speed over size) is a reasonable one.

Unfortunately, this problem becomes a killer when you attempt to send structures over a network or even write the binary data to a binary file. The padding inserted between elements of a structure or class can disrupt the data sent to the file or network. In order to write portable code (one that will go to several different compilers), you will probably have to access each element of the structure separately to ensure the proper "packing".

On the other hand, different compilers have different abilities to manage data structure packing. For example, in Visual C/C++ the compiler supports the #pragma pack command. This will allow you to adjust data packing and alignment.

For example:

#pragma pack 1
struct MyStruct
{
    int a;
    char b;
    int c;
    short d;
} myData;

I = sizeof(myData);

I should now have the length of 11. Without the pragma, I could be anything from 11 to 14 (and for some systems, as much as 32), depending on the default packing of the compiler.

How to create user for a db in postgresql?

From CLI:

$ su - postgres 
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q

PHP (as tested on localhost, it works as expected):

  $connString = 'port=5432 dbname=test_database user=tester password=test_password';
  $connHandler = pg_connect($connString);
  echo 'Connected to '.pg_dbname($connHandler);

Replace values in list using Python

This might help...

test_list = [5, 8]
test_list[0] = None
print test_list
#prints [None, 8]

Form/JavaScript not working on IE 11 with error DOM7011

I had a similar problem on Internet Explorer, and got the same error number. The culprit was an HTML comment. I know it sounds unbelievable, so here is the story.

I saw a series of 6 articles on the Internet. I liked them, so I decided to download the 6 Web-Pages and store them on my Hard Drive. At the top of each page, was a couple of HTML <a> Tags, that would allow you to go to the next article or the previous article. So I changed the href attribute to point to the next folder on my Hard Drive, instead of the next URL on the Internet.

After all of the links had been re-directed, the Browser refused to display any of the Web-Pages when I clicked on the Links. The message in the Console was the Error Number that was mentioned at the top of this page.

However, the real problem was a Comment. Whenever you download a Web-Page using Google Chrome, the Chrome Browser inserts a Comment at the very top of the page that includes the URL of the location that you got the Web-Page from. After I removed the Comment at the top of each one of the 6 Pages, all of the Links worked fine ( although I continued to get the same Error Message in the Console. )

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

Add rows to CSV File in powershell

To simply append to a file in powershell,you can use add-content.

So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.

$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file

Or,

"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file

This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.

How to draw a graph in LaTeX?

TikZ can do this.

A quick demo:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  [scale=.8,auto=left,every node/.style={circle,fill=blue!20}]
  \node (n6) at (1,10) {6};
  \node (n4) at (4,8)  {4};
  \node (n5) at (8,9)  {5};
  \node (n1) at (11,8) {1};
  \node (n2) at (9,6)  {2};
  \node (n3) at (5,5)  {3};

  \foreach \from/\to in {n6/n4,n4/n5,n5/n1,n1/n2,n2/n5,n2/n3,n3/n4}
    \draw (\from) -- (\to);

\end{tikzpicture}

\end{document}

produces:

enter image description here

More examples @ http://www.texample.net/tikz/examples/tag/graphs/

More information about TikZ: http://sourceforge.net/projects/pgf/ where I guess an installation guide will also be present.

How do I rename a local Git branch?

A simple way to do it:

git branch -m old_branch new_branch         # Rename branch locally
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

For more, see this.

python list by value not by reference

If you want to copy a one-dimensional list, use

b = a[:]

However, if a is a 2-dimensional list, this is not going to work for you. That is, any changes in a will also be reflected in b. In that case, use

b = [[a[x][y] for y in range(len(a[0]))] for x in range(len(a))]

How to print a percentage value in python?

There is a way more convenient 'percent'-formatting option for the .format() format method:

>>> '{:.1%}'.format(1/3.0)
'33.3%'

Multi-threading in VBA

I was looking for something similar and the official answer is no. However, I was able to find an interesting concept by Daniel at ExcelHero.com.

Basically, you need to create worker vbscripts to execute the various things you want and have it report back to excel. For what I am doing, retrieving HTML data from various website, it works great!

Take a look:

http://www.excelhero.com/blog/2010/05/multi-threaded-vba.html

JQuery Ajax POST in Codeigniter

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class UserController extends CI_Controller {

        public function verifyUser()    {
            $userName =  $_POST['userName'];
            $userPassword =  $_POST['userPassword'];
            $status = array("STATUS"=>"false");
            if($userName=='admin' && $userPassword=='admin'){
                $status = array("STATUS"=>"true");  
            }
            echo json_encode ($status) ;    
        }
    }


function makeAjaxCall(){
    $.ajax({
        type: "post",
        url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
        cache: false,               
        data: $('#userForm').serialize(),
        success: function(json){                        
        try{        
            var obj = jQuery.parseJSON(json);
            alert( obj['STATUS']);


        }catch(e) {     
            alert('Exception while request..');
        }       
        },
        error: function(){                      
            alert('Error while request..');
        }
 });
}

Determine path of the executing script

If rather than the script, foo.R, knowing its path location, if you can change your code to always reference all source'd paths from a common root then these may be a great help:

Given

  • /app/deeply/nested/foo.R
  • /app/other.R

This will work

#!/usr/bin/env Rscript
library(here)
source(here("other.R"))

See https://rprojroot.r-lib.org/ for how to define project roots.

How can I get a specific parameter from location.search?

The following uses regular expressions and searches only on the query string portion of the URL.

Most importantly, this method supports normal and array parameters as in http://localhost/?fiz=zip&foo[]=!!=&bar=7890#hashhashhash

function getQueryParam(param) {
    var result =  window.location.search.match(
        new RegExp("(\\?|&)" + param + "(\\[\\])?=([^&]*)")
    );

    return result ? result[3] : false;
}

console.log(getQueryParam("fiz"));
console.log(getQueryParam("foo"));
console.log(getQueryParam("bar"));
console.log(getQueryParam("zxcv"));

Output:

zip
!!=
7890
false

drop down list value in asp.net

In simple way, Its not possible. Because DropdownList contain ListItem and it will be selected by default

But, you can use ValidationControl for that:

<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic" 
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>

How can I resize an image dynamically with CSS as the browser width/height changes?

Just use this code. What most are forgeting is to specify max-width as the max-width of the image

img {   
    height: auto;
    width: 100%;
    max-width: 300px;
}

Check this demonstration http://shorturl.at/nBKVY

Windows Scipy Install: No Lapack/Blas Resources Found

This was the order I got everything working. The second point is the most important one. Scipy needs Numpy+MKL, not just vanilla Numpy.

  1. Install python 3.5
  2. pip install "file path" (download Numpy+MKL wheel from here http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)
  3. pip install scipy

sqlplus how to find details of the currently connected database session

show user

to get connected user

 select instance_name from v$instance

to get instance or set in sqlplus

set sqlprompt "_USER'@'_CONNECT_IDENTIFIER> "

psql: FATAL: database "<user>" does not exist

This is a basic misunderstanding. Simply typing:

pgres

will result in this response:

pgres <db_name> 

It will succeed without error if the user has the permissions to access the db.

One can go into the details of the exported environment variables but that's unnecessary .. this is too basic to fail for any other reason.

Python circular importing?

I think the answer by jpmc26, while by no means wrong, comes down too heavily on circular imports. They can work just fine, if you set them up correctly.

The easiest way to do so is to use import my_module syntax, rather than from my_module import some_object. The former will almost always work, even if my_module included imports us back. The latter only works if my_object is already defined in my_module, which in a circular import may not be the case.

To be specific to your case: Try changing entities/post.py to do import physics and then refer to physics.PostBody rather than just PostBody directly. Similarly, change physics.py to do import entities.post and then use entities.post.Post rather than just Post.

What does %w(array) mean?

I was given a bunch of columns from a CSV spreadsheet of full names of users and I needed to keep the formatting, with spaces. The easiest way I found to get them in while using ruby was to do:

names = %( Porter Smith
Jimmy Jones
Ronald Jackson).split('\n')

This highlights that %() creates a string like "Porter Smith\nJimmyJones\nRonald Jackson" and to get the array you split the string on the "\n" ["Porter Smith", "Jimmy Jones", "Ronald Jackson"]

So to answer the OP's original question too, they could have wrote %(cgi\ spaeinfilename.rb;complex.rb;date.rb).split(';') if there happened to be space when you want the space to exist in the final array output.

Convert string to int if string is a number

To put it on one line:

currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)

How to add onload event to a div element

Try this! And never use trigger twice on div!

You can define function to call before the div tag.

$(function(){
    $('div[onload]').trigger('onload');
});

DEMO: jsfiddle

CSS customized scroll bar in div

Here's a webkit example which works for Chrome and Safari:

CSS:

::-webkit-scrollbar 
{
    width: 40px;
    background-color:#4F4F4F;
}

::-webkit-scrollbar-button:vertical:increment 
{
    height:40px;
    background-image: url(/Images/Scrollbar/decrement.png);
    background-size:39px 30px;
    background-repeat:no-repeat;
}

::-webkit-scrollbar-button:vertical:decrement 
{
    height:40px;
    background-image: url(/Images/Scrollbar/increment.png);    
    background-size:39px 30px;
    background-repeat:no-repeat;
}

Output:

enter image description here

How to add Tomcat Server in eclipse

There are different eclipse plugins available to manage Tomcat server and create war file.

For example you can use tomcatPlugin. It permits to start/stop and build the war simply. You can read this tutorial.

What’s the best way to check if a file exists in C++? (cross platform)

If your compiler supports C++17 you don't need boost, you can simply use std::filesystem::exists

#include <iostream> // only for std::cout
#include <filesystem>

if (!std::filesystem::exists("myfile.txt"))
{
    std::cout << "File not found!" << std::endl;
}

Debugging iframes with Chrome developer tools

When the iFrame points to your site like this:

<html>
  <head>
    <script type="text/javascript" src="/jquery.js"></script>
  </head>
  <body>
    <iframe id="my_frame" src="/wherev"></iframe>
  </body>
</html>

You can access iFrame DOM through this kind of thing.

var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));

How to append a newline to StringBuilder

For Kotlin,

StringBuilder().appendLine("your text");

Though this is a java question, this is also the first google result for Kotlin, might come in handy.

Bootstrap table striped: How do I change the stripe background colour?

You have two options, either you override the styles with a custom stylesheet, or you edit the main bootstrap css file. I prefer the former.

Your custom styles should be linked after bootstrap.

<link rel="stylesheet" src="bootstrap.css">
<link rel="stylesheet" src="custom.css">

In custom.css

.table-striped>tr:nth-child(odd){
   background-color:red;
}

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static {
        Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
    }

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);
    }

    private int id;
    private String description;

    private Example(int id, String description) {
        this.id = id;
        this.description= description;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }
}

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);
}

Open Google Chrome from VBA/Excel

You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com

ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.

I hope this helps with the dynamic website you have got.

Sub multiplechrome()

    Dim WebUrl As String
    Dim i As Integer

    For i = 1 To ActiveSheet.Cells(1, 2).Value
        WebUrl = "http://" & Cells(i, 1).Value & """"
        Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)

    Next
End Sub

Reactjs convert html string to jsx

i start using npm package called react-html-parser

Change button text from Xcode?

[myButton setTitle:@"Play" forState:UIControlStateNormal];

Calculating percentile of dataset column

The quantile() function will do much of what you probably want, but since the question was ambiguous, I will provide an alternate answer that does something slightly different from quantile().

ecdf(infert$age)(infert$age)

will generate a vector of the same length as infert$age giving the proportion of infert$age that is below each observation. You can read the ecdf documentation, but the basic idea is that ecdf() will give you a function that returns the empirical cumulative distribution. Thus ecdf(X)(Y) is the value of the cumulative distribution of X at the points in Y. If you wanted to know just the probability of being below 30 (thus what percentile 30 is in the sample), you could say

ecdf(infert$age)(30)

The main difference between this approach and using the quantile() function is that quantile() requires that you put in the probabilities to get out the levels, and this requires that you put in the levels to get out the probabilities.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

Method 1: Download ojdbc.jar

add ojdbc6.jar to deployment assembly. Right click on project->properties->select deployment assembly->click on 'Add' ->select 'Archives from File System'->browse to the folder where ojdbc6.jar is saved.->add the jar->click finish->Apply/OK.

Method 2:

if you want to add ojdbc.jar to your maven dependencies you follow this link: http://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/ . . Even if you're using a maven project it is not necessary to add ojdbc to maven dependencies(method 2), method 1 (adding directly to deployment assembly) works just fine.

How do I pipe a subprocess call to a text file?

The options for popen can be used in call

args, 
bufsize=0, 
executable=None, 
stdin=None, 
stdout=None, 
stderr=None, 
preexec_fn=None, 
close_fds=False, 
shell=False, 
cwd=None, 
env=None, 
universal_newlines=False, 
startupinfo=None, 
creationflags=0

So...

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)

Then you can do what you want with myoutput (which would need to be a file btw).

Also, you can do something closer to a piped output like this.

dmesg | grep hda

would be:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

There's plenty of lovely, useful info on the python manual page.

Is jQuery $.browser Deprecated?

"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."

From http://api.jquery.com/jQuery.browser/

C: scanf to array

The %d conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.

There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:

if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
  printf("got four numbers\n");

Note that this requires whitespace between the input numbers.

If the id is a single 11-digit number, it's best to treat as a string:

char id[12];

if(scanf("%11s", id) == 1)
{
  /* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}

How to access URL segment(s) in blade in Laravel 5?

An easy way to get the first or last segment, in case you are unsure of the path length.

$segments = request()->segments();
$last  = end($segments);
$first = reset($segments);

How can I convert a .py to .exe for Python?

Steps to convert .py to .exe in Python 3.6

  1. Install Python 3.6.
  2. Install cx_Freeze, (open your command prompt and type pip install cx_Freeze.
  3. Install idna, (open your command prompt and type pip install idna.
  4. Write a .py program named myfirstprog.py.
  5. Create a new python file named setup.py on the current directory of your script.
  6. In the setup.py file, copy the code below and save it.
  7. With shift pressed right click on the same directory, so you are able to open a command prompt window.
  8. In the prompt, type python setup.py build
  9. If your script is error free, then there will be no problem on creating application.
  10. Check the newly created folder build. It has another folder in it. Within that folder you can find your application. Run it. Make yourself happy.

See the original script in my blog.

setup.py:

from cx_Freeze import setup, Executable

base = None    

executables = [Executable("myfirstprog.py", base=base)]

packages = ["idna"]
options = {
    'build_exe': {    
        'packages':packages,
    },    
}

setup(
    name = "<any name>",
    options = options,
    version = "<any number>",
    description = '<any description>',
    executables = executables
)

EDIT:

  • be sure that instead of myfirstprog.py you should put your .pyextension file name as created in step 4;
  • you should include each imported package in your .py into packages list (ex: packages = ["idna", "os","sys"])
  • any name, any number, any description in setup.py file should not remain the same, you should change it accordingly (ex:name = "<first_ever>", version = "0.11", description = '' )
  • the imported packages must be installed before you start step 8.

Disable F5 and browser refresh using JavaScript

for mac cmd+r, cmd+shift+r to need.

function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };

$(document).ready(function(){
$(document).on("keydown", disableF5);
});

CSS: image link, change on hover

The problem with changing it via JavaScript or CSS is that if you have a slower connection, the image will take a second to change to the hovered version. This will cause an undesirable flash as one disappears while the other downloads.

What I've done before is have two images. Then hide and show each depending on the hover state. This will allow for a clean switch between the two images.

<a href="/settings">
    <img class="default" src="settings-default.svg"/>
    <img class="hover" src="settings-hover.svg"/>
    <span>Settings</span>
</a>

a img.hover {
    display: none;
}
a img.default {
    display: inherit;
}
a:hover img.hover {
    display: inherit;
}
a:hover img.default {
    display: none;
}

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

REASON

This happens because for now they only ship 64bit JRE with Android Studio for Windows which produces glitches in 32 bit systems.

SOLUTION

  • do not use the embedded JDK: Go to File -> Project Structure dialog, uncheck "Use embedded JDK" and select the 32-bit JRE you've installed separately in your system
  • decrease the memory footprint for Gradle in gradle.properties(Project Properties), for eg set it to -Xmx768m.

For more details: https://code.google.com/p/android/issues/detail?id=219524

Most efficient way to find smallest of 3 numbers Java?

OP's efficient code has a bug:

when a == b, and a (or b) < c, the code will pick c instead of a or b.

How to parse XML using jQuery?

$xml = $( $.parseXML( xml ) );

$xml.find("<<your_xml_tag_name>>").each(function(index,elem){
    // elem = found XML element
});

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

Using Java with Microsoft Visual Studio 2012

If you're proficient in C# and Visual Studio, you might try IKVM. It's not exactly what you were asking for, but will certainly help with bridging the gap by allowing you to call into Java libraries from C# and vise versa. You can use it in Visual Studio, but it also has first class support in MonoDevelop.

Changing image size in Markdown

One might draw on the alt attribute that can be set in almost all Markdown implementations/renderes together with CSS-selectors based on attribute values. The advantage is that one can easily define a whole set of different picture sizes (and further attributes).

Markdown:

![minipic](mypic.jpg)

CSS:

img[alt="minipic"] { 
  max-width:  20px; 
  display: block;
}

How to resolve this System.IO.FileNotFoundException

Check all the references carefully

  • Version remains same on target machine and local machine
  • If assembly is referenced from GAC, ensure that proper version is loaded

For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.

Is it possible to forward-declare a function in Python?

Yes, we can check this.

Input

print_lyrics() 
def print_lyrics():

    print("I'm a lumberjack, and I'm okay.")
    print("I sleep all night and I work all day.")

def repeat_lyrics():
    print_lyrics()
    print_lyrics()
repeat_lyrics()

Output

I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.

As BJ Homer mentioned over above comments, A general rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.

Hope that helps.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Disable time zone. Use challenge.datetime_start.replace(tzinfo=None);

You can also use replace(tzinfo=None) for other datetime.

if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

Implementing two interfaces in a class with same method. Which interface method is overridden?

As in interface,we are just declaring methods,concrete class which implements these both interfaces understands is that there is only one method(as you described both have same name in return type). so there should not be an issue with it.You will be able to define that method in concrete class.

But when two interface have a method with the same name but different return type and you implement two methods in concrete class:

Please look at below code:

public interface InterfaceA {
  public void print();
}


public interface InterfaceB {
  public int print();
}

public class ClassAB implements InterfaceA, InterfaceB {
  public void print()
  {
    System.out.println("Inside InterfaceA");
  }
  public int print()
  {
    System.out.println("Inside InterfaceB");
    return 5;
  }
}

when compiler gets method "public void print()" it first looks in InterfaceA and it gets it.But still it gives compile time error that return type is not compatible with method of InterfaceB.

So it goes haywire for compiler.

In this way, you will not be able to implement two interface having a method of same name but different return type.

Where do I put image files, css, js, etc. in Codeigniter?

No one says that you need to modify the .htacces and add the directory in the rewrite condition. I've created a directory "public" in the root directory alongside with "system", "application", "index.php". and edited the .htaccess file like this:

RewriteCond $1 !^(index\.php|public|robots\.txt)

Now you have to just call <?php echo base_url()."/public/yourdirectory/yuorfile";?> You can add subdirectory inside "public" dir as you like.

Get string character by index - Java

CodePointAt instead of charAt is safer to use. charAt may break when there are emojis in the strtng.

How can I do an asc and desc sort using underscore.js?

Underscore Mixins

Extending on @emil_lundberg's answer, you can also write a "mixin" if you're using Underscore to make a custom function for sorting if it's a kind of sorting you might repeat in an application somewhere.

For example, maybe you have a controller or view sorting results with sort order of "ASC" or "DESC", and you want to toggle between that sort, you could do something like this:

Mixin.js

_.mixin({
    sortByOrder: function(stooges, prop, order) {
      if (String(order) === "desc") {
          return _.sortBy(stooges, prop).reverse();
      } else if (String(order) === "asc") {
          return _.sortBy(stooges, prop);
      } else {
          return stooges;
      }
    }
})

Usage Example

var sort_order = "asc";
var stooges = [
  {name: 'moe', age: 40}, 
  {name: 'larry', age: 50}, 
  {name: 'curly', age: 60},
  {name: 'July', age: 35},
  {name: 'mel', age: 38}
 ];

_.mixin({
    sortByOrder: function(stooges, prop, order) {
    if (String(order) === "desc") {
        return _.sortBy(stooges, prop).reverse();
    } else if (String(order) === "asc") {
        return _.sortBy(stooges, prop);
    } else {
        return stooges;
    }
  }
})


// find elements
var banner = $("#banner-message");
var sort_name_btn = $("button.sort-name");
var sort_age_btn = $("button.sort-age");

function showSortedResults(results, sort_order, prop) {
    banner.empty();
    banner.append("<p>Sorting: " + prop + ', ' + sort_order + "</p><hr>")
  _.each(results, function(r) {
    banner.append('<li>' + r.name + ' is '+ r.age + ' years old.</li>');
  }) 
}

// handle click and add class
sort_name_btn.on("click", function() {
  sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'name', sort_order);
  showSortedResults(sortedResults, sort_order, 'name');
})

sort_age_btn.on('click', function() {
    sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'age', sort_order);
  showSortedResults(sortedResults, sort_order, 'age');
})

Here's a JSFiddle demonstrating this: JSFiddle for SortBy Mixin

Launch Image does not show up in my iOS App

The problem with the accepted answer is that if you don't set the Launch Screen File, your application will be in upscaling mode on devices such as the iPhone 6 & 6+ => blurry rendering.

Below is what I did to have a complete working solution (I'm targeting iOS 7.1 & using Xcode 8) on every device (truly, I was getting crazy about this upscaling problem)

1. Prepare your .xcassets

To simplify it, I'm using a vector .PDF file. It is very convenient and avoid creating multiple images for each resolution (1x, 2x, 3x...). I also assume here you already created your xcassets.

  • Add your launch screen image (or vector file) to your project
  • Go to your .xcassets and create a New Image Set. In the Attributes window of the Image, select Scales -> Single Scale
  • Drag and drop the vector file in the Image Set.

Create an Image Set for your .xcassets

2. Create your Launch Screen file

Create a Launch Screen file

3. Add your image to your Launch Screen file

  • Add an Image View object to your Launch Screen file (delete the labels that were automatically created). This image view should refer to the previous .xcassets Image Set. You can refer it from the Name attribute. At this stage, you should correctly see your launch screen image in your image view.
  • Add constraints to this image view to keep aspect ratio depending on the screen resolution.

Add the splash screen image to your Launch Screen file

4. Add your Launch Screen file to your target

Fianlly, in your Target General properties, refer the Launch Screen file. Target Properties and Launch Screen

Start your app, and your splash screen should be displayed. Try also on iPhone6 & iPhone6+, and your application should be correctly displayed without any upscaling (the Launch Screen file aims to do this).

How to add include and lib paths to configure/make cycle?

This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf

Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.

After successfully running autogen.sh/configure, compile with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make

The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.

I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.

Android studio - Failed to find target android-18

Target with hash string 'android-18' is corresponding to the SDK level 18. You need to install SDK 18 from SDK manager.

Detect a finger swipe through JavaScript on the iPhone and Android

what i've used before is you have to detect the mousedown event, record its x,y location (whichever is relevant) then detect the mouseup event, and subtract the two values.

open a url on click of ok button in android

On Button click event write this:

Uri uri = Uri.parse("http://www.google.com"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

that open the your URL.

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

Concat strings by & and + in VB.Net

& and + are both concatenation operators but when you specify an integer while using +, vb.net tries to cast "Hello" into integer to do an addition. If you change "Hello" with "123", you will get the result 124.

Delete files or folder recursively on Windows CMD

Please execute the following steps:

  1. Open the command prompt
  2. Change directory to the required path
  3. Give the following command

    del /S *.svn
    

Adding a parameter to the URL with JavaScript

I like the answer of Mehmet Fatih Yildiz even he did not answer the whole question.

In the same line as his answer, I use this code:

"Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to the end"

  /** add a parameter at the end of the URL. Manage '?'/'&', but not the existing parameters.
   *  does escape the value (but not the key)
   */
  function addParameterToURL(_url,_key,_value){
      var param = _key+'='+escape(_value);

      var sep = '&';
      if (_url.indexOf('?') < 0) {
        sep = '?';
      } else {
        var lastChar=_url.slice(-1);
        if (lastChar == '&') sep='';
        if (lastChar == '?') sep='';
      }
      _url += sep + param;

      return _url;
  }

and the tester:

  /*
  function addParameterToURL_TESTER_sub(_url,key,value){
    //log(_url);
    log(addParameterToURL(_url,key,value));
  }

  function addParameterToURL_TESTER(){
    log('-------------------');
    var _url ='www.google.com';
    addParameterToURL_TESTER_sub(_url,'key','value');
    addParameterToURL_TESTER_sub(_url,'key','Text Value');
    _url ='www.google.com?';
    addParameterToURL_TESTER_sub(_url,'key','value');
    _url ='www.google.com?A=B';
    addParameterToURL_TESTER_sub(_url,'key','value');
    _url ='www.google.com?A=B&';
    addParameterToURL_TESTER_sub(_url,'key','value');
    _url ='www.google.com?A=1&B=2';
    addParameterToURL_TESTER_sub(_url,'key','value');

  }//*/

How do I make a textbox that only accepts numbers?

And just because it's always more fun to do stuff in one line...

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
    }

NOTE: This DOES NOT prevent a user from Copy / Paste into this textbox. It's not a fail safe way to sanitize your data.

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

Just coerce the StatusCode to int.

var statusNumber;
try {
   response = (HttpWebResponse)request.GetResponse();
   // This will have statii from 200 to 30x
   statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
    // Statii 400 to 50x will be here
    statusNumber = (int)we.Response.StatusCode;
}

adb doesn't show nexus 5 device

The communication with the emulator or your Android device might have problems. This communication is handled by the Android Debug Bridge (adb).

Eclipse allows you to reset the adb in case this causes problems. Select therefore the DDMS perspective via Window ? Open Perspective ? Other... ? DDMS

To restart the adb, select the "Reset adb" in the Device View.

Testing the type of a DOM element in JavaScript

roenving is correct BUT you need to change the test to:

if(element.nodeType == 1) {
//code
}

because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp

How to select the first row for each group in MySQL?

Yet another way to do it

Select max from group that works in views

SELECT * FROM action a 
WHERE NOT EXISTS (
   SELECT 1 FROM action a2 
   WHERE a2.user_id = a.user_id 
   AND a2.action_date > a.action_date 
   AND a2.action_type = a.action_type
)
AND a.action_type = "CF"

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

Populate nested array in mongoose

For someone who has the problem with populate and also wants to do this:

  • chat with simple text & quick replies (bubbles)
  • 4 database collections for chat: clients, users, rooms, messasges.
  • same message DB structure for 3 types of senders: bot, users & clients
  • refPath or dynamic reference
  • populate with path and model options
  • use findOneAndReplace/replaceOne with $exists
  • create a new document if the fetched document doesn't exist

CONTEXT

Goal

  1. Save a new simple text message to the database & populate it with the user or client data (2 different models).
  2. Save a new quickReplies message to the database and populate it with the user or client data.
  3. Save each message its sender type: clients, users & bot.
  4. Populate only the messages who have the sender clients or users with its Mongoose Models. _sender type client models is clients, for user is users.

Message schema:

const messageSchema = new Schema({
    room: {
        type: Schema.Types.ObjectId,
        ref: 'rooms',
        required: [true, `Room's id`]
    },
    sender: {
         _id: { type: Schema.Types.Mixed },
        type: {
            type: String,
            enum: ['clients', 'users', 'bot'],
            required: [true, 'Only 3 options: clients, users or bot.']
        }
    },
    timetoken: {
        type: String,
        required: [true, 'It has to be a Nanosecond-precision UTC string']
    },
    data: {
        lang: String,
        // Format samples on https://docs.chatfuel.com/api/json-api/json-api
        type: {
            text: String,
            quickReplies: [
                {
                    text: String,
                    // Blocks' ids.
                    goToBlocks: [String]
                }
            ]
        }
    }

mongoose.model('messages', messageSchema);

SOLUTION

My server side API request

My code

Utility function (on chatUtils.js file) to get the type of message that you want to save:

/**
 * We filter what type of message is.
 *
 * @param {Object} message
 * @returns {string} The type of message.
 */
const getMessageType = message => {
    const { type } = message.data;
    const text = 'text',
        quickReplies = 'quickReplies';

    if (type.hasOwnProperty(text)) return text;
    else if (type.hasOwnProperty(quickReplies)) return quickReplies;
};

/**
 * Get the Mongoose's Model of the message's sender. We use
 * the sender type to find the Model.
 *
 * @param {Object} message - The message contains the sender type.
 */
const getSenderModel = message => {
    switch (message.sender.type) {
        case 'clients':
            return 'clients';
        case 'users':
            return 'users';
        default:
            return null;
    }
};

module.exports = {
    getMessageType,
    getSenderModel
};

My server side (using Nodejs) to get the request of saving the message:

app.post('/api/rooms/:roomId/messages/new', async (req, res) => {
        const { roomId } = req.params;
        const { sender, timetoken, data } = req.body;
        const { uuid, state } = sender;
        const { type } = state;
        const { lang } = data;

        // For more info about message structure, look up Message Schema.
        let message = {
            room: new ObjectId(roomId),
            sender: {
                _id: type === 'bot' ? null : new ObjectId(uuid),
                type
            },
            timetoken,
            data: {
                lang,
                type: {}
            }
        };

        // ==========================================
        //          CONVERT THE MESSAGE
        // ==========================================
        // Convert the request to be able to save on the database.
        switch (getMessageType(req.body)) {
            case 'text':
                message.data.type.text = data.type.text;
                break;
            case 'quickReplies':
                // Save every quick reply from quickReplies[].
                message.data.type.quickReplies = _.map(
                    data.type.quickReplies,
                    quickReply => {
                        const { text, goToBlocks } = quickReply;

                        return {
                            text,
                            goToBlocks
                        };
                    }
                );
                break;
            default:
                break;
        }

        // ==========================================
        //           SAVE THE MESSAGE
        // ==========================================
        /**
         * We save the message on 2 ways:
         * - we replace the message type `quickReplies` (if it already exists on database) with the new one.
         * - else, we save the new message.
         */
        try {
            const options = {
                // If the quickRepy message is found, we replace the whole document.
                overwrite: true,
                // If the quickRepy message isn't found, we create it.
                upsert: true,
                // Update validators validate the update operation against the model's schema.
                runValidators: true,
                // Return the document already updated.
                new: true
            };

            Message.findOneAndUpdate(
                { room: roomId, 'data.type.quickReplies': { $exists: true } },
                message,
                options,
                async (err, newMessage) => {
                    if (err) {
                        throw Error(err);
                    }

                    // Populate the new message already saved on the database.
                    Message.populate(
                        newMessage,
                        {
                            path: 'sender._id',
                            model: getSenderModel(newMessage)
                        },
                        (err, populatedMessage) => {
                            if (err) {
                                throw Error(err);
                            }

                            res.send(populatedMessage);
                        }
                    );
                }
            );
        } catch (err) {
            logger.error(
                `#API Error on saving a new message on the database of roomId=${roomId}. ${err}`,
                { message: req.body }
            );

            // Bad Request
            res.status(400).send(false);
        }
    });

TIPs:

For the database:

  • Every message is a document itself.
  • Instead of using refPath, we use the util getSenderModel that is used on populate(). This is because of the bot. The sender.type can be: users with his database, clients with his database and bot without a database. The refPath needs true Model reference, if not, Mongooose throw an error.
  • sender._id can be type ObjectId for users and clients, or null for the bot.

For API request logic:

  • We replace the quickReply message (Message DB has to have only one quickReply, but as many simple text messages as you want). We use the findOneAndUpdate instead of replaceOne or findOneAndReplace.
  • We execute the query operation (the findOneAndUpdate) and the populate operation with the callback of each one. This is important if you don't know if use async/await, then(), exec() or callback(err, document). For more info look the Populate Doc.
  • We replace the quick reply message with the overwrite option and without $set query operator.
  • If we don't find the quick reply, we create a new one. You have to tell to Mongoose this with upsert option.
  • We populate only one time, for the replaced message or the new saved message.
  • We return to callbacks, whatever is the message we've saved with findOneAndUpdate and for the populate().
  • In populate, we create a custom dynamic Model reference with the getSenderModel. We can use the Mongoose dynamic reference because the sender.type for bot hasn't any Mongoose Model. We use a Populating Across Database with model and path optins.

I've spend a lot of hours solving little problems here and there and I hope this will help someone!

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

What is the most efficient string concatenation method in python?

For a small set of short strings (i.e. 2 or 3 strings of no more than a few characters), plus is still way faster. Using mkoistinen's wonderful script in Python 2 and 3:

plus 2.679107467004 (100.00% as fast)
join 3.653773699996 (73.32% as fast)
form 6.594011374000 (40.63% as fast)
intp 4.568015249999 (58.65% as fast)

So when your code is doing a huge number of separate small concatenations, plus is the preferred way if speed is crucial.

Scanner is skipping nextLine() after using next() or nextFoo()?

The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.

Try it like that:

System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();

Are multi-line strings allowed in JSON?

Write property value as a array of strings. Like example given over here https://gun.io/blog/multi-line-strings-in-json/. This will help.

We can always use array of strings for multiline strings like following.

{
    "singleLine": "Some singleline String",
    "multiline": ["Line one", "line Two", "Line Three"]
} 

And we can easily iterate array to display content in multi line fashion.

How do I find an element that contains specific text in Selenium WebDriver (Python)?

In the HTML which you have provided:

<div>My Button</div>

The text My Button is the innerHTML and have no whitespaces around it so you can easily use text() as follows:

my_element = driver.find_element_by_xpath("//div[text()='My Button']")

Note: text() selects all text node children of the context node


Text with leading/trailing spaces

In case the relevant text containing whitespaces either in the beginning:

<div>   My Button</div>

or at the end:

<div>My Button   </div>

or at both the ends:

<div> My Button </div>

In these cases you have two options:

  • You can use contains() function which determines whether the first argument string contains the second argument string and returns boolean true or false as follows:

      my_element = driver.find_element_by_xpath("//div[contains(., 'My Button')]")
    
  • You can use normalize-space() function which strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string as follows:

      driver.find_element_by_xpath("//div[normalize-space()='My Button']]")
    

XPath expression for variable text

In case the text is a variable, you can use:

foo= "foo_bar"
my_element = driver.find_element_by_xpath("//div[.='" + foo + "']")

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

Model Binding to a List MVC 4

This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.

ViewModel looks like this:

public class MyViewModel
{
   public List<Person> Persons{get;set;}
}

View(with BeginForm of course):

@model MyViewModel


@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    @Html.HiddenFor(m => m.Persons[i].PersonId)
    @Html.EditorFor(m => m.Persons[i].FirstName) 
    @Html.EditorFor(m => m.Persons[i].LastName)         
}

Action:

[HttpPost]public ViewResult(MyViewModel vm)
{
...

Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.

Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:

@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    if(i != 4)//conditionally hide 5th item, 
    { //but BUG occurs on postback, all items after 5th will not be bound to the the list
      @Html.HiddenFor(m => m.Persons[i].PersonId)
      @Html.EditorFor(m => m.Persons[i].FirstName) 
      @Html.EditorFor(m => m.Persons[i].LastName)           
    }
}

MsgBox "" vs MsgBox() in VBScript

A callable piece of code (routine) can be a Sub (called for a side effect/what it does) or a Function (called for its return value) or a mixture of both. As the docs for MsgBox

Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

MsgBox(prompt[, buttons][, title][, helpfile, context])

indicate, this routine is of the third kind.

The syntactical rules of VBScript are simple:

Use parameter list () when calling a (routine as a) Function

If you want to display a message to the user and need to know the user's reponse:

Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
   ' MyVar contains either 1 or 2, depending on which button is clicked.

Don't use parameter list () when calling a (routine as a) Sub

If you want to display a message to the user and are not interested in the response:

MsgBox "Hello World!", 65, "MsgBox Example"

This beautiful simplicity is messed up by:

The design flaw of using () for parameter lists and to force call-by-value semantics

>> Sub S(n) : n = n + 1 : End Sub
>> n = 1
>> S n
>> WScript.Echo n
>> S (n)
>> WScript.Echo n
>>
2
2

S (n) does not mean "call S with n", but "call S with a copy of n's value". Programmers seeing that

>> s = "value"
>> MsgBox(s)

'works' are in for a suprise when they try:

>> MsgBox(s, 65, "MsgBox Example")
>>
Error Number:       1044
Error Description:  Cannot use parentheses when calling a Sub

The compiler's leniency with regard to empty () in a Sub call. The 'pure' Sub Randomize (called for the side effect of setting the random seed) can be called by

Randomize()

although the () can neither mean "give me your return value) nor "pass something by value". A bit more strictness here would force prgrammers to be aware of the difference in

Randomize n

and

Randomize (n)

The Call statement that allows parameter list () in Sub calls:

s = "value" Call MsgBox(s, 65, "MsgBox Example")

which further encourage programmers to use () without thinking.

(Based on What do you mean "cannot use parentheses?")

Calculate age based on date of birth

To Calculate age from Date of birth used used query like this.

'SELECT username, email, skype, avatar, TIMESTAMPDIFF(YEAR, date, CURDATE()) AS age, signup_date, gender FROM users WHERE id="'.$id.'"';


if(isset($_GET['id']))
{
    $id = intval($_GET['id']);

    $dn = mysql_query('select username, email, skype, avatar, TIMESTAMPDIFF(YEAR, date, CURDATE()) AS age, signup_date, gender from users where id="'.$id.'"');

    $dnn = mysql_fetch_array($dn);

    echo $dnn['age'];
}

Note: don't use reserved keywords column name.

How to set app icon for Electron / Atom Shell App

Setting the icon property when creating the BrowserWindow only has an effect on Windows and Linux.

To set the icon on OS X, you can use electron-packager and set the icon using the --icon switch.

It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.

Breaking to a new line with inline-block?

You can try with:

    display: inline-table;

For me it works fine.

Trigger change event of dropdown

Try this:

$('#id').change();

Works for me.

On one line together with setting the value: $('#id').val(16).change();

segmentation fault : 11

What system are you running on? Do you have access to some sort of debugger (gdb, visual studio's debugger, etc.)?

That would give us valuable information, like the line of code where the program crashes... Also, the amount of memory may be prohibitive.

Additionally, may I recommend that you replace the numeric limits by named definitions?

As such:

#define DIM1_SZ 1000
#define DIM2_SZ 1000000

Use those whenever you wish to refer to the array dimension limits. It will help avoid typing errors.

How to check if two arrays are equal with JavaScript?

jQuery has such method for deep recursive comparison.

A homegrown general purpose strict equality check could look as follows:

function deepEquals(obj1, obj2, parents1, parents2) {
    "use strict";
    var i;
    // compare null and undefined
    if (obj1 === undefined || obj2 === undefined || 
        obj1 === null || obj2 === null) {
        return obj1 === obj2;
    }

    // compare primitives
    if (typeof (obj1) !== 'object' || typeof (obj2) !== 'object') {
        return obj1.valueOf() === obj2.valueOf();
    }

    // if objects are of different types or lengths they can't be equal
    if (obj1.constructor !== obj2.constructor || (obj1.length !== undefined && obj1.length !== obj2.length)) {
        return false;
    }

    // iterate the objects
    for (i in obj1) {
        // build the parents list for object on the left (obj1)
        if (parents1 === undefined) parents1 = [];
        if (obj1.constructor === Object) parents1.push(obj1);
        // build the parents list for object on the right (obj2)
        if (parents2 === undefined) parents2 = [];
        if (obj2.constructor === Object) parents2.push(obj2);
        // walk through object properties
        if (obj1.propertyIsEnumerable(i)) {
            if (obj2.propertyIsEnumerable(i)) {
                // if object at i was met while going down here
                // it's a self reference
                if ((obj1[i].constructor === Object && parents1.indexOf(obj1[i]) >= 0) || (obj2[i].constructor === Object && parents2.indexOf(obj2[i]) >= 0)) {
                    if (obj1[i] !== obj2[i]) {
                        return false;
                    }
                    continue;
                }
                // it's not a self reference so we are here
                if (!deepEquals(obj1[i], obj2[i], parents1, parents2)) {
                    return false;
                }
            } else {
                // obj2[i] does not exist
                return false;
            }
        }
    }
    return true;
};

Tests:

// message is displayed on failure
// clean console === all tests passed
function assertTrue(cond, msg) {
    if (!cond) {
        console.log(msg);
    }
}

var a = 'sdf',
    b = 'sdf';
assertTrue(deepEquals(b, a), 'Strings are equal.');
b = 'dfs';
assertTrue(!deepEquals(b, a), 'Strings are not equal.');
a = 9;
b = 9;
assertTrue(deepEquals(b, a), 'Numbers are equal.');
b = 3;
assertTrue(!deepEquals(b, a), 'Numbers are not equal.');
a = false;
b = false;
assertTrue(deepEquals(b, a), 'Booleans are equal.');
b = true;
assertTrue(!deepEquals(b, a), 'Booleans are not equal.');
a = null;
assertTrue(!deepEquals(b, a), 'Boolean is not equal to null.');
a = function () {
    return true;
};
assertTrue(deepEquals(
[
    [1, 1, 1],
    [2, 'asdf', [1, a]],
    [3, {
        'a': 1.0
    },
    true]
], 
[
    [1, 1, 1],
    [2, 'asdf', [1, a]],
    [3, {
        'a': 1.0
    },
    true]
]), 'Arrays are equal.');
assertTrue(!deepEquals(
[
    [1, 1, 1],
    [2, 'asdf', [1, a]],
    [3, {
        'a': 1.0
    },
    true]
],
[
    [1, 1, 1],
    [2, 'asdf', [1, a]],
    [3, {
        'a': '1'
    },
    true]
]), 'Arrays are not equal.');
a = {
    prop: 'val'
};
a.self = a;
b = {
    prop: 'val'
};
b.self = a;
assertTrue(deepEquals(b, a), 'Immediate self referencing objects are equal.');
a.prop = 'shmal';
assertTrue(!deepEquals(b, a), 'Immediate self referencing objects are not equal.');
a = {
    prop: 'val',
    inside: {}
};
a.inside.self = a;
b = {
    prop: 'val',
    inside: {}
};
b.inside.self = a;
assertTrue(deepEquals(b, a), 'Deep self referencing objects are equal.');
b.inside.self = b;
assertTrue(!deepEquals(b, a), 'Deep self referencing objects are not equeal. Not the same instance.');
b.inside.self = {foo: 'bar'};
assertTrue(!deepEquals(b, a), 'Deep self referencing objects are not equal. Completely different object.');
a = {};
b = {};
a.self = a;
b.self = {};
assertTrue(!deepEquals(b, a), 'Empty object and self reference of an empty object.');

How do you set up use HttpOnly cookies in PHP

<?php
//None HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, FALSE); 

//HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE); 

?>

Source

How do you know if Tomcat Server is installed on your PC

The port 8005 is used as service port. You can send a shutdown command (a configurable password) to that port. It will not "speak" HTTP, so you cannot use your browser to connect.

The default port for delivering web-content is 8080.

But there may be other applications listen to that port. So your tomcat may not start, if the port is not available.

You asked "How do you know, if tomcat server is installed on your PC?". The answer to that question is: You can't

You can't determine, if it is installed, because it may be only extracted from a ZIP archive or packaged within another application (Like JBoss AS (I think)).

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

How to set page content to the middle of screen?

I'm guessing you want to center the box both vertically and horizontally, regardless of browser window size. Since you have a fixed width and height for the box, this should work:

Markup:

<div></div>

CSS:

div {
    height: 200px;
    width: 400px;
    background: black;

    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -200px;
}

The div should remain in the center of the screen even if you resize the browser. Just replace the margin-top and margin-left with half of the height and width of your table.

Edit: Credit goes to CSS-Tricks, where I got the original idea.

Why is there no String.Empty in Java?

Seems like this is the obvious answer:

String empty = org.apache.commons.lang.StringUtils.EMPTY;

Awesome because "empty initialization" code no longer has a "magic string" and uses a constant.

git returns http error 407 from proxy after CONNECT

I had faced similar issue, behind corporate firewall. Did the following, and able to clone repository using git shell from my system running Windows 7 SP1.

  1. Set 'all_proxy' environment variable for your user. Required by curl.

    export all_proxy=http://DOMAIN\proxyuser:[email protected]:8080
    
  2. Set 'https_proxy' environment variable for your user. Required by curl.

    export https_proxy=http://DOMAIN\proxyuser:[email protected]:8080
    
  3. I am not sure if this has any impact. But I did this and it worked:

    git config --global http.sslverify false
    
  4. Use https:// for cloning

    git clone https://github.com/project/project.git
    

Note-1: Do not use http://. Using that can give the below error. It can be resolved by using https://.

 error: RPC failed; result=56, HTTP code = 301

Note-2: Avoid having @ in your password. Can use $ though.

How do I import a Swift file from another Swift file?

UPDATE Swift 2.x, 3.x, 4.x and 5.x

Now you don't need to add the public to the methods to test then. On newer versions of Swift it's only necessary to add the @testable keyword.

PrimeNumberModelTests.swift

import XCTest
@testable import MyProject

class PrimeNumberModelTests: XCTestCase {
    let testObject = PrimeNumberModel()
}

And your internal methods can keep Internal

PrimeNumberModel.swift

import Foundation

class PrimeNumberModel {
   init() {
   }
}

Note that private (and fileprivate) symbols are not available even with using @testable.


Swift 1.x

There are two relevant concepts from Swift here (As Xcode 6 beta 6).

  1. You don't need to import Swift classes, but you need to import external modules (targets)
  2. The Default Access Control level in Swift is Internal access

Considering that tests are on another target on PrimeNumberModelTests.swift you need to import the target that contains the class that you want to test, if your target is called MyProject will need to add import MyProject to the PrimeNumberModelTests:

PrimeNumberModelTests.swift

import XCTest
import MyProject

class PrimeNumberModelTests: XCTestCase {
    let testObject = PrimeNumberModel()
}

But this is not enough to test your class PrimeNumberModel, since the default Access Control level is Internal Access, your class won't be visible to the test bundle, so you need to make it Public Access and all the methods that you want to test:

PrimeNumberModel.swift

import Foundation

public class PrimeNumberModel {
   public init() {
   }
}

Cannot connect to MySQL 4.1+ using old authentication

Had the same issue, but executing the queries alone will not help. To fix this I did the following,

  1. Set old_passwords=0 in my.cnf file
  2. Restart mysql
  3. Login to mysql as root user
  4. Execute FLUSH PRIVILEGES;

Do you (really) write exception safe code?

  • Do you really write exception safe code?

Well, I certainly intend to.

  • Are you sure your last "production ready" code is exception safe?

I'm sure that my 24/7 servers built using exceptions run 24/7 and don't leak memory.

  • Can you even be sure, that it is?

It's very difficult to be sure that any code is correct. Typically, one can only go by results

  • Do you know and/or actually use alternatives that work?

No. Using exceptions is cleaner and easier than any of the alternatives I've used over the last 30 years in programming.

Call a Class From another class

If your class2 looks like this having static members

public class2
{
    static int var = 1;

    public static void myMethod()
    {
      // some code

    }
}

Then you can simply call them like

class2.myMethod();
class2.var = 1;

If you want to access non-static members then you would have to instantiate an object.

class2 object = new class2();
object.myMethod();  // non static method
object.var = 1;     // non static variable

CSS background-image not working

1.Use this code in stylesheet

body {
  background: URL("slide_button.png");
  background-size: 100% 100%;
  background-repeat: no repeat;

2.Put img and html file together in single folder 3.IF not worked try converting png file to jpg for that just upload pic on facebook and then download that pic from facebook it will automatically converted into jpg and while uploading tick mark private setting so that ur friends cant view that image 4.if still not work imform me..

Is there an upper bound to BigInteger?

The number is held in an int[] - the maximum size of an array is Integer.MAX_VALUE. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE.

Admittedly, this is implementation dependent, not part of the specification.


In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

push_back vs emplace_back

In addition to what visitor said :

The function void emplace_back(Type&& _Val) provided by MSCV10 is non conforming and redundant, because as you noted it is strictly equivalent to push_back(Type&& _Val).

But the real C++0x form of emplace_back is really useful: void emplace_back(Args&&...);

Instead of taking a value_type it takes a variadic list of arguments, so that means that you can now perfectly forward the arguments and construct directly an object into a container without a temporary at all.

That's useful because no matter how much cleverness RVO and move semantic bring to the table there is still complicated cases where a push_back is likely to make unnecessary copies (or move). For example, with the traditional insert() function of a std::map, you have to create a temporary, which will then be copied into a std::pair<Key, Value>, which will then be copied into the map :

std::map<int, Complicated> m;
int anInt = 4;
double aDouble = 5.0;
std::string aString = "C++";

// cross your finger so that the optimizer is really good
m.insert(std::make_pair(4, Complicated(anInt, aDouble, aString))); 

// should be easier for the optimizer
m.emplace(4, anInt, aDouble, aString);

So why didn't they implement the right version of emplace_back in MSVC? Actually, it bugged me too a while ago, so I asked the same question on the Visual C++ blog. Here is the answer from Stephan T Lavavej, the official maintainer of the Visual C++ standard library implementation at Microsoft.

Q: Are beta 2 emplace functions just some kind of placeholder right now?

A: As you may know, variadic templates aren't implemented in VC10. We simulate them with preprocessor machinery for things like make_shared<T>(), tuple, and the new things in <functional>. This preprocessor machinery is relatively difficult to use and maintain. Also, it significantly affects compilation speed, as we have to repeatedly include subheaders. Due to a combination of our time constraints and compilation speed concerns, we haven't simulated variadic templates in our emplace functions.

When variadic templates are implemented in the compiler, you can expect that we'll take advantage of them in the libraries, including in our emplace functions. We take conformance very seriously, but unfortunately, we can't do everything all at once.

It's an understandable decision. Everyone who tried just once to emulate variadic template with preprocessor horrible tricks knows how disgusting this stuff gets.

How to customize listview using baseadapter

Create your own BaseAdapter class and use it as following.

 public class NotificationScreen extends Activity
{

@Override
protected void onCreate_Impl(Bundle savedInstanceState)
{
    setContentView(R.layout.notification_screen);

    ListView notificationList = (ListView) findViewById(R.id.notification_list);
    NotiFicationListAdapter notiFicationListAdapter = new NotiFicationListAdapter();
    notificationList.setAdapter(notiFicationListAdapter);

    homeButton = (Button) findViewById(R.id.home_button);

}

}

Make your own BaseAdapter class and its separate xml file.

public class NotiFicationListAdapter  extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;


public NotiFicationListAdapter(ArrayList data)
{
this.data=data;        
    inflater =(LayoutInflater)baseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}



public int getCount() 
{
 return data.size();
}



public Object getItem(int position) 
{
 return position;
}



public long getItemId(int position) 
{
    return position;
}



public View getView(int position, View convertView, ViewGroup parent) 
{
View vi=convertView;
    if(convertView==null)

    vi = inflater.inflate(R.layout.notification_list_item, null);

    ImageView compleatImageView=(ImageView)vi.findViewById(R.id.complet_image);
    TextView name = (TextView)vi.findViewById(R.id.game_name); // name
    TextView email_id = (TextView)vi.findViewById(R.id.e_mail_id); // email ID
    TextView notification_message = (TextView)vi.findViewById(R.id.notification_message); // notification message



    compleatImageView.setBackgroundResource(R.id.address_book);
    name.setText(data.getIndex(position));
    email_id.setText(data.getIndex(position));
    notification_message.setTextdata.getIndex(position));

    return vi;
}

  }

BaseAdapter xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="@drawable/list_view_frame"
android:gravity="center_vertical"
android:padding="5dp" >

<TextView
    android:id="@+id/game_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Game name"
    android:textColor="#FFFFFF"
    android:textSize="15dip"
    android:textStyle="bold"
    android:typeface="sans" />

<TextView
    android:id="@+id/e_mail_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_marginTop="1dip"
    android:text="E-Mail Id"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />

<TextView
    android:id="@+id/notification_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_toRightOf="@id/e_mail_id"
    android:paddingLeft="5dp"
    android:text="Notification message"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />



<ImageView
    android:id="@+id/complet_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="30dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/complete_tag"
    android:visibility="invisible" />

</RelativeLayout>

Change it accordingly and use.

How to check if a variable is set in Bash?

I always find the POSIX table in the other answer slow to grok, so here's my take on it:

   +----------------------+------------+-----------------------+-----------------------+
   |   if VARIABLE is:    |    set     |         empty         |        unset          |
   +----------------------+------------+-----------------------+-----------------------+
 - |  ${VARIABLE-default} | $VARIABLE  |          ""           |       "default"       |
 = |  ${VARIABLE=default} | $VARIABLE  |          ""           | $(VARIABLE="default") |
 ? |  ${VARIABLE?default} | $VARIABLE  |          ""           |       exit 127        |
 + |  ${VARIABLE+default} | "default"  |       "default"       |          ""           |
   +----------------------+------------+-----------------------+-----------------------+
:- | ${VARIABLE:-default} | $VARIABLE  |       "default"       |       "default"       |
:= | ${VARIABLE:=default} | $VARIABLE  | $(VARIABLE="default") | $(VARIABLE="default") |
:? | ${VARIABLE:?default} | $VARIABLE  |       exit 127        |       exit 127        |
:+ | ${VARIABLE:+default} | "default"  |          ""           |          ""           |
   +----------------------+------------+-----------------------+-----------------------+

Note that each group (with and without preceding colon) has the same set and unset cases, so the only thing that differs is how the empty cases are handled.

With the preceding colon, the empty and unset cases are identical, so I would use those where possible (i.e. use :=, not just =, because the empty case is inconsistent).

Headings:

  • set means VARIABLE is non-empty (VARIABLE="something")
  • empty means VARIABLE is empty/null (VARIABLE="")
  • unset means VARIABLE does not exist (unset VARIABLE)

Values:

  • $VARIABLE means the result is the original value of the variable.
  • "default" means the result was the replacement string provided.
  • "" means the result is null (an empty string).
  • exit 127 means the script stops executing with exit code 127.
  • $(VARIABLE="default") means the result is "default" and that VARIABLE (previously empty or unset) will also be set equal to "default".

What's the regular expression that matches a square bracket?

If you're looking to find both variations of the square brackets at the same time, you can use the following pattern which defines a range of either the [ sign or the ] sign: /[\[\]]/

View not attached to window manager crash

I got a way to reproduce this exception.

I use 2 AsyncTask. One do long task and another do short task. After short task complete, call finish(). When long task complete and call Dialog.dismiss(), it crashes.

Here's my sample code:

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate");

        new AsyncTask<Void, Void, Void>(){
            @Override
            protected void onPreExecute() {
                mProgressDialog = ProgressDialog.show(MainActivity.this, "", "plz wait...", true);
            }

            @Override
            protected Void doInBackground(Void... nothing) {
                try {
                    Log.d(TAG, "long thread doInBackground");
                    Thread.sleep(20000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                Log.d(TAG, "long thread onPostExecute");
                if (mProgressDialog != null && mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
                Log.d(TAG, "long thread onPostExecute call dismiss");
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    Log.d(TAG, "short thread doInBackground");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                Log.d(TAG, "short thread onPostExecute");
                finish();
                Log.d(TAG, "short thread onPostExecute call finish");
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }
}

You can try this and find out what is the best way to fix this issue. From my study, there are at least 4 ways to fix it:

  1. @erakitin's answer: call isFinishing() to check activity's state
  2. @Kapé's answer: set flag to check activity's state
  3. Use try/catch to handle it.
  4. Call AsyncTask.cancel(false) in onDestroy(). It will prevent the asynctask to execute onPostExecute() but execute onCancelled() instead.
    Note: onPostExecute() will still execute even you call AsyncTask.cancel(false) on older Android OS, like Android 2.X.X.

You can choose the best one for you.

Java synchronized method lock on object, or method?

This might not work as the boxing and autoboxing from Integer to int and viceversa is dependant on JVM and there is high possibility that two different numbers might get hashed to same address if they are between -128 and 127.

PreparedStatement setNull(..)

preparedStatement.setNull(index, java.sql.Types.NULL);

that should work for any type. Though in some cases failure happens on the server-side, like: for SQL:

COALESCE(?, CURRENT_TIMESTAMP)

Oracle 18XE fails with the wrong type: expected DATE, got STRING -- that is a perfectly valid failure;

Bottom line: it is good to know the type if you call .setNull()

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

From the documentation of SimpleDateFormat:

Letter     Date or Time Component     Presentation     Examples  
S          Millisecond                Number           978 

So it is milliseconds, or 1/1000th of a second. You just format it with on 6 digits, so you add 3 extra leading zeroes...

You can check it this way:

    Date d =new Date();
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(d));

Output:

2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.0132
2013-10-07 12:13:27.00132
2013-10-07 12:13:27.000132

(Ideone fiddle)

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

Renew Provisioning Profile

To renew the development profile before it expired, I finally found a way that works for me. I boldfaced the steps I had been missing before.

Go to the Apple provisioning portal, select "Provisioning". You'll get a list "Development Provisioning Profiles" where you'll see your soon to expire profile with the label "Managed by XCode". Click the "New Profile" button on top, select the type of profile you want and create it. Wait half a minute, refresh the home screen and when it shows the new profile as "Active", switch back to XCode, go to the Organizer, select "Provisioning profiles" under "Library" in left top column. Click "Refresh" at the bottom, log in (if it asks) and the new profile appears in the list after a short while.

Now, crucially, connect your device and drag your new profile to the "Provisioning Profiles" row under the connected device in the left column.

Finally, you can clean up the old profiles from your device if you feel like it.

Note: interestingly, it seems that simply marking and deleting your provisioning profile on the iOS Provisioning Portal site causes a new fresh Team Provisioning Profile to be created. So maybe that is all that is needed. I will try that next time to see if that is enough, if so you don't need to create a profile as I described above.

Tar error: Unexpected EOF in archive

In my case, I had started untar before the uploading of the tar file was complete.

Order a MySQL table by two columns

This maybe help somebody who is looking for the way to sort table by two columns, but in paralel way. This means to combine two sorts using aggregate sorting function. It's very useful when for example retrieving articles using fulltext search and also concerning the article publish date.

This is only example, but if you catch the idea you can find a lot of aggregate functions to use. You can even weight the columns to prefer one over second. The function of mine takes extremes from both sorts, thus the most valued rows are on the top.

Sorry if there exists simplier solutions to do this job, but I haven't found any.

SELECT
 `id`,
 `text`,
 `date`
 FROM
   (
   SELECT
     k.`id`,
     k.`text`,
     k.`date`,
     k.`match_order_id`,
     @row := @row + 1 as `date_order_id`
     FROM
     (
       SELECT
         t.`id`,
         t.`text`,
         t.`date`,
         @row := @row + 1 as `match_order_id`
         FROM
         (
           SELECT
             `art_id` AS `id`,
             `text`   AS `text`,
             `date`   AS `date`,
             MATCH (`text`) AGAINST (:string) AS `match`
             FROM int_art_fulltext
             WHERE MATCH (`text`) AGAINST (:string IN BOOLEAN MODE)
             LIMIT 0,101
         ) t,
         (
           SELECT @row := 0
         ) r
         ORDER BY `match` DESC
     ) k,
     (
       SELECT @row := 0
     ) l
     ORDER BY k.`date` DESC
   ) s
 ORDER BY (1/`match_order_id`+1/`date_order_id`) DESC

Can I run CUDA on Intel's integrated graphics processor?

If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.

How to insert a string which contains an "&"

I've found that using either of the following options works:

SET DEF OFF

or

SET SCAN OFF

I don't know enough about databases to know if one is better or "more right" than the other. Also, if there's something better than either of these, please let me know.

python - checking odd/even numbers and changing outputs on number size

This is simple code. You can try it and grab the knowledge easily.

n = int(input('Enter integer : '))
    if n % 2 == 3`8huhubuiiujji`:
        print('digit entered is ODD')
    elif n % 2 == 0 and 2 < n < 5:
        print('EVEN AND in between [2,5]')
    elif n % 2 == 0 and 6 < n < 20:
        print('EVEN and in between [6,20]')
    elif n % 2 == 0 and n > 20:
       print('Even and greater than 20')

and so on...

How to skip the OPTIONS preflight request?

I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.

express.use('*',(req,res,next) =>{
      if (req.method == "OPTIONS") {
        res.status(200);
        res.send();
      }else{
        next();
      }
    });

Disable Rails SQL logging in console

For Rails 4 you can put the following in an environment file:

# /config/environments/development.rb

config.active_record.logger = nil

bool to int conversion

There seems to be no problem since the int to bool cast is done implicitly. This works in Microsoft Visual C++, GCC and Intel C++ compiler. No problem in either C or C++.

What is this weird colon-member (" : ") syntax in the constructor?

Foo(int num): bar(num)    

This construct is called a Member Initializer List in C++.

Simply said, it initializes your member bar to a value num.


What is the difference between Initializing and Assignment inside a constructor?

Member Initialization:

Foo(int num): bar(num) {};

Member Assignment:

Foo(int num)
{
   bar = num;
}

There is a significant difference between Initializing a member using Member initializer list and assigning it an value inside the constructor body.

When you initialize fields via Member initializer list the constructors will be called once and the object will be constructed and initialized in one operation.

If you use assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.

Cost of Member Initialization = Object Construction 
Cost of Member Assignment = Object Construction + Assignment

The latter is actually equivalent to:

Foo(int num) : bar() {bar = num;}

While the former is equivalent to just:

Foo(int num): bar(num){}

For an inbuilt (your code example) or POD class members there is no practical overhead.


When do you HAVE TO use Member Initializer list?

You will have(rather forced) to use a Member Initializer list if:

  • Your class has a reference member
  • Your class has a non static const member or
  • Your class member doesn't have a default constructor or
  • For initialization of base class members or
  • When constructor’s parameter name is same as data member(this is not really a MUST)

A code example:

class MyClass {
public:
  // Reference member, has to be Initialized in Member Initializer List
  int &i;
  int b;
  // Non static const member, must be Initialized in Member Initializer List
  const int k;

  // Constructor’s parameter name b is same as class data member
  // Other way is to use this->b to refer to data member
  MyClass(int a, int b, int c) : i(a), b(b), k(c) {
    // Without Member Initializer
    // this->b = b;
  }
};

class MyClass2 : public MyClass {
public:
  int p;
  int q;
  MyClass2(int x, int y, int z, int l, int m) : MyClass(x, y, z), p(l), q(m) {}
};

int main() {
  int x = 10;
  int y = 20;
  int z = 30;
  MyClass obj(x, y, z);

  int l = 40;
  int m = 50;
  MyClass2 obj2(x, y, z, l, m);

  return 0;
}
  • MyClass2 doesn't have a default constructor so it has to be initialized through member initializer list.
  • Base class MyClass does not have a default constructor, So to initialize its member one will need to use Member Initializer List.

Important points to Note while using Member Initializer Lists:

Class Member variables are always initialized in the order in which they are declared in the class.

They are not initialized in the order in which they are specified in the Member Initializer List.
In short, Member initialization list does not determine the order of initialization.

Given the above it is always a good practice to maintain the same order of members for Member initialization as the order in which they are declared in the class definition. This is because compilers do not warn if the two orders are different but a relatively new user might confuse member Initializer list as the order of initialization and write some code dependent on that.

Open another page in php

Use the following code:

if(processing == success) {
  header("Location:filename");
  exit();
}

And you are good to go.

How to convert latitude or longitude to meters?

There are many tools that will make this easy. See monjardin's answer for more details about what's involved.

However, doing this isn't necessarily difficult. It sounds like you're using Java, so I would recommend looking into something like GDAL. It provides java wrappers for their routines, and they have all the tools required to convert from Lat/Lon (geographic coordinates) to UTM (projected coordinate system) or some other reasonable map projection.

UTM is nice, because it's meters, so easy to work with. However, you will need to get the appropriate UTM zone for it to do a good job. There are some simple codes available via googling to find an appropriate zone for a lat/long pair.

How to remove folders with a certain name

I ended up here looking to delete my node_modules folders before doing a backup of my work in progress using rsync. A key requirements is that the node_modules folder can be nested, so you need the -prune option.

First I ran this to visually verify the folders to be deleted:

find -type d -name node_modules -prune

Then I ran this to delete them all:

find -type d -name node_modules -prune -exec rm -rf {} \;

Thanks to pistache

Post parameter is always null

Since you have only one parameter, you could try decorating it with the [FromBody] attribute, or change the method to accept a DTO with value as a property, as I suggested here: MVC4 RC WebApi parameter binding

UPDATE: The official ASP.NET site was updated today with an excellent explanation: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1

In a nutshell, when sending a single simple type in the body, send just the value prefixed with an equal sign (=), e.g. body:

=test

Laravel 5 not finding css files

To fast apply simple regex.

search : href="(.+?)"
replace : href="{{ asset('$1') }}"

and

search : src="(.+?)"
replace : src="{{ asset('$1') }}"

how to add key value pair in the JSON object already declared

You can add more key value pair in the same object without replacing old ones in following way:

var obj = {};

obj = {
"1": "aa",
"2": "bb"
};

obj["3"] = "cc";

Below is the code and jsfiddle link to sample demo that will add more key value pairs to the already existed obj on clicking of button:

var obj = {
    "1": "aa",
    "2": "bb"
};

var noOfItems = Object.keys(obj).length;

$('#btnAddProperty').on('click', function() {
    noOfItems++;
    obj[noOfItems] = $.trim($('#txtName').val());
    console.log(obj);
});

https://jsfiddle.net/shrawanlakhe/78yd9a8L/4/

get all the images from a folder in php

Here is my some code

$dir          = '/Images';
$ImagesA = Get_ImagesToFolder($dir);
print_r($ImagesA);

function Get_ImagesToFolder($dir){
    $ImagesArray = [];
    $file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];

    if (file_exists($dir) == false) {
        return ["Directory \'', $dir, '\' not found!"];
    } 
    else {
        $dir_contents = scandir($dir);
        foreach ($dir_contents as $file) {
            $file_type = pathinfo($file, PATHINFO_EXTENSION);
            if (in_array($file_type, $file_display) == true) {
                $ImagesArray[] = $file;
            }
        }
        return $ImagesArray;
    }
}

VS 2017 Git Local Commit DB.lock error on every commit

Had this and my .gitignore was inside my project folder, but the main git folders were at the solution level. Moving .gitignore out to the solution/git level folders worked. Still not sure how it got there but...

Automatically deleting related rows in Laravel (Eloquent ORM)

Relation in User model:

public function photos()
{
    return $this->hasMany('Photo');
}

Delete record and related:

$user = User::find($id);

// delete related   
$user->photos()->delete();

$user->delete();

Is there a way to get version from package.json in nodejs code?

There is another way of fetching certain information from your package.json file namely using pkginfo module.

Usage of this module is very simple. You can get all package variables using:

require('pkginfo')(module);

Or only certain details (version in this case)

require('pkginfo')(module, 'version');

And your package variables will be set to module.exports (so version number will be accessible via module.exports.version).

You could use the following code snippet:

require('pkginfo')(module, 'version');
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, module.exports.version

This module has very nice feature - it can be used in any file in your project (e.g. in subfolders) and it will automatically fetch information from your package.json. So you do not have to worry where you package.json is.

I hope that will help.

How to print to the console in Android Studio?

Run your application in debug mode by clicking on

enter image description here

in the upper menu of Android Studio.

In the bottom status bar, click 5: Debug button, next to the 4: Run button.

Now you should select the Logcat console.

In search box, you can type the tag of your message, and your message should appear, like in the following picture (where the tag is CREATION):

enter image description here

Check this article for more information.

Why is setTimeout(fn, 0) sometimes useful?

Take a look at John Resig's article about How JavaScript Timers Work. When you set a timeout, it actually queues the asynchronous code until the engine executes the current call stack.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Print directly from browser without print popup window

For IE browsers, the "VBScript solution" works.

But as mentioned by @purefusion at Bypass Printdialog in IE9, Use Print() rather than window.print()

PHP Get URL with Parameter

$_SERVER['PHP_SELF'] for the page name and $_GET['id'] for a specific parameter.

try print_r($_GET); to print out all the parameters.

for your request echo $_SERVER['PHP_SELF']."?id=".$_GET['id'];

return all the parameters echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];

Working with TIFFs (import, export) in Python using numpy

PyLibTiff worked better for me than PIL, which as of December 2020 still doesn't support color images with more than 8 bits per color.

from libtiff import TIFF

tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the currect TIFF directory as a numpy array
image = tif.read_image()

# read all images in a TIFF file:
for image in tif.iter_images(): 
    pass

tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)

You can install PyLibTiff with

pip3 install numpy libtiff

The readme of PyLibTiff also mentions the tifffile library but I haven't tried it.

..The underlying connection was closed: An unexpected error occurred on a receive

Before Execute query I put the statement as below and it resolved my error. Just FYI in case it will help someone.

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ctx.ExecuteQuery();

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Please check this link for the reason behind this issue and solution for the error:

http://support.microsoft.com/kb/312629/EN-US/

Microsoft Support Article:

PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer Print Print Email Email

To work around this problem, use one of the following methods: For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.

For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End.

For example: Response.Redirect ("nextpage.aspx", false);

If you use this workaround, the code that follows Response.Redirect is executed. For Server.Transfer, use the Server.Execute method instead.

Calling a function of a module by using its name (a string)

Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:

# Get class from globals and create an instance
m = globals()['our_class']()

# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')

# Call it
func()

For example:

class A:
    def __init__(self):
        pass

    def sampleFunc(self, arg):
        print('you called sampleFunc({})'.format(arg))

m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')

# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')

And, if not a class:

def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

globals()['sampleFunc']('sample arg')

Convert categorical data in pandas dataframe

First, to convert a Categorical column to its numerical codes, you can do this easier with: dataframe['c'].cat.codes.
Further, it is possible to select automatically all columns with a certain dtype in a dataframe using select_dtypes. This way, you can apply above operation on multiple and automatically selected columns.

First making an example dataframe:

In [75]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'),  'col3':list('ababb')})

In [76]: df['col2'] = df['col2'].astype('category')

In [77]: df['col3'] = df['col3'].astype('category')

In [78]: df.dtypes
Out[78]:
col1       int64
col2    category
col3    category
dtype: object

Then by using select_dtypes to select the columns, and then applying .cat.codes on each of these columns, you can get the following result:

In [80]: cat_columns = df.select_dtypes(['category']).columns

In [81]: cat_columns
Out[81]: Index([u'col2', u'col3'], dtype='object')

In [83]: df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)

In [84]: df
Out[84]:
   col1  col2  col3
0     1     0     0
1     2     1     1
2     3     2     0
3     4     0     1
4     5     1     1

Difference between \b and \B in regex

With a different example:

Consider this is the string and pattern to be searched for is 'cat':

text = "catmania thiscat thiscatmaina";

Now definitions,

'\b' finds/matches the pattern at the beginning or end of each word.

'\B' does not find/match the pattern at the beginning or end of each word.

Different Cases:

Case 1: At the beginning of each word

result = text.replace(/\bcat/g, "ct");

Now, result is "ctmania thiscat thiscatmaina"

Case 2: At the end of each word

result = text.replace(/cat\b/g, "ct");

Now, result is "catmania thisct thiscatmaina"

Case 3: Not in the beginning

result = text.replace(/\Bcat/g, "ct");

Now, result is "catmania thisct thisctmaina"

Case 4: Not in the end

result = text.replace(/cat\B/g, "ct");

Now, result is "ctmania thiscat thisctmaina"

Case 5: Neither beginning nor end

result = text.replace(/\Bcat\B/g, "ct");

Now, result is "catmania thiscat thisctmaina"

Hope this helps :)

Including non-Python files with setup.py

Here is a simpler answer that worked for me.

First, per a Python Dev's comment above, setuptools is not required:

package_data is also available to pure distutils setup scripts 
since 2.3. – Éric Araujo

That's great because putting a setuptools requirement on your package means you will have to install it also. In short:

from distutils.core import setup

setup(
    # ...snip...
    packages          = ['pkgname'],
    package_data      = {'pkgname': ['license.txt']},
)

Using PHP Replace SPACES in URLS with %20

    public static function normalizeUrl(string $url) {
        $parts = parse_url($url);
        return $parts['scheme'] .
            '://' .
            $parts['host'] .
            implode('/', array_map('rawurlencode', explode('/', $parts['path'])));

    }

jQuery toggle CSS?

The best option would be to set a class style in CSS like .showMenu and .hideMenu with the various styles inside. Then you can do something like

$("#user_button").addClass("showMenu"); 

Stop floating divs from wrapping

You want to define min-width on row so when it browser is re-sized it does not go below that and wrap.

CSS: Fix row height

I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.

How to get indices of a sorted array in Python

myList = [1, 2, 3, 100, 5]    
sorted(range(len(myList)),key=myList.__getitem__)

[0, 1, 2, 4, 3]

How to get the day name from a selected date?

DateTime now = DateTime.Now
string s = now.DayOfWeek.ToString();

Bad Request, Your browser sent a request that this server could not understand

If you are getting this error on the WordPress website, check the below solution.

  1. Corrupted Browser Cache & Cookies: Delete your Cookies and clear your cache
  2. Restart your server

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

What is the correct way to do a CSS Wrapper?

You don't need a wrapper, just use the body as the wrapper.

CSS:

body {
    margin:0 auto;
    width:200px;
}

HTML:

<body>
    <p>some content</p>
<body>

How to link an image and target a new window

you can do like this

<a href="http://www.w3c.org/" target="_blank">W3C Home Page</a>

find this page

http://www.corelangs.com/html/links/new-window.html

goreb

Running npm command within Visual Studio Code

One reason might be if you install the node after starting the vs code,as vs code terminal integrated or external takes the path value which was at the time of starting the vs code and gives you error:

'node' is not recognized as an internal or external command,operable program or batch file.

A simple restart of vs code will solve the issue.

How do I keep the screen on in my App?

Lots of answers already exist here! I am answering this question with additional and reliable solutions:

Using PowerManager.WakeLock is not so reliable a solution, as the app requires additional permissions.

<uses-permission android:name="android.permission.WAKE_LOCK" />

Also, if it accidentally remains holding the wake lock, it can leave the screen on.

So, I recommend not using the PowerManager.WakeLock solution. Instead of this, use any of the following solutions:

First:

We can use getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); in onCreate()

@Override
        protected void onCreate(Bundle icicle) {
            super.onCreate(icicle);    
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }

Second:

we can use keepScreenOn

1. implementation using setKeepScreenOn() in java code:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        View v = getLayoutInflater().inflate(R.layout.driver_home, null);// or any View (incase generated programmatically ) 
        v.setKeepScreenOn(true);
        setContentView(v);
       }

Docs http://developer.android.com/reference/android/view/View.html#setKeepScreenOn(boolean)

2. Adding keepScreenOn to xml layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true" >

Docs http://developer.android.com/reference/android/view/View.html#attr_android%3akeepScreenOn

Notes (some useful points):

  1. It doesn't matter that keepScreenOn should be used on a Main/Root/Parent View. It can be used with any child view and will work the same way it works in a parent view.
  2. The only thing that matters is that the view's visibility must be visible. Otherwise, it will not work!

using facebook sdk in Android studio

I fixed the

"Could not find property 'ANDROID_BUILD_SDK_VERSION' on project ':facebook'."

error on the build.gradle file, by adding in gradle.properties the values:

ANDROID_BUILD_TARGET_SDK_VERSION=21<br>
ANDROID_BUILD_MIN_SDK_VERSION=15<br>
ANDROID_BUILD_TOOLS_VERSION=21.1.2<br>
ANDROID_BUILD_SDK_VERSION=21<br>

Source: https://stackoverflow.com/a/21490651/2161698

Get path of executable

QT provides this with OS abstraction as QCoreApplication::applicationDirPath()

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

If you declare your callback as mentioned by @lex82 like

callback = "callback(item.id, arg2)"

You can call the callback method in the directive scope with object map and it would do the binding correctly. Like

scope.callback({arg2:"some value"});

without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/

Update: There is a small example of this in the documentation:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

EditText request focus

>>you can write your code like

  if (TextUtils.isEmpty(username)) {
            editTextUserName.setError("Please enter username");
            editTextUserName.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            editTextPassword.setError("Enter a password");
            editTextPassword.requestFocus();
            return;
        }

Why is this program erroneously rejected by three C++ compilers?

File format not recognized You need to properly format your file. That means using the right colors and fonts for your code. See the specific documentations for each compiler as these colors vary between compiler ;)

grep from tar.gz without extracting [faster one]

If this is really slow, I suspect you're dealing with a large archive file. It's going to uncompress it once to extract the file list, and then uncompress it N times--where N is the number of files in the archive--for the grep. In addition to all the uncompressing, it's going to have to scan a fair bit into the archive each time to extract each file. One of tar's biggest drawbacks is that there is no table of contents at the beginning. There's no efficient way to get information about all the files in the archive and only read that portion of the file. It essentially has to read all of the file up to the thing you're extracting every time; it can't just jump to a filename's location right away.

The easiest thing you can do to speed this up would be to uncompress the file first (gunzip file.tar.gz) and then work on the .tar file. That might help enough by itself. It's still going to loop through the entire archive N times, though.

If you really want this to be efficient, your only option is to completely extract everything in the archive before processing it. Since your problem is speed, I suspect this is a giant file that you don't want to extract first, but if you can, this will speed things up a lot:

tar zxf file.tar.gz
for f in hopefullySomeSubdir/*; do
  grep -l "string" $f
done

Note that grep -l prints the name of any matching file, quits after the first match, and is silent if there's no match. That alone will speed up the grepping portion of your command, so even if you don't have the space to extract the entire archive, grep -l will help. If the files are huge, it will help a lot.

How to get 'System.Web.Http, Version=5.2.3.0?

In Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

How to find whether a number belongs to a particular range in Python?

No, you can't do that. range() expects integer arguments. If you want to know if x is inside this range try some form of this:

print 0.0 <= x <= 0.5

Be careful with your upper limit. If you use range() it is excluded (range(0, 5) does not include 5!)

Remove redundant paths from $PATH variable

  1. Just echo $PATH
  2. copy details into a text editor
  3. remove unwanted entries
  4. PATH= # pass new list of entries

How does Go update third-party packages?

Go to path and type

go get -u ./..

It will update all require packages.

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, you can get it with unpyclib that can be found on pypi.

$ pip install unpyclib

Than you can decompile your .pyc file

$ python -m unpyclib.application -Dq path/to/file.pyc

How to print third column to last column?

awk '{$1=$2=$3=""}1' file

NB: this method will leave "blanks" in 1,2,3 fields but not a problem if you just want to look at output.

c# write text on bitmap

var bmp = new Bitmap(@"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
    g.DrawString( ... );
}

picturebox1.Image = bmp;

Reading RFID with Android phones

You can hijack your Android audio port using an Arduino board like this. Then, you have two options (as far as I'm concerned):

1) Buy another Arduino Shield that supports RFID. I haven't seen one that supports UHF so far.

2) Try to connect your Arduino hijack with a USB RFID reader and build some embedded hardware kit.

Right now, I'm working in the second option but with iPhone.

Python - Get path of root project structure

To get the path of the "root" module, you can use:

import os
import sys
os.path.dirname(sys.modules['__main__'].__file__)

But more interestingly if you have an config "object" in your top-most module you could -read- from it like so:

app = sys.modules['__main__']
stuff = app.config.somefunc()

Creating a select box with a search option

Here's a handy open source library I made earlier that uses jQuery: https://bitbucket.org/warwick/searchablelist/src/master/ And here is a working copy on my VPS: http://developersfound.com/SearchableList/ The library is highly customisable with overridable behavours and can have seperate designs on the same web page Hope this helps

WAMP Cannot access on local network 403 Forbidden

To expand on RiggsFolly’s answer—or for anyone who is facing the same issue but is using Apache 2.2 or below—this format should work well:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1 ::1
Allow from localhost
Allow from 192.168
Allow from 10
Satisfy Any

For more details on the format changes for Apache 2.4, the official Upgrading to 2.2 from 2.4 page is pretty clear & concise. Key point being:

The old access control idioms should be replaced by the new authentication mechanisms, although for compatibility with old configurations, the new module mod_access_compat is provided.

Which means, system admins around the world don’t necessarily have to panic about changing Apache 2.2 configs to be 2.4 compliant just yet.

Is it possible to decrypt SHA1

Since SHA-1 maps several byte sequences to one, you can't "decrypt" a hash, but in theory you can find collisions: strings that have the same hash.

It seems that breaking a single hash would cost about 2.7 million dollars worth of computer time currently, so your efforts are probably better spent somewhere else.

How to update an "array of objects" with Firestore?

Edit 08/13/2018: There is now support for native array operations in Cloud Firestore. See Doug's answer below.


There is currently no way to update a single array element (or add/remove a single element) in Cloud Firestore.

This code here:

firebase.firestore()
.collection('proprietary')
.doc(docID)
.set(
  { sharedWith: [{ who: "[email protected]", when: new Date() }] },
  { merge: true }
)

This says to set the document at proprietary/docID such that sharedWith = [{ who: "[email protected]", when: new Date() } but to not affect any existing document properties. It's very similar to the update() call you provided however the set() call with create the document if it does not exist while the update() call will fail.

So you have two options to achieve what you want.

Option 1 - Set the whole array

Call set() with the entire contents of the array, which will require reading the current data from the DB first. If you're concerned about concurrent updates you can do all of this in a transaction.

Option 2 - Use a subcollection

You could make sharedWith a subcollection of the main document. Then adding a single item would look like this:

firebase.firestore()
  .collection('proprietary')
  .doc(docID)
  .collection('sharedWith')
  .add({ who: "[email protected]", when: new Date() })

Of course this comes with new limitations. You would not be able to query documents based on who they are shared with, nor would you be able to get the doc and all of the sharedWith data in a single operation.

How to convert/parse from String to char in java?

import java.io.*;
class ss1 
{
    public static void main(String args[]) 
    {
        String a = new String("sample");
        System.out.println("Result: ");
        for(int i=0;i<a.length();i++)
        {
            System.out.println(a.charAt(i));
        }
    }
}

When to use reinterpret_cast?

The meaning of reinterpret_cast is not defined by the C++ standard. Hence, in theory a reinterpret_cast could crash your program. In practice compilers try to do what you expect, which is to interpret the bits of what you are passing in as if they were the type you are casting to. If you know what the compilers you are going to use do with reinterpret_cast you can use it, but to say that it is portable would be lying.

For the case you describe, and pretty much any case where you might consider reinterpret_cast, you can use static_cast or some other alternative instead. Among other things the standard has this to say about what you can expect of static_cast (§5.2.9):

An rvalue of type “pointer to cv void” can be explicitly converted to a pointer to object type. A value of type pointer to object converted to “pointer to cv void” and back to the original pointer type will have its original value.

So for your use case, it seems fairly clear that the standardization committee intended for you to use static_cast.

How I can get web page's content and save it into the string variable

I've run into issues with Webclient.Downloadstring before. If you do, you can try this:

WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
    html = sr.ReadToEnd();
}

How do I create a unique ID in Java?

This adds a bit more randomness to the UUID generation but ensures each generated id is the same length

import org.apache.commons.codec.digest.DigestUtils;
import java.util.UUID;

public String createSalt() {
    String ts = String.valueOf(System.currentTimeMillis());
    String rand = UUID.randomUUID().toString();
    return DigestUtils.sha1Hex(ts + rand);
}

How to connect TFS in Visual Studio code

Just as Daniel said "Git and TFVC are the two source control options in TFS". Fortunately both are supported for now in VS Code.

You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.

  1. Search for Azure Repos in VS Code and select to install the one by Microsoft
  2. Open File -> Preferences -> Settings
  3. Add the following lines to your user settings

    If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe",
        "tfvc.restrictWorkspace": true
    }

    Or for VS 2017:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
        "tfvc.restrictWorkspace": true
    }
  4. Open a local folder (repository), From View -> Command Pallette ..., type team signin

  5. Provide user name --> Enter --> Provide password to connect to TFS.

Please refer to below links for more details:

Note that Server Workspaces are not supported:

"TFVC support is limited to Local workspaces":

on installing Azure extension, visual studio code warns you "It appears you are using a Server workspace. Currently, TFVC support is limited to Local workspaces"

combining results of two select statements

Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:

WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
    SELECT tableA.Id, COUNT(tableC.Id)
    FROM tableC
        RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
    GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
                     CompanyImageUrl,NumberOfUsers) AS (
    SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
        tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
    FROM tableA
        INNER JOIN tableB ON tableB.Id = tableA.Owner
        RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
    GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
    ,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
    INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id

After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.

Should you always favor xrange() over range()?

For performance, especially when you're iterating over a large range, xrange() is usually better. However, there are still a few cases why you might prefer range():

  • In python 3, range() does what xrange() used to do and xrange() does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange().

  • range() can actually be faster in some cases - eg. if iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however)

  • xrange() isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.

[Edit] There are a couple of posts mentioning how range() will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of range() and xrange()

RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@

 for x in range(20):
-    a=range(20)
+    a=list(range(20))
     b=list(range(20))
     c=[x for x in range(20)]
     d=(x for x in range(20))
-    e=xrange(20)
+    e=range(20)

As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.

Is there a way to programmatically scroll a scroll view to a specific edit text?

In my opinion the best way to scroll to a given rectangle is via View.requestRectangleOnScreen(Rect, Boolean). You should call it on a View you want to scroll to and pass a local rectangle you want to be visible on the screen. The second parameter should be false for smooth scrolling and true for immediate scrolling.

final Rect rect = new Rect(0, 0, view.getWidth(), view.getHeight());
view.requestRectangleOnScreen(rect, false);

Why is json_encode adding backslashes?

json_encode will always add slashes.

Check some examples on the manual HERE

This is because if there are some characters which needs to escaped then they will create problem.

To use the json please Parse your json to ensure that the slashes are removed

Well whether or not you remove slashesthe json will be parsed without any problem by eval.

<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>

This is my code and i m able to parse the JSON.

Check your code May be you are missing something while parsing the JSON

In MySQL, can I copy one row to insert into the same table?

You almost had it with the your first query you just need to specify the columns, that way you can exclude your primary key in the insert which will enact the auto-increment you likely have on the table to automatically create a new primary key for the entry.

For example change this:

insert into table select * from table where primarykey=1

To this:

INSERT INTO table (col1, col2, col3) 
SELECT col1, col2, col3 
FROM table 
WHERE primarykey = 1

Just don't include the primarykey column in either the column list for the INSERT or for the SELECT portions of the query.

How to find if directory exists in Python

So close! os.path.isdir returns True if you pass in the name of a directory that currently exists. If it doesn't exist or it's not a directory, then it returns False.