Programs & Examples On #Pykde

Is it possible to insert multiple rows at a time in an SQLite database?

update

As BrianCampbell points out here, SQLite 3.7.11 and above now supports the simpler syntax of the original post. However, the approach shown is still appropriate if you want maximum compatibility across legacy databases.

original answer

If I had privileges, I would bump river's reply: You can insert multiple rows in SQLite, you just need different syntax. To make it perfectly clear, the OPs MySQL example:

INSERT INTO 'tablename' ('column1', 'column2') VALUES
  ('data1', 'data2'),
  ('data1', 'data2'),
  ('data1', 'data2'),
  ('data1', 'data2');

This can be recast into SQLite as:

     INSERT INTO 'tablename'
          SELECT 'data1' AS 'column1', 'data2' AS 'column2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'

a note on performance

I originally used this technique to efficiently load large datasets from Ruby on Rails. However, as Jaime Cook points out, it's not clear this is any faster wrapping individual INSERTs within a single transaction:

BEGIN TRANSACTION;
INSERT INTO 'tablename' table VALUES ('data1', 'data2');
INSERT INTO 'tablename' table VALUES ('data3', 'data4');
...
COMMIT;

If efficiency is your goal, you should try this first.

a note on UNION vs UNION ALL

As several people commented, if you use UNION ALL (as shown above), all rows will be inserted, so in this case, you'd get four rows of data1, data2. If you omit the ALL, then duplicate rows will be eliminated (and the operation will presumably be a bit slower). We're using UNION ALL since it more closely matches the semantics of the original post.

in closing

P.S.: Please +1 river's reply, as it presented the solution first.

AndroidStudio gradle proxy

If build failed due to gradle proxy setting then simply putting my proxy IP address and port number will solve. It worked for me. File -> setting -> http proxy -> manual configuration -> Host name: your proxy IP, port number: your proxy port number.

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

Reading value from console, interactively

@rob answer will work most of the times, but it might not work as you expect with long inputs.

That is what you should be using instead:

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', d => {
  content += d.toString();
});

stdin.addListener('end', () => {
  console.info(`Input: ${content}`);
});

Explanation on why this solution works:

addListener('data') works like a buffer, callback will be called when it is full or/and its the end of input.

What about long inputs? A single 'data' callback will not be enough, hence it you will get your input split in two or more parts. That is often not convenient.

addListener('end') will notify us when the stdin reader is done reading our input. Since we have been storing the previous data, we can now read and process it all together.

Detect home button press in android

Since API 14 you can use the function onTrimMemory() and check for the flag TRIM_MEMORY_UI_HIDDEN. This will tell you that your Application is going to the background.

So in your custom Application class you can write something like:

override fun onTrimMemory(level: Int) {
    if (level == TRIM_MEMORY_UI_HIDDEN) {
        // Application going to background, do something
    }
}

For an in-depth study of this, I invite you to read this article: http://www.developerphil.com/no-you-can-not-override-the-home-button-but-you-dont-have-to/

Multiple github accounts on the same computer?

Use HTTPS:

change remote url to https:

git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

and you are good to go:

git push

To ensure that the commits appear as performed by USERNAME, one can setup the user.name and user.email for this project, too:

git config user.name USERNAME
git config user.email [email protected]

C# Generics and Type Checking

By default know there is not a great way. Awhile back I got frustrated with this and wrote a little utility class that helped out a bit and made the syntax a bit cleaner. Essentially it turns the code into

TypeSwitcher.Do(clause[0],
  TypeSwitch.Case<int>(x => ...),  // x is an int
  TypeSwitch.Case<decimal>(d => ...), // d is a decimal 
  TypeSwitch.Case<string>(s => ...)); // s is a string

Full blog post and details on the implementation are available here

java.lang.IllegalArgumentException: contains a path separator

File file = context.getFilesDir(); 
file.mkdir();
String[] array = filePath.split("/"); 
for(int t = 0; t < array.length - 1; t++) {
    file = new File(file, array[t]); 
    file.mkdir();
}
File f = new File(file,array[array.length- 1]); 
RandomAccessFileOutputStream rvalue = 
    new RandomAccessFileOutputStream(f, append);

HTML Input - already filled in text

<input type="text" value="Your value">

Use the value attribute for the pre filled in values.

No newline after div?

Quoting Mr Initial Man from here:

Instead of this:

<div id="Top" class="info"></div><a href="#" class="a_info"></a>

Use this:

<span id="Top" class="info"></span><a href="#" class="a_info"></a>

Also, you could use this:

<div id="Top" class="info"><a href="#" class="a_info"></a></div>

And gostbustaz:

If you absoultely must use a <div>, you can set

div {
    display: inline;
}

in your stylesheet.

Of course, that essentially makes the <div> a <span>.

How to filter rows containing a string pattern from a Pandas dataframe

df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1

Step-by-step explanation (from inner to outer):

  • df['ids'] selects the ids column of the data frame (technically, the object df['ids'] is of type pandas.Series)
  • df['ids'].str allows us to apply vectorized string methods (e.g., lower, contains) to the Series
  • df['ids'].str.contains('ball') checks each element of the Series as to whether the element value has the string 'ball' as a substring. The result is a Series of Booleans indicating True or False about the existence of a 'ball' substring.
  • df[df['ids'].str.contains('ball')] applies the Boolean 'mask' to the dataframe and returns a view containing appropriate records.
  • na = False removes NA / NaN values from consideration; otherwise a ValueError may be returned.

Concatenate a NumPy array to another NumPy array

I had the same issue, and I couldn't comment on @Sven Marnach answer (not enough rep, gosh I remember when Stackoverflow first started...) anyway.

Adding a list of random numbers to a 10 X 10 matrix.

myNpArray = np.zeros([1, 10])
for x in range(1,11,1):
    randomList = [list(np.random.randint(99, size=10))]
    myNpArray = np.vstack((myNpArray, randomList))
myNpArray = myNpArray[1:]

Using np.zeros() an array is created with 1 x 10 zeros.

array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

Then a list of 10 random numbers is created using np.random and assigned to randomList. The loop stacks it 10 high. We just have to remember to remove the first empty entry.

myNpArray

array([[31., 10., 19., 78., 95., 58.,  3., 47., 30., 56.],
       [51., 97.,  5., 80., 28., 76., 92., 50., 22., 93.],
       [64., 79.,  7., 12., 68., 13., 59., 96., 32., 34.],
       [44., 22., 46., 56., 73., 42., 62.,  4., 62., 83.],
       [91., 28., 54., 69., 60., 95.,  5., 13., 60., 88.],
       [71., 90., 76., 53., 13., 53., 31.,  3., 96., 57.],
       [33., 87., 81.,  7., 53., 46.,  5.,  8., 20., 71.],
       [46., 71., 14., 66., 68., 65., 68., 32.,  9., 30.],
       [ 1., 35., 96., 92., 72., 52., 88., 86., 94., 88.],
       [13., 36., 43., 45., 90., 17., 38.,  1., 41., 33.]])

So in a function:

def array_matrix(random_range, array_size):
    myNpArray = np.zeros([1, array_size])
    for x in range(1, array_size + 1, 1):
        randomList = [list(np.random.randint(random_range, size=array_size))]
        myNpArray = np.vstack((myNpArray, randomList))
    return myNpArray[1:]

a 7 x 7 array using random numbers 0 - 1000

array_matrix(1000, 7)

array([[621., 377., 931., 180., 964., 885., 723.],
       [298., 382., 148., 952., 430., 333., 956.],
       [398., 596., 732., 422., 656., 348., 470.],
       [735., 251., 314., 182., 966., 261., 523.],
       [373., 616., 389.,  90., 884., 957., 826.],
       [587., 963.,  66., 154., 111., 529., 945.],
       [950., 413., 539., 860., 634., 195., 915.]])

What is a 'multi-part identifier' and why can't it be bound?

A multipart identifier is any description of a field or table that contains multiple parts - for instance MyTable.SomeRow - if it can't be bound that means there's something wrong with it - either you've got a simple typo, or a confusion between table and column. It can also be caused by using reserved words in your table or field names and not surrounding them with []. It can also be caused by not including all of the required columns in the target table.

Something like redgate sql prompt is brilliant for avoiding having to manually type these (it even auto-completes joins based on foreign keys), but isn't free. SQL server 2008 supports intellisense out of the box, although it isn't quite as complete as the redgate version.

How to find out if a file exists in C# / .NET?

System.IO.File:

using System.IO;

if (File.Exists(path)) 
{
    Console.WriteLine("file exists");
} 

Run reg command in cmd (bat file)?

In command line it's better to use REG tool rather than REGEDIT:

REG IMPORT yourfile.reg

REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:

>  REG IMPORT missing_file.reg

ERROR: Error opening the file. There may be a disk or file system error.

>  %windir%\System32\reg.exe /?

REG Operation [Parameter List]

  Operation  [ QUERY   | ADD    | DELETE  | COPY    |
               SAVE    | LOAD   | UNLOAD  | RESTORE |
               COMPARE | EXPORT | IMPORT  | FLAGS ]

Return Code: (Except for REG COMPARE)

  0 - Successful
  1 - Failed

For help on a specific operation type:

  REG Operation /?

Examples:

  REG QUERY /?
  REG ADD /?
  REG DELETE /?
  REG COPY /?
  REG SAVE /?
  REG RESTORE /?
  REG LOAD /?
  REG UNLOAD /?
  REG COMPARE /?
  REG EXPORT /?
  REG IMPORT /?
  REG FLAGS /?

C# Convert List<string> to Dictionary<string, string>

Try this:

var res = list.ToDictionary(x => x, x => x);

The first lambda lets you pick the key, the second one picks the value.

You can play with it and make values differ from the keys, like this:

var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));

