Programs & Examples On #Msn messenger

C# Validating input for textbox on winforms

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating event.

The Validating event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true the TextBox doesn't lose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text != "something")
        e.Cancel = true;
}

Update

You can use the ErrorProvider to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#

More Information

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

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

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

Setting PayPal return URL and making it auto return?

Sample form using PHP for direct payments.

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
    <input type="hidden" name="cmd" value="_cart">
    <input type="hidden" name="upload" value="1">
    <input type="hidden" name="business" value="[email protected]">

    <input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">
    <input type="hidden" name="amount_' . $x . '" value="' . $price . '">
    <input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '"> 
    <input type="hidden" name="custom" value="' . $product_id_array . '">
    <input type="hidden" name="notify_url" value="https://www.yoursite.com/my_ipn.php">
    <input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php">
    <input type="hidden" name="rm" value="2">
    <input type="hidden" name="cbt" value="Return to The Store">
    <input type="hidden" name="cancel_return" value="https://www.yoursite.com/paypal_cancel.php">
    <input type="hidden" name="lc" value="US">
    <input type="hidden" name="currency_code" value="USD">
    <input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!">
</form>

kindly go through the fields notify_url, return, cancel_return

sample code for handling ipn (my_ipn.php) which is requested by paypal after payment has been made.

For more information on creating a IPN, please refer to this link.

<?php
// Check to see there are posted variables coming into the script
if ($_SERVER['REQUEST_METHOD'] != "POST")
    die("No Post Variables");
// Initialize the $req variable and add CMD key value pair
$req = 'cmd=_notify-validate';
// Read the post from PayPal
foreach ($_POST as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}
// Now Post all of that back to PayPal's server using curl, and validate everything with PayPal
// We will use CURL instead of PHP for this for a more universally operable script (fsockopen has issues on some environments)
//$url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
$url = "https://www.paypal.com/cgi-bin/webscr";
$curl_result = $curl_err = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$curl_result = @curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);

$req = str_replace("&", "\n", $req);  // Make it a nice list in case we want to email it to ourselves for reporting
// Check that the result verifies
if (strpos($curl_result, "VERIFIED") !== false) {
    $req .= "\n\nPaypal Verified OK";
} else {
    $req .= "\n\nData NOT verified from Paypal!";
    mail("[email protected]", "IPN interaction not verified", "$req", "From: [email protected]");
    exit();
}

/* CHECK THESE 4 THINGS BEFORE PROCESSING THE TRANSACTION, HANDLE THEM AS YOU WISH
  1. Make sure that business email returned is your business email
  2. Make sure that the transaction?s payment status is ?completed?
  3. Make sure there are no duplicate txn_id
  4. Make sure the payment amount matches what you charge for items. (Defeat Price-Jacking) */

// Check Number 1 ------------------------------------------------------------------------------------------------------------
$receiver_email = $_POST['receiver_email'];
if ($receiver_email != "[email protected]") {
//handle the wrong business url
    exit(); // exit script
}
// Check number 2 ------------------------------------------------------------------------------------------------------------
if ($_POST['payment_status'] != "Completed") {
    // Handle how you think you should if a payment is not complete yet, a few scenarios can cause a transaction to be incomplete
}

// Check number 3 ------------------------------------------------------------------------------------------------------------
$this_txn = $_POST['txn_id'];
//check for duplicate txn_ids in the database
// Check number 4 ------------------------------------------------------------------------------------------------------------
$product_id_string = $_POST['custom'];
$product_id_string = rtrim($product_id_string, ","); // remove last comma
// Explode the string, make it an array, then query all the prices out, add them up, and make sure they match the payment_gross amount
// END ALL SECURITY CHECKS NOW IN THE DATABASE IT GOES ------------------------------------
////////////////////////////////////////////////////
// Homework - Examples of assigning local variables from the POST variables
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
$custom = $_POST['custom'];
// Place the transaction into the database
// Mail yourself the details
mail("[email protected]", "NORMAL IPN RESULT YAY MONEY!", $req, "From: [email protected]");
?>

The below image will help you in understanding the paypal process. Paypal process flow

For further reading refer to the following links;

hope this helps you..:)

error LNK2005, already defined?

And if you want these translation units to share this variable, define int k; in A.cpp and put extern int k; in B.cpp.

What is the parameter "next" used for in Express?

Before understanding next, you need to have a little idea of Request-Response cycle in node though not much in detail. It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);

let’s have a look at a very simple example.

app.get('/hello', function (req, res, next) {
  res.send('USER')
})

Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.

Now let’s take a look at another example.

