Programs & Examples On #Stlport

Can't include C++ headers like vector in Android NDK

If you are using ndk r10c or later, simply add APP_STL=c++_static to Application.mk

Get the Year/Month/Day from a datetime in php?

Check out the manual: http://www.php.net/manual/en/datetime.format.php

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Will output: 2000-01-01 00:00:00

Grouping switch statement cases together?

If you're willing to go the way of the preprocessor abuse, Boost.Preprocessor can help you.

    #include <boost/preprocessor/seq/for_each.hpp>

    #define CASE_case(ign, ign2, n) case n:

    #define CASES(seq) \
        BOOST_PP_SEQ_FOR_EACH(CASE_case, ~, seq)

    CASES((1)(3)(15)(13))

Running this through gcc with -E -P to only run the preprocessor, the expansion of CASES gives:

    case 1: case 3: case 15: case 13:

Note that this probably wouldn't pass a code review (wouldn't where I work!) so I recommend it be constrained to personal use.

It should also be possible to create a CASE_RANGE(1,5) macro to expand to

    case 1: case 2: case 3: case 4: case 5:

for you as well.

What's the difference between RANK() and DENSE_RANK() functions in oracle?

Rank and Dense rank gives the rank in the partitioned dataset.

Rank() : It doesn't give you consecutive integer numbers.

Dense_rank() : It gives you consecutive integer numbers.

enter image description here

In above picture , the rank of 10008 zip is 2 by dense_rank() function and 24 by rank() function as it considers the row_number.

Example on ToggleButton

Try this Toggle Buttons

test_activity.xml

<ToggleButton 
android:id="@+id/togglebutton" 
android:layout_width="100px" 
android:layout_height="50px" 
android:layout_centerVertical="true" 
android:layout_centerHorizontal="true"
android:onClick="toggleclick"/>

Test.java

public class Test extends Activity {

private ToggleButton togglebutton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
}

public void toggleclick(View v){
    if(togglebutton.isChecked())
        Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();
    }
}

GridView - Show headers on empty data source

ASP.Net 4.0 added the boolean ShowHeaderWhenEmpty property.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.showheaderwhenempty.aspx


<asp:GridView runat="server" ID="GridView1" ShowHeaderWhenEmpty="true" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField HeaderText="First Name" DataField="FirstName" />
        <asp:BoundField HeaderText="Last Name" DataField="LastName" />
    </Columns>
</asp:GridView>

Note: the headers will not appear unless DataBind() is called with something other than null.

GridView1.DataSource = New List(Of String)
GridView1.DataBind()

"implements Runnable" vs "extends Thread" in Java

The simplest explanation would be by implementing Runnable we can assign the same object to multiple threads and each Thread shares the same object states and behavior.

For example, suppose there are two threads, thread1 puts an integer in an array and thread2 takes integers from the array when the array is filled up. Notice that in order for thread2 to work it needs to know the state of array, whether thread1 has filled it up or not.

Implementing Runnable lets you to have this flexibility to share the object whereas extends Thread makes you to create new objects for each threads therefore any update that is done by thread1 is lost to thread2.

add an element to int [] array in java

public int[] return_Array() {

int[] a =new int[10];   
int b = 25;
for(int i=0; i<10; i++) {               
    a[i] = b * i;
    }
return a;

}

How to return a boolean method in java?

You're allowed to have more than one return statement, so it's legal to write

if (some_condition) {
  return true;
}
return false;

It's also unnecessary to compare boolean values to true or false, so you can write

if (verifyPwd())  {
  // do_task
}

Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.

boolean success = true;

if (some_condition) {
  // Handle the condition.
  success = false;
} else if (some_other_condition) {
  // Handle the other condition.
  success = false;
}
if (another_condition) {
  // Handle the third condition.
}

// Do some more critical things.

return success;

Restart pods when configmap updates in Kubernetes?

You can update a metadata annotation that is not relevant for your deployment. it will trigger a rolling-update

for example:

    spec:
      template:
        metadata:
          annotations:
            configmap-version: 1

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can customize the JsonSerializerSettings by using the Formatters.JsonFormatter.SerializerSettings property in the HttpConfiguration object.

For example, you could do that in the Application_Start() method:

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.Formatting =
        Newtonsoft.Json.Formatting.Indented;
}

ASP.NET Display "Loading..." message while update panel is updating

You can use code as below when

using Image as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

using Text as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

How can I list all collections in the MongoDB shell?

You can do...

JavaScript (shell):

db.getCollectionNames()

Node.js:

db.listCollections()

Non-JavaScript (shell only):

show collections

The reason I call that non-JavaScript is because:

$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell eval):1:5

$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
    "Profiles",
    "Unit_Info"
]

If you really want that sweet, sweet show collections output, you can:

$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info

SQL, Postgres OIDs, What are they and why are they useful?

To remove all OIDs from your database tables, you can use this Linux script:

First, login as PostgreSQL superuser:

sudo su postgres

Now run this script, changing YOUR_DATABASE_NAME with you database name:

for tbl in `psql -qAt -c "select schemaname || '.' || tablename from pg_tables WHERE schemaname <> 'pg_catalog' AND schemaname <> 'information_schema';" YOUR_DATABASE_NAME` ; do  psql -c "alter table $tbl SET WITHOUT OIDS" YOUR_DATABASE_NAME ; done

I used this script to remove all my OIDs, since Npgsql 3.0 doesn't work with this, and it isn't important to PostgreSQL anymore.

Resolve Git merge conflicts in favor of their changes during a pull

Please not that sometimes this will not work:

git checkout --ours path/to/file

or

git checkout --theirs path/to/file

I did this instead, assuming HEAD is ours and MERGE_HEAD is theirs

git checkout HEAD -- path/to/file

or:

git checkout MERGE_HEAD -- path/to/file

After we do this and we are good:

git add .

If you want to understand more, see wonderful post of torek here : git checkout --ours does not remove files from unmerged files list

ECONNREFUSED error when connecting to mongodb from node.js

you can go to mongoDB compass client and follow these steps: 1.Click Fill in connection fields individually: enter image description here

2.In hostname type : 127.0.0.1 enter image description here

3. Click CONNECT.

How do I catch a PHP fatal (`E_ERROR`) error?

Nice solution found in Zend Framework 2:

/**
 * ErrorHandler that can be used to catch internal PHP errors
 * and convert to an ErrorException instance.
 */
abstract class ErrorHandler
{
    /**
     * Active stack
     *
     * @var array
     */
    protected static $stack = array();

    /**
     * Check if this error handler is active
     *
     * @return bool
     */
    public static function started()
    {
        return (bool) static::getNestedLevel();
    }

    /**
     * Get the current nested level
     *
     * @return int
     */
    public static function getNestedLevel()
    {
        return count(static::$stack);
    }

    /**
     * Starting the error handler
     *
     * @param int $errorLevel
     */
    public static function start($errorLevel = \E_WARNING)
    {
        if (!static::$stack) {
            set_error_handler(array(get_called_class(), 'addError'), $errorLevel);
        }

        static::$stack[] = null;
    }

    /**
     * Stopping the error handler
     *
     * @param  bool $throw Throw the ErrorException if any
     * @return null|ErrorException
     * @throws ErrorException If an error has been catched and $throw is true
     */
    public static function stop($throw = false)
    {
        $errorException = null;

        if (static::$stack) {
            $errorException = array_pop(static::$stack);

            if (!static::$stack) {
                restore_error_handler();
            }

            if ($errorException && $throw) {
                throw $errorException;
            }
        }

        return $errorException;
    }

    /**
     * Stop all active handler
     *
     * @return void
     */
    public static function clean()
    {
        if (static::$stack) {
            restore_error_handler();
        }

        static::$stack = array();
    }

    /**
     * Add an error to the stack
     *
     * @param int    $errno
     * @param string $errstr
     * @param string $errfile
     * @param int    $errline
     * @return void
     */
    public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)
    {
        $stack = & static::$stack[count(static::$stack) - 1];
        $stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);
    }
}

This class allows you to start the specific ErrorHandler sometimes if you need it. And then you can also stop the Handler.

Use this class e.g. like this:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;

Link to the full class code:
https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ErrorHandler.php


A maybe better solution is that one from Monolog:

Link to the full class code:
https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php

It can also handle FATAL_ERRORS using the register_shutdown_function function. According to this class a FATAL_ERROR is one of the following array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR).

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}

Why can't radio buttons be "readonly"?

The best solution is to set the checked or unchecked state (either from client or server) and to not let the user change it after wards (i.e make it readonly) do the following:

<input type="radio" name="name" onclick="javascript: return false;" />

How to convert Excel values into buckets?

I use this trick for equal data bucketing. Instead of text result you get the number. Here is example for four buckets. Suppose you have data in A1:A100 range. Put this formula in B1:

=MAX(ROUNDUP(PERCENTRANK($A$1:$A$100,A1) *4,0),1)

Fill down the formula all across B column and you are done. The formula divides the range into 4 equal buckets and it returns the bucket number which the cell A1 falls into. The first bucket contains the lowest 25% of values.

Adjust the number of buckets according to thy wish:

=MAX(ROUNDUP(PERCENTRANK([Range],[OneCellOfTheRangeToTest]) *[NumberOfBuckets],0),1)

The number of observation in each bucket will be equal or almost equal. For example if you have a 100 observations and you want to split it into 3 buckets (like in your example) then the buckets will contain 33, 33, 34 observations. So almost equal. You do not have to worry about that - the formula works that out for you.

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


EDIT 2019:

The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

CREATE TABLE Source
(
  EmployeeID int,
  DateStarted date,
  DepartmentID int
)

INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)


SELECT *, 
  ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
  newid() as GroupKey,
  CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;

UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 GroupKey
    FROM #RankedData sub 
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID = sup.DepartmentID AND
      NOT EXISTS 
        (
          SELECT * 
          FROM #RankedData bot 
          WHERE bot.EmployeeID = sup.EmployeeID AND
            bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
            bot.DepartmentID <> sup.DepartmentID
        )
      ORDER BY DateStarted ASC
    ) beginDate (GroupKey);

UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 DateStarted
    FROM #RankedData sub
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID <> sup.DepartmentID AND
      sub.EntryRank > sup.EntryRank
    ORDER BY EntryRank ASC
  ) nextGroup (DateStarted);

SELECT * FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;

DROP TABLE #RankedData
DROP TABLE Source

web-api POST body object always null

Just one more thing to look at... my model was marked as [Serializable] and that was causing the failure.

addEventListener, "change" and option selection

The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.

function start(){
      document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
      }

function addActivityItem(){
      //option is selected
      alert("yeah");
}

window.addEventListener("load", start, false);

Android SQLite Example

The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