If your list contains duplicates, add Distinct() like this:

var res = list.Distinct().ToDictionary(x => x, x => x);

EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String> would provide a much better fit for your situation:

var res = new HashSet<string>(list);
if (res.Contains("string1")) ...

Spring Boot War deployed to Tomcat

Your Application.java class should extend the SpringBootServletInitializer class ex:

public class Application extends SpringBootServletInitializer {}

Convert byte slice to io.Reader

r := strings(byteData)

This also works to turn []byte into io.Reader

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Use fetch instead of XHR,then the request will not be prelighted even it's cross-domained.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

How to set a header in an HTTP response?

In my Controller, I merely added an HttpServletResponse parameter and manually added the headers, no filter or intercept required and it works fine:

httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, WWW-Authenticate, Authorization");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "false");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");

How do I 'svn add' all unversioned files to SVN?

This worked for me:

svn add `svn status . | grep "^?" | awk '{print $2}'`

(Source)

As you already solved your problem for Windows, this is a UNIX solution (following Sam). I added here as I think it is still useful for those who reach this question asking for the same thing (as the title does not include the keyword "WINDOWS").

Note (Feb, 2015): As commented by "bdrx", the above command could be further simplified in this way:

 svn add `svn status . | awk '/^[?]/{print $2}'`

How to get only the date value from a Windows Forms DateTimePicker control?

I'm assuming you mean a datetime picker in a winforms application.

in your code, you can do the following:

string theDate = dateTimePicker1.Value.ToShortDateString();

or, if you'd like to specify the format of the date:

string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");

C# How to change font of a label

You can't change a Font once it's created - so you need to create a new one:

  mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

ES6 modules implementation, how to load a json file

First of all you need to install json-loader:

npm i json-loader --save-dev

Then, there are two ways how you can use it:

  1. In order to avoid adding json-loader in each import you can add to webpack.config this line:

    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      // other loaders 
    ]
    

    Then import json files like this

    import suburbs from '../suburbs.json';
    
  2. Use json-loader directly in your import, as in your example:

    import suburbs from 'json!../suburbs.json';
    

Note: In webpack 2.* instead of keyword loaders need to use rules.,

also webpack 2.* uses json-loader by default

*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.

v2.1.0-beta.28

How to add a new project to Github using VS Code

Yes you can upload your git repo from vs code. You have to get in the projects working directory and type git init in the terminal. Then add the files to your repository like you do with regular git commits.

HTTP 400 (bad request) for logical error, not malformed request syntax

On Java EE servers a 400 is returned if your URL refers to a non-existent "web -application". Is that a "syntax error"? Depends on what you mean by syntax error. I would say yes.

In English syntax rules prescribe certain relationships between parts of speech. For instance "Bob marries Mary" is syntactically correct, because it follows the pattern {Noun + Verb + Noun}. Whereas "Bob marriage Mary" would be syntactically incorrect, {Noun + Noun + Noun}.

The syntax of a simple URLis { protocol + : + // + server + : + port }. According to this "http://www.google.com:80" is syntactically correct.

But what about "abc://www.google.com:80"? It seems to follow the exact same pattern. But really it is a syntax error. Why? Because 'abc' is not a DEFINED protocol.

The point is that determining whether or not we have a 400 situation requires more than parsing the characters and spaces and delimiters. It must also recognize what are the valid "parts of speech".

Redirect to specified URL on PHP script completion?

<?
ob_start(); // ensures anything dumped out will be caught

// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever

// clear out the output buffer
while (ob_get_status()) 
{
    ob_end_clean();
}

// no redirect
header( "Location: $url" );
?>

SQL Query to search schema of all tables

For me I only have read access to run querys so I need to use this function often here is what I use:

SELECT  *
FROM    INFORMATION_SCHEMA.TABLES
where   TABLES.TABLE_NAME like '%your table name here%'

You can replace .TABLES with .COLUMNS then it would look like this:

 SELECT *
 FROM   INFORMATION_SCHEMA.COLUMNS
 WHERE  columns.COLUMN_NAME like '%your column name here%'

Implementation difference between Aggregation and Composition in Java

Aggregation vs Composition

Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist.

whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human.

Aggregation relation is “has-a” and composition is “part-of” relation.

Composition is a strong Association whereas Aggregation is a weak Association.

Java - Check if input is a positive integer, negative integer, natural number and so on.

You could use if(number >= 0). The fact that you use int number = input.nextInt(); makes sure that it has to be an Integer.

Count elements with jQuery

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});

Granting Rights on Stored Procedure to another user of Oracle

You can't do what I think you're asking to do.

The only privileges you can grant on procedures are EXECUTE and DEBUG.

If you want to allow user B to create a procedure in user A schema, then user B must have the CREATE ANY PROCEDURE privilege. ALTER ANY PROCEDURE and DROP ANY PROCEDURE are the other applicable privileges required to alter or drop user A procedures for user B. All are wide ranging privileges, as it doesn't restrict user B to any particular schema. User B should be highly trusted if granted these privileges.

EDIT:

As Justin mentioned, the way to give execution rights to A for a procedure owned by B:

GRANT EXECUTE ON b.procedure_name TO a;

HAX kernel module is not installed

Recently, I have faced this issue. And fixed it by changing CPU/ABI from Intel Atom (x86) to ARM(armeabi-v7a).

  • Select the Virtual Device. Click on Edit
  • Click on CPU/ABI option
  • Change it to ARM(armeabi-v7a) from intel. Click OK

Job done.

How to know if .keyup() is a character key (jQuery)

I wanted to do exactly this, and I thought of a solution involving both the keyup and the keypress events.

(I haven't tested it in all browsers, but I used the information compiled at http://unixpapa.com/js/key.html)

Edit: rewrote it as a jQuery plugin.

(function($) {
    $.fn.normalkeypress = function(onNormal, onSpecial) {
        this.bind('keydown keypress keyup', (function() {
            var keyDown = {}, // keep track of which buttons have been pressed
                lastKeyDown;
            return function(event) {
                if (event.type == 'keydown') {
                    keyDown[lastKeyDown = event.keyCode] = false;
                    return;
                }
                if (event.type == 'keypress') {
                    keyDown[lastKeyDown] = event; // this keydown also triggered a keypress
                    return;
                }

                // 'keyup' event
                var keyPress = keyDown[event.keyCode];
                if ( keyPress &&
                     ( ( ( keyPress.which >= 32 // not a control character
                           //|| keyPress.which == 8  || // \b
                           //|| keyPress.which == 9  || // \t
                           //|| keyPress.which == 10 || // \n
                           //|| keyPress.which == 13    // \r
                           ) &&
                         !( keyPress.which >= 63232 && keyPress.which <= 63247 ) && // not special character in WebKit < 525
                         !( keyPress.which == 63273 )                            && //
                         !( keyPress.which >= 63275 && keyPress.which <= 63277 ) && //
                         !( keyPress.which === event.keyCode && // not End / Home / Insert / Delete (i.e. in Opera < 10.50)
                            ( keyPress.which == 35  || // End
                              keyPress.which == 36  || // Home
                              keyPress.which == 45  || // Insert
                              keyPress.which == 46  || // Delete
                              keyPress.which == 144    // Num Lock
                              )
                            )
                         ) ||
                       keyPress.which === undefined // normal character in IE < 9.0
                       ) &&
                     keyPress.charCode !== 0 // not special character in Konqueror 4.3
                     ) {

                    // Normal character
                    if (onNormal) onNormal.call(this, keyPress, event);
                } else {
                    // Special character
                    if (onSpecial) onSpecial.call(this, event);
                }
                delete keyDown[event.keyCode];
            };
        })());
    };
})(jQuery);

How to declare a static const char* in your header file?

With C++11 you can use the constexpr keyword and write in your header:

private:
    static constexpr const char* SOMETHING = "something";


Notes:

  • constexpr makes SOMETHING a constant pointer so you cannot write

    SOMETHING = "something different";
    

    later on.

  • Depending on your compiler, you might also need to write an explicit definition in the .cpp file:

    constexpr const char* MyClass::SOMETHING;
    

Bootstrap 3 - 100% height of custom div inside column

You need to set the height of every parent element of the one you want the height defined.

<html style="height: 100%;">
  <body style="height: 100%;">
    <div style="height: 100%;">
      <p>
        Make this division 100% height.
      </p>
    </div>
  </body>
</html>

Article.

JsFiddle example

Str_replace for multiple items

str_replace(
    array("search","items"),
    array("replace", "items"),
    $string
);

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

Javascript equivalent of php's strtotime()?

_x000D_
_x000D_
var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');_x000D_
var date = moment(strdate).format('DD.MM.YYYY');_x000D_
$("#result").text(date); //07.02.2017
_x000D_
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>_x000D_
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How to convert object to Dictionary<TKey, TValue> in C#?

The above answers are all cool. I found it easy to json serialize the object and deserialize as a dictionary.

var json = JsonConvert.SerializeObject(obj);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

I don't know how performance is effected but this is much easier to read. You could also wrap it inside a function.

public static Dictionary<string, TValue> ToDictionary<TValue>(object obj)
{       
    var json = JsonConvert.SerializeObject(obj);
    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TValue>>(json);   
    return dictionary;
}

Use like so:

var obj = new { foo = 12345, boo = true };
var dictionary = ToDictionary<string>(obj);

C# how to convert File.ReadLines into string array?

string[] lines = File.ReadLines("c:\\file.txt").ToArray();

Although one wonders why you'll want to do that when ReadAllLines works just fine.

Or perhaps you just want to enumerate with the return value of File.ReadLines:

var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
    Console.WriteLine("\t" + line);
}

Rails :include vs. :joins

'joins' just used to join tables and when you called associations on joins then it will again fire query (it mean many query will fire)