app.get('/hello', function (req, res, next) {
  res.send("Hello World !!!!");
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.

But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.

app.get('/hello', function (req, res, next) {
  if(some condition){
    next();
    return;
  }
  res.send("Hello World !!!!");  
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

What’s the next doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!" response.

So, next pass the control to the next function in the middleware stack.

What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.

Something like below:-

app.get('/hello', function (req, res, next) {
  // Your piece of logic
  next();
});

app.get('/hello', function (req, res, next) {
  res.send("Hello !!!!");
});

In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();

What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.

How to fill a Javascript object literal with many static key/value pairs efficiently?

Give this a try:

var map = {"aaa": "rrr", "bbb": "ppp"};

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Change action bar color in android

Just simply go to res/values/styles.xml file and edit the xml file to change the color of xml file .Here is the sample code

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->

// below code is for changing the color of action bar

    <item name="colorPrimary">"type your color code here. eg:#ffffff"</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

Hope it will help you...

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

From the Errata: ModelState.AddRuleViolations(dinner.GetRuleViolations());

Should be:

ModelState.AddModelErrors(dinner.GetRuleViolations());

Reference: http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-MVC-1-0.productCd-0470384611,descCd-ERRATA.html

How to check the function's return value if true or false

Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:

if(!ValidateForm()) { ...

You could test against the constant false, but it's rather ugly and generally frowned upon:

if(ValidateForm() == false) { ...

The executable was signed with invalid entitlements

pJosh, this might help understanding. In my case, my Team Provisioning Profile was expiring (the Provisioning Portal indicated it is managed by XCode), as well as the device testing profile for the app. (I still don't know why, but the portal had a "Renew" button next to the team profile, but it wouldn't do anything when I clicked it.)

So, I deleted the profiles about to expire, then in XCode go to Organizer (Command-Shift-2), under Library / Provisioning Profiles, I deleted the expiring ones. Then click "Refresh" at the bottom, enter my Apple ID, and it renewed the expiring ones.

Finally, on my Target, I went to Build Settings, Code Signing, and made sure to select the provisioning profile. Voila, now it builds to my device.

List files with certain extensions with ls and grep

No need for grep. Shell wildcards will do the trick.

ls *.mp4 *.mp3 *.exe

If you have run

shopt -s nullglob

then unmatched globs will be removed altogether and not be left on the command line unexpanded.

If you want case-insensitive globbing (so *.mp3 will match foo.MP3):

shopt -s nocaseglob

What does @media screen and (max-width: 1024px) mean in CSS?

That’s a media query. It prevents the CSS inside it from being run unless the browser passes the tests it contains.

The tests in this media query are:

  1. @media screen — The browser identifies itself as being in the “screen” category. This roughly means the browser considers itself desktop-class — as opposed to e.g. an older mobile phone browser (note that the iPhone, and other smartphone browsers, do identify themselves as being in the screen category), or a screenreader — and that it’s displaying the page on-screen, rather than printing it.

  2. max-width: 1024px — the width of the browser window (including the scroll bar) is 1024 pixels or less. (CSS pixels, not device pixels.)

That second test suggests this is intended to limit the CSS to the iPad, iPhone, and similar devices (because some older browsers don’t support max-width in media queries, and a lot of desktop browsers are run wider than 1024 pixels).

However, it will also apply to desktop browser windows less than 1024 pixels wide, in browsers that support the max-width media query.

Here’s the Media Queries spec, it’s pretty readable:

jQuery - find child with a specific class

$(this).find(".bgHeaderH2").html();

or

$(this).find(".bgHeaderH2").text();

How to create an array of 20 random bytes?

Try the Random.nextBytes method:

byte[] b = new byte[20];
new Random().nextBytes(b);

How to use phpexcel to read data and insert into database?

    if($this->mng_auth->get_language()=='en')
          {
                    $excel->getActiveSheet()->setRightToLeft(false); 
          }
                else
                {  
                    $excel->getActiveSheet()->setRightToLeft(true); 
                }

       $styleArray = array(
                'borders' => array(
                    'allborders' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                            'color' => array('argb' => '00000000'),
                    ),
                ),
            );

          //SET property
          $objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->applyFromArray($styleArray);


    $objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->getAlignment()->setWrapText(true); 


$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->applyFromArray($styleArray);  

$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->getAlignment()->setWrapText(true); 

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Another solution is to migrate the database to e.g 2012 when you "export" the DB from e.g. Sql Server manager 2014. This is done in menu Tasks-> generate scripts when right-click on DB. Just follow this instruction:

https://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/

It generates an scripts with everything and then in your SQL server manager e.g. 2012 run the script as specified in the instruction. I have performed the test with success.

plain count up timer in javascript

Extending from @Chandu, with some UI added:

<html>
<head>
<script   src="https://code.jquery.com/jquery-3.2.1.min.js"   integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="   crossorigin="anonymous"></script>
</head>
<style>
button {
background: steelblue; 
border-radius: 4px; 
height: 40px; 
width: 100px; 
color: white; 
font-size: 20px; 
cursor: pointer; 
border: none; 
}
button:focus {
outline: 0; 
}
#minutes, #seconds {
font-size: 40px; 
}
.bigger {
font-size: 40px; 
}
.button {
  box-shadow: 0 9px #999;
}

.button:hover {background-color: hotpink}

.button:active {
  background-color: hotpink;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}
</style>
<body align='center'>
<button onclick='set_timer()' class='button'>START</button>
<button onclick='stop_timer()' class='button'>STOP</button><br><br>
<label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
</body>
</html>
<script>

function pad(val) {
  valString = val + "";
  if(valString.length < 2) {
     return "0" + valString;
     } else {
     return valString;
     }
}

totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
    totalSeconds++;
    secondsLabel.innerHTML = pad(totalSeconds%60);
    minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
    }

function set_timer() {
    minutesLabel = document.getElementById("minutes");
    secondsLabel = document.getElementById("seconds");
    my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}

function stop_timer() {
  clearInterval(my_int);
}


</script>

Looks as follows:

enter image description here

javascript /jQuery - For Loop

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

How do I change select2 box height

For v4.0.7 You can increase the height by overriding CSS classes like this example:

    .select2-container .select2-selection--single {
    height: 36px;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 36px;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 36px;
}

How can I turn a List of Lists into a List in Java 8?

Method to convert a List<List> to List :

listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());

See this example:

public class Example {

    public static void main(String[] args) {
        List<List<String>> listOfLists = Collections.singletonList(Arrays.asList("a", "b", "v"));
        List<String> list = listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());

        System.out.println("listOfLists => " + listOfLists);
        System.out.println("list => " + list);
    }

}       

It prints:

listOfLists => [[a, b, c]]
list => [a, b, c]

In Python this can be done using List Comprehension.

list_of_lists = [['Roopa','Roopi','Tabu', 'Soudipta'],[180.0, 1231, 2112, 3112], [130], [158.2], [220.2]]

flatten = [val for sublist in list_of_lists for val in sublist]

print(flatten)
['Roopa', 'Roopi', 'Tabu', 'Soudipta', 180.0, 1231, 2112, 3112, 130, 158.2, 220.2]

Scroll Automatically to the Bottom of the Page

You can attach any id to reference attribute href of link element:

<a href="#myLink" id="myLink">
    Click me
</a>

In the example above when user clicks Click me at the bottom of page, navigation navigates to Click me itself.

start/play embedded (iframe) youtube-video on click of an image

To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

Convert UTC to local time in Rails 3

Don't know why but in my case it doesn't work the way suggested earlier. But it works like this:

Time.now.change(offset: "-3000")

Of course you need to change offset value to yours.

How can I combine flexbox and vertical scroll in a full-height app?

The current spec says this regarding flex: 1 1 auto:

Sizes the item based on the width/height properties, but makes them fully flexible, so that they absorb any free space along the main axis. If all items are either flex: auto, flex: initial, or flex: none, any positive free space after the items have been sized will be distributed evenly to the items with flex: auto.

http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#flex-common

It sounds to me like if you say an element is 100px tall, it is treated more like a "suggested" size, not an absolute. Because it is allowed to shrink and grow, it takes up as much space as its allowed to. That's why adding this line to your "main" element works: height: 0 (or any other smallish number).

How do I format XML in Notepad++?

Step 1: Install XML Tools plugin
Step 2: Format ....completed

enter image description here

Is Task.Result the same as .GetAwaiter.GetResult()?

As already mentioned if you can use await. If you need to run the code synchronously like you mention .GetAwaiter().GetResult(), .Result or .Wait() is a risk for deadlocks as many have said in comments/answers. Since most of us like oneliners you can use these for .Net 4.5<

Acquiring a value via an async method:

var result = Task.Run(() => asyncGetValue()).Result;

Syncronously calling an async method

Task.Run(() => asyncMethod()).Wait();

No deadlock issues will occur due to the use of Task.Run.

Source:

https://stackoverflow.com/a/32429753/3850405

Update:

Could cause a deadlock if the calling thread is from the threadpool. The following happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.

Source:

https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d

Delete commits from a branch in Git

use git revert https://git-scm.com/docs/git-revert .It will revert all code then you can do next commit.Then head will point to that last commit. reverted commits never delete but it will not affect on you last commit.

INSERT INTO from two different server database

You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.

I found this solution when I faced the same situation. Hope this helps you too.

How to find the files that are created in the last hour in unix

find ./ -cTime -1 -type f

OR

find ./ -cmin -60 -type f

Convert integer into byte array (Java)

It's my solution:

public void getBytes(int val) {
    byte[] bytes = new byte[Integer.BYTES];
    for (int i = 0;i < bytes.length; i ++) {
        int j = val % Byte.MAX_VALUE;
        bytes[i] = (j == 0 ? Byte.MAX_VALUE : j);
    }
}

Also Stringy method:

public void getBytes(int val) {
    String hex = Integer.toHexString(val);
    byte[] val = new byte[hex.length()/2]; // because byte is 2 hex chars
    for (int i = 0; i < hex.length(); i+=2)
        val[i] = Byte.parseByte("0x" + hex.substring(i, i+2), 16);
    return val;
}

How to convert unix timestamp to calendar date moment.js

new moment(timeStamp,'yyyyMMddHHmmssfff').toDate()

Use .corr to get the correlation between two columns

Without actual data it is hard to answer the question but I guess you are looking for something like this:

Top15['Citable docs per Capita'].corr(Top15['Energy Supply per Capita'])

That calculates the correlation between your two columns 'Citable docs per Capita' and 'Energy Supply per Capita'.

To give an example:

import pandas as pd

df = pd.DataFrame({'A': range(4), 'B': [2*i for i in range(4)]})

   A  B
0  0  0
1  1  2
2  2  4
3  3  6

Then

df['A'].corr(df['B'])

gives 1 as expected.

Now, if you change a value, e.g.

df.loc[2, 'B'] = 4.5

   A    B
0  0  0.0
1  1  2.0
2  2  4.5
3  3  6.0

the command

df['A'].corr(df['B'])

returns

0.99586

which is still close to 1, as expected.

If you apply .corr directly to your dataframe, it will return all pairwise correlations between your columns; that's why you then observe 1s at the diagonal of your matrix (each column is perfectly correlated with itself).

df.corr()

will therefore return

          A         B
A  1.000000  0.995862
B  0.995862  1.000000

In the graphic you show, only the upper left corner of the correlation matrix is represented (I assume).

There can be cases, where you get NaNs in your solution - check this post for an example.

If you want to filter entries above/below a certain threshold, you can check this question. If you want to plot a heatmap of the correlation coefficients, you can check this answer and if you then run into the issue with overlapping axis-labels check the following post.

Dynamic loading of images in WPF

You could try attaching handlers to various events of BitmapImage:

They might tell you a little about what's going on, as far as the image is concerned.

How to resolve conflicts in EGit

As it's an issue we face more than often, below are the steps to resolve it.

  1. Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...

  2. It should auto select Remote Tracking ? *origin/master. Press Merge.

  3. Launch stage view in Eclipse.

  4. Double click the files which initially showed conflict

  5. In the conflict merge view, by selecting the left arrow for all the non-conflict + conflict changes from left to right, you can resolve all the conflicts.

  6. Save the merged file.

  7. Do a Team ? pull from Eclipse again.

You are all set :)

Delete the first five characters on any line of a text file in Linux with sed

Use cut:

cut -c6-

This prints each line of the input starting at column 6 (the first column is 1).

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

Is there a java setting for disabling certificate validation?

In addition to the answers above. You can do it programmatically by implementing the TrustManager:

TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
           return null;
          }
          @Override
          public void checkClientTrusted(X509Certificate[] arg0, String arg1)
           throws CertificateException {}

          @Override
          public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {}
          }
     };

  SSLContext sc=null;
  try {
   sc = SSLContext.getInstance("SSL");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  try {
   sc.init(null, trustAllCerts, new java.security.SecureRandom());
  } catch (KeyManagementException e) {
   e.printStackTrace();
  }
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  // Create all-trusting host name verifier
  HostnameVerifier validHosts = new HostnameVerifier() {
  @Override
  public boolean verify(String arg0, SSLSession arg1) {
   return true;
  }
  };
  // All hosts will be valid
  HttpsURLConnection.setDefaultHostnameVerifier(validHosts);

However this is not a good practice for production.

This example on How to disable SSL certificat validation in Java contains a utility class you can copy in your project.

Bootstrap 3 jquery event for active tab change

To add to Mosh Feu answer, if the tabs where created on the fly like in my case, you would use the following code

$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    var tab = $(e.target);
    var contentId = tab.attr("href");

    //This check if the tab is active
    if (tab.parent().hasClass('active')) {
         console.log('the tab with the content id ' + contentId + ' is visible');
    } else {
         console.log('the tab with the content id ' + contentId + ' is NOT visible');
    }

});

I hope this helps someone

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

How do I overload the [] operator in C#

public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}

android listview item height

This is my solution(There is a nested LinearLayout):

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/item"
            android:layout_width="match_parent"
            android:layout_height="47dp"
            android:background="@drawable/box_arrow_top_bg"
            android:gravity="center"
            android:text="????"
            android:textColor="#666"
            android:textSize="16sp" />
    </LinearLayout>

</LinearLayout>

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

How to count items in JSON object using command line?

Just throwing another solution in the mix...

Try jq, a lightweight and flexible command-line JSON processor:

jq length /tmp/test.json

Prints the length of the array of objects.

How to convert QString to std::string?

Best thing to do would be to overload operator<< yourself, so that QString can be passed as a type to any library expecting an output-able type.