CHAR is a fixed-length data type that uses as much space as possible. So a:= a||'one '; will require more space than is available. Your problem can be reduced to the following example:

declare
  v_foo char(50);
begin
  v_foo := 'A';
  dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
  -- next line will raise:
  -- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
  v_foo := v_foo || 'B';
  dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));  
end;
/

Never use char. For rationale check the following question (read also the links):

Rounded table corners CSS only

The best solution I've found for rounded corners and other CSS3 behavior for IE<9 can be found here: http://css3pie.com/

Download the plug-in, copy to a directory in your solution structure. Then in your stylesheet make sure to have the behavior tag so that it pulls in the plug-in.

Simple example from my project which gives me rounded corners, color gradient, and box shadow for my table:

.table-canvas 
{
    -webkit-border-radius: 8px;
    -moz-border-radius: 8px;
    overflow:hidden;
    border-radius: 10px;
    -pie-background: linear-gradient(#ece9d8, #E5ECD8);   
    box-shadow: #666 0px 2px 3px;
    behavior: url(Include/PIE.htc);
    overflow: hidden;
}

Don't worry if your Visual Studio CSS intellisense gives you the green underline for unknown properites, it still works when you run it. Some of the elements are not very clearly documented, but the examples are pretty good, especially on the front page.

Using css transform property in jQuery

I started using the 'prefix-free' Script available at http://leaverou.github.io/prefixfree so I don't have to take care about the vendor prefixes. It neatly takes care of setting the correct vendor prefix behind the scenes for you. Plus a jQuery Plugin is available as well so one can still use jQuery's .css() method without code changes, so the suggested line in combination with prefix-free would be all you need:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

Adding a new SQL column with a default value

Try This :)

ALTER TABLE TABLE_NAME ADD COLUMN_NAME INT NOT NULL DEFAULT 0;

jQuery: serialize() form and other parameters

If you want to send data with form serialize you may try this

var form= $("#formId");
$.ajax({
    type: form.attr('method'),
    url: form.attr('action'),
    data: form.serialize()+"&variable="+otherData,
    success: function (data) {
    var result=data;
    $('#result').attr("value",result);

    }
});

Pandas read_csv from url

The problem you're having is that the output you get into the variable 's' is not a csv, but a html file. In order to get the raw csv, you have to modify the url to:

'https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv'

Your second problem is that read_csv expects a file name, we can solve this by using StringIO from io module. Third problem is that request.get(url).content delivers a byte stream, we can solve this using the request.get(url).text instead.

End result is this code:

from io import StringIO

import pandas as pd
import requests
url='https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv'
s=requests.get(url).text

c=pd.read_csv(StringIO(s))

output:

>>> c.head()
    Country  Region
0   Algeria  AFRICA
1    Angola  AFRICA
2     Benin  AFRICA
3  Botswana  AFRICA
4   Burkina  AFRICA

Calling a particular PHP function on form submit

In the following line

<form method="post" action="display()">

the action should be the name of your script and you should call the function, Something like this

<form method="post" action="yourFileName.php">
    <input type="text" name="studentname">
    <input type="submit" value="click" name="submit"> <!-- assign a name for the button -->
</form>

<?php
function display()
{
    echo "hello ".$_POST["studentname"];
}
if(isset($_POST['submit']))
{
   display();
} 
?>

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

Convert Iterator to ArrayList

Note there is a difference between Iterable and Iterator.

If you have an Iterable, then with Java 8 you can use this solution:

Iterable<Element> iterable = createIterable();
List<Element> array = StreamSupport
    .stream(iterable.spliterator(), false)
    .collect(Collectors.toList());

As I know Collectors.toList() creates ArrayList instance.

Actually in my opinion, it also looks good in one line.
For example if you need to return List<Element> from some method:

return StreamSupport.stream(iter.spliterator(), false).collect(Collectors.toList());

Command line input in Python

If you're using Python 3, raw_input has changed to input

Python 3 example:

line = input('Enter a sentence:')

IsNumeric function in c#

You could make a helper method. Something like:

public bool IsNumeric(string input) {
    int test;
    return int.TryParse(input, out test);
}

How to find the unclosed div tag

I made an online tool called Unclosed Tag Finder which will do what you need.

Paste in your HTML, and it will give you output like "Closing tag on line 188 does not match open tag on line 62."

Update: The new location of the Unclosed Tag Finder is https://jonaquino.blogspot.com/2013/05/unclosed-tag-finder.html

How to disable "prevent this page from creating additional dialogs"?

function alertWithoutNotice(message){
    setTimeout(function(){
        alert(message);
    }, 1000);
}

Add / Change parameter of URL and redirect to the new URL

I think something like this would work, upgrading the @Marc code:

//view-all parameter does NOT exist  
$params = $_GET;  
if(!isset($_GET['view-all'])){  
  //Adding view-all parameter  
  $params['view-all'] = 'Yes';  
}  
else{  
  //view-all parameter does exist!  
  $params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');  
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);

How to show DatePickerDialog on Button click?

enter image description here

I. In your build.gradle add latest appcompat library, at the time 24.2.1

dependencies {  
    compile 'com.android.support:appcompat-v7:X.X.X' 
    // where X.X.X version
}

II. Make your activity extend android.support.v7.app.AppCompatActivity and implement the DatePickerDialog.OnDateSetListener interface.

public class MainActivity extends AppCompatActivity  
    implements DatePickerDialog.OnDateSetListener {

III. Create your DatePickerDialog setting a context, the implementation of the listener and the start year, month and day of the date picker.

DatePickerDialog datePickerDialog = new DatePickerDialog(  
    context, MainActivity.this, startYear, starthMonth, startDay);

IV. Show your dialog on the click event listener of your button

((Button) findViewById(R.id.myButton))
    .setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        datePickerDialog.show();
    }
});

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.


1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

How to implement a custom AlertDialog View

Custom AlertDialog

This full example includes passing data back to the Activity.

enter image description here

Create a custom layout

A layout with an EditText is used for this simple example, but you can replace it with anything you like.

custom_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:paddingLeft="20dp"
              android:paddingRight="20dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Use the dialog in code

The key parts are

  • using setView to assign the custom layout to the AlertDialog.Builder
  • sending any data back to the activity when a dialog button is clicked.

This is the full code from the example project shown in the image above:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showAlertDialogButtonClicked(View view) {

        // create an alert builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Name");

        // set the custom layout
        final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
        builder.setView(customLayout);

        // add a button
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // send data from the AlertDialog to the Activity
                EditText editText = customLayout.findViewById(R.id.editText);
                sendDialogDataToActivity(editText.getText().toString());
            }
        });

        // create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    // do something with the data coming from the AlertDialog
    private void sendDialogDataToActivity(String data) {
        Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
    }
}

Notes

  • If you find yourself using this in multiple places, then consider making a DialogFragment subclass as is described in the documentation.

See also

MySQL: Fastest way to count number of rows

If you need to get the count of the entire result set you can take following approach:

SELECT SQL_CALC_FOUND_ROWS * FROM table_name LIMIT 5;
SELECT FOUND_ROWS();

This isn't normally faster than using COUNT albeit one might think the opposite is the case because it's doing the calculation internally and doesn't send the data back to the user thus the performance improvement is suspected.

Doing these two queries is good for pagination for getting totals but not particularly for using WHERE clauses.

ReferenceError: Invalid left-hand side in assignment

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen - see specification:

Assignment

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

How to differentiate single click event and double click event?

Instead of utilizing more ad-hoc states and setTimeout, turns out there is a native property called detail that you can access from the event object!

element.onclick = event => {
   if (event.detail === 1) {
     // it was a single click
   } else if (event.detail === 2) {
     // it was a double click
   }
};

Modern browsers and even IE-9 supports it :)

Source: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

How do I find out if first character of a string is a number?

Character.isDigit(string.charAt(0))

Note that this will allow any Unicode digit, not just 0-9. You might prefer:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

Or the slower regex solutions:

s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")

However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

To make the entire condition one line and avoid length checks, you can alter the regexes to the following:

s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")

If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.

Adding values to specific DataTable cells

If it were a completely new row that you wanted to only set one value, you would need to add the whole row and then set the individual value:

DataRow dr = dt.NewRow();
dr[3].Value = "Some Value";
dt.Rows.Add(dr);

Otherwise, you can find the existing row and set the cell value

DataRow dr = dt.Rows[theRowNumber];
dr[3] = "New Value";

How do I access refs of a child component in the parent component

Recommended for React versions prior to 16.3

If it cannot be avoided the suggested pattern extracted from the React docs would be:

import React, { Component } from 'react';

const Child = ({ setRef }) => <input type="text" ref={setRef} />;

class Parent extends Component {
    constructor(props) {
        super(props);
        this.setRef = this.setRef.bind(this);
    }

    componentDidMount() {
        // Calling a function on the Child DOM element
        this.childRef.focus();
    }

    setRef(input) {
        this.childRef = input;
    }

    render() {
        return <Child setRef={this.setRef} />
    }
}

The Parent forwards a function as prop bound to Parent's this. When React calls the Child's ref prop setRef it will assign the Child's ref to the Parent's childRef property.

Recommended for React >= 16.3

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

We create Components that forward their ref with React.forwardRef. The returned Component ref prop must be of the same type as the return type of React.createRef. Whenever React mounts the DOM node then property current of the ref created with React.createRef will point to the underlying DOM node.

import React from "react";

const LibraryButton = React.forwardRef((props, ref) => (
  <button ref={ref} {...props}>
    FancyButton
  </button>
));

class AutoFocus extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
    this.onClick = this.onClick.bind(this);
  }

  componentDidMount() {
    this.childRef.current.focus();
  }

  onClick() {
    console.log("fancy!");
  }

  render() {
    return <LibraryButton onClick={this.onClick} ref={this.childRef} />;
  }
}

Forwarding refs HOC example

Created Components are forwarding their ref to a child node.

function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      const {forwardedRef, ...rest} = this.props;

      // Assign the custom prop "forwardedRef" as a ref
      return <Component ref={forwardedRef} {...rest} />;
    }
  }

  // Note the second param "ref" provided by React.forwardRef.
  // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
  // And it can then be attached to the Component.
  return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;
  });
}

See Forwarding Refs in React docs.

Python Matplotlib Y-Axis ticks on Right Side of Plot

Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:

import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()

It will show this:

enter image description here

Max size of an iOS application

Please be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.

enter image description here

The simplest way to resize an UIImage?

use this extension

extension UIImage {
    public func resize(size:CGSize, completionHandler:(resizedImage:UIImage, data:NSData?)->()) {
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { () -> Void in
            let newSize:CGSize = size
            let rect = CGRectMake(0, 0, newSize.width, newSize.height)
            UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
            self.drawInRect(rect)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            let imageData = UIImageJPEGRepresentation(newImage, 0.5)
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                completionHandler(resizedImage: newImage, data:imageData)
            })
        })
    }
}