lets suppose you have tow model, User and Organisation
User has_many organisations
suppose you have 10 organisation for a user 
@records= User.joins(:organisations).where("organisations.user_id = 1")
QUERY will be 
 select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1

it will return all records of organisation related to user
and @records.map{|u|u.organisation.name}
it run QUERY like 
select * from organisations where organisations.id = x then time(hwo many organisation you have)

total number of SQL is 11 in this case

But with 'includes' will eager load the included associations and add them in memory(load all associations on first load) and not fire query again

when you get records with includes like @records= User.includes(:organisations).where("organisations.user_id = 1") then query will be

select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1
and 


 select * from organisations where organisations.id IN(IDS of organisation(1, to 10)) if 10 organisation
and when you run this 

@records.map{|u|u.organisation.name} no query will fire

event.preventDefault() function not working in IE

If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter. It will always contain the preventDefault() method.

Try out this fiddle to see the difference in event binding. http://jsfiddle.net/pFqrY/8/

// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
 alert(typeof(event.preventDefault));
});

// preventDefault missing in IE
<button
  id="htmlbutton"
  onclick="alert(typeof(event.preventDefault));">
  button</button>

For all jQuery users out there you can fix an event when needed. Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.

e = $.event.fix(e);

After that e.preventDefault(); works fine.

How can I change the value of the elements in a vector?

Just use:

for (int i = 0; i < v.size(); i++)
{
    v[i] -= valueToSubstract;
}

Or its equivalent (and more readable?):

for (int i = 0; i < v.size(); i++)
    v[i] = v[i] - valueToSubstract;

Algorithm: efficient way to remove duplicate integers from an array

In Java I would solve it like this. Don't know how to write this in C.

   int length = array.length;
   for (int i = 0; i < length; i++) 
   {
      for (int j = i + 1; j < length; j++) 
      {
         if (array[i] == array[j]) 
         {
            int k, j;
            for (k = j + 1, l = j; k < length; k++, l++) 
            {
               if (array[k] != array[i]) 
               {
                  array[l] = array[k];
               }
               else
               {
                  l--;
               }
            }
            length = l;
         }
      }
   }

jQuery when element becomes visible