std::ostream& operator<<(std::ostream& str, const QString& string) {
    return str << string.toStdString();
}

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

I have fixed it with removing below code from

C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf file

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error.log"
    CustomLog "logs/dummy-host.example.com-access.log" common
 </VirtualHost>

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
    ServerName dummy-host2.example.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

And added

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot "c:/wamp/www"
    ServerName localhost
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" common
</VirtualHost>

And it has worked like charm

RSA: Get exponent and modulus given a public key

It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it's a one-off (always the same key) or whether you need to script it.

Command-line / OpenSSL

If you want to use something like OpenSSL on a unix command line, you can do something as follows. I'm assuming you public.key file contains something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmBAjFv+29CaiQqYZIw4P
J0q5Qz2gS7kbGleS3ai8Xbhu5n8PLomldxbRz0RpdCuxqd1yvaicqpDKe/TT09sR
mL1h8Sx3Qa3EQmqI0TcEEqk27Ak0DTFxuVrq7c5hHB5fbJ4o7iEq5MYfdSl4pZax
UxdNv4jRElymdap8/iOo3SU1RsaK6y7kox1/tm2cfWZZhMlRFYJnpoXpyNYrp+Yo
CNKxmZJnMsS698kaFjDlyznLlihwMroY0mQvdD7dCeBoVlfPUGPAlamwWyqtIU+9
5xVkSp3kxcNcNb/mePSKQIPafQ1sAmBKPwycA/1I5nLzDVuQa95ZWMn0JkphtFIh
HQIDAQAB
-----END PUBLIC KEY-----

Then, the commands would be:

PUBKEY=`grep -v -- ----- public.key | tr -d '\n'`

Then, you can look into the ASN.1 structure:

echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i

This should give you something like this:

    0:d=0  hl=4 l= 290 cons: SEQUENCE          
    4:d=1  hl=2 l=  13 cons:  SEQUENCE          
    6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
   17:d=2  hl=2 l=   0 prim:   NULL              
   19:d=1  hl=4 l= 271 prim:  BIT STRING 

The modulus and public exponent are in the last BIT STRING, offset 19, so use -strparse:

 echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i -strparse 19

This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim:  INTEGER           :98102316FFB6F426A242A619230E0F274AB9433DA04BB91B1A5792DDA8BC5DB86EE67F0F2E89A57716D1CF4469742BB1A9DD72BDA89CAA90CA7BF4D3D3DB1198BD61F12C7741ADC4426A88D1370412A936EC09340D3171B95AEAEDCE611C1E5F6C9E28EE212AE4C61F752978A596B153174DBF88D1125CA675AA7CFE23A8DD253546C68AEB2EE4A31D7FB66D9C7D665984C951158267A685E9C8D62BA7E62808D2B199926732C4BAF7C91A1630E5CB39CB96287032BA18D2642F743EDD09E0685657CF5063C095A9B05B2AAD214FBDE715644A9DE4C5C35C35BFE678F48A4083DA7D0D6C02604A3F0C9C03FD48E672F30D5B906BDE5958C9F4264A61B452211D
  265:d=1  hl=2 l=   3 prim:  INTEGER           :010001

That's probably fine if it's always the same key, but this is probably not very convenient to put in a script.

Alternatively (and this might be easier to put into a script),

openssl rsa -pubin -inform PEM -text -noout < public.key

will return this:

Modulus (2048 bit):
    00:98:10:23:16:ff:b6:f4:26:a2:42:a6:19:23:0e:
    0f:27:4a:b9:43:3d:a0:4b:b9:1b:1a:57:92:dd:a8:
    bc:5d:b8:6e:e6:7f:0f:2e:89:a5:77:16:d1:cf:44:
    69:74:2b:b1:a9:dd:72:bd:a8:9c:aa:90:ca:7b:f4:
    d3:d3:db:11:98:bd:61:f1:2c:77:41:ad:c4:42:6a:
    88:d1:37:04:12:a9:36:ec:09:34:0d:31:71:b9:5a:
    ea:ed:ce:61:1c:1e:5f:6c:9e:28:ee:21:2a:e4:c6:
    1f:75:29:78:a5:96:b1:53:17:4d:bf:88:d1:12:5c:
    a6:75:aa:7c:fe:23:a8:dd:25:35:46:c6:8a:eb:2e:
    e4:a3:1d:7f:b6:6d:9c:7d:66:59:84:c9:51:15:82:
    67:a6:85:e9:c8:d6:2b:a7:e6:28:08:d2:b1:99:92:
    67:32:c4:ba:f7:c9:1a:16:30:e5:cb:39:cb:96:28:
    70:32:ba:18:d2:64:2f:74:3e:dd:09:e0:68:56:57:
    cf:50:63:c0:95:a9:b0:5b:2a:ad:21:4f:bd:e7:15:
    64:4a:9d:e4:c5:c3:5c:35:bf:e6:78:f4:8a:40:83:
    da:7d:0d:6c:02:60:4a:3f:0c:9c:03:fd:48:e6:72:
    f3:0d:5b:90:6b:de:59:58:c9:f4:26:4a:61:b4:52:
    21:1d
Exponent: 65537 (0x10001)

Java

It depends on the input format. If it's an X.509 certificate in a keystore, use (RSAPublicKey)cert.getPublicKey(): this object has two getters for the modulus and the exponent.

If it's in the format as above, you might want to use BouncyCastle and its PEMReader to read it. I haven't tried the following code, but this would look more or less like this:

PEMReader pemReader = new PEMReader(new FileReader("file.pem"));
Object obj = pemReader.readObject();
pemReader.close();
if (obj instanceof X509Certificate) {
   // Just in case your file contains in fact an X.509 certificate,
   // useless otherwise.
   obj = ((X509Certificate)obj).getPublicKey();
}
if (obj instanceof RSAPublicKey) {
   // ... use the getters to get the BigIntegers.
}

(You can use BouncyCastle similarly in C# too.)

PowerShell array initialization

Yet another alternative:

for ($i = 0; $i -lt 5; $i++) 
{ 
  $arr += @($false) 
}

This one works if $arr isn't defined yet.

NOTE - there are better (and more performant) ways to do this... see https://stackoverflow.com/a/234060/4570 below as an example.

How to create a file in memory for user to download, but not through server?

Simple solution for HTML5 ready browsers...

_x000D_
_x000D_
function download(filename, text) {_x000D_
  var element = document.createElement('a');_x000D_
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));_x000D_
  element.setAttribute('download', filename);_x000D_
_x000D_
  element.style.display = 'none';_x000D_
  document.body.appendChild(element);_x000D_
_x000D_
  element.click();_x000D_