Bootstrap 3 and Youtube in Modal

<a href="#" class="btn btn-default" id="btnforvideo" data-toggle="modal" data-target="#videoModal">VIDEO</a>

<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <div>
                    <iframe width="100%" height="315" src="https://www.youtube.com/embed/myvideocode" frameborder="0" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

"Active Directory Users and Computers" MMC snap-in for Windows 7?

As "me1" has mentioned you can do this assuming that your version of Windows 7 is either Professional or Ultimate, the PC is on the domain and you have preinstall the Remote Server Administration Tools (Windows6.1-KB958830-x64-RefreshPkg.msu or newer) then you'll be able to do the following:

Step 1. Select "Start", select "Control Panel", select "Programs" and click on "Turn Windows features on or off".

Step 2. Check the following 5 features:

"remote server administration tools>feature administration tools>group policy management tools"

"remote server administration tools>feature administration tools>smtp server tools"

"remote server administration tools>role administration tools>ad ds and ad lds tools>active directory module for windows powershell"

"remote server administration tools>role administration tools>ad ds and ad lds tools>ad ds tools>active directory administrative center"

"remote server administration tools>role administration tools>ad ds and ad lds tools>ad ds tools>ad ds snap-ins and command-line tools"

Step 3. Click "OK".

Post-increment and Pre-increment concept?

The difference between the postfix increment, x++, and the prefix increment, ++x, is precisely in how the two operators evaluate their operands. The postfix increment conceptually copies the operand in memory, increments the original operand and finally yields the value of the copy. I think this is best illustrated by implementing the operator in code:

int operator ++ (int& n)  // postfix increment
{
    int tmp = n;
    n = n + 1;
    return tmp;
}

The above code will not compile because you can't re-define operators for primitive types. The compiler also can't tell here we're defining a postfix operator rather than prefix, but let's pretend this is correct and valid C++. You can see that the postfix operator indeed acts on its operand, but it returns the old value prior to the increment, so the result of the expression x++ is the value prior to the increment. x, however, is incremented.

The prefix increment increments its operand as well, but it yields the value of the operand after the increment:

int& operator ++ (int& n)
{
    n = n + 1;
    return n;
}

This means that the expression ++x evaluates to the value of x after the increment.

It's easy to think that the expression ++x is therefore equivalent to the assignmnet (x=x+1). This is not precisely so, however, because an increment is an operation that can mean different things in different contexts. In the case of a simple primitive integer, indeed ++x is substitutable for (x=x+1). But in the case of a class-type, such as an iterator of a linked list, a prefix increment of the iterator most definitely does not mean "adding one to the object".

How to pass props to {this.props.children}

None of the answers address the issue of having children that are NOT React components, such as text strings. A workaround could be something like this:

// Render method of Parent component
render(){
    let props = {
        setAlert : () => {alert("It works")}
    };
    let childrenWithProps = React.Children.map( this.props.children, function(child) {
        if (React.isValidElement(child)){
            return React.cloneElement(child, props);
        }
          return child;
      });
    return <div>{childrenWithProps}</div>

}

Which MySQL data type to use for storing boolean values

Until MySQL implements a bit datatype, if your processing is truly pressed for space and/or time, such as with high volume transactions, create a TINYINT field called bit_flags for all your boolean variables, and mask and shift the boolean bit you desire in your SQL query.

For instance, if your left-most bit represents your bool field, and the 7 rightmost bits represent nothing, then your bit_flags field will equal 128 (binary 10000000). Mask (hide) the seven rightmost bits (using the bitwise operator &), and shift the 8th bit seven spaces to the right, ending up with 00000001. Now the entire number (which, in this case, is 1) is your value.

SELECT (t.bit_flags & 128) >> 7 AS myBool FROM myTable t;

if bit_flags = 128 ==> 1 (true)
if bit_flags = 0 ==> 0 (false)

You can run statements like these as you test

SELECT (128 & 128) >> 7;

SELECT (0 & 128) >> 7;

etc.

Since you have 8 bits, you have potentially 8 boolean variables from one byte. Some future programmer will invariably use the next seven bits, so you must mask. Don’t just shift, or you will create hell for yourself and others in the future. Make sure you have MySQL do your masking and shifting — this will be significantly faster than having the web-scripting language (PHP, ASP, etc.) do it. Also, make sure that you place a comment in the MySQL comment field for your bit_flags field.

You’ll find these sites useful when implementing this method:

Explanation of JSONB introduced by PostgreSQL

Peeyush:

The short answer is:

  • If you are doing a lot of JSON manipulation inside PostgreSQL, such as sorting, slicing, splicing, etc., you should use JSONB for speed reasons.
  • If you need indexed lookups for arbitrary key searches on JSON, then you should use JSONB.
  • If you are doing neither of the above, you should probably use JSON.
  • If you need to preserve key ordering, whitespace, and duplicate keys, you should use JSON.

For a longer answer, you'll need to wait for me to do a full "HowTo" writeup closer to the 9.4 release.

How do you do natural logs (e.g. "ln()") with numpy in Python?

from numpy.lib.scimath import logn
from math import e

#using: x - var
logn(e, x)

How to increment datetime by custom months in python without using library

since no one suggested any solution, here is how i solved so far

year, month= divmod(mydate.month+1, 12)
if month == 0: 
      month = 12
      year = year -1
next_month = datetime.datetime(mydate.year + year, month, 1)

SVG fill color transparency / alpha?

As a not yet fully standardized solution (though in alignment with the color syntax in CSS3) you can use e.g fill="rgba(124,240,10,0.5)". Works fine in Firefox, Opera, Chrome.

Here's an example.

Differences between Lodash and Underscore.js

Underscore vs Lo-Dash by Ben McCormick is the latest article comparing the two:

  1. Lodash's API is a superset of Underscore.js's.
  1. Under the hood, Lodash has been completely rewritten.
  1. Lodash is definitely not slower than Underscore.js.
  1. What has Lodash added?
  • Usability improvements
  • Extra functionality
  • Performance gains
  • Shorthand syntaxes for chaining
  • Custom builds to only use what you need
  • Semantic versioning and 100% code coverage

Connection pooling options with JDBC: DBCP vs C3P0

Just got done wasting a day and a half with DBCP. Even though I'm using the latest DBCP release, I ran into exactly the same problems as j pimmel did. I would not recommend DBCP at all, especially it's knack of throwing connections out of the pool when the DB goes away, its inability to reconnect when the DB comes back and its inability to dynamically add connection objects back into the pool (it hangs forever on a post JDBCconnect I/O socket read)

I'm switching over to C3P0 now. I've used that in previous projects and it worked and performed like a charm.

How to start debug mode from command prompt for apache tomcat server?

  1. From your IDE, create a remote debug configuration, configure it for the default JPDA Tomcat port which is port 8000.

  2. From the command line:

    Linux:

    cd apache-tomcat/bin
    export JPDA_SUSPEND=y
    ./catalina.sh jpda run
    

    Windows:

    cd apache-tomcat\bin
    set JPDA_SUSPEND=y
    catalina.bat jpda run
    
  3. Execute the remote debug configuration from your IDE, and Tomcat will start running and you are now able to set breakpoints in the IDE.

Note:

The JPDA_SUSPEND=y line is optional, it is useful if you want that Apache Tomcat doesn't start its execution until step 3 is completed, useful if you want to troubleshoot application initialization issues.

How to remove all ListBox items?

You should be able to use the Clear() method.

php stdClass to array

Please use following php function to convert php stdClass to array

get_object_vars($data)

Objective C - Assign, Copy, Retain

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"First",@"Second", nil];
NSMutableArray *copiedArray = [array mutableCopy];
NSMutableArray *retainedArray = [array retain];

[retainedArray addObject:@"Retained Third"];
[copiedArray addObject:@"Copied Third"];

NSLog(@"array = %@",array);
NSLog(@"Retained Array = %@",retainedArray);
NSLog(@"Copied Array = %@",copiedArray);

array = (
    First,
    Second,
    "Retained Third"
)
Retained Array = (
    First,
    Second,
    "Retained Third"
)
Copied Array = (
    First,
    Second,
    "Copied Third"
)

How to return a complex JSON response with Node.js?

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation

Virtual network interface in Mac OS X

Here's a good guide: https://web.archive.org/web/20160301104014/http://gerrydevstory.com/2012/08/20/how-to-create-virtual-network-interface-on-mac-os-x/

Basically you select a network adapter in the Networks pane of system preferences, then click the gear to "Duplicate Service". After the service is duplicated, you manually assign an IP in one of the private address ranges. Then ping it to make sure ;)

Why can't I change my input value in React even with the onChange listener

You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:

<input type="text" onChange={e => this.setState({ text: e.target.value })}/>

DateTimePicker: pick both date and time

Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.

To use the DateTimePicker for times, set the Format property to either Time or Custom (Use Custom if you want to control the format of the time using the CustomFormat property). Then set the ShowUpDown property to true.

Although a user may set the date and time together manually, they cannot use the GUI to set both.

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

How to subtract X days from a date using Java calendar?

Eli Courtwright second solution is wrong, it should be:

Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
date.setTime(c.getTime().getTime());

string sanitizer for filename

What about using rawurlencode() ? http://www.php.net/manual/en/function.rawurlencode.php

Here is a function that sanitize even Chinese Chars:

public static function normalizeString ($str = '')
{
    $str = strip_tags($str); 
    $str = preg_replace('/[\r\n\t ]+/', ' ', $str);
    $str = preg_replace('/[\"\*\/\:\<\>\?\'\|]+/', ' ', $str);
    $str = strtolower($str);
    $str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
    $str = htmlentities($str, ENT_QUOTES, "utf-8");
    $str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
    $str = str_replace(' ', '-', $str);
    $str = rawurlencode($str);
    $str = str_replace('%', '-', $str);
    return $str;
}

Here is the explaination

  1. Strip HTML Tags
  2. Remove Break/Tabs/Return Carriage
  3. Remove Illegal Chars for folder and filename
  4. Put the string in lower case
  5. Remove foreign accents such as Éàû by convert it into html entities and then remove the code and keep the letter.
  6. Replace Spaces with dashes
  7. Encode special chars that could pass the previous steps and enter in conflict filename on server. ex. "?????"
  8. Replace "%" with dashes to make sure the link of the file will not be rewritten by the browser when querying th file.

OK, some filename will not be releavant but in most case it will work.

ex. Original Name: "???????-??-????????????.jpg"