I just Improved ProllyGeek`s answer

Someone may find it useful. you can access displayChanged(event, state) event when .show(), .hide() or .toggle() is called on element

(function() {
  var eventDisplay = new $.Event('displayChanged'),
    origShow = $.fn.show,
    origHide = $.fn.hide;
  //
  $.fn.show = function() {
    origShow.apply(this, arguments);
    $(this).trigger(eventDisplay,['show']);
  };
  //
  $.fn.hide = function() {
    origHide.apply(this, arguments);
    $(this).trigger(eventDisplay,['hide']);
  };
  //
})();

$('#header').on('displayChanged', function(e,state) {
      console.log(state);
});

$('#header').toggle(); // .show() .hide() supported

SQL selecting rows by most recent date with two unique columns

I see most of the developers use inline query without looking out it's impact on huge data.

in simple you can achieve this by:

select a.chargeId, a.chargeType, a.serviceMonth 
from invoice a
left outer join invoice b
on a.chargeId=b.chargeId and a.serviceMonth <b.serviceMonth 
where b.chargeId is null
order by a.serviceMonth desc

Hadoop/Hive : Loading data from .csv on a local machine

You can load local CSV file to Hive only if:

  1. You are doing it from one of the Hive cluster nodes.
  2. You installed Hive client on non-cluster node and using hive or beeline for upload.

Swift presentViewController

For those getting blank/black screens this code worked for me.

    let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
    self.present(vc, animated: true, completion: nil)

To set the "Identifier" to your VC just go to identity inspector for the VC in the storyboard. Set the 'Storyboard ID' to what ever you want to identifier to be. Look at the image below for reference.

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

java -jar server-0.0.1-SNAPSHOT.jar --spring.config.location=application-prod.properties

C: printf a float value

Use %.6f. This will print 6 decimals.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Remove Android App Title Bar

If you have import android.support.v7.app.ActionBarActivity; and your class extends ActionBarActivity then use this in your OnCreate:

android.support.v7.app.ActionBar AB=getSupportActionBar();
AB.hide();

Plotting 4 curves in a single plot, with 3 y-axes

In your case there are 3 extra y axis (4 in total) and the best code that could be used to achieve what you want and deal with other cases is illustrated above:

clear
clc

x = linspace(0,1,10);
N = numel(x);
y = rand(1,N);
y_extra_1 = 5.*rand(1,N)+5;
y_extra_2 = 50.*rand(1,N)+20;
Y = [y;y_extra_1;y_extra_2];

xLimit = [min(x) max(x)];
xWidth = xLimit(2)-xLimit(1);
numberOfExtraPlots = 2;
a = 0.05;
N_ = numberOfExtraPlots+1;

for i=1:N_
    L=1-(numberOfExtraPlots*a)-0.2;
    axesPosition = [(0.1+(numberOfExtraPlots*a)) 0.1 L 0.8];
    if(i==1)
        color = [rand(1),rand(1),rand(1)];
        figure('Units','pixels','Position',[200 200 1200 600])
        axes('Units','normalized','Position',axesPosition,...
            'Color','w','XColor','k','YColor',color,...
            'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
            'NextPlot','add');
        plot(x,Y(i,:),'Color',color);
        xlabel('Time (s)');

        ylab = strcat('Values of dataset 0',num2str(i));
        ylabel(ylab)

        numberOfExtraPlots = numberOfExtraPlots - 1;
    else
        color = [rand(1),rand(1),rand(1)];
        axes('Units','normalized','Position',axesPosition,...
            'Color','none','XColor','k','YColor',color,...
            'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
            'XTick',[],'XTickLabel',[],'NextPlot','add');
        V = (xWidth*a*(i-1))/L;
        b=xLimit+[V 0];
        x_=linspace(b(1),b(2),10);
        plot(x_,Y(i,:),'Color',color);
        ylab = strcat('Values of dataset 0',num2str(i));
        ylabel(ylab)

        numberOfExtraPlots = numberOfExtraPlots - 1;
    end
end

The code above will produce something like this:

Refresh DataGridView when updating data source

You are setting the datasource inside of the loop and sleeping 500 after each add. Why not just add to itemstates and then set your datasource AFTER you have added everything. If you want the thread sleep after that fine. The first block of code here is yours the second block I modified.

for (int i = 0; i < 10; i++) { 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = itemStates;
    System.Threading.Thread.Sleep(500);
}

Change your Code As follows: this is much faster.

for (int i = 0; i < 10; i++) { 
    itemStates.Add(new ItemState { Id = i.ToString() });

}
    dataGridView1.DataSource = typeof(List); 
    dataGridView1.DataSource = itemStates;
    System.Threading.Thread.Sleep(500);

OSError - Errno 13 Permission denied

Another option is to ensure the file is not open anywhere else on your machine.

Running Groovy script from the command line

You need to run the script like this:

groovy helloworld.groovy

Generate Controller and Model

Models:

php artisan krlove:generate:model Videos --table-name=videos

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

Passing structs to functions

It is possible to construct a struct inside the function arguments:

function({ .variable = PUT_DATA_HERE });

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

Should C# or C++ be chosen for learning Games Programming (consoles)?

If you want to be employed professionally as a game developer you need to know C/C++. End of story!

Getting HTTP headers with Node.js

I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

HEAD

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


Something like this, based it on this question:

var cli = require('cli');
var http = require('http');
var url = require('url');

cli.parse();

cli.main(function(args, opts) {
        this.debug(args[0]);

        var siteUrl = url.parse(args[0]);
        var site = http.createClient(80, siteUrl.host);
        console.log(siteUrl);

        var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
        request.end();

        request.on('response', function(response) {
                response.setEncoding('utf8');
                console.log('STATUS: ' + response.statusCode);
                response.on('data', function(chunk) {
                        console.log("DATA: " + chunk);
                });
        });
});

how to check for null with a ng-if values in a view with angularjs?

Here is a simple example that I tried to explain.

<div>
    <div *ngIf="product">     <!--If "product" exists-->
      <h2>Product Details</h2><hr>
      <h4>Name: {{ product.name }}</h4>
      <h5>Price: {{ product.price | currency }}</h5>
      <p> Description: {{ product.description }}</p>
    </div>

    <div *ngIf="!product">     <!--If "product" not exists-->
       *Product not found
    </div>
</div>

Programmatically getting the MAC of an Android device

Using this simple method

WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            String WLANMAC = wm.getConnectionInfo().getMacAddress();

Is there an effective tool to convert C# code to Java code?

Well the syntax is almost the same but they rely on different frameworks so the only way to convert is by getting someone who knows both languages and convert the code :) the answer to your question is no there is no "effective" tool to convert c# to java

Cross-browser custom styling for file upload button

It's also easy to style the label if you are working with Bootstrap and LESS:

label {
    .btn();
    .btn-primary();

    > input[type="file"] {
        display: none;
    }
}

How do I serialize a Python dictionary into a string, and then back to a dictionary?

pyyaml should also be mentioned here. It is both human readable and can serialize any python object.
pyyaml is hosted here:
https://bitbucket.org/xi/pyyaml

OS X: equivalent of Linux's wget

You could use curl instead. It is installed by default into /usr/bin.

How to run a shell script in OS X by double-clicking?

No need to use third-party apps such as Platypus.

Just create an Apple Script with Script Editor and use the command do shell script "shell commands" for direct command calls or executable shell script files, keep the editable script file safe somewhere then export it to create an Application script. the app script is launch-able by double click or selection in bar folder.

Truncate number to two decimal places without rounding

I opted to write this instead to manually remove the remainder with strings so I don't have to deal with the math issues that come with numbers:

num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
Number(num); //If you need it back as a Number

This will give you "15.77" with num = 15.7784514;

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

Mac version. From terminal run:

open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files

Does :before not work on img elements?

The before and after pseudo-selectors don't insert HTML elements — they insert text before or after the existing content of the targeted element. Because image elements don't contain text or have descendants, neither img:before or img:after will do you any good. This is also the case for elements like <br> and <hr> for the same reason.

phpmyadmin logs out after 1440 secs

You will then get another warning: “Your PHP parameter session.gc_maxlifetime is lower that cookie validity configured in phpMyAdmin, because of this, your login will expire sooner than configured in phpMyAdmin.“. That makes sense because php’s session will time out first anyways. So we will need to change /etc/php.ini .

session.gc_maxlifetime = 43200
That’s 12 hours in seconds. 

Restart your apache server and you are done!

source: http://birdchan.com/home/2011/06/06/phpmyadmin-timeout-after-1440-seconds/

this works for me! :)

Iteration over std::vector: unsigned vs signed index variable

Use size_t :

for (size_t i=0; i < polygon.size(); i++)

Quoting Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

How to show an alert box in PHP?

echo '<script language="javascript>';

Seems like a simple typo. You're missing a double-quote.

echo '<script language="javascript">';

This should do.

Call a method of a controller from another controller using 'scope' in AngularJS

Each controller has it's own scope(s) so that's causing your issue.

Having two controllers that want access to the same data is a classic sign that you want a service. The angular team recommends thin controllers that are just glue between views and services. And specifically- "services should hold shared state across controllers".

Happily, there's a nice 15-minute video describing exactly this (controller communication via services): video

One of the original author's of Angular, Misko Hevery, discusses this recommendation (of using services in this situation) in his talk entitled Angular Best Practices (skip to 28:08 for this topic, although I very highly recommended watching the whole talk).

You can use events, but they are designed just for communication between two parties that want to be decoupled. In the above video, Misko notes how they can make your app more fragile. "Most of the time injecting services and doing direct communication is preferred and more robust". (Check out the above link starting at 53:37 to hear him talk about this)

What is the difference between instanceof and Class.isAssignableFrom(...)?

instanceof cannot be used with primitive types or generic types either. As in the following code:

//Define Class< T > type ... 

Object e = new Object();

if(e instanceof T) {
  // Do something.
}

The error is: Cannot perform instanceof check against type parameter T. Use it's erasure Object instead since further generic type information will be erased at runtime.

Does not compile due to type erasure removing the runtime reference. However, the code below will compile:

if( type.isAssignableFrom(e.getClass())){
  // Do something.
}

Why not inherit from List<T>?

It depends on the context

When you consider your team as a list of players, you are projecting the "idea" of a foot ball team down to one aspect: You reduce the "team" to the people you see on the field. This projection is only correct in a certain context. In a different context, this might be completely wrong. Imagine you want to become a sponsor of the team. So you have to talk to the managers of the team. In this context the team is projected to the list of its managers. And these two lists usually don't overlap very much. Other contexts are the current versus the former players, etc.

Unclear semantics

So the problem with considering a team as a list of its players is that its semantic depends on the context and that it cannot be extended when the context changes. Additionally it is hard to express, which context you are using.

Classes are extensible

When you using a class with only one member (e.g. IList activePlayers), you can use the name of the member (and additionally its comment) to make the context clear. When there are additional contexts, you just add an additional member.

Classes are more complex

In some cases it might be overkill to create an extra class. Each class definition must be loaded through the classloader and will be cached by the virtual machine. This costs you runtime performance and memory. When you have a very specific context it might be OK to consider a football team as a list of players. But in this case, you should really just use a IList , not a class derived from it.

Conclusion / Considerations

When you have a very specific context, it is OK to consider a team as a list of players. For example inside a method it is completely OK to write:

IList<Player> footballTeam = ...

When using F#, it can even be OK to create a type abbreviation:

type FootballTeam = IList<Player>

But when the context is broader or even unclear, you should not do this. This is especially the case when you create a new class whose context in which it may be used in the future is not clear. A warning sign is when you start to add additional attributes to your class (name of the team, coach, etc.). This is a clear sign that the context where the class will be used is not fixed and will change in the future. In this case you cannot consider the team as a list of players, but you should model the list of the (currently active, not injured, etc.) players as an attribute of the team.

How to change the color of a SwitchCompat from AppCompat library

To have greater control of the track color (no API controlled alpha changes), I extended SwitchCompat and style the elements programmatically:

    public class CustomizedSwitch extends SwitchCompat {

    public CustomizedSwitch(Context context) {
        super(context);
        initialize(context);
    }

    public CustomizedSwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    public CustomizedSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    public void initialize(Context context) {
        // DisplayMeasurementConverter is just a utility to convert from dp to px and vice versa
        DisplayMeasurementConverter displayMeasurementConverter = new DisplayMeasurementConverter(context);
        // Sets the width of the switch
        this.setSwitchMinWidth(displayMeasurementConverter.dpToPx((int) getResources().getDimension(R.dimen.tp_toggle_width)));
        // Setting up my colors
        int mediumGreen = ContextCompat.getColor(context, R.color.medium_green);
        int mediumGrey = ContextCompat.getColor(context, R.color.medium_grey);
        int alphaMediumGreen = Color.argb(127, Color.red(mediumGreen), Color.green(mediumGreen), Color.blue(mediumGreen));
        int alphaMediumGrey = Color.argb(127, Color.red(mediumGrey), Color.green(mediumGrey), Color.blue(mediumGrey));
        // Sets the tints for the thumb in different states
        DrawableCompat.setTintList(this.getThumbDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        mediumGreen,
                        ContextCompat.getColor(getContext(), R.color.light_grey)
                }));
        // Sets the tints for the track in different states
        DrawableCompat.setTintList(this.getTrackDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        alphaMediumGreen,
                        alphaMediumGrey
                }));
    }
}

Whenever I want to use the CustomizedSwitch, I just add one to my xml file.

How to put multiple statements in one line?

if you want it without try and except then there is the solution

what you are trying to do is print 'hello' if 'harry' in a list then the solution is

'hello' if 'harry' in sam else ''

PHP compare two arrays and get the matched values not the difference

OK.. We needed to compare a dynamic number of product names...

There's probably a better way... but this works for me...

... because....Strings are just Arrays of characters.... :>}

//  Compare Strings ...  Return Matching Text and Differences with Product IDs...

//  From MySql...
$productID1 = 'abc123';
$productName1 = "EcoPlus Premio Jet 600";   

$productID2 = 'xyz789';
$productName2 = "EcoPlus Premio Jet 800";   

$ProductNames = array(
    $productID1 => $productName1,
    $productID2 => $productName2
);


function compareNames($ProductNames){   

    //  Convert NameStrings to Arrays...    
    foreach($ProductNames as $id => $product_name){
        $Package1[$id] = explode(" ",$product_name);    
    }

    // Get Matching Text...
    $Matching = call_user_func_array('array_intersect', $Package1 );
    $MatchingText = implode(" ",$Matching);

    //  Get Different Text...
    foreach($Package1 as $id => $product_name_chunks){
        $Package2 = array($product_name_chunks,$Matching);
        $diff = call_user_func_array('array_diff', $Package2 );
        $DifferentText[$id] = trim(implode(" ", $diff));
    }

    $results[$MatchingText]  = $DifferentText;              
    return $results;    
}

$Results =  compareNames($ProductNames);

print_r($Results);

// Gives us this...
[EcoPlus Premio Jet] 
        [abc123] => 600
        [xyz789] => 800

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

MongoDB SELECT COUNT GROUP BY

This would be the easier way to do it using aggregate:

db.contest.aggregate([
    {"$group" : {_id:"$province", count:{$sum:1}}}
])

How can I make a "color map" plot in matlab?

By default mesh will color surface values based on the (default) jet colormap (i.e. hot is higher). You can additionally use surf for filled surface patches and set the 'EdgeColor' property to 'None' (so the patch edges are non-visible).

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;

% surface in 3D
figure;
surf(Z,'EdgeColor','None');

enter image description here

2D map: You can get a 2D map by switching the view property of the figure

% 2D map using view
figure;
surf(Z,'EdgeColor','None');
view(2);    

enter image description here

... or treating the values in Z as a matrix, viewing it as a scaled image using imagesc and selecting an appropriate colormap.

% using imagesc to view just Z
figure;
imagesc(Z); 
colormap jet; 

enter image description here

The color pallet of the map is controlled by colormap(map), where map can be custom or any of the built-in colormaps provided by MATLAB:

enter image description here

Update/Refining the map: Several design options on the map (resolution, smoothing, axis etc.) can be controlled by the regular MATLAB options. As @Floris points out, here is a smoothed, equal-axis, no-axis labels maps, adapted to this example:

figure;
surf(X, Y, Z,'EdgeColor', 'None', 'facecolor', 'interp');
view(2);
axis equal; 
axis off;

enter image description here

Read SQL Table into C# DataTable

Here, give this a shot (this is just a pseudocode)

using System;
using System.Data;
using System.Data.SqlClient;


public class PullDataTest
{
    // your data table
    private DataTable dataTable = new DataTable();

    public PullDataTest()
    {
    }

    // your method to pull data from database to datatable   
    public void PullData()
    {
        string connString = @"your connection string here";
        string query = "select * from table";

        SqlConnection conn = new SqlConnection(connString);        
        SqlCommand cmd = new SqlCommand(query, conn);
        conn.Open();

        // create data adapter
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        // this will query your database and return the result to your datatable
        da.Fill(dataTable);
        conn.Close();
        da.Dispose();
    }
}

How can I have a newline in a string in sh?

If you're using Bash, the solution is to use $'string', for example:

$ STR=$'Hello\nWorld'
$ echo "$STR" # quotes are required here!
Hello
World

If you're using pretty much any other shell, just insert the newline as-is in the string:

$ STR='Hello
> World'

Bash is pretty nice. It accepts more than just \n in the $'' string. Here is an excerpt from the Bash manual page:

   Words of the form $'string' are treated specially.  The word expands to
   string, with backslash-escaped characters replaced as specified by  the
   ANSI  C  standard.  Backslash escape sequences, if present, are decoded
   as follows:
          \a     alert (bell)
          \b     backspace
          \e
          \E     an escape character
          \f     form feed
          \n     new line
          \r     carriage return
          \t     horizontal tab
          \v     vertical tab
          \\     backslash
          \'     single quote
          \"     double quote
          \nnn   the eight-bit character whose value is  the  octal  value
                 nnn (one to three digits)
          \xHH   the  eight-bit  character  whose value is the hexadecimal
                 value HH (one or two hex digits)
          \cx    a control-x character

   The expanded result is single-quoted, as if the  dollar  sign  had  not
   been present.

   A double-quoted string preceded by a dollar sign ($"string") will cause
   the string to be translated according to the current  locale.   If  the
   current  locale  is  C  or  POSIX,  the dollar sign is ignored.  If the
   string is translated and replaced, the replacement is double-quoted.

WPF: ItemsControl with scrollbar (ScrollViewer)

You have to modify the control template instead of ItemsPanelTemplate:

<ItemsControl >
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.

Which is more efficient, a for-each loop, or an iterator?

To expand on Paul's own answer, he has demonstrated that the bytecode is the same on that particular compiler (presumably Sun's javac?) but different compilers are not guaranteed to generate the same bytecode, right? To see what the actual difference is between the two, let's go straight to the source and check the Java Language Specification, specifically 14.14.2, "The enhanced for statement":

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiers(opt) Type Identifier = #i.next();    
    Statement 
}

In other words, it is required by the JLS that the two are equivalent. In theory that could mean marginal differences in bytecode, but in reality the enhanced for loop is required to:

  • Invoke the .iterator() method
  • Use .hasNext()
  • Make the local variable available via .next()

So, in other words, for all practical purposes the bytecode will be identical, or nearly-identical. It's hard to envisage any compiler implementation which would result in any significant difference between the two.

Importing a GitHub project into Eclipse

When the local git projects are cloned in eclipse and are viewable in git perspective but not in package explorer (workspace), the following steps worked for me:

  • Select the repository in git perspective
  • Right click and select import projects

How can I show data using a modal when clicking a table row (using bootstrap)?

One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.

I am just going to show as a static example which you can accommodate in your real world.

On each of your <tr>'s add a data attribute for id (i.e. data-id) with the corresponding id value and specify a data-target, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal to make this a trigger for modal.

  <tr data-toggle="modal" data-id="1" data-target="#orderModal">
            <td>1</td>
            <td>24234234</td>
            <td>A</td>
  </tr>
  <tr data-toggle="modal" data-id="2" data-target="#orderModal">
            <td>2</td>
            <td>24234234</td>
            <td>A</td>
        </tr>
  <tr data-toggle="modal" data-id="3" data-target="#orderModal">
            <td>3</td>
            <td>24234234</td>
            <td>A</td>
  </tr>

And now in the javascript just set up the modal just once and event listen to its events so you can do your work.

$(function(){
    $('#orderModal').modal({
        keyboard: true,
        backdrop: "static",
        show:false,

    }).on('show', function(){ //subscribe to show method
          var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });
});

Demo

Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.

Alternative ways here:

Demo2 or Demo3

Yarn: How to upgrade yarn version using terminal?

For macOS users, if you installed yarn via brew, you can upgrade it using the below command:

brew upgrade yarn

On Linux, just run the below command at the terminal:

$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

On Windows, upgrade with Chocolatey

choco upgrade yarn

Credits: Added answers with the help of the below answers

Initializing entire 2D array with one value

You get this behavior, because int array [ROW][COLUMN] = {1}; does not mean "set all items to one". Let me try to explain how this works step by step.

The explicit, overly clear way of initializing your array would be like this:

#define ROW 2
#define COLUMN 2

int array [ROW][COLUMN] =
{
  {0, 0},
  {0, 0}
};

However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:

int array [ROW][COLUMN] =
{
  {1, 2}
};

This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.

So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.

Next, there is a rule in C allowing lax brace style. The first example could as well be written as

int array [ROW][COLUMN] = {0, 0, 0, 0};

although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write

int array [ROW][COLUMN] = {0};

which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."

therefore, if you attempt

int array [ROW][COLUMN] = {1};

it means "initialize the very first column in the first row to 1 and set all other items to zero".

How to get an array of unique values from an array containing duplicates in JavaScript?

Array.prototype.unique =function(){
    var uniqObj={};
    for(var i=0;i< this.length;i++){
      uniqObj[this[i]]=this[i]; 
    }
    return uniqObj;
}

php refresh current page?

PHP refresh current page

With PHP code:

<?php
$secondsWait = 1;
header("Refresh:$secondsWait");
echo date('Y-m-d H:i:s');
?>

Note: Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

if you send any output, you can use javascript:

<?php
echo date('Y-m-d H:i:s');
echo '<script type="text/javascript">location.reload(true);</script>';
?>

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

Or you can explicitly use "meta refresh" (with pure html):

<?php
$secondsWait = 1;
echo date('Y-m-d H:i:s');
echo '<meta http-equiv="refresh" content="'.$secondsWait.'">';
?>

Greetings and good code,

React won't load local images

Here is what worked for me. First, let us understand the problem. You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time.

When I got the error, I thought it may be related to path issue as in absolute vs relative. So I passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. It was working fine. But in my case the value is a variable coming from props. I tried to pass a string literal variable as some suggested. It did not work. Also I tried to define a local method using switch case for all 10 values (I knew it was not best solution, but I just wanted it to work somehow). That too did not work. Then I came to know that we can NOT pass variable to the require.

As a workaround I have modified the data in the data.json file to confine it to just the name of my image. This image name which is coming from the props as a String literal. I concatenated it to the hard coded value, like so:

import React from "react";

function JobCard(props) {  

  const { logo } = props;
  
  return (
      <div className="jobCards">
          <img src={require(`../assets/images/${logo}`)} alt="" /> 
      </div>
    )
} 
  

The actual value contained in the logo would be coming from data.json file and would refer to some image name like photosnap.svg.

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

How do you right-justify text in an HTML textbox?

Apply style="text-align: right" to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.

Calling Javascript function from server side

You can call the function from code behind like this :

MyForm.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}

MyForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#ButtonRow").show();
    }
    function AnotherFunction()
    {
        alert("This is another function");
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()"  RepeatDirection="Horizontal"  BorderStyle="Solid">
               <asp:ListItem>Merchant</asp:ListItem>
               <asp:ListItem>Store</asp:ListItem>
               <asp:ListItem>Terminal</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="ButtonRow"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
        </td>
    </tr>
    </table> 
</form>

How to get root view controller?

As suggested here by @0x7fffffff, if you have UINavigationController it can be easier to do:

YourViewController *rootController =
    (YourViewController *)
        [self.navigationController.viewControllers objectAtIndex: 0];

The code in the answer above returns UINavigation controller (if you have it) and if this is what you need, you can use self.navigationController.

Datetime format Issue: String was not recognized as a valid DateTime

DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",  
                                           CultureInfo.InvariantCulture);

Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.

For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).

How to return a result from a VBA function

Just setting the return value to the function name is still not exactly the same as the Java (or other) return statement, because in java, return exits the function, like this:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Since this is the case, it's also nice to know that you can use the return variable like any other variable in the method. Like this:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

For there to be a Smart Cast of the properties, the data type of the property must be the class that contains the method or behavior that you want to access and NOT that the property is of the type of the super class.


e.g on Android

Be:

class MyVM : ViewModel() {
    fun onClick() {}
}

Solution:

From: private lateinit var viewModel: ViewModel
To: private lateinit var viewModel: MyVM

Usage:

viewModel = ViewModelProvider(this)[MyVM::class.java]
viewModel.onClick {}

GL

How to overplot a line on a scatter plot in python?

Another way to do it, using axes.get_xlim():

import matplotlib.pyplot as plt
import numpy as np

def scatter_plot_with_correlation_line(x, y, graph_filepath):
    '''
    http://stackoverflow.com/a/34571821/395857
    x does not have to be ordered.
    '''
    # Create scatter plot
    plt.scatter(x, y)

    # Add correlation line
    axes = plt.gca()
    m, b = np.polyfit(x, y, 1)
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)
    plt.plot(X_plot, m*X_plot + b, '-')

    # Save figure
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')

def main():
    # Data
    x = np.random.rand(100)
    y = x + np.random.rand(100)*0.1

    # Plot
    scatter_plot_with_correlation_line(x, y, 'scatter_plot.png')

if __name__ == "__main__":
    main()
    #cProfile.run('main()') # if you want to do some profiling

enter image description here

Can you require two form fields to match with HTML5?

A simple solution with minimal javascript is to use the html attribute pattern (supported by most modern browsers). This works by setting the pattern of the second field to the value of the first field.

Unfortunately, you also need to escape the regex, for which no standard function exists.

<form>
    <input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
    <input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
    function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
</script>

Rearrange columns using cut

Just as an addition to answers that suggest to duplicate the columns and then to do cut. For duplication, paste etc. will work only for files, but not for streams. In that case, use sed instead.

cat file.txt | sed s/'.*'/'&\t&'/ | cut -f2,3

This works on both files and streams, and this is interesting if instead of just reading from a file with cat, you do something interesting before re-arranging the columns.

By comparison, the following does not work:

cat file.txt | paste - - | cut -f2,3

Here, the double stdin placeholder paste does not duplicate stdin, but reads the next line.

"Eliminate render-blocking CSS in above-the-fold content"

Hi For jQuery You can only use like this

Use async and type="text/javascript" only

How to declare and display a variable in Oracle

If you are using pl/sql then the following code should work :

set server output on -- to retrieve and display a buffer

DECLARE

    v_text VARCHAR2(10); -- declare
BEGIN

    v_text := 'Hello';  --assign
    dbms_output.Put_line(v_text); --display
END; 

/

-- this must be use to execute pl/sql script

How do I get AWS_ACCESS_KEY_ID for Amazon?

It is very dangerous to create an access_key_id in "My Account ==> Security Credentials". Because the key has all authority. Please create "IAM" user and attach only some policies you need.

Could not open ServletContext resource

I think currently the application-context.xml file is into src/main/resources AND the social.properties file is into src/main/java... so when you package (mvn package) or when you run tomcat (mvn tomcat:run) your social.properties disappeared (I know you said when you checked into the .war the files are here... but your exception says the opposite).

The solution is simply to put all your configuration files (application-context.xml and social.properties) into src/main/resources to follow the maven standard structure.

Running Google Maps v2 on the Android emulator

Please try the following. It was successfully for me.

Steps:

  1. Create a new emulator with this configuration: AVD configuration

  2. Start the emulator and install the following APK files: GoogleLoginService.apk, GoogleServicesFramework.apk, and Phonesky.apk. You can do this with the following commands:

    adb shell mount -o remount,yourAvdName -t yaffs2 /dev/block/mtdblock0 /system
    adb shell chmod 777 /system/app
    adb push GoogleLoginService.apk /system/app/
    adb push GoogleServicesFramework.apk /system/app/
    adb push Phonesky.apk /system/app/
    

    Links for APKs:

    1. GoogleLoginService.apk
    2. GoogleServicesFramework.apk
    3. Phonesky.apk AKA Google Play Store, v.3.5.16
    4. Google Maps, v.6.14.1
    5. Google Play services, v.2.0.10
  3. Install Google Play services and Google Maps in the emulator

    adb install com.google.android.apps.maps-1.apk
    adb install com.google.android.gms-2.apk
    
  4. Download Google Play Service revision 4 from this link and extra to folder sdkmanager->extra->google play service.
  5. Import google-play-services_lib from androidsdk\extras\google\google_play_services.
  6. Create a new project and reference the above project as a library project.
  7. Run the project.

What is this Javascript "require"?

You know how when you are running JavaScript in the browser, you have access to variables like "window" or Math? You do not have to declare these variables, they have been written for you to use whenever you want.

Well, when you are running a file in the Node.js environment, there is a variable that you can use. It is called "module" It is an object. It has a property called "exports." And it works like this:

In a file that we will name example.js, you write:

example.js

module.exports = "some code";

Now, you want this string "some code" in another file.

We will name the other file otherFile.js

In this file, you write:

otherFile.js

let str = require('./example.js')

That require() statement goes to the file that you put inside of it, finds whatever data is stored on the module.exports property. The let str = ... part of your code means that whatever that require statement returns is stored to the str variable.

So, in this example, the end-result is that in otherFile.js you now have this:

let string = "some code";

  • or -

let str = ('./example.js').module.exports

Note:

the file-name that is written inside of the require statement: If it is a local file, it should be the file-path to example.js. Also, the .js extension is added by default, so I didn't have to write it.

You do something similar when requiring node.js libraries, such as Express. In the express.js file, there is an object named 'module', with a property named 'exports'.

So, it looks something like along these lines, under the hood (I am somewhat of a beginner so some of these details might not be exact, but it's to show the concept:

express.js

module.exports = function() {
    //It returns an object with all of the server methods
    return {
        listen: function(port){},
        get: function(route, function(req, res){}){}
     }
}

If you are requiring a module, it looks like this: const moduleName = require("module-name");

If you are requiring a local file, it looks like this: const localFile = require("./path/to/local-file");

(notice the ./ at the beginning of the file name)


Also note that by default, the export is an object .. eg module.exports = {} So, you can write module.exports.myfunction = () => {} before assigning a value to the module.exports. But you can also replace the object by writing module.exports = "I am not an object anymore."

How to initialize std::vector from C-style array?

You use the word initialize so it's unclear if this is one-time assignment or can happen multiple times.

If you just need a one time initialization, you can put it in the constructor and use the two iterator vector constructor:

Foo::Foo(double* w, int len) : w_(w, w + len) { }

Otherwise use assign as previously suggested:

void set_data(double* w, int len)
{
    w_.assign(w, w + len);
}

An invalid form control with name='' is not focusable

There are many ways to fix this like

  1. Add novalidate to your form but its totally wrong as it will remove form validation which will lead to wrong information entered by the users.

<form action="...." class="payment-details" method="post" novalidate>

  1. Use can remove the required attribute from required fields which is also wrong as it will remove form validation once again.

    Instead of this:

<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" required="required">

   Use this:

<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text">

  1. Use can disable the required fields when you are not going to submit the form instead of doing some other option. This is the recommended solution in my opinion.

    like:

<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" disabled="disabled">

or disable it through javascript / jquery code dependes upon your scenario.

How to add title to subplots in Matplotlib?

A shorthand answer assuming import matplotlib.pyplot as plt:

plt.gca().set_title('title')

as in:

plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...

Then there is no need for superfluous variables.

How can I close a login form and show the main form without my application closing?

I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.

MySQL, Concatenate two columns

In query, CONCAT_WS() function.

This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).

Syntax –

CONCAT_WS( SEPERATOR, column1, column2, ... )

Example

SELECT 
topic, 
CONCAT_WS( " ", subject, year ) AS subject_year 
FROM table

When do I need to use a semicolon vs a slash in Oracle SQL?

I only use the forward slash once at the end of each script, to tell sqlplus that there is not more lines of code. In the middle of a script, I do not use a slash.

Import a module from a relative path

Simply you can use: from Desktop.filename import something

Example:

given that the file is name test.py in directory Users/user/Desktop , and will import everthing.

the code:

from Desktop.test import *

But make sure you make an empty file called "__init__.py" in that directory

Conda command is not recognized on Windows 10

In Windows, you will have to set the path to the location where you installed Anaconda3 to.

For me, I installed anaconda3 into C:\Anaconda3. Therefore you need to add C:\Anaconda3 as well as C:\Anaconda3\Scripts\ to your path variable, e.g. set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\.

You can do this via powershell (see above, https://msdn.microsoft.com/en-us/library/windows/desktop/bb776899(v=vs.85).aspx ), or hit the windows key ? enter environment ? choose from settings ? edit environment variables for your account ? select Path variable ? Edit ? New.

To test it, open a new dos shell, and you should be able to use conda commands now. E.g., try conda --version.

Convert date to another timezone in JavaScript

You can use to toLocaleString() method for setting the timezone.

new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })

For India you can use "Indian/Christmas" and the following are the various timeZones,

"Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

Flask-SQLalchemy update a row's information

Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit().

For example:

admin = User.query.filter_by(username='admin').first()
admin.email = '[email protected]'
db.session.commit()

user = User.query.get(5)
user.name = 'New Name'
db.session.commit()

Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.

Comparing two strings in C?

if(strcmp(sr1,str2)) // this returns 0 if strings r equal 
    flag=0;
else flag=1; // then last check the variable flag value and print the message 

                         OR

char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);

for(int i=0;str1[i]!='\0';i++)
{
    if(str[i]==str2[i])
         flag=0;
    else {flag=1; break;}
}

 //check the value of flag if it is 0 then strings r equal simple :)

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

Get root view from current activity

For those of you who are using the Data Binding Library, to get the root of the current activity, simply use:

View rootView = dataBinding.getRoot();

And for Kotlin users, it's even simpler:

val rootView = dataBinding.root

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

Running a shell script through Cygwin on Windows

Just wanted to add that you can do this to apply dos2unix fix for all files under a directory, as it saved me heaps of time when we had to 'fix' a bunch of our scripts.

find . -type f -exec dos2unix.exe {} \;

I'd do it as a comment to Roman's answer, but I don't have access to commenting yet.

curl POST format for CURLOPT_POSTFIELDS

According to the PHP manual, data passed to cURL as a string should be URLencoded. See the page for curl_setopt() and search for CURLOPT_POSTFIELDS.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Based on different answers but mainly on this, this works for what I need:

UIImage *image1 = ...; // The image from where you want a pixel data
int pixelX = ...; // The X coordinate of the pixel you want to retrieve
int pixelY = ...; // The Y coordinate of the pixel you want to retrieve

uint32_t pixel1; // Where the pixel data is to be stored
CGContextRef context1 = CGBitmapContextCreate(&pixel1, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
CGContextDrawImage(context1, CGRectMake(-pixelX, -pixelY, CGImageGetWidth(image1.CGImage), CGImageGetHeight(image1.CGImage)), image1.CGImage);
CGContextRelease(context1);

As a result of this lines, you will have a pixel in AARRGGBB format with alpha always set to FF in the 4 byte unsigned integer pixel1.

Push local Git repo to new remote including all branches and tags

The manpage for git-push is worth a read. Combined with this website I wrote the following in my .git/config:

[remote "origin"]
    url = …
    fetch = …
    push = :
    push = refs/tags/*

The push = : means "push any 'matching' branches (i.e. branches that already exist in the remote repository and have a local counterpart)", while push = refs/tags/* means "push all tags".

So now I only have to run git push to push all matching branches and all tags.

Yes, this is not quite what the OP wanted (all of the branches to push must already exist on the remote side), but might be helpful for those who find this question while googling for "how do I push branches and tags at the same time".

How to read a specific line using the specific line number from a file in Java?

Although as said in other answers, it is not possible to get to the exact line without knowing the offset ( pointer ) before. So, I've achieved this by creating an temporary index file which would store the offset values of every line. If the file is small enough, you could just store the indexes ( offset ) in memory without needing a separate file for it.

The offsets can be calculated by using the RandomAccessFile

    RandomAccessFile raf = new RandomAccessFile("myFile.txt","r"); 
    //above 'r' means open in read only mode
    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    String cur_line = "";
    while((cur_line=raf.readLine())!=null)
    {
    arrayList.add(raf.getFilePointer());
    }
    //Print the 32 line
    //Seeks the file to the particular location from where our '32' line starts
    raf.seek(raf.seek(arrayList.get(31));
    System.out.println(raf.readLine());
    raf.close();

Also visit the java docs for more information: https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#mode

Complexity : This is O(n) as it reads the entire file once. Please be aware for the memory requirements. If it's too big to be in memory, then make a temporary file that stores the offsets instead of ArrayList as shown above.

Note : If all you want in '32' line, you just have to call the readLine() also available through other classes '32' times. The above approach is useful if you want to get the a specific line (based on line number of course) multiple times.

Thanks !

Convert String to SecureString

If you would like to compress the conversion of a string to a SecureString into a LINQ statement you can express it as follows:

var plain  = "The quick brown fox jumps over the lazy dog";
var secure = plain
             .ToCharArray()
             .Aggregate( new SecureString()
                       , (s, c) => { s.AppendChar(c); return s; }
                       , (s)    => { s.MakeReadOnly(); return s; }
                       );

However, keep in mind that using LINQ does not improve the security of this solution. It suffers from the same flaw as any conversion from string to SecureString. As long as the original string remains in memory the data is vulnerable.

That being said, what the above statement can offer is keeping together the creation of the SecureString, its initialization with data and finally locking it from modification.

Which characters are valid/invalid in a JSON key name?

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.

Example:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

JavaScript: How do I print a message to the error console?

The simplest way to do this is:

console.warn("Text to print on console");

Add space between HTML elements only using CSS

Just use margin or padding.

In your specific case, you could use margin:0 10px only on the 2nd <span>.

UPDATE

Here's a nice CSS3 solution (jsFiddle):

span {
    margin: 0 10px;
}

span:first-of-type {
    margin-left: 0;
}

span:last-of-type {
    margin-right: 0;
}

Advanced element selection using selectors like :nth-child(), :last-child, :first-of-type, etc. is supported since Internet Explorer 9.

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

phpmailer error "Could not instantiate mail function"

Your code looks good, did you forget to install PostFix on your server?

sudo apt-get install postfix

It worked for me ;)

Cheers

Extract number from string with Oracle function

If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr function like this:

regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')

Running java with JAVA_OPTS env variable has no effect

You can setup _JAVA_OPTIONS instead of JAVA_OPTS. This should work without $_JAVA_OPTIONS.

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

How to create a jQuery plugin with methods?

This can actually be made to work in a "nice" way using defineProperty. Where "nice" means without having to use () to get plugin namespace nor having to pass function name by string.

Compatibility nit: defineProperty doesn't work in ancient browsers such as IE8 and below. Caveat: $.fn.color.blue.apply(foo, args) won't work, you need to use foo.color.blue.apply(foo, args).

function $_color(color)
{
    return this.css('color', color);
}

function $_color_blue()
{
    return this.css('color', 'blue');
}

Object.defineProperty($.fn, 'color',
{
    enumerable: true,
    get: function()
    {
        var self = this;

        var ret = function() { return $_color.apply(self, arguments); }
        ret.blue = function() { return $_color_blue.apply(self, arguments); }

        return ret;
    }
});

$('#foo').color('#f00');
$('#bar').color.blue();

JSFiddle link

How to publish a website made by Node.js to Github Pages?

GitHub pages host only static HTML pages. No server side technology is supported, so Node.js applications won't run on GitHub pages. There are lots of hosting providers, as listed on the Node.js wiki.

App fog seems to be the most economical as it provides free hosting for projects with 2GB of RAM (which is pretty good if you ask me).
As stated here, AppFog removed their free plan for new users.

If you want to host static pages on GitHub, then read this guide. If you plan on using Jekyll, then this guide will be very helpful.

Why am I getting "Thread was being aborted" in ASP.NET?

ASP.NET spawns and kills worker processes all the time as needed. Your thread may just be getting shut down by ASP.NET.

Old Answer:

Known issue: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Response.Redirect ("bla.aspx", false);

or

try
{
    Response.Redirect("bla.aspx");
}
catch (ThreadAbortException ex)
{
}

How to know if a DateTime is between a DateRange in C#

Usually I create Fowler's Range implementation for such things.

public interface IRange<T>
{
    T Start { get; }
    T End { get; }
    bool Includes(T value);
    bool Includes(IRange<T> range);
}

public class DateRange : IRange<DateTime>         
{
    public DateRange(DateTime start, DateTime end)
    {
        Start = start;
        End = end;
    }

    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public bool Includes(DateTime value)
    {
        return (Start <= value) && (value <= End);
    }

    public bool Includes(IRange<DateTime> range)
    {
        return (Start <= range.Start) && (range.End <= End);
    }
}

Usage is pretty simple:

DateRange range = new DateRange(startDate, endDate);
range.Includes(date)

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

array_push() with key value pair

$data['cat'] = 'wagon';

That's all you need to add the key and value to the array.

What is the syntax for an inner join in LINQ to SQL?

To extend the expression chain syntax answer by Clever Human:

If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:

var dealerInfo = DealerContact.Join(Dealer, 
                              dc => dc.DealerId,
                              d => d.DealerId,
                              (dc, d) => new { DealerContact = dc, Dealer = d })
                          .Where(dc_d => dc_d.Dealer.FirstName == "Glenn" 
                              && dc_d.DealerContact.City == "Chicago")
                          .Select(dc_d => new {
                              dc_d.Dealer.DealerID,
                              dc_d.Dealer.FirstName,
                              dc_d.Dealer.LastName,
                              dc_d.DealerContact.City,
                              dc_d.DealerContact.State });

The interesting part is the lambda expression in line 4 of that example:

(dc, d) => new { DealerContact = dc, Dealer = d }

...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields.

We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses dc_d as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.

How to handle an IF STATEMENT in a Mustache template?

I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :

function buildOptions (object) {
    var validTypes = ['string', 'number', 'boolean'];
    var value;
    var key;
    for (key in object) {
        value = object[key];
        if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
            object[key + '=' + value] = true;
        }
    }
    return object;
}

With this hack, an object like this:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};

Will look like this before transformation:

var contact = {
  "id": 1364,
  "id=1364": true,
  "author_name": "Mr Nobody",
  "author_name=Mr Nobody": true,
  "notified_type": "friendship",
  "notified_type=friendship": true,
  "action": "create",
  "action=create": true
};

And your mustache template will look like this:

{{#notified_type=friendship}}
    friendship…
{{/notified_type=friendship}}

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}

How to break/exit from a each() function in JQuery?

if (condition){ // where condition evaluates to true 
    return false
}

see similar question asked 3 days ago.

What are these ^M's that keep showing up in my files in emacs?

See also:

Hiding ^M in emacs

Be careful if you choose to remove the ^M characters and resubmit to your team. They may see a file without carriage returns afterward.

`col-xs-*` not working in Bootstrap 4

I just wondered, why col-xs-6 did not work for me but then I found the answer in the Bootstrap 4 documentation. The class prefix for extra small devices is now col- while in the previous versions it was col-xs.

https://getbootstrap.com/docs/4.1/layout/grid/#grid-options

Bootstrap 4 dropped all col-xs-* classes, so use col-* instead. For example col-xs-6 replaced by col-6.

Converting integer to string in Python

The most decent way in my opinion is ``.

i = 32   -->    `i` == '32'

iterating through Enumeration of hastable keys throws NoSuchElementException error

Each time you do e.nextElement() you skip one. So you skip two elements in each iteration of your loop.

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

This article here nicely explains it. Essentially, you can look at it as such:

CREATE TABLE t AS
SELECT 'a' v FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'b'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'd'   FROM dual UNION ALL
SELECT 'e'   FROM dual;

SELECT
  v,
  ROW_NUMBER() OVER (ORDER BY v) row_number,
  RANK()       OVER (ORDER BY v) rank,
  DENSE_RANK() OVER (ORDER BY v) dense_rank
FROM t
ORDER BY v;

The above will yield:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

In words

  • ROW_NUMBER() attributes a unique value to each row
  • RANK() attributes the same row number to the same value, leaving "holes"
  • DENSE_RANK() attributes the same row number to the same value, leaving no "holes"

Accessing Websites through a Different Port?

You can use ssh to forward ports onto somewhere else.

If you have two computers, one you browse from, and one which is free to access websites, and is not logged (ie. you own it and it's sitting at home), then you can set up a tunnel between them to forward http traffic over.

For example, I connect to my home computer from work using ssh, with port forwarding, like this:

ssh -L 22222:<target_website>:80 <home_computer>

Then I can point my browser to

http://localhost:22222/

And this request will be forwarded over ssh. Since the work computer is first contacting the home computer, and then contacting the target website, it will be hard to log.

However, this is all getting into 'how to bypass web proxies' and the like, and I suggest you create a new question asking what exactly you want to do.

Ie. "How do I bypass web proxies to avoid my traffic being logged?"

How to convert JSON string into List of Java object?

For any one who looks for answer yet:

1.Add jackson-databind library to your build tools like Gradle or Maven

2.in your Code:

ObjectMapper mapper = new ObjectMapper();

List<Student> studentList = new ArrayList<>();

studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));

How can I combine multiple nested Substitute functions in Excel?

Thanks for the idea of breaking down a formula Werner!

Using Alt+Enter allows one to put each bit of a complex substitute formula on separate lines: they become easier to follow and automatically line themselves up when Enter is pressed.

Just make sure you have enough end statements to match the number of substitute( lines either side of the cell reference.

As in this example:

=
substitute(
substitute(
substitute(
substitute(
B11
,"(","")
,")","")
,"[","")
,"]","")

becomes:

=
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

which works fine as is, but one can always delete the extra paragraphs manually:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

Name > substitute()

[American Samoa] > American Samoa

How to prevent favicon.ico requests?

if you use nginx

# skip favicon.ico
#
location = /favicon.ico {
    access_log off;
    return 204;
}

TypeError: $(...).on is not a function

This problem is solved, in my case, by encapsulating my jQuery in:

(function($) {
//my jquery 
})(jQuery);

How to show image using ImageView in Android

If you want to display an image file on the phone, you can do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));

If you want to display an image from your drawable resources, do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);

You'll find the drawable folder(s) in the project res folder. You can put your image files there.

Difference between fprintf, printf and sprintf?

sprintf: Writes formatted data to a character string in memory instead of stdout

Syntax of sprintf is:

#include <stdio.h>
int sprintf (char *string, const char *format
[,item [,item]…]);

Here,

String refers to the pointer to a buffer in memory where the data is to be written.

Format refers to pointer to a character string defining the format.

Each item is a variable or expression specifying the data to write.

The value returned by sprintf is greater than or equal to zero if the operation is successful or in other words the number of characters written, not counting the terminating null character is returned and returns a value less than zero if an error occurred.

printf: Prints to stdout

Syntax for printf is:

printf format [argument]…

The only difference between sprintf() and printf() is that sprintf() writes data into a character array, while printf() writes data to stdout, the standard output device.

Run a controller function whenever a view is opened/shown

If you have assigned a certain controller to your view, then your controller will be invoked every time your view loads. In that case, you can execute some code in your controller as soon as it is invoked, for example this way:

<ion-nav-view ng-controller="indexController" name="other" ng-init="doSomething()"></ion-nav-view>

And in your controller:

app.controller('indexController', function($scope) {
    /*
        Write some code directly over here without any function,
        and it will be executed every time your view loads.
        Something like this:
    */
    $scope.xyz = 1;
});

Edit: You might try to track state changes and then execute some code when the route is changed and a certain route is visited, for example:

$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ ... })

You can find more details here: State Change Events.

Storing data into list with class

Here's the extension method version:

public static class ListOfEmailDataExtension
{
    public static void Add(this List<EmailData> list, 
        string firstName, string lastName, string location)
    {
        if (null == list)
            throw new NullReferenceException();

        var emailData = new EmailData
                            {
                                FirstName = firstName, 
                                LastName = lastName, 
                                Location = location
                            };
        list.Add(emailData);
    }
}

Usage:

List<EmailData> myList = new List<EmailData>();
myList.Add("Ron", "Klein", "Israel");

Simulating ENTER keypress in bash script

You can just use yes.

# yes "" | someCommand

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

browser sessionStorage. share between tabs?

Using sessionStorage for this is not possible.

From the MDN Docs

Opening a page in a new tab or window will cause a new session to be initiated.

That means that you can't share between tabs, for this you should use localStorage

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

HTTP status code for update and delete?

Since the question delves into if DELETE "should" return 200 vs 204 it is worth considering that some people recommend returning an entity with links so the preference is for 200.

"Instead of returning 204 (No Content), the API should be helpful and suggest places to go. In this example I think one obvious link to provide is to" 'somewhere.com/container/' (minus 'resource') "- the container from which the client just deleted a resource. Perhaps the client wishes to delete more resources, so that would be a helpful link."

http://blog.ploeh.dk/2013/04/30/rest-lesson-learned-avoid-204-responses/

If a client encounters a 204 response, it can either give up, go to the entry point of the API, or go back to the previous resource it visited. Neither option is particularly good.

Personally I would not say 204 is wrong (neither does the author; he says "annoying") because good caching at the client side has many benefits. Best is to be consistent either way.

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

If you are using java 1.8, remove XX:-UseSplitVerifier and use -noverify in your JVM properties.

How to set focus on an input field after rendering?

If you just want to make autofocus in React, it's simple.

<input autoFocus type="text" />

While if you just want to know where to put that code, answer is in componentDidMount().

v014.3

componentDidMount() {
    this.refs.linkInput.focus()
}

In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all.

Read the API documents here: https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode

How to get a unique device ID in Swift?

For Swift 3.X Latest Working Code, Easily usage;

   let deviceID = UIDevice.current.identifierForVendor!.uuidString
   print(deviceID)

Upgrading PHP on CentOS 6.5 (Final)

I managed to install php54w according to Simon's suggestion, but then my sites stopped working perhaps because of an incompatibility with php-mysql or some other module. Even frantically restoring the old situation was not amusing: for anyone in my own situation the sequence is:

sudo yum remove php54w
sudo yum remove php54w-common
sudo yum install php-common
sudo yum install php-mysql
sudo yum install php

It would be nice if someone submitted the full procedure to update all the php packet. That was my production server and my heart is still rapidly beating.

How to check for null in Twig?

How to set default values in twig: http://twig.sensiolabs.org/doc/filters/default.html

{{ my_var | default("my_var doesn't exist") }}

Or if you don't want it to display when null:

{{ my_var | default("") }}

How would you count occurrences of a string (actually a char) within a string?

String in string:

Find "etc" in " .. JD JD JD JD etc. and etc. JDJDJDJDJDJDJDJD and etc."

var strOrigin = " .. JD JD JD JD etc. and etc. JDJDJDJDJDJDJDJD and etc.";
var searchStr = "etc";
int count = (strOrigin.Length - strOrigin.Replace(searchStr, "").Length)/searchStr.Length.

Check performance before discarding this one as unsound/clumsy...

Extracting the last n characters from a string in R

Use stri_sub function from stringi package. To get substring from the end, use negative numbers. Look below for the examples:

stri_sub("abcde",1,3)
[1] "abc"
stri_sub("abcde",1,1)
[1] "a"
stri_sub("abcde",-3,-1)
[1] "cde"

You can install this package from github: https://github.com/Rexamine/stringi

It is available on CRAN now, simply type

install.packages("stringi")

to install this package.

jQuery Selector: Id Ends With?

An example: to select all <a>s with ID ending in _edit:

jQuery("a[id$=_edit]")

or

jQuery("a[id$='_edit']")

SQL Server - Adding a string to a text column (concat equivalent)

The + (String Concatenation) does not work on SQL Server for the image, ntext, or text data types.

In fact, image, ntext, and text are all deprecated.

ntext, text, and image data types will be removed in a future version of MicrosoftSQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

That said if you are using an older version of SQL Server than you want to use UPDATETEXT to perform your concatenation. Which Colin Stasiuk gives a good example of in his blog post String Concatenation on a text column (SQL 2000 vs SQL 2005+).

Split data frame string column into multiple columns

Another approach if you want to stick with strsplit() is to use the unlist() command. Here's a solution along those lines.

tmp <- matrix(unlist(strsplit(as.character(before$type), '_and_')), ncol=2,
   byrow=TRUE)
after <- cbind(before$attr, as.data.frame(tmp))
names(after) <- c("attr", "type_1", "type_2")

How to completely uninstall python 2.7.13 on Ubuntu 16.04

caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.

To completely uninstall Python2.x.x and everything depends on it. use this command:

sudo apt purge python2.x-minimal

As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.

Thanks, I hope it will be helpful for you.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} 
   };

User $resource("apiUrl").query();

How to "grep" out specific line ranges of a file

If I understand correctly, you want to find a pattern between two line numbers. The awk one-liner could be

awk '/whatev/ && NR >= 1234 && NR <= 5555' file

You don't need to run grep followed by sed.

Perl one-liner:

perl -ne 'if (/whatev/ && $. >= 1234 && $. <= 5555') {print}' file

WPF Check box: Check changed handling

What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.

IOS: verify if a point is inside a rect

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
            UITouch *touch = [[event allTouches] anyObject];
            CGPoint touchLocation = [touch locationInView:self.view];
            CGRect rect1 = CGRectMake(vwTable.frame.origin.x, 
            vwTable.frame.origin.y, vwTable.frame.size.width, 
            vwTable.frame.size.height);
            if (CGRectContainsPoint(rect1,touchLocation))
            NSLog(@"Inside");
            else
            NSLog(@"Outside");
    }

How to extract the hostname portion of a URL in JavaScript

Regex provides much more flexibility.

    //document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
    //1.
     var r = new RegExp(/http:\/\/[^/]+/);
     var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com

    //2. 
     var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
     var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf

"No Content-Security-Policy meta tag found." error in my phonegap application

There are errors in your meta tag.

Yours:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src: 'self' 'unsafe-inline' 'unsafe-eval'>

Corrected:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"/>

Note the colon after "script-src", and the end double-quote of the meta tag.

Django CSRF Cookie Not Set

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def your_view(request):
    if request.method == "POST":
        # do something
    return HttpResponse("Your response")

Regex: Specify "space or start of string" and "space or end of string"

(^|\s) would match space or start of string and ($|\s) for space or end of string. Together it's:

(^|\s)stackoverflow($|\s)

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

How to print spaces in Python?

To print any amount of lines between printed text use:

print("Hello" + '\n' *insert number of whitespace lines+ "World!")

'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.

Creating a REST API using PHP

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon - REST API building - Easy to use all in one framework with huge performance

Apigility - A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

Suddenly, without any major change in my project, I too got this error.

All the above did not work for me, since I needed both the support libs V4 and V7.

At the end, because 2 hours ago the project compiled with no problems, I simply told Android Studio to REBUILD the project, and the error was gone.