_x000D_
  document.body.removeChild(element);_x000D_
}
_x000D_
form * {_x000D_
  display: block;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<form onsubmit="download(this['name'].value, this['text'].value)">_x000D_
  <input type="text" name="name" value="test.txt">_x000D_
  <textarea name="text"></textarea>_x000D_
  <input type="submit" value="Download">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Usage

download('test.txt', 'Hello world!');

Remove whitespaces inside a string in javascript

For space-character removal use

"hello world".replace(/\s/g, "");

for all white space use the suggestion by Rocket in the comments below!

How to know function return type and argument types?

Well things have changed a little bit since 2011! Now there's type hints in Python 3.5 which you can use to annotate arguments and return the type of your function. For example this:

def greeting(name):
  return 'Hello, {}'.format(name)

can now be written as this:

def greeting(name: str) -> str:
  return 'Hello, {}'.format(name)

As you can now see types, there's some sort of optional static type checking which will help you and your type checker to investigate your code.

for more explanation I suggest to take a look at the blog post on type hints in PyCharm blog.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I had the same problem. In my case cordova platform update ios helped. The reason was in outdated version.

Returning http 200 OK with error within response body

Even if I want to return a business logic error as HTTP code there is no such acceptable HTTP error code for that errors rather than using HTTP 200 because it will misrepresent the actual error.

So, HTTP 200 will be good for business logic errors. But all errors which are covered by HTTP error codes should use them.

Basically HTTP 200 means what server correctly processes user request (in case of there is no seats on the plane it is no matter because user request was correctly processed, it can even return just a number of seats available on the plane, so there will be no business logic errors at all or that business logic can be on client side. Business logic error is an abstract meaning, but HTTP error is more definite).

Ruby on Rails - Import Data from a CSV file

You might try Upsert:

require 'upsert' # add this to your Gemfile
require 'csv'    

u = Upsert.new Moulding.connection, Moulding.table_name
CSV.foreach(file, headers: true) do |row|
  selector = { name: row['name'] } # this treats "name" as the primary key and prevents the creation of duplicates by name
  setter = row.to_hash
  u.row selector, setter
end

If this is what you want, you might also consider getting rid of the auto-increment primary key from the table and setting the primary key to name. Alternatively, if there is some combination of attributes that form a primary key, use that as the selector. No index is necessary, it will just make it faster.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Jquery UI tooltip does not support html content

another solution will be to grab the text inside the title tag & then use .html() method of jQuery to construct the content of the tooltip.

$(function() {
  $(document).tooltip({
    position: {
      using: function(position, feedback) {
        $(this).css(position);
        var txt = $(this).text();
        $(this).html(txt);
        $("<div>")
          .addClass("arrow")
          .addClass(feedback.vertical)
          .addClass(feedback.horizontal)
          .appendTo(this);
      }
    }
  });
});

Example: http://jsfiddle.net/hamzeen/0qwxfgjo/

Git update submodules recursively

As it may happens that the default branch of your submodules are not master (which happens a lot in my case), this is how I automate the full Git submodules upgrades:

git submodule init
git submodule update
git submodule foreach 'git fetch origin; git checkout $(git rev-parse --abbrev-ref HEAD); git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); git submodule update --recursive; git clean -dfx'

Attach to a processes output for viewing

How would I 'attach' a console/terminal-view to an applications output so I can see what it may be saying?

About this question, I know it is possible to catch the output, even when you didn't launch sceen command before launching the processus.

While I never tried it, I've found an interesting article which explains how to do using GDB (and without restarting your process).

redirecting-output-from-a-running-process

Basically:

  1. Check the open files list for your process, thanks to /proc/xxx/fd
  2. Attach your process with GDB
  3. While it is paused, close the file you are interested in, calling close() function (you can any function of your process in GDB. I suspect you need debug symbols in your process..)
  4. Open the a new file calling the create() or open() function. (Have a look in comments at the end, you'll see people suggest to use dup2() to ensure the same handle will be in use)
  5. Detach the process and let in run.

By the way, if you are running a linux OS on i386 box, comments are talking about a better tool to redirect output to a new console : 'retty' . If so, consider its use.

Illegal pattern character 'T' when parsing a date string to java.util.Date

There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:

import java.time.Instant;
public static void main(String[] args) {
    String date="2010-10-02T12:23:23Z";
    try {
        Instant myDate = Instant.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant directly, can be done via Calendar in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:

myDate.toString().substring(0,4);

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

How to call a function in shell Scripting?

#!/bin/bash

process_install()
{
    commands... 
    commands... 
}

process_exit()
{
    commands... 
    commands... 
}


if [ "$choice" = "true" ] then
    process_install
else
    process_exit
fi

How to undo a SQL Server UPDATE query?

Considering that you already have a full backup I’d just restore that backup into separate database and migrate the data from there.

If your data has changed after the latest backup then what you recover all data that way but you can try to recover that by reading transaction log.

If your database was in full recovery mode than transaction log has enough details to recover updates to your data after the latest backup.

You might want to try with DBCC LOG, fn_log functions or with third party log reader such as ApexSQL Log

Unfortunately there is no easy way to read transaction log because MS doesn’t provide documentation for this and stores the data in its proprietary format.

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

Just faced the issue of Unexpected end of JSON input while parsing near.. while adding the 'radium' package in my React App. As a matter of fact, I am facing this issue even when trying to update the NPM to the latest version.

Anyways, NPM didn't work after clearing the cache and it also won't update to the latest version right now but adding the package via Yarn did the trick for me.

So, if you are in a hurry to solve this issue but you are not able to, then give yarn a try instead of npm.

Happy Coding!

Update

After trying few things finally sudo npm cache clean --force worked for me.

This can be a temporary glitch in your network or with something else in the npm registry.

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

Permanently Set Postgresql Schema Path

You can set the default search_path at the database level:

ALTER DATABASE <database_name> SET search_path TO schema1,schema2;

Or at the user or role level:

ALTER ROLE <role_name> SET search_path TO schema1,schema2;

Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.

When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name> to create your databases.

Regular expression matching a multiline block of text

Try this:

re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE)

I think your biggest problem is that you're expecting the ^ and $ anchors to match linefeeds, but they don't. In multiline mode, ^ matches the position immediately following a newline and $ matches the position immediately preceding a newline.

Be aware, too, that a newline can consist of a linefeed (\n), a carriage-return (\r), or a carriage-return+linefeed (\r\n). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:

re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE)

BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything except newlines.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

I faced the same error.

I solved the problem by deleting all the contents of bin folders of all the dependent projects/libraries.

This error mainly happens due to version changes.

Select Rows with id having even number

SELECT * FROM ( SELECT *, Row_Number() 
OVER(ORDER BY country_gid) AS sdfg  FROM eka_mst_tcountry ) t 
WHERE t.country_gid % 2 = 0 

How to return JSON with ASP.NET & jQuery

Just return object: it will be parser to JSON.

public Object Get(string id)
{
    return new { id = 1234 };
}

Angular ng-repeat add bootstrap row every 3 or 4 cols

After combining many answers and suggestion here, this is my final answer, which works well with flex, which allows us to make columns with equal height, it also checks the last index, and you don't need to repeat the inner HTML. It doesn't use clearfix:

<div ng-repeat="prod in productsFiltered=(products | filter:myInputFilter)" ng-if="$index % 3 == 0" class="row row-eq-height">
    <div ng-repeat="i in [0, 1, 2]" ng-init="product = productsFiltered[$parent.$parent.$index + i]"  ng-if="$parent.$index + i < productsFiltered.length" class="col-xs-4">
        <div class="col-xs-12">{{ product.name }}</div>
    </div>
</div>

It will output something like this:

<div class="row row-eq-height">
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
</div>
<div class="row row-eq-height">
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
</div>

flutter corner radius with transparent background

It's an old question. But for those who come across this question...

The white background behind the rounded corners is not actually the container. That is the canvas color of the app.

TO FIX: Change the canvas color of your app to Colors.transparent

Example:

return new MaterialApp(
  title: 'My App',
  theme: new ThemeData(
    primarySwatch: Colors.green,
    canvasColor: Colors.transparent, //----Change to this------------
    accentColor: Colors.blue,
  ),
  home: new HomeScreen(),
);

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

Unable to create migrations after upgrading to ASP.NET Core 2.0

Sample DB context class for .net core console applications

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace EmailServerConsole.Data
{
    public class EmailDBContext : DbContext
    {
        public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options) { }
        public DbSet<EmailQueue> EmailsQueue { get; set; }
    }

    public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
    {
        EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            var builder = new DbContextOptionsBuilder<EmailDBContext>();
            var connectionString = configuration.GetConnectionString("connection_string");
            builder.UseSqlServer(connectionString);
            return new EmailDBContext(builder.Options);
        }
    }
}

Button Center CSS

Another nice option is to use :

width: 40%;
margin-left: 30%;
margin-right: 30%

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

Clone Object without reference javascript

A and B reference the same object, so A.a and B.a reference the same property of the same object.

Edit

Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.

There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?

So have a look at the following, it's a slightly different approach to others.

/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give 
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
   var o, prop, type;

  if (typeof source != 'object' || source === null) {
    // What do to with functions, throw an error?
    o = source;
    return o;
  }

  o = new source.constructor();

  for (prop in source) {

    if (source.hasOwnProperty(prop)) {
      type = typeof source[prop];

      if (deep && type == 'object' && source[prop] !== null) {
        o[prop] = copy(source[prop]);

      } else {
        o[prop] = source[prop];
      }
    }
  }
  return o;
}

Chrome extension id - how to find it

If you just need to do it one-off, navigate to chrome://extensions. Enable Developer Mode at upper right. The ID will be shown in the box for each extension.

Or, if you're working on developing a userscript or extension, purposefully throw an error. Look in the javascript console, and the ID will be there, on the right side of the console, in the line describing the error.

Lastly, you can look in your chrome extensions directory; it stores extensions in directories named by the ID. This is the worst choice, as you'd have extension IDs, and have to read each manifest.json to figure out which ID was the right one. But if you just installed something, you can also just sort by creation date, and the newest extension directory will be the ID you want.

How to set Python's default version to 3.x on OS X?

If you are using macports, that has a easier way to do:

run:

port install python37

after install, set default:

sudo port select --set python python37

sudo port select --set python3 python37

restart your cmd window, finished.

How do I find out which DOM element has the focus?

If you want to get a object that is instance of Element, you must use document.activeElement, but if you want to get a object that is instance of Text, you must to use document.getSelection().focusNode.

I hope helps.

Import txt file and having each line as a list

Do not create separate lists; create a list of lists:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))

or better still, use the csv module:

import csv