Output Name: "-E1-83-A1-E1-83-90-E1-83-91-E1-83-94-E1-83-AD-E1-83-93-E1-83-98--E1-83-93-E1-83-90--E1-83-A2-E1-83-98-E1-83-9E-E1-83-9D-E1-83-92-E1-83-A0-E1-83-90-E1-83-A4-E1-83-98-E1-83-A3-E1-83-9A-E1-83-98.jpg"

It's better like that than an 404 error.

Hope that was helpful.

Carl.

How do you read from stdin?

argparse is an easy solution

Example compatible with both Python versions 2 and 3:

#!/usr/bin/python

import argparse
import sys

parser = argparse.ArgumentParser()

parser.add_argument('infile',
                    default=sys.stdin,
                    type=argparse.FileType('r'),
                    nargs='?')

args = parser.parse_args()

data = args.infile.read()

You can run this script in many ways:

1. Using stdin

echo 'foo bar' | ./above-script.py

  or shorter by replacing echo by here string:

./above-script.py <<< 'foo bar'

2. Using a filename argument

echo 'foo bar' > my-file.data
./above-script.py my-file.data

3. Using stdin through the special filename -

echo 'foo bar' | ./above-script.py -

Pad with leading zeros

The concept of leading zero is meaningless for an int, which is what you have. It is only meaningful, when printed out or otherwise rendered as a string.

Console.WriteLine("{0:0000000}", FileRecordCount);

Forgot to end the double quotes!

Get public/external IP address?

Or this, it works quite well i think for what i needed. It's from here.

public IPAddress GetExternalIP()
{
    WebClient lol = new WebClient();
    string str = lol.DownloadString("http://www.ip-adress.com/");
    string pattern = "<h2>My IP address is: (.+)</h2>"
    MatchCollection matches1 = Regex.Matches(str, pattern);
    string ip = matches1(0).ToString;
    ip = ip.Remove(0, 21);
    ip = ip.Replace("

    ", "");
    ip = ip.Replace(" ", "");
    return IPAddress.Parse(ip);
}

Easiest way to mask characters in HTML(5) text input

Yes, according to HTML5 drafts you can use the pattern attribute to specify the allowed input using a regular expression. For some types of data, you can use special input fields like <input type=email>. But these features still widely lack support or have qualitatively poor support.

What does it mean to bind a multicast (UDP) socket?

Correction for What does it mean to bind a multicast (udp) socket? as long as it partially true at the following quote:

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application

There is one exception. Multiple applications can share the same port for listening (usually it has practical value for multicast datagrams), if the SO_REUSEADDR option applied. For example

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create UDP socket somehow
...
int set_option_on = 1;
// it is important to do "reuse address" before bind, not after
int res = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, 
    sizeof(set_option_on));
res = bind(sock, src_addr, len);

If several processes did such "reuse binding", then every UDP datagram received on that shared port will be delivered to each of the processes (providing natural joint with multicasts traffic).

Here are further details regarding what happens in a few cases:

  1. attempt of any bind ("exclusive" or "reuse") to free port will be successful

  2. attempt to "exclusive binding" will fail if the port is already "reuse-binded"

  3. attempt to "reuse binding" will fail if some process keeps "exclusive binding"

Spacing between elements

If you want vertical spacing between elements, use a margin.

Don't add extra elements if you don't need to.

RegEx to exclude a specific string constant

You have to use a negative lookahead assertion.

(?!^ABC$)

You could for example use the following.

(?!^ABC$)(^.*$)

If this does not work in your editor, try this. It is tested to work in ruby and javascript:

^((?!ABC).)*$

How to npm install to a specified directory?

In the documentation it's stated: Use the prefix option together with the global option:

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.

When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.

(Emphasis by them)

So in your root directory you could install with

npm install --prefix <path/to/prefix_folder> -g

and it will install the node_modules folder into the folder

<path/to/prefix_folder>/lib/node_modules

Change project name on Android Studio

Just go to res>values>strings.xml. One line says Somethig-your name

<string name="app_name">Somethig-your name</string>

Just replace your original name to

 <string name="app_name">Your Name</string>

Spring Boot application.properties value not populating

Actually, For me below works fine.

@Component
public class MyBean {

   public static String prop;

   @Value("${some.prop}")
   public void setProp(String prop) {
      this.prop= prop;
   }

   public MyBean() {

   }

   @PostConstruct
   public void init() {
      System.out.println("================== " + prop + "================== ");
   }

}

Now whereever i want, just invoke

MyBean.prop

it will return value.

Screen width in React Native

React Native Dimensions is only a partial answer to this question, I came here looking for the actual pixel size of the screen, and the Dimensions actually gives you density independent layout size.

You can use React Native Pixel Ratio to get the actual pixel size of the screen.

You need the import statement for both Dimenions and PixelRatio

import { Dimensions, PixelRatio } from 'react-native';

You can use object destructuring to create width and height globals or put it in stylesheets as others suggest, but beware this won't update on device reorientation.

const { width, height } = Dimensions.get('window');

From React Native Dimension Docs:

Note: Although dimensions are available immediately, they may change (e.g due to >device rotation) so any rendering logic or styles that depend on these constants >should try to call this function on every render, rather than caching the value >(for example, using inline styles rather than setting a value in a StyleSheet).

PixelRatio Docs link for those who are curious, but not much more there.

To actually get the screen size use:

PixelRatio.getPixelSizeForLayoutSize(width);

or if you don't want width and height to be globals you can use it anywhere like this

PixelRatio.getPixelSizeForLayoutSize(Dimensions.get('window').width);

remove space between paragraph and unordered list

This simple way worked fine for me:

<ul style="margin-top:-30px;">

Could not reserve enough space for object heap

Sometimes, this error indicates that physical memory and swap on the server actually are fully utilized!

I was seeing this problem recently on a server running RedHat Enterprise Linux 5.7 with 48 GB of RAM. I found that even just running

java -version

caused the same error, which established that the problem was not specific to my application.

Running

cat /proc/meminfo

reported that MemFree and SwapFree were both well under 1% of the MemTotal and SwapTotal values, respectively:

MemTotal:     49300620 kB
MemFree:        146376 kB
...
SwapTotal:     4192956 kB
SwapFree:         1364 kB

Stopping a few other running applications on the machine brought the free memory figures up somewhat:

MemTotal:     49300620 kB
MemFree:       2908664 kB
...
SwapTotal:     4192956 kB
SwapFree:      1016052 kB

At this point, a new instance of Java would start up okay, and I was able to run my application.

(Obviously, for me, this was just a temporary solution; I still have an outstanding task to do a more thorough examination of the processes running on that machine to see if there's something that can be done to reduce the nominal memory utilization levels, without having to resort to stopping applications.)

Converting Array to List

If you don't want to alter the list:

List<Integer> list = Arrays.asList(array)

But if you want to modify it then you can use this:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(ints));

Or just use java8 like the following:

List<Integer> list = Arrays.stream(ints).collect(Collectors.toList());

Java9 has introduced this method:

List<Integer> list = List.of(ints);

However, this will return an immutable list that you can't add to.

You need to do the following to make it mutable:

List<Integer> list = new ArrayList<Integer>(List.of(ints));

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

I just ran into this problem myself.

The fix I come out with was to go to the organizer, click on the "provisioning profiles" tab, and press refresh in the low corner.

You ll be asked to give your itunes connect password , just follow the instruction.

Hope it helps

Allowing Untrusted SSL Certificates with HttpClient

With Windows 8.1, you can now trust invalid SSL certs. You have to either use the Windows.Web.HttpClient or if you want to use the System.Net.Http.HttpClient, you can use the message handler adapter I wrote: http://www.nuget.org/packages/WinRtHttpClientHandler

Docs are on the GitHub: https://github.com/onovotny/WinRtHttpClientHandler

How do I use the Tensorboard callback of Keras?

This is how you use the TensorBoard callback:

from keras.callbacks import TensorBoard

tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0,
                          write_graph=True, write_images=False)
# define model
model.fit(X_train, Y_train,
          batch_size=batch_size,
          epochs=nb_epoch,
          validation_data=(X_test, Y_test),
          shuffle=True,
          callbacks=[tensorboard])

How do I fill arrays in Java?

Check out the Arrays.fill methods.

int[] array = new int[4];
Arrays.fill(array, 0);

How to update a menu item shown in the ActionBar?

Option #1: Try invalidateOptionsMenu(). I don't know if this will force an immediate redraw of the action bar or not.

Option #2: See if getActionView() returns anything for the affected MenuItem. It is possible that showAsAction simply automatically creates action views for you. If so, you can presumably enable/disable that View.

I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.

You can hang onto the Menu object you were handed in onCreateOptionsMenu(). Quoting the docs:

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

For SQL2008,

  • open Management Studio
  • Rt click on instance
  • go to properties
  • select Security
  • Under Server Authentication, check SQL Server and Windows Authentication Mode
  • hit OK

Restart the server using configuration manager.

How to detect idle time in JavaScript elegantly?

I wrote a small ES6 class to detect activity and otherwise fire events on idle timeout. It covers keyboard, mouse and touch, can be activated and deactivated and has a very lean API:

const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
timer.activate();

It does not depend on jQuery, though you might need to run it through Babel to support older browsers.

https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096

I might release it as an npm package once I get some feedback.

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

How to select a schema in postgres when using psql?

if you in psql just type

set schema 'temp';

and after that \d shows all relations in "temp

Best way to find the months between two dates

This is my way to do this:

Start_date = "2000-06-01"
End_date   = "2001-05-01"

month_num  = len(pd.date_range(start = Start_date[:7], end = End_date[:7] ,freq='M'))+1

I just use the month to create a date range and calculate the length.

How to automatically convert strongly typed enum into int?

A C++14 version of the answer provided by R. Martinho Fernandes would be:

#include <type_traits>

template <typename E>
constexpr auto to_underlying(E e) noexcept
{
    return static_cast<std::underlying_type_t<E>>(e);
}

As with the previous answer, this will work with any kind of enum and underlying type. I have added the noexcept keyword as it will never throw an exception.


Update
This also appears in Effective Modern C++ by Scott Meyers. See item 10 (it is detailed in the final pages of the item within my copy of the book).

How to send control+c from a bash script?

CTRL-C generally sends a SIGINT signal to the process so you can simply do:

kill -INT <processID>

from the command line (or a script), to affect the specific processID.

I say "generally" because, as with most of UNIX, this is near infinitely configurable. If you execute stty -a, you can see which key sequence is tied to the intr signal. This will probably be CTRL-C but that key sequence may be mapped to something else entirely.


The following script shows this in action (albeit with TERM rather than INT since sleep doesn't react to INT in my environment):

#!/usr/bin/env bash

sleep 3600 &
pid=$!
sleep 5

echo ===
echo PID is $pid, before kill:
ps -ef | grep -E "PPID|$pid" | sed 's/^/   /'
echo ===

( kill -TERM $pid ) 2>&1
sleep 5

echo ===
echo PID is $pid, after kill:
ps -ef | grep -E "PPID|$pid" | sed 's/^/   /'
echo ===

It basically starts an hour-log sleep process and grabs its process ID. It then outputs the relevant process details before killing the process.

After a small wait, it then checks the process table to see if the process has gone. As you can see from the output of the script, it is indeed gone:

===
PID is 28380, before kill:
   UID   PID     PPID    TTY     STIME      COMMAND
   pax   28380   24652   tty42   09:26:49   /bin/sleep
===
./qq.sh: line 12: 28380 Terminated              sleep 3600
===
PID is 28380, after kill:
   UID   PID     PPID    TTY     STIME      COMMAND
===

Char Comparison in C

I believe you are trying to compare two strings representing values, the function you are looking for is:

int atoi(const char *nptr);

or

long int strtol(const char *nptr, char **endptr, int base);

these functions will allow you to convert a string to an int/long int:

int val = strtol("555", NULL, 10);

and compare it to another value.

int main (int argc, char *argv[])
{
    long int val = 0;
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s number\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    val = strtol(argv[1], NULL, 10);
    printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");

    return 0;
}

Read binary file as string in Ruby

To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.

contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }

How to save public key from a certificate in .pem format

if it is a RSA key

openssl rsa  -pubout -in my_rsa_key.pem

if you need it in a format for openssh , please see Use RSA private key to generate public key?

Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a similar issue but from reading this question I figured I could run on UI thread:

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        alertDialog.show();
    }
});

Seems to do the trick for me.

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

I tried this in Ubuntu 18.04 and is the only solution that worked for me:

ALTER USER my_user@'%' IDENTIFIED WITH mysql_native_password BY 'password';

Get model's fields in Django

The model fields contained by _meta are listed in multiple locations as lists of the respective field objects. It may be easier to work with them as a dictionary where the keys are the field names.

In my opinion, this is most irredundant and expressive way to collect and organize the model field objects:

def get_model_fields(model):
  fields = {}
  options = model._meta
  for field in sorted(options.concrete_fields + options.many_to_many + options.virtual_fields):
    fields[field.name] = field
  return fields

(See This example usage in django.forms.models.fields_for_model.)

Can I change the fill color of an svg path with CSS?

Yes, you can apply CSS to SVG, but you need to match the element, just as when styling HTML. If you just want to apply it to all SVG paths, you could use, for example:

?path {
    fill: blue;
}?

External CSS appears to override the path's fill attribute, at least in WebKit and Gecko-based browsers I tested. Of course, if you write, say, <path style="fill: green"> then that will override external CSS as well.

What's the maximum value for an int in PHP?

32-bit builds of PHP:

  • Integers can be from -2,147,483,648 to 2,147,483,647 (~ ± 2 billion)

64-bit builds of PHP:

  • Integers can be from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (~ ± 9 quintillion)

Numbers are inclusive.

Note: some 64-bit builds once used 32-bit integers, particularly older Windows builds of PHP

Values outside of these ranges are represented by floating point values, as are non-integer values within these ranges. The interpreter will automatically determine when this switch to floating point needs to happen based on whether the result value of a calculation can't be represented as an integer.

PHP has no support for "unsigned" integers as such, limiting the maximum value of all integers to the range of a "signed" integer.

Overlay with spinner

use a css3 class "spinner". It's more beautiful and you don't need .gif

enter image description here

.spinner {
   position: absolute;
   left: 50%;
   top: 50%;
   height:60px;
   width:60px;
   margin:0px auto;
   -webkit-animation: rotation .6s infinite linear;
   -moz-animation: rotation .6s infinite linear;
   -o-animation: rotation .6s infinite linear;
   animation: rotation .6s infinite linear;
   border-left:6px solid rgba(0,174,239,.15);
   border-right:6px solid rgba(0,174,239,.15);
   border-bottom:6px solid rgba(0,174,239,.15);
   border-top:6px solid rgba(0,174,239,.8);
   border-radius:100%;
}

@-webkit-keyframes rotation {
   from {-webkit-transform: rotate(0deg);}
   to {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
   from {-moz-transform: rotate(0deg);}
   to {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
   from {-o-transform: rotate(0deg);}
   to {-o-transform: rotate(359deg);}
}
@keyframes rotation {
   from {transform: rotate(0deg);}
   to {transform: rotate(359deg);}
}

Exemple of what is looks like : http://jsbin.com/roqakuxebo/1/edit

You can find a lot of css spinners like this here : http://cssload.net/en/spinners/

Eclipse Problems View not showing Errors anymore

Try following:

  1. Open Problems window (Windows -> Show View -> Problems)

  2. Right click on the error and then Quick Fix

This procedure helped me solve the same problem.

How can I hide or encrypt JavaScript code?

You can obfuscate it, but there's no way of protecting it completely.

example obfuscator: https://obfuscator.io

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

If u want to Selected text clear then using to this code i will make by my self ;)

If e.KeyCode = Keys.Delete Then
    TextBox1.SelectedText = ""
End If

thats it

How do you beta test an iphone app?

In 2014 along with iOS 8 and XCode 6 apple introduced Beta Testing of iOS App using iTunes Connect.

You can upload your build to iTunes connect and invite testers using their mail id's. You can invite up to 2000 external testers using just their email address. And they can install the beta app through TestFlight

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I had faced this similar error too. In my case it was one of my picture files in my drawable folder. Removing the picture that was unused solved the problem for me. So, make sure to remove any unused items from drawable folder.

Meaning of *& and **& in C++

To understand those phrases let's look at the couple of things:

typedef double Foo;
void fooFunc(Foo &_bar){ ... }

So that's passing a double by reference.

typedef double* Foo;
void fooFunc(Foo &_bar){ ... }

now it's passing a pointer to a double by reference.

typedef double** Foo;
void fooFunc(Foo &_bar){ ... }

Finally, it's passing a pointer to a pointer to a double by reference. If you think in terms of typedefs like this you'll understand the proper ordering of the & and * plus what it means.

Find if a textbox is disabled or not using jquery

 if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))
 {

    // code when element is disabled

  }

Extracting double-digit months and days from a Python date

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file

Binary Data in JSON String. Something better than Base64

yEnc might work for you:

http://en.wikipedia.org/wiki/Yenc

"yEnc is a binary-to-text encoding scheme for transferring binary files in [text]. It reduces the overhead over previous US-ASCII-based encoding methods by using an 8-bit Extended ASCII encoding method. yEnc's overhead is often (if each byte value appears approximately with the same frequency on average) as little as 1–2%, compared to 33%–40% overhead for 6-bit encoding methods like uuencode and Base64. ... By 2003 yEnc became the de facto standard encoding system for binary files on Usenet."

However, yEnc is an 8-bit encoding, so storing it in a JSON string has the same problems as storing the original binary data — doing it the naïve way means about a 100% expansion, which is worse than base64.

What does it mean when a PostgreSQL process is "idle in transaction"?

The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.

If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.

Android Fastboot devices not returning device

I had the same issue, but I was running Ubuntu 12.04 through a VM. I am using a Nexus 10. I had added the usb device as a filter for the VM (using virtual box in the virtual machine's settings).

The device I had added was "samsung Nexus 10".

The problem is that once the device is in fastboot mode, it shows up as a different device: "Google, Inc Android 1.0." So doing "lsusb" in the VM showed no device connected, and obviously "fastboot devices" returned nothing until I added the "second" device as a filter for the VM as well.

Hope this helps someone.

How do I get the picture size with PIL?

This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

How to add a constant column in a Spark DataFrame?

Spark 2.2+

Spark 2.2 introduces typedLit to support Seq, Map, and Tuples (SPARK-19254) and following calls should be supported (Scala):

import org.apache.spark.sql.functions.typedLit

df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withColumn("some_struct", typedLit(("foo", 1, 0.3)))
df.withColumn("some_map", typedLit(Map("key1" -> 1, "key2" -> 2)))

Spark 1.3+ (lit), 1.4+ (array, struct), 2.0+ (map):

The second argument for DataFrame.withColumn should be a Column so you have to use a literal:

from pyspark.sql.functions import lit

df.withColumn('new_column', lit(10))

If you need complex columns you can build these using blocks like array:

from pyspark.sql.functions import array, create_map, struct

df.withColumn("some_array", array(lit(1), lit(2), lit(3)))
df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))
df.withColumn("some_map", create_map(lit("key1"), lit(1), lit("key2"), lit(2)))

Exactly the same methods can be used in Scala.

import org.apache.spark.sql.functions.{array, lit, map, struct}

df.withColumn("new_column", lit(10))
df.withColumn("map", map(lit("key1"), lit(1), lit("key2"), lit(2)))

To provide names for structs use either alias on each field:

df.withColumn(
    "some_struct",
    struct(lit("foo").alias("x"), lit(1).alias("y"), lit(0.3).alias("z"))
 )

or cast on the whole object

df.withColumn(
    "some_struct", 
    struct(lit("foo"), lit(1), lit(0.3)).cast("struct<x: string, y: integer, z: double>")
 )

It is also possible, although slower, to use an UDF.

Note:

The same constructs can be used to pass constant arguments to UDFs or SQL functions.

Why does .json() return a promise?

This difference is due to the behavior of Promises more than fetch() specifically.

When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.

The 2nd snippet could also have been written as:

iterator.then(response =>
    response.json().then(post => document.write(post.title))
);

In both this form and yours, the value of post is provided by the Promise returned from response.json().


When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:

iterator.then(response =>
    Promise.resolve({
      data: response.json(),
      status: response.status
    })
    .then(post => document.write(post.data))
);

post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.

Explain why constructor inject is better than other options

(...) by using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner

This mean that you can enforce requirements for all injected fields without using any container specific solution.


Setter injection example

With setter injection special spring annotation @Required is required.

@Required

Marks a method (typically a JavaBean setter method) as being 'required': that is, the setter method must be configured to be dependency-injected with a value.

Usage

import org.springframework.beans.factory.annotation.Required;

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class Foo {

    private Bar bar;

    @Inject
    @Required
    public void setBar(Bar bar) {
        this.bar = bar;
    }
}

Constructor injection example

All required fields are defined in constructor, pure Java solution.

Usage

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class Foo {

    private Bar bar;

    @Inject
    public Foo(Bar bar) {
        this.bar = bar;
    }

}

Unit testing

This is especially useful in Unit Testing. Such kind of tests should be very simple and doesn't understand annotation like @Required, they generally not need a Spring for running simple unit test. When constructor is used, setup of this class for testing is much easier, there is no need to analyze how class under test is implemented.