results = []
with open('inputfile.txt', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there.

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

import csv

with open('inputfile.txt', newline='') as inputfile:
    results = list(csv.reader(inputfile))

How do I combine two lists into a dictionary in Python?

I found myself needing to create a dictionary of three lists (latitude, longitude, and a value), with the following doing the trick:

> lat = [45.3,56.2,23.4,60.4]
> lon = [134.6,128.7,111.9,75.8]
> val = [3,6,2,5]
> dict(zip(zip(lat,lon),val))
{(56.2, 128.7): 6, (60.4, 75.8): 5, (23.4, 111.9): 2, (45.3, 134.6): 3}

or similar to the above examples:

> list1 = [1,2,3,4]
> list2 = [1,2,3,4]
> list3 = ['a','b','c','d']
> dict(zip(zip(list1,list2),list3))
{(3, 3): 'c', (4, 4): 'd', (1, 1): 'a', (2, 2): 'b'}

Note: Dictionaries are "orderless", but if you would like to view it as "sorted", refer to THIS question if you'd like to sort by key, or THIS question if you'd like to sort by value.

Can we cast a generic object to a custom object type in javascript?

This is just a wrap up of Sayan Pal answer in a shorter form, ES5 style :

var Foo = function(){
    this.bar = undefined;
    this.buzz = undefined;
}

var foo = Object.assign(new Foo(),{
    bar: "whatever",
    buzz: "something else"
});

I like it because it is the closest to the very neat object initialisation in .Net:

var foo = new Foo()
{
    bar: "whatever",
    ...

Reading a plain text file in Java

Below is a one-liner of doing it in the Java 8 way. Assuming text.txt file is in the root of the project directory of the Eclipse.

Files.lines(Paths.get("text.txt")).collect(Collectors.toList());

parseInt with jQuery

var test = parseInt($("#testid").val(), 10);

You have to tell it you want the value of the input you are targeting.

And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.

Providing 10 assumes you are wanting a base 10 number.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

Method call if not null in C#

Events can be initialized with an empty default delegate which is never removed:

public event EventHandler MyEvent = delegate { };

No null-checking necessary.

[Update, thanks to Bevan for pointing this out]

Be aware of the possible performance impact, though. A quick micro benchmark I did indicates that handling an event with no subscribers is 2-3 times slower when using the the "default delegate" pattern. (On my dual core 2.5GHz laptop that means 279ms : 785ms for raising 50 million not-subscribed events.). For application hot spots, that might be an issue to consider.

How to get max value of a column using Entity Framework?

int maxAge = context.Persons.Max(p => p.Age);

This version, if the list is empty:

  • Returns null - for nullable overloads
  • Throws Sequence contains no element exception - for non-nullable overloads

-

int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max();

This version handles the empty list case, but it generates more complex query, and for some reason doesn't work with EF Core.

-

int maxAge = context.Persons.Max(p => (int?)p.Age) ?? 0;

This version is elegant and performant (simple query and single round-trip to the database), works with EF Core. It handles the mentioned exception above by casting the non-nullable type to nullable and then applying the default value using the ?? operator.

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

issue = “UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.”

And this worked for me

import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Qt5Agg')

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

Viewing unpushed Git commits

To list all unpushed commit in all branches easily you can use this command:

 git log --branches  @{u}..

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

How do I install a custom font on an HTML site

For the best possible browser support, your CSS code should look like this :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

body {
  font-family: 'MyWebFont', Fallback, sans-serif;
}

For more info, see the article Using @font-face at CSS-tricks.com.

MySQL Workbench Dark Theme

For disabling Dark mode in MySQL workbench on mac: Open terminal use mentioned command:

defaults write com.oracle.workbench.MySQLWorkbench NSRequiresAquaSystemAppearance -bool yes

For Enabling Dark mode in MySQL workbench on mac: Open terminal:

defaults write com.oracle.workbench.MySQLWorkbench NSRequiresAquaSystemAppearance -bool no

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.

Instead we can use React ref system to access and manipulate Dom as shown in below example:

constructor(props){

    super(props);
    this.imageRef = React.createRef(); // create react ref
}

componentDidMount(){

    **console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
}


render = (props) => {

const {urls,description} = this.props.image;
    return (

            <img
             **ref = {this.imageRef} // assign the ref of img tag here**
             src = {urls.regular} 
             alt = {description}
             />

        );

}

}

git stash -> merge stashed change with current changes

Running git stash pop or git stash apply is essentially a merge. You shouldn't have needed to commit your current changes unless the files changed in the stash are also changed in the working copy, in which case you would've seen this error message:

error: Your local changes to the following files would be overwritten by merge:
       file.txt
Please, commit your changes or stash them before you can merge.
Aborting

In that case, you can't apply the stash to your current changes in one step. You can commit the changes, apply the stash, commit again, and squash those two commits using git rebase if you really don't want two commits, but that may be more trouble that it's worth.

How do I start a process from C#?

Include the using System.Diagnostics;.

And then call this Process.Start("Paste your URL string here!");

Try something like this:

using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

namespace btnproce
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string t ="Balotelli";
            Process.Start("http://google.com/search?q=" + t);
        }
    }
}

Please note that it is a sample ASP.NET page as an example. You should try and improvise a little bit.

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

What is the difference between Nexus and Maven?

Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.

Here's a quote from "What is Nexus?":

Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.

And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:

Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.

So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.

Pass by pointer & Pass by reference

Use references all the time and pointers only when you have to refer to NULL which reference cannot refer.

See this FAQ : http://www.parashift.com/c++-faq-lite/references.html#faq-8.6

Jenkins not executing jobs (pending - waiting for next executor)

In my case, I had just installed the "Authorize Project" plugin and incorrectly setup the strategy in "Manage Jenkins -> Configure Global Security -> Access Control for Builds" as "Run as anonymous". So 'anonymous' had no rights to execute the job.

Setting the first strategy as "Run as User who Triggered Build" unlocked the queued jobs.

How to get a specific output iterating a hash in Ruby?

You can also refine Hash::each so it will support recursive enumeration. Here is my version of Hash::each(Hash::each_pair) with block and enumerator support:

module HashRecursive
    refine Hash do
        def each(recursive=false, &block)
            if recursive
                Enumerator.new do |yielder|
                    self.map do |key, value|
                        value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
                        yielder << [[key], value]
                    end
                end.entries.each(&block)
            else
                super(&block)
            end
        end
        alias_method(:each_pair, :each)
    end
end

using HashRecursive

Here are usage examples of Hash::each with and without recursive flag:

hash = {
    :a => {
        :b => {
            :c => 1,
            :d => [2, 3, 4]
        },
        :e => 5
    },
    :f => 6
}

p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2

p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6

hash.each do |key, value|
    puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6

hash.each(true) do |key, value|
    puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6

hash.each_pair(recursive=true) do |key, value|
    puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6

Here is example from the question itself:

hash = {
    1   =>  ["a", "b"], 
    2   =>  ["c"], 
    3   =>  ["a", "d", "f", "g"], 
    4   =>  ["q"]
}

hash.each(recursive=false) do |key, value|
    puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]

Also take a look at my recursive version of Hash::merge(Hash::merge!) here.

Best/Most Comprehensive API for Stocks/Financial Data

Yahoo's api provides a CSV dump:

Example: http://finance.yahoo.com/d/quotes.csv?s=msft&f=price

I'm not sure if it is documented or not, but this code sample should showcase all of the features (namely the stat types [parameter f in the query string]. I'm sure you can find documentation (official or not) if you search for it.

http://www.goldb.org/ystockquote.html

Edit

I found some unofficial documentation:

http://ilmusaham.wordpress.com/tag/stock-yahoo-data/

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

Pip install - Python 2.7 - Windows 7

This is one way of installing pip on a Windows system.

  1. Download the "get-pip" python script from here: https://bootstrap.pypa.io/get-pip.py

  2. Save the file as getpip.py

  3. Run it from cmd: python getpip.py install

Apple Cover-flow effect using jQuery or other library?

This one looks really promising, and closer to the actual Apple coverflow effect than the other examples:

blarnee.com/projects/cflow

Read a file in Node.js

var fs = require('fs');
var path = require('path');

exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = +process.env.NODE_COMMON_PORT || 12346;

// Read File
fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) {
  if (err) {
    got_error = true;
  } else {
    console.log('cat returned some content: ' + content);
    console.log('this shouldn\'t happen as the file doesn\'t exist...');
    //assert.equal(true, false);
  }
});

Cannot simply use PostgreSQL table name ("relation does not exist")

Put the dbname parameter in your connection string. It works for me while everything else failed.

Also when doing the select, specify the your_schema.your_table like this:

select * from my_schema.your_table

.htaccess deny from all

A little alternative to @gasp´s answer is to simply put the actual domain name you are running it from. Docs: https://httpd.apache.org/docs/2.4/upgrading.html

In the following example, there is no authentication and all hosts in the example.org domain are allowed access; all other hosts are denied access.

Apache 2.2 configuration:

Order Deny,Allow
Deny from all
Allow from example.org

Apache 2.4 configuration:

Require host example.org

How can I add a box-shadow on one side of an element?

This could be a simple way

border-right : 1px solid #ddd;
height:85px;    
box-shadow : 10px 0px 5px 1px #eaeaea;

Assign this to any div

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How can I get CMake to find my alternative Boost installation?

After digging around in CMake and experimenting, I determined that CMake was unhappy with the fact that all of my Boost libraries were contained in /usr/local/lib/boost and not /usr/local/lib. Once I soft-linked them back out, the build worked.

What does "var" mean in C#?

"var" means the compiler will determine the explicit type of the variable, based on usage. For example,

var myVar = new Connection();

would give you a variable of type Connection.

HTML if image is not found

For the alternative, if the image doesn't exist - show nothing at all. (what I was looking for)

You can swap the function from Robby Shaw's answer in the "onerror" attribute to "this.remove()".

_x000D_
_x000D_
<img id="currentPhoto" src="SomeImage.jpg" alt='1' width="100" height="120">_x000D_
<img id="currentPhoto" src="SomeImage.jpg" onerror="this.onerror=null; this.remove();" alt="2" width="100" height="120">
_x000D_
_x000D_
_x000D_

PHP Echo text Color

How about writing out some HTML tags and some CSS if you're outputting this to the browser?

echo '<span style="color:#AFA;text-align:center;">Request has been sent. Please wait for my reply!</span>';

Won't work from console though, only through browser.

Detect if an element is visible with jQuery

if($('#testElement').is(':visible')){
    //what you want to do when is visible
}

Difference between .on('click') vs .click()

As mentioned by the other answers:

$("#whatever").click(function(){ });
// is just a shortcut for
$("#whatever").on("click", function(){ })

Noting though that .on() supports several other parameter combinations that .click() doesn't, allowing it to handle event delegation (superceding .delegate() and .live()).

(And obviously there are other similar shortcut methods for "keyup", "focus", etc.)

The reason I'm posting an extra answer is to mention what happens if you call .click() with no parameters:

$("#whatever").click();
// is a shortcut for
$("#whatever").trigger("click");

Noting that if you use .trigger() directly you can also pass extra parameters or a jQuery event object, which you can't do with .click().

I also wanted to mention that if you look at the jQuery source code (in jquery-1.7.1.js) you'll see that internally the .click() (or .keyup(), etc.) function will actually call .on() or .trigger(). Obviously this means you can be assured that they really do have the same result, but it also means that using .click() has a tiny bit more overhead - not anything to worry or even think about in most circumstances, but theoretically it might matter in extraordinary circumstances.