Centering image and text in R Markdown for a PDF report

You can set the center (or other) alignment for the whole document as a Knitr option, using:

knitr::opts_chunk$set(echo = TRUE, fig.align="center")

Export DataBase with MySQL Workbench with INSERT statements

You can do it using mysqldump tool in command-line:

mysqldump your_database_name > script.sql

This creates a file with database create statements together with insert statements.

More info about options for mysql dump: https://dev.mysql.com/doc/refman/5.7/en/mysqldump-sql-format.html

"Could not find Developer Disk Image"

To run the project to latest devices from the older versions of Xcode, follow the following steps :

Go To Finder -> Applications -> Right Click on latest Xcode version -> select show package content -> Developer -> Platforms -> iPhoneOS.platform -> DeviceSupport -> Copy the latest version folder and paste at the same location of your old Xcode i.e in the DeviceSupport folder of your old Xcode.

Then Restart Xcode.enter image description here

Sql connection-string for localhost server

In .Net configuration I would use something like:

"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=..."

This information is from https://www.connectionstrings.com/sql-server-2016/

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

How do I increment a DOS variable in a FOR /F loop?

The problem with your code snippet is the way variables are expanded. Variable expansion is usually done when a statement is first read. In your case the whole FOR loop and its block is read and all variables, except the loop variables are expanded to their current value.

This means %c% in your echo %%i, %c% expanded instantly and so is actually used as echo %%i, 1 in each loop iteration.

So what you need is the delayed variable expansion. Find some good explanation about it here.

Variables that should be delay expanded are referenced with !VARIABLE! instead of %VARIABLE%. But you need to activate this feature with setlocal ENABLEDELAYEDEXPANSION and reset it with a matching endlocal.

Your modified code would look something like that:

set TEXT_T="myfile.txt"

set /a c=1

setlocal ENABLEDELAYEDEXPANSION

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
  set /a c=c+1

  echo %%i, !c!
)

endlocal

How to close a JavaFX application on window close?

You MUST override the "stop()" method in your Application instance to make it works. If you have overridden even empty "stop()" then the application shuts down gracefully after the last stage is closed (actually the last stage must be the primary stage to make it works completely as in supposed to be). No any additional Platform.exit or setOnCloseRequest calls are need in such case.

How to Rotate a UIImage 90 degrees?

Swift 4.2 version of RawMean's answer:

extension UIImage {

func rotated(byDegrees degree: Double) -> UIImage {
    let radians = CGFloat(degree * .pi) / 180.0 as CGFloat
    let rotatedSize = self.size
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(rotatedSize, false, scale)
    let bitmap = UIGraphicsGetCurrentContext()
    bitmap?.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
    bitmap?.rotate(by: radians)
    bitmap?.scaleBy(x: 1.0, y: -1.0)
    bitmap?.draw(
        self.cgImage!,
        in: CGRect.init(x: -self.size.width / 2, y: -self.size.height / 2 , width: self.size.width, height: self.size.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext() // this is needed
    return newImage!
}

}

SQL distinct for 2 fields in a database

How about simply:

select distinct c1, c2 from t

or

select c1, c2, count(*)
from t
group by c1, c2

How to install older version of node.js on Windows?

run:

npm install -g [email protected]

- or whatever version you want after the @ symbol (This works as of 2019)

How do I write a backslash (\) in a string?

There is a special function made for this Path.Combine()

var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");

CURRENT_DATE/CURDATE() not working as default DATE value

It doesn't work because it's not supported

The DEFAULT clause specifies a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column

http://dev.mysql.com/doc/refman/5.5/en/create-table.html

What is the size of column of int(11) in mysql in bytes?

4294967295 is the answer, because int(11) shows maximum of 11 digits IMO

How do I export html table data as .csv file?

I've briefly covered a simple way to do this with Google Spreadsheets (importHTML) and in Python (Pandas read_html and to_csv) as well as an example Python script in my SO answer here: https://stackoverflow.com/a/28083469/1588795.

validate natural input number with ngpattern

<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone  required  name='strMobileNo' ng-model="formModel.strMobileNo" type="text"  placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>

the following code will help for phone number validation and the respected directive is

app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = PHONE_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

How to check if a given directory exists in Ruby

All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:

File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true

Use custom build output folder when using create-react-app

Quick compatibility build script (also works on Windows):

"build": "react-scripts build && rm -rf docs && mv build docs"

Home does not contain an export named Home

You can use two ways to resolve this problem, first way that i think it as best way is replace importing segment of your code with bellow one:

import Home from './layouts/Home'

or export your component without default which is called named export like this

import React, { Component } from 'react';

class Home extends Component{
    render(){
        return(
        <p className="App-intro">
          Hello Man
        </p>
        )
    }
} 

export {Home};

You must enable the openssl extension to download files via https

make sure you have correct path to extension folder

extension_dir = "ext"

by default it is commented with ; character

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

I was solving same problem recently. I was designing a write cmdlet for my Subtitle module. I had six different user stories:

  • Subtitle only
  • Subtitle and path (original file name is used)
  • Subtitle and new file name (original path is used)
  • Subtitle and name suffix is used (original path and modified name is used).
  • Subtile, new path and new file name is is used.
  • Subtitle, new path and suffix is used.

I end up in the big frustration because I though that 4 parameters will be enough. Like most of the times, the frustration was pointless because it was my fault. I didn't know enough about parameter sets.

After some research in documentation, I realized where is the problem. With knowledge how the parameter sets should be used, I developed a general and simple approach how to solve this problem. A pencil and a sheet of paper is required but a spreadsheet editor is better:

  1. Write down all intended ways how the cmdlet should be used => user stories.
  2. Keep adding parameters with meaningful names and mark the use of the parameters until you have a unique collection set => no repetitive combination of parameters.
  3. Implement parameter sets into your code.
  4. Prepare tests for all possible user stories.
  5. Run tests (big surprise, right?). IDEs doesn't checks parameter sets collision, tests could save lots of trouble later one.

Example:

Unique parameter binding resolution approach.

The practical example could be seen over here.

BTW: The parameter uniqueness within parameter sets is the reason why the ParameterSetName property doesn't support [String[]]. It doesn't really make any sense.

ASP.NET MVC - passing parameters to the controller

public ActionResult ViewNextItem(int? id) makes the id integer a nullable type, no need for string<->int conversions.

How to download a branch with git?

you can use :

git clone <url> --branch <branch>

to clone/download only the contents of the branch.

This was helpful to me especially, since the contents of my branch were entirely different from the master branch (though this is not usually the case). Hence, the suggestions listed by others above didn't help me and I would end up getting a copy of the master even after I checked out the branch and did a git pull.

This command would directly give you the contents of the branch. It worked for me.

How to determine the current language of a wordpress page when using polylang?

pll_current_language

Returns the current language

Usage:

pll_current_language( $value ); 
  • $value => (optional) either name or locale or slug, defaults to slug

returns either the full name, or the WordPress locale (just as the WordPress core function ‘get_locale’ or the slug ( 2-letters code) of the current language.

How to change the text of a label?

try this

$("label").html(your value); or $("label").text(your value);

Log.INFO vs. Log.DEBUG

Also remember that all info(), error(), and debug() logging calls provide internal documentation within any application.

How to stop app that node.js express 'npm start'

When I tried the suggested solution I realized that my app name was truncated. I read up on process.title in the nodejs documentation (https://nodejs.org/docs/latest/api/process.html#process_process_title) and it says

On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory.

My app does not use any arguments, so I can add this line of code to my app.js

process.title = process.argv[2];

and then add these few lines to my package.json file

  "scripts": {
    "start": "node app.js this-name-can-be-as-long-as-it-needs-to-be",
    "stop": "killall -SIGINT this-name-can-be-as-long-as-it-needs-to-be"
  },

to use really long process names. npm start and npm stop work, of course npm stop will always terminate all running processes, but that is ok for me.

How do I detect if a user is already logged in Firebase?

If you are allowing anonymous users as well as those logged in with email you can use firebase.auth().currentUser.isAnonymous, which will return either true or false.

Sorting a list with stream.sorted() in Java

This might help for people ending up here searching how to sort list alphabetically.

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortService {
    public static void main(String[] args) {
        List<TestData> test = new ArrayList<>();
        test.add(prepareTestData("Asmin",1));
        test.add(prepareTestData("saurav",4));
        test.add(prepareTestData("asmin",2));
        test.add(prepareTestData("Saurav",3));

        test.forEach(data-> System.out.println(data));
        /** Output
         *  TestData(name=Asmin, id=1)
         *  TestData(name=saurav, id=4)
         *  TestData(name=asmin, id=2)
         *  TestData(name=Saurav, id=3)
         */

        test.sort(Comparator.comparing(TestData::getName,String::compareToIgnoreCase));
        test.forEach(data-> System.out.println(data));
        /**Sorted Output
         * TestData(name=Asmin, id=1)
         * TestData(name=asmin, id=2)
         * TestData(name=saurav, id=4)
         * TestData(name=Saurav, id=3)
         */
    }
    private static TestData prepareTestData(String name, int id){
        TestData testData= new TestData();
        testData.setId(id);
        testData.setName(name);
        return testData;
    }
}

@Getter
@Setter
@ToString
class TestData{
    private String name;
    private int id;
}

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

Execute a file with arguments in Python shell

execfile runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.

If you want to run a program from within Python, use subprocess.call. E.g.

import subprocess
subprocess.call(['./abc.py', arg1, arg2])

How to convert JSON string into List of Java object?

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

React - Display loading screen while DOM is rendering?

The starting of react app is based on the main bundle download. React app only starts after the main bundle being downloaded in the browser. This is even true in case of lazy loading architecture. But the fact is we cannot exactly state the name of any bundles. Because webpack will add a hash value at the end of each bundle at the time when you run 'npm run build' command. Of course we can avoid that by changing hash settings, but it will seriously affect the cache data problem in the Browser. Browsers might not take the new version because of the same bundle name. . we need a webpack + js + CSS approach to handle this situation.

change the public/index.html as below

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en" xml:lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=3.0, shrink-to-fit=no">_x000D_
  <meta name="theme-color" content="#000000">_x000D_
  <!--_x000D_
      manifest.json provides metadata used when your web app is added to the_x000D_
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/_x000D_
    -->_x000D_
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json">_x000D_
  <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">_x000D_
  <style>_x000D_
 .percentage {_x000D_
      position: absolute;_x000D_
      top: 50%;_x000D_
      left: 50%;_x000D_
      width: 150px;_x000D_
      height: 150px;_x000D_
      border: 1px solid #ccc;_x000D_
      background-color: #f3f3f3;_x000D_
      -webkit-transform: translate(-50%, -50%);_x000D_
          -ms-transform: translate(-50%, -50%);_x000D_
              transform: translate(-50%, -50%);_x000D_
      border: 1.1em solid rgba(0, 0, 0, 0.2);_x000D_
      border-radius: 50%;_x000D_
      overflow: hidden;_x000D_
      display: -webkit-box;_x000D_
      display: -ms-flexbox;_x000D_
      display: flex;_x000D_
      -webkit-box-pack: center;_x000D_
          -ms-flex-pack: center;_x000D_
              justify-content: center;_x000D_
      -webkit-box-align: center;_x000D_
          -ms-flex-align: center;_x000D_
              align-items: center;_x000D_
    }_x000D_
_x000D_
    .innerpercentage {_x000D_
      font-size: 20px;_x000D_
    }_x000D_
  </style>_x000D_
  <script>_x000D_
    function showPercentage(value) {_x000D_
      document.getElementById('percentage').innerHTML = (value * 100).toFixed() + "%";_x000D_
    }_x000D_
    var req = new XMLHttpRequest();_x000D_
    req.addEventListener("progress", function (event) {_x000D_
      if (event.lengthComputable) {_x000D_
        var percentComplete = event.loaded / event.total;_x000D_
        showPercentage(percentComplete)_x000D_
        // ..._x000D_
      } else {_x000D_
        document.getElementById('percentage').innerHTML = "Loading..";_x000D_
      }_x000D_
    }, false);_x000D_
_x000D_
    // load responseText into a new script element_x000D_
    req.addEventListener("load", function (event) {_x000D_
      var e = event.target;_x000D_
      var s = document.createElement("script");_x000D_
      s.innerHTML = e.responseText;_x000D_
      document.documentElement.appendChild(s);_x000D_
      document.getElementById('parentDiv').style.display = 'none';_x000D_
_x000D_
    }, false);_x000D_
_x000D_
    var bundleName = "<%= htmlWebpackPlugin.files.chunks.main.entry %>";_x000D_
    req.open("GET", bundleName);_x000D_
    req.send();_x000D_
_x000D_
  </script>_x000D_
  <!--_x000D_
      Notice the use of %PUBLIC_URL% in the tags above._x000D_
      It will be replaced with the URL of the `public` folder during the build._x000D_
      Only files inside the `public` folder can be referenced from the HTML._x000D_
_x000D_
      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will_x000D_
      work correctly both with client-side routing and a non-root public URL._x000D_
      Learn how to configure a non-root public URL by running `npm run build`._x000D_
    -->_x000D_
_x000D_
  <title>App Name</title>_x000D_
  <link href="<%= htmlWebpackPlugin.files.chunks.main.css[0] %>" rel="stylesheet">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <noscript>_x000D_
    You need to enable JavaScript to run this app._x000D_
  </noscript>_x000D_
  <div id="parentDiv" class="percentage">_x000D_
    <div id="percentage" class="innerpercentage">loading</div>_x000D_
  </div>_x000D_
  <div id="root"></div>_x000D_
  <!--_x000D_
      This HTML file is a template._x000D_
      If you open it directly in the browser, you will see an empty page._x000D_
_x000D_
      You can add webfonts, meta tags, or analytics to this file._x000D_
      The build step will place the bundled scripts into the <body> tag._x000D_
_x000D_
      To begin the development, run `npm start` or `yarn start`._x000D_
      To create a production bundle, use `npm run build` or `yarn build`._x000D_
    -->_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

In your production webpack configuration change the HtmlWebpackPlugin option to below

 new HtmlWebpackPlugin({
          inject: false,
...

You may need to use 'eject' command to get the configuration file. latest webpack might have the option to configure the HtmlWebpackPlugin without ejecting project. enter image description here

Angular 5 ngHide ngShow [hidden] not working

Your [hidden] will work but you need to check the css:

<input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden" />

And the css:

[hidden] {
  display: none !important;
}

That should work as you want.

Reading a single char in Java

Here is a class 'getJ' with a static function 'chr()'. This function reads one char.

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

class getJ {
    static char  chr()throws IOException{  
        BufferedReader bufferReader =new BufferedReader(new InputStreamReader(System.in));
        return bufferReader.readLine().charAt(0);
    }
}

In order to read a char use this:

anyFunc()throws IOException{
...
...
char c=getJ.chr();
}

Because of 'chr()' is static, you don't have to create 'getJ' by 'new' ; I mean you don't need to do:

getJ ob = new getJ;
c=ob.chr();

You should remember to add 'throws IOException' to the function's head. If it's impossible, use try / catch as follows:

anyFunc(){// if it's impossible to add 'throws IOException' here
...
try
{
char c=getJ.chr(); //reads a char into c
} 
catch(IOException e)
{
System.out.println("IOException has been caught");
}

Credit to: tutorialspoint.com

See also: geeksforgeeks.

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

Guid.NewGuid() vs. new Guid()

new Guid() makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).

Guid.NewGuid() makes an actual guid with a unique value, what you probably want.

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

Groovy method with optional parameters

Can't be done as it stands... The code

def myMethod(pParm1='1', pParm2='2'){
    println "${pParm1}${pParm2}"
}

Basically makes groovy create the following methods:

Object myMethod( pParm1, pParm2 ) {
    println "$pParm1$pParm2"
}

Object myMethod( pParm1 ) {
    this.myMethod( pParm1, '2' )
}

Object myMethod() {
    this.myMethod( '1', '2' )
}

One alternative would be to have an optional Map as the first param:

def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
    println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}

myMethod( 'a', 'b' )                // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd')    // prints 'a b 1 2nd'

Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)

Reset par to the default values at startup

Every time a new device is opened par() will reset, so another option is simply do dev.off() and continue.

base64 encode in MySQL

For those interested, these are the only alternatives so far:

1) Using these Functions:

http://wi-fizzle.com/downloads/base64.sql

2) If you already have the sys_eval UDF, (Linux) you can do this:

sys_eval(CONCAT("echo '",myField,"' | base64"));

The first method is known to be slow. The problem with the second one, is that the encoding is actually happening "outside" MySQL, which can have encoding problems (besides the security risks that you are adding with sys_* functions).

Unfortunately there is no UDF compiled version (which should be faster) nor a native support in MySQL (Posgresql supports it!).

It seems that the MySQL development team are not interested in implement it as this function already exists in other languages, which seems pretty silly to me.

Multiple github accounts on the same computer?

Got my private repo working using SSH key pairs. This was tested on git for Windows.

Source: https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

A. Generate public and private key pairs

  1. Start git bash
  2. Run ssh-keygen -t ed25519 -C "[email protected]"
  3. When you're prompted to "Enter a file in which to save the key," press Enter to accept the default.
  4. Press enter for a blank passphrase.
  5. Start the ssh agent: eval $(ssh-agent)
  6. Add private key to ssh agent and store the passphrase: ssh-add ~/.ssh/id_ed25519

B. Add SSH keys to GitHub account

  1. Copy the public key to the clipboard: clip < ~/.ssh/id_ed25519.pub
  2. On GitHub, go to Profile -> Settings -> SSH Keys -> New SSH Key
  3. Give a title. E.g. "Windows on MacBook Pro"
  4. Paste the key and hit "Add SSH Key".

C. Test SSH connection

  1. Enter: ssh -T [email protected]
  2. Hit "yes" for any warning message.
  3. It should show: "Hi username!..." indicating a successful test.

D. Setup local repository to use SSH keys

  1. Change email and user name:
git config user.email [email protected]
git config user.name github_username
  1. Update remote links to use git. First list remote URI's:
git remote -v
git remote set-url origin [email protected]:github_username/your-repo-name.git

E. Test

git remote show origin

Javascript date regex DD/MM/YYYY

Scape slashes is simply use \ before / and it will be escaped. (\/=> /).

Otherwise you're regex DD/MM/YYYY could be next:

/^[0-9]{2}[\/]{1}[0-9]{2}[\/]{1}[0-9]{4}$/g

Explanation:

  • [0-9]: Just Numbers
  • {2} or {4}: Length 2 or 4. You could do {2,4} as well to length between two numbers (2 and 4 in this case)
  • [\/]: Character /
  • g : Global -- Or m: Multiline (Optional, see your requirements)
  • $: Anchor to end of string. (Optional, see your requirements)
  • ^: Start of string. (Optional, see your requirements)

An example of use:

_x000D_
_x000D_
var regex = /^[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}$/g;

var dates = ["2009-10-09", "2009.10.09", "2009/10/09", "200910-09", "1990/10/09", 
    "2016/0/09", "2017/10/09", "2016/09/09", "20/09/2016", "21/09/2016", "22/09/2016",
    "23/09/2016", "19/09/2016", "18/09/2016", "25/09/2016", "21/09/2018"];

//Iterate array
dates.forEach(
    function(date){
        console.log(date + " matches with regex?");
      console.log(regex.test(date));
    });
_x000D_
_x000D_
_x000D_

Of course you can use as boolean:

if(regex.test(date)){
     //do something
}

What is the difference between atomic / volatile / synchronized?

Synchronized Vs Atomic Vs Volatile:

  • Volatile and Atomic is apply only on variable , While Synchronized apply on method.
  • Volatile ensure about visibility not atomicity/consistency of object , While other both ensure about visibility and atomicity.
  • Volatile variable store in RAM and it’s faster in access but we can’t achive Thread safety or synchronization whitout synchronized keyword.
  • Synchronized implemented as synchronized block or synchronized method while both not. We can thread safe multiple line of code with help of synchronized keyword while with both we can’t achieve the same.
  • Synchronized can lock the same class object or different class object while both can’t.

Please correct me if anything i missed.

Java Replacing multiple different substring in a string at once (or in the most efficient way)

Check this:

String.format(str,STR[])

For instance:

String.format( "Put your %s where your %s is", "money", "mouth" );

validate a dropdownlist in asp.net mvc

I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:

public class MyViewModel
{
    [Required]
    public string CategoryId { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}

and in your controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Categories = Repository.GetCategories()
        }
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // there was a validation error =>
            // rebind categories and redisplay view
            model.Categories = Repository.GetCategories();
            return View(model);
        }
        // At this stage the model is OK => do something with the selected category
        return RedirectToAction("Success");
    }
}

and then in your strongly typed view:

@Html.DropDownListFor(
    x => x.CategoryId, 
    new SelectList(Model.Categories, "ID", "CategoryName"), 
    "-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)

Also if you want client side validation don't forget to reference the necessary scripts:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

Executing periodic actions in Python

Simply sleeping for 10 seconds or using threading.Timer(10,foo) will result in start time drift. (You may not care about this, or it may be a significant source of problems depending on your exact situation.) There can be two causes for this - inaccuracies in the wake up time of your thread or execution time for your function.

You can see some results at the end of this post, but first an example of how to fix it. You need to track when your function should next be called as opposed to when it actually got called and account for the difference.

Here's a version that drifts slightly:

import datetime, threading

def foo():
    print datetime.datetime.now()
    threading.Timer(1, foo).start()

foo()

Its output looks like this:

2013-08-12 13:05:36.483580
2013-08-12 13:05:37.484931
2013-08-12 13:05:38.485505
2013-08-12 13:05:39.486945
2013-08-12 13:05:40.488386
2013-08-12 13:05:41.489819
2013-08-12 13:05:42.491202
2013-08-12 13:05:43.492486
2013-08-12 13:05:44.493865
2013-08-12 13:05:45.494987
2013-08-12 13:05:46.496479
2013-08-12 13:05:47.497824
2013-08-12 13:05:48.499286
2013-08-12 13:05:49.500232

You can see that the sub-second count is constantly increasing and thus, the start time is "drifting".

This is code that correctly accounts for drift:

import datetime, threading, time

next_call = time.time()

def foo():
  global next_call
  print datetime.datetime.now()
  next_call = next_call+1
  threading.Timer( next_call - time.time(), foo ).start()

foo()

Its output looks like this:

2013-08-12 13:21:45.292565
2013-08-12 13:21:47.293000
2013-08-12 13:21:48.293939
2013-08-12 13:21:49.293327
2013-08-12 13:21:50.293883
2013-08-12 13:21:51.293070
2013-08-12 13:21:52.293393

Here you can see that there is no longer any increase in the sub-second times.

If your events are occurring really frequently you may want to run the timer in a single thread, rather than starting a new thread for each event. While accounting for drift this would look like:

import datetime, threading, time

def foo():
    next_call = time.time()
    while True:
        print datetime.datetime.now()
        next_call = next_call+1;
        time.sleep(next_call - time.time())

timerThread = threading.Thread(target=foo)
timerThread.start()

However your application will not exit normally, you'll need to kill the timer thread. If you want to exit normally when your application is done, without manually killing the thread, you should use

timerThread = threading.Thread(target=foo)
timerThread.daemon = True
timerThread.start()

Select Multiple Fields from List in Linq

var selectedCategories =
    from value in
        (from data in listObject
        orderby data.category_name descending
        select new { ID = data.category_id, Name = data.category_name })
    group value by value.Name into g
    select g.First();

foreach (var category in selectedCategories) Console.WriteLine(category);

Edit: Made it more LINQ-ey!

Where does application data file actually stored on android device?

Application Private Data files are stored within <internal_storage>/data/data/<package>

Files being stored in the internal storage can be accessed with openFileOutput() and openFileInput()

When those files are created as MODE_PRIVATE it is not possible to see/access them within another application such as a FileManager.

Converting map to struct

The simplest way would be to use https://github.com/mitchellh/mapstructure

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

If you want to do it yourself, you could do something like this:

http://play.golang.org/p/tN8mxT_V9h

func SetField(obj interface{}, name string, value interface{}) error {
    structValue := reflect.ValueOf(obj).Elem()
    structFieldValue := structValue.FieldByName(name)

    if !structFieldValue.IsValid() {
        return fmt.Errorf("No such field: %s in obj", name)
    }

    if !structFieldValue.CanSet() {
        return fmt.Errorf("Cannot set %s field value", name)
    }

    structFieldType := structFieldValue.Type()
    val := reflect.ValueOf(value)
    if structFieldType != val.Type() {
        return errors.New("Provided value type didn't match obj field type")
    }

    structFieldValue.Set(val)
    return nil
}

type MyStruct struct {
    Name string
    Age  int64
}

func (s *MyStruct) FillStruct(m map[string]interface{}) error {
    for k, v := range m {
        err := SetField(s, k, v)
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    myData := make(map[string]interface{})
    myData["Name"] = "Tony"
    myData["Age"] = int64(23)

    result := &MyStruct{}
    err := result.FillStruct(myData)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(result)
}

Add left/right horizontal padding to UILabel

UIView* bg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 70)];
bg.backgroundColor = [UIColor blackColor];
UILabel* yourLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, y, yourWidth, yourHeight)];
[bg addSubview:yourLabel];

[self addSubview:bg];

How to create batch file in Windows using "start" with a path and command with spaces

Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.

Try something like this:

start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"

How to hide a <option> in a <select> menu with CSS?

For HTML5, you can use the 'hidden' attribute.

<option hidden>Hidden option</option>

It is not supported by IE < 11. But if you need only to hide a few elements, maybe it would be better to just set the hidden attribute in combination with disabled in comparison to adding/removing elements or doing not semantically correct constructions.

_x000D_
_x000D_
<select>  _x000D_
  <option>Option1</option>_x000D_
  <option>Option2</option>_x000D_
  <option hidden>Hidden Option</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Reference.

How can I disable editing cells in a WPF Datagrid?

The WPF DataGrid has an IsReadOnly property that you can set to True to ensure that users cannot edit your DataGrid's cells.

You can also set this value for individual columns in your DataGrid as needed.

How can I make a list of installed packages in a certain virtualenv?

list out the installed packages in the virtualenv

step 1:

workon envname

step 2:

pip freeze

it will display the all installed packages and installed packages and versions

Aligning label and textbox on same line (left and right)

You can do it with a table, like this:

<table width="100%">
  <tr>
    <td style="width: 50%">Left Text</td>
    <td style="width: 50%; text-align: right;">Right Text</td>
  </tr>
</table>

Or, you can do it with CSS like this:

<div style="float: left;">
    Left text
</div>
<div style="float: right;">
    Right text
</div>

jQuery Mobile: document ready vs. page events

This is the correct way:

To execute code that will only be available to the index page, we could use this syntax:

$(document).on('pageinit', "#index",  function() {
    ...
});

What's the difference between Docker Compose vs. Dockerfile

Imagine you are the manager of a software company and you just bought a brand new server. Just the hardware.

Think of Dockerfile as a set of instructions you would tell your system adminstrator what to install on this brand new server. For example:

  • We need a Debian linux
  • add an apache web server
  • we need postgresql as well
  • install midnight commander
  • when all done, copy all *.php, *.jpg, etc. files of our project into the webroot of the webserver (/var/www)

By contrast, think of docker-compose.yml as a set of instructions you would tell your system administrator how the server can interact with the rest of the world. For example,

  • it has access to a shared folder from another computer,
  • it's port 80 is the same as the port 8000 of the host computer,
  • and so on.

(This is not a precise explanation but good enough to start with.)

Moment.js - tomorrow, today and yesterday

I have similar solution, but allows to use locales:

    let date = moment(someDate);
    if (moment().diff(date, 'days') >= 1) {
        return date.fromNow(); // '2 days ago' etc.
    }
    return date.calendar().split(' ')[0]; // 'Today', 'yesterday', 'tomorrow'

Responsive Google Map?

Responsive with CSS You can make the Iframe responsive with the following CSS codes.

.map {
    position: relative;
    padding-bottom: 26.25%;
    padding-top: 30px;
    height: 0;
    overflow: hidden;
}

.map iframe,
.map object,
.map embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

Responsive with JavaScript

This possible through window.resize event and you can apply this on google map like google.maps.event.addDomListener(window, 'resize', initialize);

Consider the following example:

function initialize() {
    var mapOptions = {
           zoom: 9,
           center: new google.maps.LatLng(28.9285745, 77.09149350000007),  
           mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    
    var map = new google.maps.Map(document.getElementById('location-canvas'), mapOptions);
    var marker = new google.maps.Marker({
           map: map,
           draggable: false,
           position: new google.maps.LatLng(28.9285745, 77.09149350000007)
     });
}
google.maps.event.addDomListener(window, 'resize', initialize);

Take a look for more details - https://webomnizz.com/how-to-make-responsive-google-map-with-google-map-api/

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

Angular 5 - Copy to clipboard

Modified version of jockeisorby's answer that fixes the event handler not being properly removed.

copyToClipboard(item): void {
    let listener = (e: ClipboardEvent) => {
        e.clipboardData.setData('text/plain', (item));
        e.preventDefault();
    };

    document.addEventListener('copy', listener);
    document.execCommand('copy');
    document.removeEventListener('copy', listener);
}

Use multiple css stylesheets in the same html page

You can't control which you're referencing, given the same level of specificity in the rule (e.g. both are simply .banner) the stylesheet included last will win.

It's per-property, so if there's a combination going on (for example one has background, the other has color) then you'll get the combination...if a property is defined in both, whatever it is the last time it appears in stylesheet order wins.

How do I remove a single file from the staging area (undo git add)?

In case you just want to remove a subset of the changes to your file, you can use:

git reset -p

or

git reset -p <file_name>

This command is basically the reverse of git add -p: it will only remove the selected changes from the staging area. I find it extremely useful in "unadding" something that I added by mistake.

Twitter-Bootstrap-2 logo image on top of navbar

If you do not increase the height of navbar..

 .navbar .brand {
 position: fixed;    
 overflow: visible;
 padding-left: 0;    
 padding-top: 0;
 }

see http://jsfiddle.net/petrfox/S84wP/

Java - How do I make a String array with values?

By using the array initializer list syntax, ie:

String myArray[] = { "one", "two", "three" };

System.Net.WebException: The operation has timed out

I encountered the same error than adding

Task.Delay(2000);

in each request solved the problem

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

Try to set :

default_socket_timeout = 120

in your php.ini file.

Save current directory in variable using Bash?

Your assignment has an extra $:

export PATH=$PATH:${PWD}:/foo/bar

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

How does "cat << EOF" work in bash?

This is called heredoc format to provide a string into stdin. See https://en.wikipedia.org/wiki/Here_document#Unix_shells for more details.


From man bash:

Here Documents

This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen.

All of the lines read up to that point are then used as the standard input for a command.

The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.

If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.

Wait one second in running program

Busy waiting won't be a severe drawback if it is short. In my case there was the need to give visual feedback to the user by flashing a control (it is a chart control that can be copied to clipboard, which changes its background for some milliseconds). It works fine this way:

using System.Threading;
...
Clipboard.SetImage(bm);   // some code
distribution_chart.BackColor = Color.Gray;
Application.DoEvents();   // ensure repaint, may be not needed
Thread.Sleep(50);
distribution_chart.BackColor = Color.OldLace;
....

Method to Add new or update existing item in Dictionary

Functionally, they are equivalent.

Performance-wise map[key] = value would be quicker, as you are only making single lookup instead of two.

Style-wise, the shorter the better :)

The code will in most cases seem to work fine in multi-threaded context. It however is not thread-safe without extra synchronization.