EDIT: Finally, note that .on() allows you to bind several events to the same function in one line, e.g.:

$("#whatever").on("click keypress focus", function(){});

How To Run PHP From Windows Command Line in WAMPServer

In windows, put your php.exe file in windows/system32 or any other system executable folders and then go to command line and type php and hit enter following it, if it doesnt generate any error then you are ready to use PHP on command line. If you have set your php.exe somewhere else than default system folders then you need to set the path of it in the environment variables! You can get there in following path....

control panel -> System -> Edith the environment variables of your account -> Environment Vaiables -> path -> edit then set the absolute path of your php.exe there and follow the same procedure as in first paragraph, if nothing in the error department, then you are ready to use php from command line!

General error: 1364 Field 'user_id' doesn't have a default value

So, after After reviewing the code again, I found the error. I am wondering how no one notice that! In the above code I wrote

Post::create(request([  // <= the error is Here!!!
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => auth()->id()
]));

actually, there is no need for the request function warping the body of the create function.

// this is right
Post::create([
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => auth()->id()
]);

Converts scss to css

If you click on the title CSS (SCSS) in CodePen (don't change the pre-processor with the gear) it will switch to the compiled CSS view.

Codepen Screenshot of Compiled Preview

What is the difference between & and && in Java?

It depends on the type of the arguments...

For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.

For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.

For all other argument types and combinations, a compile-time error should occur.

onclick open window and specific size

window.open('http://somelocation.com','mywin','width=500,height=500');

CSS show div background image on top of other contained elements

I would put an absolutely positioned, z-index: 100; span (or spans) with the background: url("myImageWithRoundedCorners.jpg"); set on it inside the #mainWrapperDivWithBGImage .

How can I change the current URL?

If you just want to update the relative path you can also do

window.location.pathname = '/relative-link'

"http://domain.com" -> "http://domain.com/relative-link"

Create a string with n characters

My contribution based on the algorithm for fast exponentiation.

/**
 * Repeats the given {@link String} n times.
 * 
 * @param str
 *            the {@link String} to repeat.
 * @param n
 *            the repetition count.
 * @throws IllegalArgumentException
 *             when the given repetition count is smaller than zero.
 * @return the given {@link String} repeated n times.
 */
public static String repeat(String str, int n) {
    if (n < 0)
        throw new IllegalArgumentException(
                "the given repetition count is smaller than zero!");
    else if (n == 0)
        return "";
    else if (n == 1)
        return str;
    else if (n % 2 == 0) {
        String s = repeat(str, n / 2);
        return s.concat(s);
    } else
        return str.concat(repeat(str, n - 1));
}

I tested the algorithm against two other approaches:

  • Regular for loop using String.concat() to concatenate string
  • Regular for loop using a StringBuilder

Test code (concatenation using a for loop and String.concat() becomes to slow for large n, so I left it out after the 5th iteration).

/**
 * Test the string concatenation operation.
 * 
 * @param args
 */
public static void main(String[] args) {
    long startTime;
    String str = " ";

    int n = 1;
    for (int j = 0; j < 9; ++j) {
        n *= 10;
        System.out.format("Performing test with n=%d\n", n);

        startTime = System.currentTimeMillis();
        StringUtil.repeat(str, n);
        System.out
                .format("\tStringUtil.repeat() concatenation performed in    %d milliseconds\n",
                        System.currentTimeMillis() - startTime);

        if (j <5) {
            startTime = System.currentTimeMillis();
            String string = "";
            for (int i = 0; i < n; ++i)
                string = string.concat(str);
            System.out
                    .format("\tString.concat() concatenation performed in        %d milliseconds\n",
                            System.currentTimeMillis() - startTime);
        } else
            System.out
                    .format("\tString.concat() concatenation performed in        x milliseconds\n");
        startTime = System.currentTimeMillis();
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < n; ++i)
            b.append(str);
        b.toString();
        System.out
                .format("\tStringBuilder.append() concatenation performed in %d milliseconds\n",
                        System.currentTimeMillis() - startTime);
    }
}

Results:

Performing test with n=10
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        0 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=100
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=1000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=10000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        43 milliseconds
    StringBuilder.append() concatenation performed in 5 milliseconds
Performing test with n=100000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1579 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=1000000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 10 milliseconds
Performing test with n=10000000
    StringUtil.repeat() concatenation performed in    7 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 112 milliseconds
Performing test with n=100000000
    StringUtil.repeat() concatenation performed in    80 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 1107 milliseconds
Performing test with n=1000000000
    StringUtil.repeat() concatenation performed in    1372 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 12125 milliseconds

Conclusion:

  • For large n - use the recursive approach
  • For small n - for loop has sufficient speed

Safari 3rd party cookie iframe trick no longer working?

You said you were willing to have your users click a button before the content loads. My solution was to have a button open a new browser window. That window sets a cookie for my domain, refreshes the opener and then closes.

So your main script could look like:

<?php if(count($_COOKIE) > 0): ?>
<!--Main Content Stuff-->
<?php else: ?>
<a href="/safari_cookie_fix.php" target="_blank">Click here to load content</a>
<?php endif ?>

Then safari_cookie_fix.php looks like:

<?php
setcookie("safari_test", "1");
?>
<html>
    <head>
        <title>Safari Fix</title>
        <script type="text/javascript" src="/libraries/prototype.min.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    document.observe('dom:loaded', function(){
        window.opener.location.reload();
        window.close();
    })
    </script>
    This window should close automatically
    </body>
</html>

How to get all of the immediate subdirectories in Python

os.walk is your friend in this situation.

Straight from the documentation:

walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

What does git push -u mean?

This is no longer up-to-date!

Push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.

Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.

What does file:///android_asset/www/index.html mean?

If someone uses AndroidStudio make sure that the assets folder is placed in

  1. app/src/main/assets

    directory.

How to create dispatch queue in Swift 3

Compiles under >=Swift 3. This example contains most of the syntax that we need.

QoS - new quality of service syntax

weak self - to disrupt retain cycles

if self is not available, do nothing

async global utility queue - for network query, does not wait for the result, it is a concurrent queue, the block (usually) does not wait when started. Exception for a concurrent queue could be, when its task limit has been previously reached, then the queue temporarily turns into a serial queue and waits until some previous task in that queue completes.

async main queue - for touching the UI, the block does not wait for the result, but waits for its slot at the start. The main queue is a serial queue.

Of course, you need to add some error checking to this...

DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in

    guard let strongSelf = self else { return }

    strongSelf.flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in

        if error != nil {
            print("error:\(error)")
        } else {
            DispatchQueue.main.async { () -> Void in
                activityIndicator.removeFromSuperview()
                strongSelf.imageView.image = strongSelf.flickrPhoto.largeImage
            }
        }
    }
}

Matrix Multiplication in pure Python?

All the below answers would return you the list.Your need to convert it to matrix

def MATMUL(X, Y):
    rows_A = len(X)
    cols_A = len(X[0])
    rows_B = len(Y)
    cols_B = len(Y[0])

    if cols_A != rows_B:
        print "Matrices are not compatible to Multiply. Check condition C1==R2"
        return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]

    C = numpy.matrix(C).reshape(len(A),len(B[0]))

    return C

PDO closing connection

According to documentation you're correct (http://php.net/manual/en/pdo.connections.php):

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.

How to combine two vectors into a data frame

Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.

myfunc <- function(a, b, names = NULL) {
  setNames(data.frame(c(rep(deparse(substitute(a)), length(a)), 
                        rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}

An example:

x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"

myfunc(x, y, c(x_name, y_name))

  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300

Apache SSL Configuration Error (SSL Connection Error)

It turns out that the SSL certificate was installed improperly. Re-installing it properly fixed the problem

How do I change the hover over color for a hover over table in Bootstrap?

Give this a try:

.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
  background-color: #color;
}

OpenSSL and error in reading openssl.conf file

The problem here is that there ISN'T an openssl.cnf file given with the GnuWin32 openssl stuff. You have to create it. You can find out HOW to create an openssl.cnf file by going here:

http://www.flatmtn.com/article/setting-ssl-certificates-apache

Where it lays it all out for you on how to do it.

PLEASE NOTE: The openssl command given with the backslash at the end is for UNIX. For Windows : 1)Remove the backslash, and 2)Move the second line up so it is at the end of the first line. (So you get just one command.)

ALSO: It is VERY important to read through the comments. There are some changes you might want to make based upon them.

Sending emails through SMTP with PHPMailer

As far as I can see everything is right with your code. Your error is:

SMTP Error: Could not authenticate.

Which means that the credentials you've sending are rejected by the SMTP server. Make sure the host, port, username and password are good.

If you want to use STARTTLS, try adding:

$mail->SMTPSecure = 'tls';

If you want to use SMTPS (SSL), try adding:

$mail->SMTPSecure = 'ssl';

Keep in mind that:

  • Some SMTP servers can forbid connections from "outsiders".
  • Some SMTP servers don't support SSL (or TLS) connections.

Maybe this example can help (GMail secure SMTP).

[Source]

Git pull - Please move or remove them before you can merge

Apparently the files were added in remote repository, no matter what was the content of .gitignore file in the origin.

As the files exist in the remote repository, git has to pull them to your local work tree as well and therefore complains that the files already exist.

.gitignore is used only for scanning for the newly added files, it doesn't have anything to do with the files which were already added.

So the solution is to remove the files in your work tree and pull the latest version. Or the long-term solution is to remove the files from the repository if they were added by mistake.

A simple example to remove files from the remote branch is to

$git checkout <brachWithFiles>
$git rm -r *.extension
$git commit -m "fixin...."
$git push

Then you can try the $git merge again

Where is `%p` useful with printf?

They do not do the same thing. The latter printf statement interprets b as an unsigned int, which is wrong, as b is a pointer.

Pointers and unsigned ints are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems become more common), %x will only print half of the address. On a Mac (and probably some other systems), that will ruin the address; the output will be wrong.

Always use %p for pointers.

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

React won't load local images

When using Webpack you need to require images in order for Webpack to process them, which would explain why external images load while internal do not, so instead of <img src={"/images/resto.png"} /> you need to use <img src={require('/images/image-name.png')} /> replacing image-name.png with the correct image name for each of them. That way Webpack is able to process and replace the source img.

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Please use test flight to obtain UDID from testers but not using untrusted source e.g. http://get.udid.io/

You can 1. Invite testers in email from test flight webpage. Testers open the link in email and install a profile from test flight. Therefore developers can obtain UDIDs on the test flight webpage. 2. Add those UDIDs on the Apple provisioning portal.

(Ref: http://help.testflightapp.com/customer/portal/articles/829537-how-does-it-work-)

The process doesn't require testers to use Mac/ PC to obtain UDID (more convenient). And I think test flight is a company that can be trusted (no worries when passing UDID to this company).

I have tested this method and it works on iOS 8.

Media Queries - In between two widths

_x000D_
_x000D_
.class {_x000D_
    display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
    .class {_x000D_
        display: block; /* just an example display property */_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How can I compile a Java program in Eclipse without running it?

Right click on Yourproject(in project Explorer)-->Build Project

It will compile all files in your project and updates your build folder, all without running.

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

remove table row with specific id

Remove by id -

$("#3").remove();

Also I would suggest to use better naming, like row-1, row-2

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

How do Mockito matchers work?

Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);

is the order that ensures the (probably) desired result:

foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false

If you inverse the when calls then the result would always be true.

How to fetch the row count for all tables in a SQL SERVER database

I would make a minor change to Frederik's solution. I would use the sp_spaceused system stored procedure which will also include data and index sizes.


declare c_tables cursor fast_forward for 
select table_name from information_schema.tables 

open c_tables 
declare @tablename varchar(255) 
declare @stmt nvarchar(2000) 
declare @rowcount int 
fetch next from c_tables into @tablename 

while @@fetch_status = 0 
begin 

    select @stmt = 'sp_spaceused ' + @tablename 

    exec sp_executesql @stmt

    fetch next from c_tables into @tablename 

end 

close c_tables 
deallocate c_tables 

How to clear the Entry widget after a button is pressed in Tkinter?

You shall proceed with ent.delete(0,"end") instead of using 'END', use 'end' inside quotation.

 secret = randrange(1,100)
print(secret)
def res(real, secret):
    if secret==eval(real):
        showinfo(message='that is right!')
    real.delete(0, END)

def guess():
    ge = Tk()
    ge.title('guessing game')

    Label(ge, text="what is your guess:").pack(side=TOP)

    ent = Entry(ge)
    ent.pack(side=TOP)

    btn=Button(ge, text="Enter", command=lambda: res(ent.get(),secret))
    btn.pack(side=LEFT)

    ge.mainloop()

This shall solve your problem

How do I do an initial push to a remote repository with Git?

If your project doesn't have an upstream branch, that is if this is the very first time the remote repository is going to know about the branch created in your local repository the following command should work.

git push --set-upstream origin <branch-name>

Set style for TextView programmatically

I met the problem too, and I found the way to set style programatically. Maybe you all need it, So I update there.

The third param of View constructor accepts a type of attr in your theme as the source code below:

public TextView(Context context, AttributeSet attrs) {
    this(context, attrs, com.android.internal.R.attr.textViewStyle);
}

So you must pass a type of R.attr.** rather than R.style.**

In my codes, I did following steps:

First, customize a customized attr to be used by themes in attr.xml.

<attr name="radio_button_style" format="reference" />

Second, specific your style in your used theme in style.xml.

 <style name="AppTheme" parent="android:Theme.Translucent">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="radio_button_style">@style/radioButtonStyle</item>
</style>
<style name="radioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">64dp</item>
    <item name="android:background">#000</item>
    <item name="android:button">@null</item>
    <item name="android:gravity">center</item>
    <item name="android:saveEnabled">false</item>
    <item name="android:textColor">@drawable/option_text_color</item>
    <item name="android:textSize">9sp</item>
</style>

At the end, use it!

            RadioButton radioButton = new RadioButton(mContext, null, R.attr.radio_button_style);

the view created programatically will use the specified style in your theme.

You can have a try, and hope it can work for you perfectly.

How do I change the number of open files limit in Linux?

If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting

[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread

Try to put ulimit -s unlimited into /etc/init.d/httpd. This does not require a server reboot.

Control the size of points in an R scatterplot?

Try the cex argument:

?par

  • cex
    A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. Note that some graphics functions such as plot.default have an argument of this name which multiplies this graphical parameter, and some functions such as points accept a vector of values which are recycled. Other uses will take just the first value if a vector of length greater than one is supplied.

Get host domain from URL?

WWW is an alias, so you don't need it if you want a domain. Here is my litllte function to get the real domain from a string

private string GetDomain(string url)
    {
        string[] split = url.Split('.');
        if (split.Length > 2)
            return split[split.Length - 2] + "." + split[split.Length - 1];
        else
            return url;

    }

Invert match with regexp

It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*

Using Server.MapPath in external C# Classes in ASP.NET

The server.mappath("") will work on aspx page,if you want to get the absolute path from a class file you have to use this-

HttpContext.Current.Server.MapPath("~/EmailLogic/RegistrationTemplate.html")

maxReceivedMessageSize and maxBufferSize in app.config

Easy solution: Check if it works for you..

Goto web.config

Find binding used by client.

change as,

maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"

Done.

How to change the name of an iOS app?

If you want to change display name only then you can directly change from property file(plist) of app.

You can add a new row with the following key : bundle display name

Here is an example for this

enter image description here

When you use this the app name which you have given with this key will be display.

So you can do this simply.

Input type "number" won't resize

Rather than set the length, set the max and min values for the number input.

The input box then resizes to fit the longest valid value.

If you want to allow a 3-digit number then set 999 as the max

 <input type="number" name="quantity" min="0" max="999">

Android: How can I pass parameters to AsyncTask's onPreExecute()?

You can either pass the parameter in the task constructor or when you call execute:

AsyncTask<Object, Void, MyTaskResult>

The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).

public class MyActivity extends AppCompatActivity {

    TextView textView1;
    TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);    
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

        String input1 = "test";
        boolean input2 = true;
        int input3 = 100;
        long input4 = 100000000;

        new MyTask(input3, input4).execute(input1, input2);
    }

    private class MyTaskResult {
        String text1;
        String text2;
    }

    private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
        private String val1;
        private boolean val2;
        private int val3;
        private long val4;


        public MyTask(int in3, long in4) {
            this.val3 = in3;
            this.val4 = in4;

            // Do something ...
        }

        protected void onPreExecute() {
            // Do something ...
        }

        @Override
        protected MyTaskResult doInBackground(Object... params) {
            MyTaskResult res = new MyTaskResult();
            val1 = (String) params[0];
            val2 = (boolean) params[1];

            //Do some lengthy operation    
            res.text1 = RunProc1(val1);
            res.text2 = RunProc2(val2);

            return res;
        }

        @Override
        protected void onPostExecute(MyTaskResult res) {
            textView1.setText(res.text1);
            textView2.setText(res.text2);

        }
    }

}

How do I deploy Node.js applications as a single executable file?

First, we're talking about packaging a Node.js app for workshops, demos, etc. where it can be handy to have an app "just running" without the need for the end user to care about installation and dependencies.

You can try the following setup:

  1. Get your apps source code
  2. npm install all dependencies (via package.json) to the local node_modules directory. It is important to perform this step on each platform you want to support separately, in case of binary dependencies.
  3. Copy the Node.js binary – node.exe on Windows, (probably) /usr/local/bin/node on OS X/Linux to your project's root folder. On OS X/Linux you can find the location of the Node.js binary with which node.

For Windows:
Create a self extracting archive, 7zip_extra supports a way to execute a command right after extraction, see: http://www.msfn.org/board/topic/39048-how-to-make-a-7-zip-switchless-installer/.

For OS X/Linux:
You can use tools like makeself or unzipsfx (I don't know if this is compiled with CHEAP_SFX_AUTORUN defined by default).

These tools will extract the archive to a temporary directory, execute the given command (e.g. node app.js) and remove all files when finished.

How to modify a text file?

Python's mmap module will allow you to insert into a file. The following sample shows how it can be done in Unix (Windows mmap may be different). Note that this does not handle all error conditions and you might corrupt or lose the original file. Also, this won't handle unicode strings.

import os
from mmap import mmap

def insert(filename, str, pos):
    if len(str) < 1:
        # nothing to insert
        return

    f = open(filename, 'r+')
    m = mmap(f.fileno(), os.path.getsize(filename))
    origSize = m.size()

    # or this could be an error
    if pos > origSize:
        pos = origSize
    elif pos < 0:
        pos = 0

    m.resize(origSize + len(str))
    m[pos+len(str):] = m[pos:origSize]
    m[pos:pos+len(str)] = str
    m.close()
    f.close()

It is also possible to do this without mmap with files opened in 'r+' mode, but it is less convenient and less efficient as you'd have to read and temporarily store the contents of the file from the insertion position to EOF - which might be huge.

How to set Grid row and column positions programmatically

For attached properties you can either call SetValue on the object for which you want to assign the value:

tblock.SetValue(Grid.RowProperty, 4);

Or call the static Set method (not as an instance method like you tried) for the property on the owner type, in this case SetRow:

Grid.SetRow(tblock, 4);

HTML list-style-type dash

Instead of using lu li, used dl (definition list) and dd. <dd> can be defined using standard css style such as {color:blue;font-size:1em;} and use as marker whatever symbol you place after the html tag. It works like ul li, but allows you to use any symbol, you just have to indent it to get the indented list effect you normally get with ul li.

CSS:
dd{text-indent:-10px;}

HTML
<dl>
<dd>- One</dd>
<dd>- Two</dd>
<dd>- Three</dd></dl>

Gives you much cleaner code! That way, you could use any type of character as marker! Indent is of about -10px and it works perfect!

How to get response from S3 getObject in Node.js?

When doing a getObject() from the S3 API, per the docs the contents of your file are located in the Body property, which you can see from your sample output. You should have code that looks something like the following

const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary

var getParams = {
    Bucket: 'abc', // your bucket name,
    Key: 'abc.txt' // path to the object you're looking for
}

s3.getObject(getParams, function(err, data) {
    // Handle any error and exit
    if (err)
        return err;

  // No error happened
  // Convert Body from a Buffer to a String

  let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});

You may not need to create a new buffer from the data.Body object but if you need you can use the sample above to achieve that.

Format Float to n decimal places

You can use Decimal format if you want to format number into a string, for example:

String a = "123455";
System.out.println(new 
DecimalFormat(".0").format(Float.valueOf(a)));

The output of this code will be:

123455.0

You can add more zeros to the decimal format, depends on the output that you want.

Swift: print() vs println() vs NSLog()

To add to Rob's answer, since iOS 10.0, Apple has introduced an entirely new "Unified Logging" system that supersedes existing logging systems (including ASL and Syslog, NSLog), and also surpasses existing logging approaches in performance, thanks to its new techniques including log data compression and deferred data collection.

From Apple:

The unified logging system provides a single, efficient, performant API for capturing messaging across all levels of the system. This unified system centralizes the storage of log data in memory and in a data store on disk.

Apple highly recommends using os_log going forward to log all kinds of messages, including info, debug, error messages because of its much improved performance compared to previous logging systems, and its centralized data collection allowing convenient log and activity inspection for developers. In fact, the new system is likely so low-footprint that it won't cause the "observer effect" where your bug disappears if you insert a logging command, interfering the timing of the bug to happen.

Performance of Activity Tracing, now part of the new Unified Logging system

You can learn more about this in details here.

To sum it up: use print() for your personal debugging for convenience (but the message won't be logged when deployed on user devices). Then, use Unified Logging (os_log) as much as possible for everything else.

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

There are chances that you might end up with Scientific Number when you convert Integer to Str... safer way is

SET @ActualWeightDIMS = STR(@Actual_Dims_Width); OR Select STR(@Actual_Dims_Width) + str(@Actual_Dims_Width)

How can I change the text color with jQuery?

Place the following in your jQuery mouseover event handler:

$(this).css('color', 'red');

To set both color and size at the same time:

$(this).css({ 'color': 'red', 'font-size': '150%' });

You can set any CSS attribute using the .css() jQuery function.

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?

There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.

Socket.io + Node.js Cross-Origin Request Blocked

I had the same problem and any solution worked for me.

The cause was I am using allowRequest to accept or reject the connection using a token I pass in a query parameter.

I have a typo in the query parameter name in the client side, so the connection was always rejected, but the browser complained about cors...

As soon as I fixed the typo, it started working as expected, and I don't need to use anything extra, the global express cors settings is enough.

So, if anything is working for you, and you are using allowRequest, check that this function is working properly, because the errors it throws shows up as cors errors in the browser. Unless you add there the cors headers manually when you want to reject the connection, I guess.

How to check if a socket is connected/disconnected in C#?

As Alexander Logger pointed out in zendars answer, you have to send something to be completely sure. In case your connected partner does not read on this socket at all, you can use the following code.

bool SocketConnected(Socket s)
{
  // Exit if socket is null
  if (s == null)
    return false;
  bool part1 = s.Poll(1000, SelectMode.SelectRead);
  bool part2 = (s.Available == 0);
  if (part1 && part2)
    return false;
  else
  {
    try
    {
      int sentBytesCount = s.Send(new byte[1], 1, 0);
      return sentBytesCount == 1;
    }
    catch
    {
      return false;
    }
  }
}

But even then it might take a few seconds until a broken network cable or something similar is detected.

Wait until page is loaded with Selenium WebDriver for Python

You can do that very simple by this function:

def page_is_loading(driver):
    while True:
        x = driver.execute_script("return document.readyState")
        if x == "complete":
            return True
        else:
            yield False

and when you want do something after page loading complete,you can use:

Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')
Driver.get("https://www.google.com/")

while not page_is_loading(Driver):
    continue

Driver.execute_script("alert('page is loaded')")

Keyboard shortcut to change font size in Eclipse?

The Eclipse-Fonts extension will add toolbar buttons and keyboard shortcuts for changing font size. You can then use AutoHotkey to make Ctrl+Mousewheel zoom.

Under Help | Install New Software... in the menu, paste the update URL (http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/) into the Works with: text box and press Enter. Expand the tree and select FontsFeature as in the following image:

Eclipse extension installation screen capture

Complete the installation and restart Eclipse, then you should see the A toolbar buttons (circled in red in the following image) and be able to use the keyboard shortcuts Ctrl+- and Ctrl+= to zoom (although you may have to unbind those keys from Eclipse first).

Eclipse screen capture with the font size toolbar buttons circled

To get Ctrl+MouseWheel zooming, you can use AutoHotkey with the following script:

; Ctrl+MouseWheel zooming in Eclipse.
; Requires Eclipse-Fonts (https://code.google.com/p/eclipse-fonts/).
; Thank you for the unique window class, SWT/Eclipse.
#IfWinActive ahk_class SWT_Window0
    ^WheelUp:: Send ^{=}
    ^WheelDown:: Send ^-
#IfWinActive

Convert long/lat to pixel x/y on a given picture

my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823

error: Error parsing XML: not well-formed (invalid token) ...?

I had this problem, and when I had android:text="< Go back" it had the correct syntax highlighting, but then I realized it's the < symbol that is messing everything up.

How do I use MySQL through XAMPP?

Changing XAMPP Default Port: If you want to get XAMPP up and running, you should consider changing the port from the default 80 to say 7777.

  • In the XAMPP Control Panel, click on the Apache – Config button which is located next to the ‘Logs’ button.

  • Select ‘Apache (httpd.conf)’ from the drop down. (Notepad should open)

  • Do Ctrl+F to find ’80’ and change line Listen 80 to Listen 7777

  • Find again and change line ServerName localhost:80 to ServerName localhost:7777

  • Save and re-start Apache. It should be running by now.

The only demerit to this technique is, you have to explicitly include the port number in the localhost url. Rather than http://localhost it becomes http://localhost:7777.

Replace image src location using CSS

Here is another dirty hack :)

.application-title > img {
display: none;
}

.application-title::before {
content: url(path/example.jpg);
}

How to set an HTTP proxy in Python 2.7?

cd C:\Python34\Scripts

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

pip.exe install PackageName

Delete from a table based on date

Delete data that is 30 days and older

   DELETE FROM Table
   WHERE DateColumn < GETDATE()- 30

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

I used all above changes but still I was getting same issue on my web application.

Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.

They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.

Hope this answer will help someone.This is what worked for me

Clear screen in shell

import os

os.system('cls')  # For Windows
os.system('clear')  # For Linux/OS X

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

ExtJs Gridpanel store refresh

Combination of Dasha's and MMT solutions:

  Ext.getCmp('yourGridId').getView().ds.reload();

How to see docker image contents

To list the detailed content of an image you have to run docker run --rm image/name ls -alR where --rm means remove as soon as exits form a container.

enter image description here

I need to get all the cookies from the browser

You cannot. By design, for security purpose, you can access only the cookies set by your site. StackOverflow can't see the cookies set by UserVoice nor those set by Amazon.

Create Django model or update if exists

This should be the answer you are looking for

EmployeeInfo.objects.update_or_create(
    #id or any primary key:value to search for
    identifier=your_id, 
    #if found update with the following or save/create if not found
    defaults={'name':'your_name'}
)

How to Set a Custom Font in the ActionBar Title?

No custom textview is required!

First, disable the title in the toobar in your java code : getSupportActionBar().setDisplayShowTitleEnabled(false);

Then, simply add a TextView inside the toolbar :

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textSize="18sp"
        android:fontFamily="@font/roboto" />

    </android.support.v7.widget.Toolbar>

React - Component Full Screen (with height 100%)

You could also do:

body > #root > div {
  height: 100vh;
}

Select elements by attribute

if (!$("#element").attr('my_attr')){
  //return false
  //attribute doesn't exists
}

Java: how to use UrlConnection to post request with authorization?

A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.

Below is the code to do that,

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty ("Authorization", encodedCredentials);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(data);
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new 
                                     InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

Change URLConnection to HttpURLConnection, to make it POST request.

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

Suggestion (...in comments):

You might need to set these properties too,

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );

What is the difference between print and puts?

If you would like to output array within string using puts, you will get the same result as if you were using print:

puts "#{[0, 1, nil]}":
[0, 1, nil]

But if not withing a quoted string then yes. The only difference is between new line when we use puts.