Programs & Examples On #Explode

explode() is a PHP function that splits a string based on a delimiter, returning an array.

How do I hide the PHP explode delimiter from submitted form results?

<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

Explode string by one or more spaces or tabs

The author asked for explode, to you can use explode like this

$resultArray = explode("\t", $inputString);

Note: you must used double quote, not single.

PHP: Split string into array, like explode with no delimiter

str_split can do the trick. Note that strings in PHP can be accessed just like a chars array, in most cases, you won't need to split your string into a "new" array.

Convert array values from string to int?

This is almost 3 times faster than explode(), array_map() and intval():

$integerIDs = json_decode('[' . $string . ']', true);

Php multiple delimiters in explode

This will work:

$stringToSplit = 'This is my String!' ."\n\r". 'Second Line';
$split = explode (
  ' ', implode (
    ' ', explode (
      "\n\r", $stringToSplit
    )
  )
);

As you can see, it first glues the by \n\r exploded parts together with a space, to then cut it apart again, this time taking the spaces with him.

Mysql where id is in array

Change

$array=array_map('intval', explode(',', $string));

To:

$array= implode(',', array_map('intval', explode(',', $string)));

array_map returns an array, not a string. You need to convert the array to a comma separated string in order to use in the WHERE clause.

How can I increment a char?

There is a way to increase character using ascii_letters from string package which ascii_letters is a string that contains all English alphabet, uppercase and lowercase:

>>> from string import ascii_letters
>>> ascii_letters[ascii_letters.index('a') + 1]
'b'
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Also it can be done manually;

>>> letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> letters[letters.index('c') + 1]
'd'

Equivalent of .bat in mac os

I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:

  • Make a bash (shell) script version of your .bat file (like other
    answers, with \ changed to / in file paths). For example:

    # File "example.command":
    #!/bin/bash
    java -cp  ".;./supportlibraries/Framework_Core.jar; ...etc.
    
  • Then rename it to have the Mac OS file extension .command.
    That should make the script run using the Terminal app.

  • If the app user is going to use a bash script version of the file on Linux
    or run it from the command line, they need to add executable rights
    (change mode bits) using this command, in the folder that has the file:

    chmod +rx [filename].sh
    #or:# chmod +rx [filename].command
    

The forum page question:

Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.

Info from some answers after the question:

Write a shell script, and give it the extension ".command". For example:

#!/bin/bash 
printf "Hello World\n" 

- Mar 23, 2010, Tony T1.

The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.

However, OS X adds the feature that if you give the file the suffix .command, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).

Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]

#!/bin/sh
echo Hello World

- Mar 23, 2010, J D McIninch.

Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:

On mac, there is a specific extension for executing shell
scripts by double clicking them: this is .command.

Why XML-Serializable class need a parameterless constructor

First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?

I think there is a workaround to make constructor private.

Displaying standard DataTables in MVC

This is not "wrong" at all, it's just not what the cool guys typically do with MVC. As an aside, I wish some of the early demos of ASP.NET MVC didn't try to cram in Linq-to-Sql at the same time. It's pretty awesome and well suited for MVC, sure, but it's not required. There is nothing about MVC that prevents you from using ADO.NET. For example:

Controller action:

public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    DataTable dt = new DataTable("MyTable");
    dt.Columns.Add(new DataColumn("Col1", typeof(string)));
    dt.Columns.Add(new DataColumn("Col2", typeof(string)));
    dt.Columns.Add(new DataColumn("Col3", typeof(string)));

    for (int i = 0; i < 3; i++)
    {
        DataRow row = dt.NewRow();
        row["Col1"] = "col 1, row " + i;
        row["Col2"] = "col 2, row " + i;
        row["Col3"] = "col 3, row " + i;
        dt.Rows.Add(row);
    }

    return View(dt); //passing the DataTable as my Model
}

View: (w/ Model strongly typed as System.Data.DataTable)

<table border="1">
    <thead>
        <tr>
            <%foreach (System.Data.DataColumn col in Model.Columns) { %>
                <th><%=col.Caption %></th>
            <%} %>
        </tr>
    </thead>
    <tbody>
    <% foreach(System.Data.DataRow row in Model.Rows) { %>
        <tr>
            <% foreach (var cell in row.ItemArray) {%>
                <td><%=cell.ToString() %></td>
            <%} %>
        </tr>
    <%} %>         
    </tbody>
</table>

Now, I'm violating a whole lot of principles and "best-practices" of ASP.NET MVC here, so please understand this is just a simple demonstration. The code creating the DataTable should reside somewhere outside of the controller, and the code in the View might be better isolated to a partial, or html helper, to name a few ways you should do things.

You absolutely are supposed to pass objects to the View, if the view is supposed to present them. (Separation of concerns dictates the view shouldn't be responsible for creating them.) In this case I passed the DataTable as the actual view Model, but you could just as well have put it in ViewData collection. Alternatively you might make a specific IndexViewModel class that contains the DataTable and other objects, such as the welcome message.

I hope this helps!

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Go to the Users & Groups pane of the System Preferences -> Select the User -> Click the lock to make changes (bottom left corner) -> right click the current user select Advanced options... -> Select the Login Shell: /bin/zsh and OK

TypeError: $ is not a function WordPress

I was able to resolve this very easily my simply enqueuing jQuery wp_enqueue_script("jquery");

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Changing the version of the support library of the last one enabled (28.0.0) by the previous (27.1.0), the error Android Resource Linking Failed disappeared.

It should be noted that version 27.1.0 is the maximum allowed in our implementations, which works, but you could use an older one if you wish. And this has to be used in all dependencies that start with the string com.android.support:

project/app/build.gradle

implementation "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
implementation "com.android.support:support-v4:$rootProject.supportLibraryVersion"

project/build.gradle

ext {
    supportLibraryVersion= '27.1.0'
}

Then, Sync Project with Gradle Files

GL

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

Rule 1: You can not add a new table without specifying the primary key constraint[not a good practice if you create it somehow]. So the code:

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id));

Rule 2: You are not allowed to use the keywords(words with predefined meaning) as a field name. Here type is something like that is used(commonly used with Join Types). So the code:

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
transaction_type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id));

Now you please try with this code. First check it in your database user interface(I am running HeidiSQL, or you can try it in your xampp/wamp server also)and make sure this code works. Now delete the table from your db and execute the code in your program. Thank You.

Create component to specific module with Angular-CLI

I didn't find an answer that showed how to use the cli to generate a component inside a top level module folder, and also have the component automatically added the the module's declaration collection.

To create the module run this:

ng g module foo

To create the component inside the foo module folder and have it added to the foo.module.ts's declaration collection run this:

ng g component foo/fooList --module=foo.module.ts

And the cli will scaffold out the module and component like this:

enter image description here

--EDIT the new version of the angular cli behaves differently. 1.5.5 doesn't want a module file name so the command with v1.5.5 should be

ng g component foo/fooList --module=foo

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

Internet Explorer cache location

By default, the locations of Temporary Internet Files (for Internet Explorer) are:

Windows 95, Windows 98, and Windows ME

c:\WINDOWS\Temporary Internet Files

Windows 2000 and Windows XP

C:\Documents and Settings\\[User]\Local Settings\Temporary Internet Files

Windows Vista and Windows 7

%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files

%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low

Windows 8

%userprofile%\AppData\Local\Microsoft\Windows\INetCache

Windows 10

%localappdata%\Microsoft\Windows\INetCache\IE

Some information came from The Windows Club.

JQuery: How to get selected radio button value?

$('input[name=myradiobutton]:radio:checked') will get you the selected radio button $('input[name=myradiobutton]:radio:not(:checked)') will get you the unselected radio buttons

Using this you can do this

$('input[name=myradiobutton]:radio:not(:checked)').val("0");

Update: After reading your Update I think I understand You will want to do something like this

var myRadioValue;

function radioValue(jqRadioButton){
  if (jqRadioButton.length) {
    myRadioValue = jqRadioButton.val();
  }
  else {
    myRadioValue = 0;
  }
}

$(document).ready(function () {
  $('input[name=myradiobutton]:radio').click(function () {   //Hook the click event for selected elements
    radioValue($('input[name=myradiobutton]:radio:checked'));
  });

  radioValue($('input[name=myradiobutton]:radio:checked')); //check for value on page load
});

Git: how to reverse-merge a commit?

To revert a merge commit, you need to use: git revert -m <parent number>. So for example, to revert the recent most merge commit using the parent with number 1 you would use:

git revert -m 1 HEAD

To revert a merge commit before the last commit, you would do:

git revert -m 1 HEAD^

Use git show <merge commit SHA1> to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2

git merge documentation: http://schacon.github.com/git/git-merge.html

git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt

How to increase heap size of an android application?

Is there a way to increase this size of memory an application can use?

Applications running on API Level 11+ can have android:largeHeap="true" on the <application> element in the manifest to request a larger-than-normal heap size, and getLargeMemoryClass() on ActivityManager will tell you how big that heap is. However:

  1. This only works on API Level 11+ (i.e., Honeycomb and beyond)

  2. There is no guarantee how large the large heap will be

  3. The user will perceive your large-heap request, because it will force their other apps out of RAM terminate other apps' processes to free up system RAM for use by your large heap

  4. Because of #3, and the fact that I expect that android:largeHeap will be abused, support for this may be abandoned in the future, or the user may be warned about this at install time (e.g., you will need to request a special permission for it)

  5. Presently, this feature is lightly documented

How do I delete all the duplicate records in a MySQL table without temp tables

Tested in mysql 5.Dont know about other versions. If you want to keep the row with the lowest id value:

DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id > n2.id AND n1.member_id = n2.member_id and n1.answer_num =n2.answer_num

If you want to keep the row with the highest id value:

DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id < n2.id AND n1.member_id = n2.member_id and n1.answer_num =n2.answer_num

Set variable value to array of strings

In SQL you can not have a variable array.
However, the best alternative solution is to use a temporary table.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

For me logging in as -Y instead of -X worked.

In case you've got untrusted X11 as shown below, then try -Y flag instead (if you trust the host):

Warning: untrusted X11 forwarding setup failed: xauth key data not generated

Controlling fps with requestAnimationFrame?

Here's a good explanation I found: CreativeJS.com, to wrap a setTimeou) call inside the function passed to requestAnimationFrame. My concern with a "plain" requestionAnimationFrame would be, "what if I only want it to animate three times a second?" Even with requestAnimationFrame (as opposed to setTimeout) is that it still wastes (some) amount of "energy" (meaning that the Browser code is doing something, and possibly slowing the system down) 60 or 120 or however many times a second, as opposed to only two or three times a second (as you might want).

Most of the time I run my browsers with JavaScript intentially off for just this reason. But, I'm using Yosemite 10.10.3, and I think there's some kind of timer problem with it - at least on my old system (relatively old - meaning 2011).

How to verify if $_GET exists?

Normally it is quite good to do:

echo isset($_GET['id']) ? $_GET['id'] : 'wtf';

This is so when assigning the var to other variables you can do defaults all in one breath instead of constantly using if statements to just give them a default value if they are not set.

Java integer list

code that works, but output is:

10
20
30
40
50

so:

    List<Integer> myCoords = new ArrayList<Integer>();
    myCoords.add(10);
    myCoords.add(20);
    myCoords.add(30);
    myCoords.add(40);
    myCoords.add(50);
    for (Integer number : myCoords) {
        System.out.println(number);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Change priorityQueue to max priorityqueue

How about like this:

PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
queue.offer(1);
queue.offer(2);
queue.offer(3);
//...

Integer val = null;
while( (val = queue.poll()) != null) {
    System.out.println(val);
}

The Collections.reverseOrder() provides a Comparator that would sort the elements in the PriorityQueue in a the oposite order to their natural order in this case.

Regex: Check if string contains at least one digit

I'm surprised nobody has mentioned the simplest version:

\d

This will match any digit. If your regular expression engine is Unicode-aware, this means it will match anything that's defined as a digit in any language, not just the Arabic numerals 0-9.

There's no need to put it in [square brackets] to define it as a character class, as one of the other answers did; \d works fine by itself.

Since it's not anchored with ^ or $, it will match any subset of the string, so if the string contains at least one digit, this will match.

And there's no need for the added complexity of +, since the goal is just to determine whether there's at least one digit. If there's at least one digit, this will match; and it will do so with a minimum of overhead.

Finding duplicate values in a SQL table

This is the easy thing I've come up with. It uses a common table expression (CTE) and a partition window (I think these features are in SQL 2008 and later).

This example finds all students with duplicate name and dob. The fields you want to check for duplication go in the OVER clause. You can include any other fields you want in the projection.

with cte (StudentId, Fname, LName, DOB, RowCnt)
as (
SELECT StudentId, FirstName, LastName, DateOfBirth as DOB, SUM(1) OVER (Partition By FirstName, LastName, DateOfBirth) as RowCnt
FROM tblStudent
)
SELECT * from CTE where RowCnt > 1
ORDER BY DOB, LName

Jupyter/IPython Notebooks: Shortcut for "run all"?

As of 5.5 you can run Kernel > Restart and Run All

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

This is Oracle bug, memory leak in shared_pool, most likely db managing lots of partitions. Solution: In my opinion patch not exists, check with oracle support. You can try with subpools or en(de)able AMM ...

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

Copy mysql database from remote server to local computer

Often our databases are really big and the take time to take dump directly from remote machine to other machine as our friends other have suggested above.

In such cases what you can do is to take the dump on remote machine using MYSQLDUMP Command

MYSQLDUMP -uuser -p --all-databases > file_name.sql

and than transfer that file from remote server to your machine using Linux SCP Command

scp user@remote_ip:~/mysql_dump_file_name.sql ./

Parameterize an SQL IN clause

I would pass a table type parameter (since it's SQL Server 2008), and do a where exists, or inner join. You may also use XML, using sp_xml_preparedocument, and then even index that temporary table.

document .click function for touch device

To apply it everywhere, you could do something like

$('body').on('click', function() {
   if($('.children').is(':visible')) {
      $('ul.children').slideUp('slow');
   }
});

When to choose mouseover() and hover() function?

You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.

In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.

lambda expression for exists within list

I would look at the Join operator:

from r in list join i in listofIds on r.Id equals i select r

I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.

Edit: Extension method syntax for completeness (now that I've figured it out):

var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);

R: invalid multibyte string

If you want an R solution, here's a small convenience function I sometimes use to find where the offending (multiByte) character is lurking. Note that it is the next character to what gets printed. This works because print will work fine, but substr throws an error when multibyte characters are present.

find_offending_character <- function(x, maxStringLength=256){  
  print(x)
  for (c in 1:maxStringLength){
    offendingChar <- substr(x,c,c)
    #print(offendingChar) #uncomment if you want the indiv characters printed
    #the next character is the offending multibyte Character
  }    
}

string_vector <- c("test", "Se\x96ora", "works fine")

lapply(string_vector, find_offending_character)

I fix that character and run this again. Hope that helps someone who encounters the invalid multibyte string error.

How to print Boolean flag in NSLog?

NSArray *array1 = [NSArray arrayWithObjects:@"todd1", @"todd2", @"todd3", nil];
bool objectMembership = [array1 containsObject:@"todd1"];
NSLog(@"%d",objectMembership);  // prints 1 or 0

TypeError: '<=' not supported between instances of 'str' and 'int'

If you're using Python3.x input will return a string,so you should use int method to convert string to integer.

Python3 Input

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

By the way,it's a good way to use try catch if you want to convert string to int:

try:
  i = int(s)
except ValueError as err:
  pass 

Hope this helps.

Could not complete the operation due to error 80020101. IE

when do you call timerReset()? Perhaps you get that error when trying to call it after setTimeout() has already done its thing?

wrap it in

if (window.myTimeout) { 
  clearTimeout(myTimeout);
  myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

edit: Actually, upon further reflection, since you did mention jQuery (and yet don't have any actual jQuery code here... I wonder if you have this nested within some jQuery (like inside a $(document).ready(.. and this is a matter of variable scope. If so, try this:

window.message="Logged in";
window.myTimeout = setTimeout("timerDone()",1000 * 1440);
function timerDone()
{
    window.message="Logged out";   
}
function timerReset()
{


    clearTimeout(window.myTimeout);
    window.myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

Displaying output of a remote command with Ansible

Prints pubkey and avoid the changed status by adding changed_when: False to cat task:

- name: Generate SSH keys for vagrant user   
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048

- name: Check SSH public key   
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
  changed_when: False

- name: Print SSH public key
  debug: var=cat.stdout

- name: Wait for user to copy SSH public key   
  pause: prompt="Please add the SSH public key above to your GitHub account"

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

Using CMake with GNU Make: How can I see the exact commands?

I was trying something similar to ensure the -ggdb flag was present.

Call make in a clean directory and grep the flag you are looking for. Looking for debug rather than ggdb I would just write.

make VERBOSE=1 | grep debug

The -ggdb flag was obscure enough that only the compile commands popped up.

How do I change the font size of a UILabel in Swift?

If you want just change size of your font i create this extension

// Add extension

extension UILabel {
    func setSizeFont (sizeFont: Double) {
        self.font =  UIFont(name: self.font.fontName, size: sizeFont)!
        self.sizeToFit()
    }
}

// Use

myLabel.setSizeFont(60)

Vibrate and Sound defaults on notification

An extension to TeeTracker's answer,

to get the default notification sound you can do as follows

NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notify)
            .setContentTitle("Device Connected")
            .setContentText("Click to monitor");

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);

This will give you the default notification sound.

How to remove a TFS Workspace Mapping?

Following are the steps to remove mapping of a project from TFS:

(1) Click on View Button.

(2) Open Team Explorer

(3) Click on Source Control

(4) Right click on your project/Directory

(5) Click on Remove Mapping

(6) Finally Delete the Project form local directory.

How get permission for camera in android.(Specifically Marshmallow)

click here for full source code and learn more.

Before get permission you can check api version,

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
  {
      if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {

      } 
      else
      {
         ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 401);
      }
  }
  else
  {
    // if version is below m then write code here,          
  }

Get the Result of the permission dialog,

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 401) {
        if (grantResults.length == 0 || grantResults == null) {

        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openGallery();
        } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
        }
    } else if (requestCode == 402) {
        if (grantResults.length == 0 || grantResults == null) {

        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
        }
    }
} 

calling another method from the main method in java

If you want to use do() in your main method there are 2 choices because one is static but other (do()) not

  1. Create new instance and invoke do() like new Foo().do();
  2. make static do() method

Have a look at this sun tutorial

How to upgrade Angular CLI project?

Just use the build-in feature of Angular CLI

ng update

to update to the latest version.

Find the 2nd largest element in an array with minimum number of comparisons

try this.

max1 = a[0].
max2.
for i = 0, until length:
  if a[i] > max:
     max2 = max1.
     max1 = a[i].
     #end IF
  #end FOR
return min2.

it should work like a charm. low in complexity.

here is a java code.

int secondlLargestValue(int[] secondMax){
int max1 = secondMax[0]; // assign the first element of the array, no matter what, sorted or not.
int max2 = 0; // anything really work, but zero is just fundamental.
   for(int n = 0; n < secondMax.length; n++){ // start at zero, end when larger than length, grow by 1. 
        if(secondMax[n] > max1){ // nth element of the array is larger than max1, if so.
           max2 = max1; // largest in now second largest,
           max1 = secondMax[n]; // and this nth element is now max.
        }//end IF
    }//end FOR
    return max2;
}//end secondLargestValue()

Location of sqlite database on the device

By Default it stores to:    

String DATABASE_PATH = "/data/data/" + PACKAGE_NAME + "/databases/" + DATABASE_NAME;

Where:

String DATABASE_NAME = "your_dbname";
String PACKAGE_NAME = "com.example.your_app_name";

And check whether your database is stored to Device Storage. If So, You have to use permission in Manifest.xml :

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

Difference between require, include, require_once and include_once?

From the manual:

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

The same is true for the _once() variants.

Good way of getting the user's location in Android

Recently refactored to obtain the location of the code, learn some good ideas, and finally achieved a relatively perfect library and Demo.

@Gryphius's answer is good

    //request all valid provider(network/gps)
private boolean requestAllProviderUpdates() {
    checkRuntimeEnvironment();
    checkPermission();

    if (isRequesting) {
        EasyLog.d("Request location update is busy");
        return false;
    }


    long minTime = getCheckTimeInterval();
    float minDistance = getCheckMinDistance();

    if (mMapLocationListeners == null) {
        mMapLocationListeners = new HashMap<>();
    }

    mValidProviders = getValidProviders();
    if (mValidProviders == null || mValidProviders.isEmpty()) {
        throw new IllegalArgumentException("Not available provider.");
    }

    for (String provider : mValidProviders) {
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if (location == null) {
                    EasyLog.e("LocationListener callback location is null.");
                    return;
                }
                printf(location);
                mLastProviderTimestamp = location.getTime();

                if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    finishResult(location);
                } else {
                    doLocationResult(location);
                }

                removeProvider(location.getProvider());
                if (isEmptyValidProviders()) {
                    requestTimeoutMsgInit();
                    removeUpdates();
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };
        getLocationManager().requestLocationUpdates(provider, minTime, minDistance, locationListener);
        mMapLocationListeners.put(provider, locationListener);
        EasyLog.d("Location request %s provider update.", provider);
    }
    isRequesting = true;
    return true;
}

//remove request update
public void removeUpdates() {
    checkRuntimeEnvironment();

    LocationManager locationManager = getLocationManager();
    if (mMapLocationListeners != null) {
        Set<String> keys = mMapLocationListeners.keySet();
        for (String key : keys) {
            LocationListener locationListener = mMapLocationListeners.get(key);
            if (locationListener != null) {
                locationManager.removeUpdates(locationListener);
                EasyLog.d("Remove location update, provider is " + key);
            }
        }
        mMapLocationListeners.clear();
        isRequesting = false;
    }
}

//Compared with the last successful position, to determine whether you need to filter
private boolean isNeedFilter(Location location) {
    checkLocation(location);

    if (mLastLocation != null) {
        float distance = location.distanceTo(mLastLocation);
        if (distance < getCheckMinDistance()) {
            return true;
        }
        if (location.getAccuracy() >= mLastLocation.getAccuracy()
                && distance < location.getAccuracy()) {
            return true;
        }
        if (location.getTime() <= mLastProviderTimestamp) {
            return true;
        }
    }
    return false;
}

private void doLocationResult(Location location) {
    checkLocation(location);

    if (isNeedFilter(location)) {
        EasyLog.d("location need to filtered out, timestamp is " + location.getTime());
        finishResult(mLastLocation);
    } else {
        finishResult(location);
    }
}

//Return to the finished position
private void finishResult(Location location) {
    checkLocation(location);

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    float accuracy = location.getAccuracy();
    long time = location.getTime();
    String provider = location.getProvider();

    if (mLocationResultListeners != null && !mLocationResultListeners.isEmpty()) {
        String format = "Location result:<%f, %f> Accuracy:%f Time:%d Provider:%s";
        EasyLog.i(String.format(format, latitude, longitude, accuracy, time, provider));

        mLastLocation = location;
        synchronized (this) {
            Iterator<LocationResultListener> iterator =  mLocationResultListeners.iterator();
            while (iterator.hasNext()) {
                LocationResultListener listener = iterator.next();
                if (listener != null) {
                    listener.onResult(location);
                }
                iterator.remove();
            }
        }
    }
}

Complete implementation: https://github.com/bingerz/FastLocation/blob/master/fastlocationlib/src/main/java/cn/bingerz/fastlocation/FastLocation.java

1.Thanks @Gryphius solution ideas, I also share the complete code.

2.Each request to complete the location, it is best to removeUpdates, otherwise the phone status bar will always display the positioning icon

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

It seems odd that this directory was not created at install - have you manually changed the path of the socket file in the my.cfg?

Have you tried simply creating this directory yourself, and restarting the service?

mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld

How to base64 encode image in linux bash / shell

To base64 it and put it in your clipboard:

file="test.docx"
base64 -w 0 $file  | xclip -selection clipboard

What version of MongoDB is installed on Ubuntu

To be complete, a short introduction for "shell noobs":

First of all, start your shell - you can find it inside the common desktop environments under the name "Terminal" or "Shell" somewhere in the desktops application menu.

You can also try using the key combo CTRL+F2, followed by one of those commands (depending on the desktop envrionment you're using) and the ENTER key:

xfce4-terminal
gnome-console
terminal
rxvt
konsole

If all of the above fail, try using xterm - it'll work in most cases.

Hint for the following commands: Execute the commands without the $ - it's just a marker identifying that you're on the shell.

After that just fire up mongod with the --version flag:

$ mongod --version

It shows you then something like

$ mongod --version
db version v2.4.6
Wed Oct 16 16:17:00.241 git version: nogitversion

To update it just execute

$ sudo apt-get update

and then

$ sudo apt-get install mongodb

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

If one or both of the files you wish to compare isn't in an Eclipse project:

  1. Open the Quick Access search box

    • Linux/Windows: Ctrl+3
    • Mac: ?+3
  2. Type compare and select Compare With Other Resource

  3. Select the files to compare ? OK

You can also create a keyboard shortcut for Compare With Other Resource by going to Window ? Preferences ? General ? Keys

What is PostgreSQL equivalent of SYSDATE from Oracle?

You may want to use statement_timestamp(). This give the timestamp when the statement was executed. Whereas NOW() and CURRENT_TIMESTAMP give the timestamp when the transaction started.

More details in the manual

The application was unable to start correctly (0xc000007b)

It is a missing dll. Possibly, your dll that works with com ports have an unresolved dll dependence. You can use dependency walker and windows debugger. Check all of the mfc library, for example. Also, you can use nrCommlib - it is great components to work with com ports.

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

Getting the encoding of a Postgres database

Method 1:

If you're already logged in to the db server, just copy and paste this.

SHOW SERVER_ENCODING;

Result:

  server_encoding 
-----------------  
UTF8

For Client encoding :

 SHOW CLIENT_ENCODING;

Method 2:

Again if you are already logged in, use this to get the list based result

\l 

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

enter image description here

For me these two files I have deleted by mistake, after undo these two files and get added in my changes, I was able to commit my changes to git.

Get a JSON object from a HTTP response

Do this to get the JSON

String json = EntityUtils.toString(response.getEntity());

More details here : get json from HttpResponse

How to check if directory exists in %PATH%?

Add Directory to PATH if not already exists:

set myPath=c:\mypath
For /F "Delims=" %%I In ('echo %PATH% ^| find /C /I "%myPath%"') Do set pathExists=%%I 2>Nul
If %pathExists%==0 (set PATH=%myPath%;%PATH%)

Why does adb return offline after the device string?

To complete the previous answers, another possible solution is to change the USB socket in which your cable is plugged in.

I had this problem (with the classical answer about using adb kill-server / start-server not working) and it solved it.

Actually, it took some time to find that because Windows was correctly recognizing the device in my first socket. But not ADB. As Windows was recognizing the device, I had no real need to test other USB physical sockets. I should have.

So you can try to plug the cable in all your USB physical sockets directly available on your computer. It did worked for me. Sometimes the USB sockets are not managed the same way by a computer.

Run a Python script from another Python script, passing in arguments

This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:

import script1

In an ideal world, you will be able to call a function inside script1 directly:

for i in range(whatever):
    script1.some_function(i)

If necessary, you can hack sys.argv. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.

import contextlib
@contextlib.contextmanager
def redirect_argv(num):
    sys._argv = sys.argv[:]
    sys.argv=[str(num)]
    yield
    sys.argv = sys._argv

with redirect_argv(1):
    print(sys.argv)

I think this is preferable to passing all your data to the OS and back; that's just silly.

What are the differences in die() and exit() in PHP?

They sound about the same, however, the exit() also allows you to set the exit code of your PHP script.

Usually you don't really need this, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way.

Then you can use exit() and catch that later on. Die() however doesn't support that.

Die() always exists with code 0. So essentially a die() command does the following:

<?php
echo "I am going to die";
exit(0);
?>

Which is the same as:

<?php
die("I am going to die");
?>

What method in the String class returns only the first N characters?

The .NET Substring method is fraught with peril. I developed extension methods that handle a wide variety of scenarios. The nice thing is it preserves the original behavior, but when you add an additional "true" parameter, it then resorts to the extension method to handle the exception, and returns the most logical values, based on the index and length. For example, if length is negative, and counts backward. You can look at the test results with wide variety of values on the fiddle at: https://dotnetfiddle.net/m1mSH9. This will give you a clear idea on how it resolves substrings.

I always add these methods to all my projects, and never have to worry about code breaking, because something changed and the index is invalid. Below is the code.

    public static String Substring(this String val, int startIndex, bool handleIndexException)
    {
        if (!handleIndexException)
        { //handleIndexException is false so call the base method
            return val.Substring(startIndex);
        }
        if (string.IsNullOrEmpty(val))
        {
            return val;
        }
        return val.Substring(startIndex < 0 ? 0 : startIndex > (val.Length - 1) ? val.Length : startIndex);
    }

    public static String Substring(this String val, int startIndex, int length, bool handleIndexException)
    {
        if (!handleIndexException)
        { //handleIndexException is false so call the base method
            return val.Substring(startIndex, length);
        }
        if (string.IsNullOrEmpty(val))
        {
            return val;
        }
        int newfrom, newlth, instrlength = val.Length;
        if (length < 0) //length is negative
        {
            newfrom = startIndex + length;
            newlth = -1 * length;
        }
        else //length is positive
        {
            newfrom = startIndex;
            newlth = length;
        }
        if (newfrom + newlth < 0 || newfrom > instrlength - 1)
        {
            return string.Empty;
        }
        if (newfrom < 0)
        {
            newlth = newfrom + newlth;
            newfrom = 0;
        }
        return val.Substring(newfrom, Math.Min(newlth, instrlength - newfrom));
    }

I blogged about this back in May 2010 at: http://jagdale.blogspot.com/2010/05/substring-extension-method-that-does.html

MS-access reports - The search key was not found in any record - on save

Thew problem is because of spaces in the titles(Headers). Remove spaces in all headers and it works fine.

What exactly is an instance in Java?

Objects, which are also called instances, are self-contained elements of a program with related features and data. For the most part, you use the class merely to create instances and then work with those instances.

-Definition taken from the book "Sams Teach Yourself Java in 21 days".

Say you have 2 Classes, public class MainClass and public class Class_2 and you want to make an instance of Class_2 in MainClass.

This is a very simple and basic way to do it:

public MainClass()      /*******this is the constructor of MainClass*******/

{

 Class_2 nameyouwant = new Class_2();

}

I hope this helps!

Import Excel spreadsheet columns into SQL Server database

You could use OPENROWSET, something like:

SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
  'Excel 8.0;IMEX=1;HDR=NO;DATABASE=C:\FILE.xls', 'Select * from [Sheet1$]'

Just make sure the path is a path on the server, not your local machine.

How to run multiple DOS commands in parallel?

I suggest you to see "How do I run a bat file in the background from another bat file?"

Also, good answer (of using start command) was given in "Parallel execution of shell processes" question page here;

But my recommendation is to use PowerShell. I believe it will perfectly suit your needs.

How can I get the class name from a C++ object?

Just write simple template:

template<typename T>
const char* getClassName(T) {
  return typeid(T).name();
}

struct A {} a;

void main() {
   std::cout << getClassName(a);
}

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I solved this issue. use below taglib

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

and add jstl-1.2.jar

How do I comment out a block of tags in XML?

You can easily comment out the data using this:

<!-- 
 <data>
        <data-field1></data-field1>
        <data-field2></data-field2>
        <data-field3></data-field3>
 </data>
-->

method of commenting in xml.

best practice to generate random token for forgot password

This may be helpful whenever you need a very very random token

<?php
   echo mb_strtoupper(strval(bin2hex(openssl_random_pseudo_bytes(16))));
?>

What is the difference between ELF files and bin files?

some resources:

  1. ELF for the ARM architecture
    http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
  2. ELF from wiki
    http://en.wikipedia.org/wiki/Executable_and_Linkable_Format

ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:

  arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]

or using fromELF utility(built in most IDEs such as ADS though):

 fromelf -bin -o [binary-output-file] [elf-input-file]

Most efficient way to check if a file is empty in Java on Windows

You can choose try the FileReader approach but it may not be time to give up just yet. If is the BOM field destroying for you try this solution posted here at stackoverflow.

Byte order mark screws up file reading in Java

How to get the selected value from drop down list in jsp?

Direct value should work just fine:

var sel = document.getElementsByName('item');
var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

What should I set JAVA_HOME environment variable on macOS X 10.6?

As other answers note, the correct way to find the Java home directory is to use /usr/libexec/java_home.

The official documentation for this is in Apple's Technical Q&A QA1170: Important Java Directories on OS X: https://developer.apple.com/library/mac/qa/qa1170/_index.html

filters on ng-model in an input

If you are using read only input field, you can use ng-value with filter.

for example:

ng-value="price | number:8"

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);

int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
    myValueLookup = myDictionay[keyToFind];
    // do work...
}
else
{
    // the key doesn't exist.
}

MAX function in where clause mysql

We can't reference the result of an aggregate function (for example MAX() ) in a WHERE clause of the same SELECT.

The normative pattern for solving this type of problem is to use an inline view, something like this:

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
  JOIN ( SELECT MAX(mx.id) AS max_id
           FROM mytable mx
       ) m
    ON m.max_id = t.id

This is just one way to get the specified result. There are several other approaches to get the same result, and some of those can be much less efficient than others. Other answers demonstrate this approach:

 WHERE t.id = (SELECT MAX(id) FROM ... )

Sometimes, the simplest approach is to use an ORDER BY with a LIMIT. (Note that this syntax is specific to MySQL)

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
 ORDER BY t.id DESC
 LIMIT 1

Note that this will return only one row; so if there is more than one row with the same id value, then this won't return all of them. (The first query will return ALL the rows that have the same id value.)

This approach can be extended to get more than one row, you could get the five rows that have the highest id values by changing it to LIMIT 5.

Note that performance of this approach is particularly dependent on a suitable index being available (i.e. with id as the PRIMARY KEY or as the leading column in another index.) A suitable index will improve performance of queries using all of these approaches.

Best way to store passwords in MYSQL database

Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.

Assert a function/method was not called using Mock

When you test using class inherits unittest.TestCase you can simply use methods like:

  • assertTrue
  • assertFalse
  • assertEqual

and similar (in python documentation you find the rest).

In your example we can simply assert if mock_method.called property is False, which means that method was not called.

import unittest
from unittest import mock

import my_module

class A(unittest.TestCase):
    def setUp(self):
        self.message = "Method should not be called. Called {times} times!"

    @mock.patch("my_module.method_to_mock")
    def test(self, mock_method):
        my_module.method_to_mock()

        self.assertFalse(mock_method.called,
                         self.message.format(times=mock_method.call_count))

Retrieving a property of a JSON object by index?

it is quite simple...

_x000D_
_x000D_
var obj = {_x000D_
    "set1": [1, 2, 3],_x000D_
    "set2": [4, 5, 6, 7, 8],_x000D_
    "set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
jQuery.each(obj, function(i, val) {_x000D_
 console.log(i); // "set1"_x000D_
 console.log(val); // [1, 2, 3]_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

gcc-arm-linux-gnueabi command not found

Its a bit counter-intuitive. The toolchain is called gcc-arm-linux-gnueabi. To invoke the tools execute the following: arm-linux-gnueabi-xxx

where xxx is gcc or ar or ld, etc

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

Https to http redirect using htaccess

The difference between http and https is that https requests are sent over an ssl-encrypted connection. The ssl-encrypted connection must be established between the browser and the server before the browser sends the http request.

Https requests are in fact http requests that are sent over an ssl encrypted connection. If the server rejects to establish an ssl encrypted connection then the browser will have no connection to send the request over. The browser and the server will have no way of talking to each other. The browser will not be able to send the url that it wants to access and the server will not be able to respond with a redirect to another url.

So this is not possible. If you want to respond to https links, then you need an ssl certificate.

Empty responseText from XMLHttpRequest

This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.

In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.

Now sure why it worked, but it did.

Determine device (iPhone, iPod Touch) with iOS

I use this in my app. Up to date as of December 2012.

- (NSString *) platformString {
    // Gets a string with the device model
    size_t size;  
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);  
    char *machine = malloc(size);  
    sysctlbyname("hw.machine", machine, &size, NULL, 0);  
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];  
    free(machine); 

    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"iPhone 4 (CDMA)";    
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";

    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch (1 Gen)";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch (2 Gen)";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch (3 Gen)";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch (4 Gen)";
    if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch (5 Gen)";

    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad1,2"])      return @"iPad 3G";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"iPad2,4"])      return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([platform isEqualToString:@"iPad2,6"])      return @"iPad Mini";
    if ([platform isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([platform isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,3"])      return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";

    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"Simulator";

    return platform;
}  

Saving excel worksheet to CSV files with filename+worksheet name using VB

I think this is what you want...

Sub SaveWorksheetsAsCsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long

CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"

For Each WS In Application.ActiveWorkbook.Worksheets
    WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next

Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
'  about overwriting the original file.

End Sub

How to modify a specified commit?

For me it was for removing some credentials from a repo. I tried rebasing and ran into a ton of seemingly unrelated conflicts along the way when trying to rebase --continue. Don't bother attempting to rebase yourself, use the tool called BFG (brew install bfg) on mac.

const to Non-const Conversion in C++

Leaving this here for myself,

If I get this error, I probably used const char* when I should be using char* const.

This makes the pointer constant, and not the contents of the string.

const char* const makes it so the value and the pointer is constant also.

How to ping an IP address

Check your connectivity. On my Computer this prints REACHABLE for both IP's:

Sending Ping Request to 127.0.0.1
Host is reachable
Sending Ping Request to 173.194.32.38
Host is reachable

EDIT:

You could try modifying the code to use getByAddress() to obtain the address:

public static void main(String[] args) throws UnknownHostException, IOException {
    InetAddress inet;

    inet = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
    System.out.println("Sending Ping Request to " + inet);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");

    inet = InetAddress.getByAddress(new byte[] { (byte) 173, (byte) 194, 32, 38 });
    System.out.println("Sending Ping Request to " + inet);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");
}

The getByName() methods may attempt some kind of reverse DNS lookup which may not be possible on your machine, getByAddress() might bypass that.

How to check which locks are held on a table

This is not exactly showing you which rows are locked, but this may helpful to you.

You can check which statements are blocked by running this:

select cmd,* from sys.sysprocesses
where blocked > 0

It will also tell you what each block is waiting on. So you can trace that all the way up to see which statement caused the first block that caused the other blocks.

Edit to add comment from @MikeBlandford:

The blocked column indicates the spid of the blocking process. You can run kill {spid} to fix it.

Text on image mouseover?

This is using the :hover pseudoelement in CSS3.

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper .text {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

#wrapper:hover .text {
visibility:visible;
}

?Demo HERE.


This instead is a way of achieving the same result by using jquery:

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper p {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

jquery code:

$('.hover').mouseover(function() {
  $('.text').css("visibility","visible");
});

$('.hover').mouseout(function() {
  $('.text').css("visibility","hidden");
});

You can put the jquery code where you want, in the body of the HTML page, then you need to include the jquery library in the head like this:

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>

You can see the demo HERE.

When you want to use it on your website, just change the <img src /> value and you can add multiple images and captions, just copy the format i used: insert image with class="hover" and p with class="text"

Revert to Eclipse default settings

I am not an expert on this, but I'll share my example with you. One guy suggested to create new eclipse preferences file or epf file using another clean install of eclipse. I made a file called clean.epf and compared it with RainbowDrops.epf (the one which messed up my highlighting and such). I noticed a huge difference between the two epf files. So, you might not want to use this method.

The whole windows --- preferences thing did not help. So, I just closed eclipse. Went to

My workspace directory/.metadata/.plugins/org.eclipse.core.runtime/.settings/

and deleted the file org.eclipse.ui.editors.prefs and opened eclipse. It works. BTW, keep a back up of your .settings folders just in case.

In case you want to see some difference between rainbow and clean epf -

Rainbow -

file_export_version=3.0
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION=167,236,33
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.bold=false
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.enabled=true
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.italic=false
/instance/ccw.core/ccw.preferences.editor_color.GLOBAL_VAR=141,218,248
...more here

Clean (exporting all) -

/instance/org.eclipse.jdt.ui/tabWidthPropagated=true
/instance/org.eclipse.mylyn.monitor.ui/org.eclipse.mylyn.monitor.activity.tracking.enabled.checked=true
/instance/org.eclipse.mylyn.tasks.ui/org.eclipse.mylyn.tasks.ui.filters.nonmatching.encouraged=true
@org.eclipse.mylyn.monitor.ui=3.13.0.v20140702-2155
/instance/org.eclipse.jdt.ui/useQuickDiffPrefPage=true
...more here

Clean (exporting only java) -

file_export_version=3.0
/instance/org.eclipse.jdt.ui/org.eclipse.jdt.ui.formatterprofiles.version=12
@org.eclipse.jdt.ui=3.10.100.v20140905-1343
\!/=
...end of file

So, I am not sure if this is the best way to go.

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

c# razor url parameter from view

@(ViewContext.RouteData.Values["parameterName"])

worked with ROUTE PARAM.

Request.Params["paramName"]

did not work with ROUTE PARAM.

How do you build a Singleton in Dart?

Dart singleton by const constructor & factory

class Singleton {
  factory Singleton() =>
    Singleton._internal_();
  Singleton._internal_();
}
 
 
void main() {
  print(new Singleton() == new Singleton());
  print(identical(new Singleton() , new Singleton()));
}

Using "like" wildcard in prepared statement

We can use the CONCAT SQL function.

PreparedStatement pstmt = con.prepareStatement(
      "SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();

This works perfectly for my case.

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

How to configure Visual Studio to use Beyond Compare

I got bored of doing this every 6 months when a new version of Visual Studio comes out, or I move PCs, or a new member joins the team. So, PowerShell:

# .Synopsys
# Sets up Beyond Compare professional as Diff tool for all instances of Visual Studio on this PC
# If you don't use TFS, change the sccProvider as appropriate
[CmdLetBinding()]
param(
    $bcPath = 'C:\Program Files (x86)\Beyond Compare 3\BComp.exe',
    $sccProvider = 'TeamFoundation'
)

$ErrorActionPreference = 'stop';
$baseKey = 'REGISTRY::\HKCU\Software\Microsoft\VisualStudio\*'

function SetRegKeyProperties($keyPath, [hashtable]$keyProps){
    if(!(Test-Path $keyPath)){
        Write-Verbose "Creating $keyPath"
        # Force required here to recursively create registry path
        [void] (new-item $keyPath -Type:Directory -Force);
    }
    foreach($prop in $keyProps.GetEnumerator()){
        Set-ItemProperty -Path:$keyPath -Name:$prop.Key -Value:$prop.Value;
    }
}

$configBases = dir $baseKey | ? { $_.PSChildName -match '^\d+\.\d$' }
foreach($item in $configBases){
    Write-Host "Configuring $item"

    $diffToolsKey = Join-Path $item.PSPath "$sccProvider\SourceControl\DiffTools"
    SetRegKeyProperties (Join-path $diffToolsKey '.*\Compare') @{Command=$bcPath;Arguments='%1 %2 /title1=%6 /title2=%7'}
    SetRegKeyProperties (Join-path $diffToolsKey '.*\Merge') @{Command=$bcPath;Arguments='%1 %2 %3 %4 /title1=%6 /title2=%7 /title3=%8 /title4=%9'}
}

Works on my machine. YMMV. No warranties, no refunds. VS doesn't appear to cache the key, so takes effect immediately.

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

How to convert integers to characters in C?

char c1 = (char)97;  //c1 = 'a'

int i = 98;
char c2 = (char)i;  //c2 = 'b'

Looking for a 'cmake clean' command to clear up CMake output

It's funny to see this question gets so many attentions and complicated solutions, which indeed shows a pain to not have a clean method with cmake.

Well, you can definitely cd build to do you work, then do a rm -rf * when you need to clean. However, rm -rf * is a dangerous command given that many people are often not aware which dir they are in.

If you cd .., rm -rf build and then mkdir build and then cd build, that's just too much typing.

So a good solution is to just stay out of the build folder and tell cmake the path:
to configure: cmake -B build
to build: cmake --build build
to clean: rm -rf build
to recreate build folder: you don't even need mkdir build, just configure it with cmake -B build and cmake will create it

How to redirect to a different domain using NGINX?

That should work via HTTPRewriteModule.

Example rewrite from www.example.com to example.com:

server {    
    server_name www.example.com;    
    rewrite ^ http://example.com$request_uri? permanent; 
}

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

PHP sessions that have already been started

session_status() === PHP_SESSION_ACTIVE ?: session_start();

Closed Game

What are the uses of "using" in C#?

In conclusion, when you use a local variable of a type that implements IDisposable, always, without exception, use using1.

If you use nonlocal IDisposable variables, then always implement the IDisposable pattern.

Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.


1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose explicitly in the finally block.

Count character occurrences in a string in C++

Old-fashioned solution with appropriately named variables. This gives the code some spirit.

#include <cstdio>
int _(char*__){int ___=0;while(*__)___='_'==*__++?___+1:___;return ___;}int main(){char*__="_la_blba_bla__bla___";printf("The string \"%s\" contains %d _ characters\n",__,_(__));}

Edit: about 8 years later, looking at this answer I'm ashamed I did this (even though I justified it to myself as a snarky poke at a low-effort question). This is toxic and not OK. I'm not removing the post; I'm adding this apology to help shifting the atmosphere on StackOverflow. So OP: I apologize and I hope you got your homework right despite my trolling and that answers like mine did not discourage you from participating on the site.

Detecting a long press with Android

option: custom detector class

abstract public class
Long_hold
extends View.OnTouchListener
{
  public@Override boolean
  onTouch(View view, MotionEvent touch)
  {
    switch(touch.getAction())
    {
    case ACTION_DOWN: down(touch); return true;
    case ACTION_MOVE: move(touch);
    }
    return true;
  }

  private long
  time_0;
  private float
  x_0, y_0;

  private void
  down(MotionEvent touch)
  {
    time_0= touch.getEventTime();
    x_0= touch.getX();
    y_0= touch.getY();
  }

  private void
  move(MotionEvent touch)
  {
    if(held_too_short(touch) {return;}
    if(moved_too_much(touch)) {return;}

    long_press(touch);
  }
  abstract protected void
  long_hold(MotionEvent touch);
}

use

private double
moved_too_much(MotionEvent touch)
{
  return Math.hypot(
      x_0 -touch.getX(),
      y_0 -touch.getY()) >TOLERANCE;
}

private double
held_too_short(MotionEvent touch)
{
  return touch.getEventTime()-time_0 <DOWN_PERIOD;
}

where

  • TOLERANCE is the maximum tolerated movement

  • DOWN_PERIOD is the time one has to press

import

static android.view.MotionEvent.ACTION_MOVE;
static android.view.MotionEvent.ACTION_DOWN;

in code

setOnTouchListener(new Long_hold()
  {
  protected@Override boolean
  long_hold(MotionEvent touch)
  {
    /*your code on long hold*/
  }
});

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

How to use OpenCV SimpleBlobDetector

// creation 
            cv::SimpleBlobDetector * blob_detector; 
            blob_detector = new SimpleBlobDetector(); 
            blob_detector->create("SimpleBlobDetector"); 
// change params - first move it to public!! 
            blob_detector->params.filterByArea = true; 
            blob_detector->params.minArea = 1; 
            blob_detector->params.maxArea = 32000; 
// or read / write them with file 
            FileStorage fs("test_fs.yml", FileStorage::WRITE); 
            FileNode fn = fs["features"]; 

            //blob_detector->read(fn); 
// detect 
            vector<KeyPoint> keypoints; 
            blob_detector->detect(img_text, keypoints); 
            fs.release(); 

I do know why, but params are protected. So I moved it in file features2d.hpp to be public:

  virtual void read( const FileNode& fn ); 
  virtual void write( FileStorage& fs ) const; 

public: 
Params params; 




protected: 
struct CV_EXPORTS Center 
  { 
      Point2d loc 

If you will not do this, the only way to change params is to create file (FileStorage fs("test_fs.yml", FileStorage::WRITE);), than open it in notepad, and edit. Or maybe there is another way, but I`m not aware of it.

php delete a single file in directory

unlink is the right php function for your use case.

unlink('/path/to/file');

Without more information, I can't tell you what went wrong when you used it.

Add back button to action bar

There are two ways to approach this.

Option 1: Update the Android Manifest If the settings Activity is always called from the same activity, you can make the relationship in the Android Manifest. Android will automagically show the 'back' button in the ActionBar

<activity
    android:name=".SettingsActivity"
    android:label="Setting Activity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.example.MainActivity" />
</activity>

Option 2: Change a setting for the ActionBar If you don't know which Activity will call the Settings Activity, you can create it like this. First in your activity that extends ActionBarActivity (Make sure your @imports match the level of compatibility you are looking for).

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings_test);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
}

Then, detect the 'back button' press and tell Android to close the currently open Activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

That should do it!

How to read a line from the console in C?

This function should do what you want:

char* readLine( FILE* file )
 {
 char buffer[1024];
 char* result = 0;
 int length = 0;

 while( !feof(file) )
  {
  fgets( buffer, sizeof(buffer), file );
  int len = strlen(buffer);
  buffer[len] = 0;

  length += len;
  char* tmp = (char*)malloc(length+1);
  tmp[0] = 0;

  if( result )
   {
   strcpy( tmp, result );
   free( result );
   result = tmp;
   }

  strcat( result, buffer );

  if( strstr( buffer, "\n" ) break;
  }

 return result;
 }

char* line = readLine( stdin );
/* Use it */
free( line );

I hope this helps.

Python != operation vs "is not"

Consider the following:

class Bad(object):
    def __eq__(self, other):
        return True

c = Bad()
c is None # False, equivalent to id(c) == id(None)
c == None # True, equivalent to c.__eq__(None)

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:
=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?

Iterating through all the cells in Excel VBA or VSTO 2005

For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.

For Excel 2003, this MSDN article is a good place to start. Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective

You'll basically need to do the following:

  • Start the Excel application.
  • Open the Excel workbook.
  • Retrieve the worksheet from the workbook by name or index.
  • Iterate through all the Cells in the worksheet which were retrieved as a range.
  • Sample (untested) code excerpt below for the last step.

    Excel.Range allCellsRng;
    string lowerRightCell = "IV65536";
    allCellsRng = ws.get_Range("A1", lowerRightCell).Cells;
    foreach (Range cell in allCellsRng)
    {
        if (null == cell.Value2 || isBlank(cell.Value2))
        {
          // Do something.
        }
        else if (isText(cell.Value2))
        {
          // Do something.
        }
        else if (isNumeric(cell.Value2))
        {
          // Do something.
        }
    }

For Excel 2007, try this MSDN reference.

How to initialize a variable of date type in java?

To initialize to current date, you could do something like:

Date firstDate = new Date();

To get it from String, you could use SimpleDateFormat like:

String dateInString = "10-Jan-2016";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
} catch (ParseException e) {
    //handle exception if date is not in "dd-MMM-yyyy" format
}

var functionName = function() {} vs function functionName() {}

Difference function declaration and function expression:

Javascript has first class functions. This means that they can be treated just like any other variable. Functions can be passed as arguments in a function, be returned from a function, and can be stored in variables.

However storing function in a variable (function expression) isn't the only way to create a function, this can also be done via a function declaration. Here are the key differences:

  1. Function expressions can be anonymous whereas a function declaration must have a name.
  2. Both have a name property which is used to identify the function. A function expression's name property is the name of the variable which it is bound to, whereas the name of a function declaration is simply the given name.
  3. Function declarations are hoisted whereas, function expressions are not. Only the variable is hoisted to have the value of undefined.

Here is an example:

_x000D_
_x000D_
try {_x000D_
  functionOne();_x000D_
} catch (e) {_x000D_
  console.log('i cant run because im not hoisted');_x000D_
}_x000D_
_x000D_
functionTwo();_x000D_
_x000D_
// function expression, does not get hoisted_x000D_
let functionOne = function randomName() {_x000D_
    // Some code_x000D_
};_x000D_
_x000D_
// function declaration, gets hoisted_x000D_
function functionTwo() {_x000D_
   console.log('I get hoisted');_x000D_
}_x000D_
_x000D_
try {_x000D_
  randomName(); // this isn't the proper name, it is functionOne_x000D_
} catch (e) {_x000D_
  console.log('You cant call me with randomName my name is function one');_x000D_
}
_x000D_
_x000D_
_x000D_

:

jQuery Set Selected Option Using Next

Update:

As of jQuery 1.6+ you should use prop() instead of attr() in this case.

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);


Original Answer:

If you want to select by the value of the option, REGARDLESS of its position (this example assumes you have an ID for your select):

var theValue = "whatever";
$("#selectID").val( theValue ).attr('selected',true);

You do not need to "unselect". That happens automatically when you select another.

How to make a TextBox accept only alphabetic characters?

This one is working absolutely fine...

 private void manufacturerOrSupplierTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (char.IsControl(e.KeyChar) || char.IsLetter(e.KeyChar))
        {
            return;
        }
        e.Handled = true;
    }

How do multiple clients connect simultaneously to one port, say 80, on a server?

Important:

I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.

First remember below two rules:

  1. Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL} not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT} - Protocol is an important part of a socket's definition.

  2. OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.

Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP} and socket2{SRC-B, 100, DEST-X,80, TCP}. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.

To answer the original question of the post:

Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.

To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.

A bit more for completeness:

Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.

Server Types - single & multiple:

When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).

Suggested Books and rest of the two volumes if you can.

A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')

Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.

Ruby class instance variable vs. class variable

Source

Availability to instance methods

  • Class instance variables are available only to class methods and not to instance methods.
  • Class variables are available to both instance methods and class methods.

Inheritability

  • Class instance variables are lost in the inheritance chain.
  • Class variables are not.
class Vars

  @class_ins_var = "class instance variable value"  #class instance variable
  @@class_var = "class variable value" #class  variable

  def self.class_method
    puts @class_ins_var
    puts @@class_var
  end

  def instance_method
    puts @class_ins_var
    puts @@class_var
  end
end

Vars.class_method

puts "see the difference"

obj = Vars.new

obj.instance_method

class VarsChild < Vars


end

VarsChild.class_method

How are echo and print different in PHP?

As the PHP.net manual suggests, take a read of this discussion.

One major difference is that echo can take multiple parameters to output. E.g.:

echo 'foo', 'bar';   // Concatenates the 2 strings
print('foo', 'bar'); // Fatal error

If you're looking to evaluate the outcome of an output statement (as below) use print. If not, use echo.

$res = print('test');
var_dump($res); //bool(true)

What is the purpose of willSet and didSet in Swift?

My understanding is that set and get are for computed properties (no backing from stored properties)

if you are coming from an Objective-C bare in mind that the naming conventions have changed. In Swift an iVar or instance variable is named stored property

Example 1 (read only property) - with warning:

var test : Int {
    get {
        return test
    }
}

This will result in a warning because this results in a recursive function call (the getter calls itself).The warning in this case is "Attempting to modify 'test' within its own getter".

Example 2. Conditional read/write - with warning

var test : Int {
    get {
        return test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        //(prevents same value being set)
        if (aNewValue != test) {
            test = aNewValue
        }
    }
}

Similar problem - you cannot do this as it's recursively calling the setter. Also, note this code will not complain about no initialisers as there is no stored property to initialise.

Example 3. read/write computed property - with backing store

Here is a pattern that allows conditional setting of an actual stored property

//True model data
var _test : Int = 0

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Note The actual data is called _test (although it could be any data or combination of data) Note also the need to provide an initial value (alternatively you need to use an init method) because _test is actually an instance variable

Example 4. Using will and did set

//True model data
var _test : Int = 0 {

    //First this
    willSet {
        println("Old value is \(_test), new value is \(newValue)")
    }

    //value is set

    //Finaly this
    didSet {
        println("Old value is \(oldValue), new value is \(_test)")
    }
}

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Here we see willSet and didSet intercepting a change in an actual stored property. This is useful for sending notifications, synchronisation etc... (see example below)

Example 5. Concrete Example - ViewController Container

//Underlying instance variable (would ideally be private)
var _childVC : UIViewController? {
    willSet {
        //REMOVE OLD VC
        println("Property will set")
        if (_childVC != nil) {
            _childVC!.willMoveToParentViewController(nil)
            self.setOverrideTraitCollection(nil, forChildViewController: _childVC)
            _childVC!.view.removeFromSuperview()
            _childVC!.removeFromParentViewController()
        }
        if (newValue) {
            self.addChildViewController(newValue)
        }

    }

    //I can't see a way to 'stop' the value being set to the same controller - hence the computed property

    didSet {
        //ADD NEW VC
        println("Property did set")
        if (_childVC) {
//                var views  = NSDictionaryOfVariableBindings(self.view)    .. NOT YET SUPPORTED (NSDictionary bridging not yet available)

            //Add subviews + constraints
            _childVC!.view.setTranslatesAutoresizingMaskIntoConstraints(false)       //For now - until I add my own constraints
            self.view.addSubview(_childVC!.view)
            let views = ["view" : _childVC!.view] as NSMutableDictionary
            let layoutOpts = NSLayoutFormatOptions(0)
            let lc1 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("|[view]|",  options: layoutOpts, metrics: NSDictionary(), views: views)
            let lc2 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: layoutOpts, metrics: NSDictionary(), views: views)
            self.view.addConstraints(lc1)
            self.view.addConstraints(lc2)

            //Forward messages to child
            _childVC!.didMoveToParentViewController(self)
        }
    }
}


//Computed property - this is the property that must be used to prevent setting the same value twice
//unless there is another way of doing this?
var childVC : UIViewController? {
    get {
        return _childVC
    }
    set(suggestedVC) {
        if (suggestedVC != _childVC) {
            _childVC = suggestedVC
        }
    }
}

Note the use of BOTH computed and stored properties. I've used a computed property to prevent setting the same value twice (to avoid bad things happening!); I've used willSet and didSet to forward notifications to viewControllers (see UIViewController documentation and info on viewController containers)

I hope this helps, and please someone shout if I've made a mistake anywhere here!

Windows equivalent of the 'tail' command

more /e filename.txt P n

where n = the number of rows to display. Works fast and is exactly like head command.

Generate sha256 with OpenSSL and C++

Here's the function I personally use - I simply derived it from the function I used for sha-1 hashing:

char *str2sha256( const char *str, int length ) {
  int n;
  SHA256_CTX c;
  unsigned char digest[ SHA256_DIGEST_LENGTH ];
  char *out = (char*) malloc( 33 );

  SHA256_Init( &c );

  while ( length > 0 ) {
    if ( length > 512 ) SHA256_Update( &c, str, 512 );
    else SHA256_Update( &c, str, length );

    length -= 512;
    str += 512;
  }

  SHA256_Final ( digest, &c );

  for ( n = 0; n < SHA256_DIGEST_LENGTH; ++n )
    snprintf( &( out[ n*2 ] ), 16*2, "%02x", (unsigned int) digest[ n ] );

  return out;
}

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

What does flex: 1 mean?

In Chrome Ver 84, flex: 1 is equivalent to flex: 1 1 0%. The followings are a bunch of screenshots.

enter image description here

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.

Some reasons why this might happen:

  • Tomcat may have crashed
  • The web application did not respond in time and the request from Apache timed out
  • The Tomcat threads are timing out
  • A network device is blocking the request, perhaps as some sort of connection timeout or DoS attack prevention system

If the problem is related to timeout settings, you may be able to resolve it by investigating the following:

  • ProxyTimeout directive of Apache's mod_proxy
  • Connector config of Apache Tomcat
  • Your network device's manual

How to call javascript function from code-behind

There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:

<head runat="server"> 
    <title>Calling javascript function from code behind example</title> 
        <script type="text/javascript"> 
            function showDialogue() { 
                alert("this dialogue has been invoked through codebehind."); 
            } 
        </script> 
</head>

..........

lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";

Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm

How do I convert NSMutableArray to NSArray?

Objective-C

Below is way to convert NSMutableArray to NSArray:

//oldArray is having NSMutableArray data-type.
//Using Init with Array method.
NSArray *newArray1 = [[NSArray alloc]initWithArray:oldArray];

//Make copy of array
NSArray *newArray2 = [oldArray copy];

//Make mutablecopy of array
NSArray *newArray3 = [oldArray mutableCopy];

//Directly stored NSMutableArray to NSArray.
NSArray *newArray4 = oldArray;

Swift

In Swift 3.0 there is new data type Array. Declare Array using let keyword then it would become NSArray And if declare using var keyword then it's become NSMutableArray.

Sample code:

let newArray = oldArray as Array

Inheriting constructors

You have to explicitly define the constructor in B and explicitly call the constructor for the parent.

B(int x) : A(x) { }

or

B() : A(5) { }

Setting DEBUG = False causes 500 Error

I know this is late but I ended up here with a search for my error 500 with DEBUG=False, in my case it did turn out to be the ALLOWED_HOSTS but I was using os.environ.get('variable') to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False:

# settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}

Incorrect integer value: '' for column 'id' at row 1

To let MySql generate sequence numbers for an AUTO_INCREMENT field you have three options:

  1. specify list a column list and omit your auto_incremented column from it as njk suggested. That would be the best approach. See comments.
  2. explicitly assign NULL
  3. explicitly assign 0

3.6.9. Using AUTO_INCREMENT:

...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

These three statements will produce the same result:

$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";

Byte Array to Image object

Since it sounds like you already know what format the byte[] array is in (e.g. RGB, ARGB, BGR etc.) you might be able to use BufferedImage.setRGB(...), or a combination of BufferedImage.getRaster() and WritableRaster.setPixels(...) or WritableRaster.setSamples(...). Unforunately both of these methods require you transform your byte[] into one of int[], float[] or double[] depending on the image format.

Remove .php extension with .htaccess

Here's a method if you want to do it for just one specific file:

RewriteRule ^about$ about.php [L]

Ref: http://css-tricks.com/snippets/htaccess/remove-file-extention-from-urls/

Python MYSQL update statement

You've got the syntax all wrong:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))

For more, read the documentation.

Search in lists of lists by given index

>>> my_list =[ ['a', 'b'], ['a', 'c'], ['b', 'd'] ]
>>> 'd' in (x[1] for x in my_list)
True

Editing to add:

Both David's answer using any and mine using in will end when they find a match since we're using generator expressions. Here is a test using an infinite generator to show that:

def mygen():
    ''' Infinite generator '''
    while True:
        yield 'xxx'  # Just to include a non-match in the generator
        yield 'd'

print 'd' in (x for x in mygen())     # True
print any('d' == x for x in mygen())  # True
# print 'q' in (x for x in mygen())     # Never ends if uncommented
# print any('q' == x for x in mygen())  # Never ends if uncommented

I just like simply using in instead of both == and any.

Getting Django admin url for an object

from django.core.urlresolvers import reverse
def url_to_edit_object(obj):
  url = reverse('admin:%s_%s_change' % (obj._meta.app_label,  obj._meta.model_name),  args=[obj.id] )
  return u'<a href="%s">Edit %s</a>' % (url,  obj.__unicode__())

This is similar to hansen_j's solution except that it uses url namespaces, admin: being the admin's default application namespace.

Mutex lock threads

A process consists of at least one thread (think of the main function). Multi threaded code will just spawn more threads. Mutexes are used to create locks around shared resources to avoid data corruption / unexpected / unwanted behaviour. Basically it provides for sequential execution in an asynchronous setup - the requirement for which stems from non-const non-atomic operations on shared data structures.

A vivid description of what mutexes would be the case of people (threads) queueing up to visit the restroom (shared resource). While one person (thread) is using the bathroom easing him/herself (non-const non-atomic operation), he/she should ensure the door is locked (mutex), otherwise it could lead to being caught in full monty (unwanted behaviour)

How can I convert JSON to a HashMap using Gson?

I have overcome a similar problem with a Custom JsonDeSerializer. I tried to make it a bit generic but still not enough. It is a solution though that fits my needs.

First of all you need to implement a new JsonDeserializer for Map objects.

public class MapDeserializer<T, U> implements JsonDeserializer<Map<T, U>>

And the deserialize method will look similar to this:

public Map<T, U> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

        if (!json.isJsonObject()) {
            return null;
        }

        JsonObject jsonObject = json.getAsJsonObject();
        Set<Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
        Map<T, U> deserializedMap = new HashMap<T, U>();

        for (Entry<java.lang.String, JsonElement> entry : jsonEntrySet) {
            try {
                U value = context.deserialize(entry.getValue(), getMyType());
                deserializedMap.put((T) entry.getKey(), value);
            } catch (Exception ex) {
                logger.info("Could not deserialize map.", ex);
            }
        }

        return deserializedMap;
    }

The con with this solution, is that my Map's key is always of Type "String". However by chaning some things someone can make it generic. In addition, i need to say, that the value's class should be passed in the constructor. So the method getMyType() in my code returns the type of the Map's values, which was passed in the constructor.

You can reference this post How do I write a custom JSON deserializer for Gson? in order to learn more about custom deserializers.

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

The Problem is related to MySql Driver

Class.forName("com.mysql.jdbc.Driver");

Add the MySQL jdbc driver jar file in to your classpath.

Also i have this error on JDK. I build the ClassPath Properly then I put the "mysql-connector-java-5.1.25-bin" in dir "C:\Program Files\Java\jre7\lib\ext" in this dir i have my JDK. then compile and Run again then it's working fine.

How to import csv file in PHP?

From the PHP manual:

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

Outline radius?

I like this way.

.circle:before {
   content: "";
   width: 14px;
   height: 14px;
   border: 3px solid #fff;
   background-color: #ced4da;
   border-radius: 7px;
   display: inline-block;
   margin-bottom: -2px;
   margin-right: 7px;
   box-shadow: 0px 0px 0px 1px #ced4da;
}

It will create gray circle with wit border around it and again 1px around border!

Have a reloadData for a UITableView animate when changing

The way to approach this is to tell the tableView to remove and add rows and sections with the

insertRowsAtIndexPaths:withRowAnimation:,
deleteRowsAtIndexPaths:withRowAnimation:,
insertSections:withRowAnimation: and
deleteSections:withRowAnimation:

methods of UITableView.

When you call these methods, the table will animate in/out the items you requested, then call reloadData on itself so you can update the state after this animation. This part is important - if you animate away everything but don't change the data returned by the table's dataSource, the rows will appear again after the animation completes.

So, your application flow would be:

[self setTableIsInSecondState:YES];

[myTable deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES]];

As long as your table's dataSource methods return the correct new set of sections and rows by checking [self tableIsInSecondState] (or whatever), this will achieve the effect you're looking for.

Boolean.parseBoolean("1") = false...?

I had the same question and i solved it with that:

Boolean use_vote = o.get('uses_votes').equals("1") ? true : false;

Changing Vim indentation behavior by file type

Use ftplugins or autocommands to set options.

ftplugin

In ~/.vim/ftplugin/python.vim:

setlocal shiftwidth=2 softtabstop=2 expandtab

And don't forget to turn them on in ~/.vimrc:

filetype plugin indent on

(:h ftplugin for more information)

autocommand

In ~/.vimrc:

autocmd FileType python setlocal shiftwidth=2 softtabstop=2 expandtab

You can replace any of the long commands or settings with their short versions:
autocmd: au
setlocal: setl
shiftwidth: sw
tabstop: ts
softtabstop: sts
expandtab: et

I would also suggest learning the difference between tabstop and softtabstop. A lot of people don't know about softtabstop.

Change width of select tag in Twitter Bootstrap

I did a workaround by creating a new css class in my custom stylesheet as follows:

.selectwidthauto
{
     width:auto !important;
}

And then applied this class to all my select elements either manually like:

<select id="State" class="selectwidthauto">
...
</select>

Or using jQuery:

$('select').addClass('selectwidthauto');

Bootstrap carousel multiple frames at once

All the above solutions are hacky and buggy. Don't even try. Use other libs. The best I have found - http://sachinchoolur.github.io/lightslider Works great with bootstrap, does not add junk html, highly-configurable, responsive, mobile-friendly etc...

$('.multi-item-carousel').lightSlider({
    item: 4,
    pager: false,
    autoWidth: false,
    slideMargin: 0
});

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.

Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.

Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).

Can you force Vue.js to reload/re-render?

sorry guys, except page reload method(flickering), none of them works for me (:key didn't worked).

and i found this method from old vue.js forum which is works for me:

https://github.com/vuejs/Discussion/issues/356

<template>
    <div v-if="show">
       <button @click="rerender">re-render</button>
    </div>
</template>
<script>
    export default {
        data(){
            return {show:true}
        },
        methods:{
            rerender(){
                this.show = false
                this.$nextTick(() => {
                    this.show = true
                    console.log('re-render start')
                    this.$nextTick(() => {
                        console.log('re-render end')
                    })
                })
            }
        }
    }
</script>

How do I reference a cell within excel named range?

To read a particular date from range EJ_PAYDATES_2021 (index is next to the last "1")

=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,1,1)  // Jan
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,2,1)  // Feb
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,3,1)  // Mar

This allows reading a particular element of a range [0] etc from another spreadsheet file. Target file need not be open. Range in the above example is named EJ_PAYDATES_2021, with one element for each month contained within that range.

Took me a while to parse this out, but it works, and is the answer to the question asked above.

Removing first x characters from string?

Another way (depending on your actual needs): If you want to pop the first n characters and save both the popped characters and the modified string:

s = 'lipsum'
n = 3
a, s = s[:n], s[n:]
print(a)
# lip
print(s)
# sum

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

On a SpringBoot project using IntelliJ and Gradle, I got the warning "Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0" when running my integration test. What solved the problem was: - Going to: File > Settings > Build, Execution, Deployment - Selecting for "Build and run using": Intellij IDEA (instead of "Gradle") - Same for "Run tests using" That did not explain why Gradle is displaying the warning, but that let me perform the test and progress in my work.

Including jars in classpath on commandline (javac or apt)

In windows:

java -cp C:/.../jardir1/*;C:/.../jardir2/* class_with_main_method

make sure that the class with the main function is in one of the included jars

Center image horizontally within a div

Style.css

img#center-img{

 display: block;
 margin: auto;
}

Html

<html>
  <body>
    <div>
      <img src='pic.png' id='center-img'>
    </div>
  </body>
</html>

How to go to a specific element on page?

To scroll to a specific element on your page, you can add a function into your jQuery(document).ready(function($){...}) as follows:

$("#fromTHIS").click(function () {
    $("html, body").animate({ scrollTop: $("#toTHIS").offset().top }, 500);
    return true;
});

It works like a charm in all browsers. Adjust the speed according to your need.

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

jQuery how to find an element based on a data-attribute value?

You have to inject the value of current into an Attribute Equals selector:

$("ul").find(`[data-slide='${current}']`)

For older JavaScript environments (ES5 and earlier):

$("ul").find("[data-slide='" + current + "']"); 

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

How to import classes defined in __init__.py

Add something like this to lib/__init__.py

from .helperclass import Helper

now you can import it directly:

from lib import Helper

How to add a new project to Github using VS Code

Here are the detailed steps needed to achieve this.

The existing commands can be simply run via the CLI terminal of VS-CODE. It is understood that Git is installed in the system, configured with desired username and email Id.

1) Navigate to the local project directory and create a local git repository:

 git init

2) Once that is successful, click on the 'Source Control' icon on the left navbar in VS-Code.One should be able to see files ready to be commit-ed. Press on 'Commit' button, provide comments, stage the changes and commit the files. Alternatively you can run from CLI

git commit -m "Your comment"

3) Now you need to visit your GitHub account and create a new Repository. Exclude creating 'README.md', '.gitIgnore' files. Also do not add any License to the repo. Sometimes these settings cause issue while pushing in.

4) Copy the link to this newly created GitHub Repository.

5) Come back to the terminal in VS-CODE and type these commands in succession:

git remote add origin <Link to GitHub Repo>     //maps the remote repo link to local git repo

git remote -v                                  //this is to verify the link to the remote repo 

git push -u origin master                      // pushes the commit-ed changes into the remote repo

Note: If it is the first time the local git account is trying to connect to GitHub, you may be required to enter credentials to GitHub in a separate window.

6) You can see the success message in the Terminal. You can also verify by refreshing the GitHub repo online.

Hope this helps

How can I add comments in MySQL?

You can use single line comments:

-- this is a comment
# this is also a comment

Or a multiline comment:

/*
   multiline
   comment
*/

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Make the DropDownStyle to DropDownList

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Given a filesystem path, is there a shorter way to extract the filename without its extension?

Try this,

string FilePath=@"C:\mydir\myfile.ext";
string Result=Path.GetFileName(FilePath);//With Extension
string Result=Path.GetFileNameWithoutExtension(FilePath);//Without Extension

linux script to kill java process

pkill -f for whatever reason does not work for me. Whatever that does, it seems very finicky about actually grepping through what ps aux shows me clearly is there.

After an afternoon of swearing I went for putting the following in my start script:

(ps aux | grep -v -e 'grep ' | grep MainApp | tr -s " " | cut -d " " -f 2 | xargs kill -9 ) || true

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

From commons-lang3

org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)

Change background color on mouseover and remove it after mouseout

Try this , its working and simple

HTML

?????????????????????<html>
<head></head>
<body>
    <div class="forum">
        test
    </div>
</body>
</html>?????????????????????????????????????????????

Javascript

$(document).ready(function() {
    var colorOrig=$(".forum").css('background-color');
    $(".forum").hover(
    function() {
        //mouse over
        $(this).css('background', '#ff0')
    }, function() {
        //mouse out
        $(this).css('background', colorOrig)
    });
});?

css ?

.forum{
    background:#f0f;
}?

live demo

http://jsfiddle.net/caBzg/

How to enter ssh password using bash?

Create a new keypair: (go with the defaults)

ssh-keygen

Copy the public key to the server: (password for the last time)

ssh-copy-id [email protected]

From now on the server should recognize your key and not ask you for the password anymore:

ssh [email protected]

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

System.IO.IOException: file used by another process

I realize that I is kinda late, but still better late than never. I was having similar problem recently. I used XMLWriter to subsequently update XML file and was receiving the same errors. I found the clean solution for this:

The XMLWriter uses underlying FileStream to access the modified file. Problem is that when you call XMLWriter.Close() method, the underlying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter with settings and specify that you need that underlying stream closed.

Example:

XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);

Hope it helps.

how to count the total number of lines in a text file using python

count=0
with open ('filename.txt','rb') as f:
    for line in f:
        count+=1

print count

Get SSID when WIFI is connected

Android 9 SSID showing NULL values use this code..

ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            wifiInfo.getSSID();
            String name = networkInfo.getExtraInfo();
            String ssid = wifiInfo.getSSID();
            return ssid.replaceAll("^\"|\"$", "");
        }

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

Connecting an input stream to an outputstream

How about just using

void feedInputToOutput(InputStream in, OutputStream out) {
   IOUtils.copy(in, out);
}

and be done with it?

from jakarta apache commons i/o library which is used by a huge amount of projects already so you probably already have the jar in your classpath already.

Explicit Return Type of Lambda

You can have more than one statement when still return:

[]() -> your_type {return (
        your_statement,
        even_more_statement = just_add_comma,
        return_value);}

http://www.cplusplus.com/doc/tutorial/operators/#comma

How to convert a full date to a short date in javascript?

var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)"); 
document.getElementById("demo").innerHTML = d.toLocaleDateString();

Bulk create model objects in django

worked for me to use manual transaction handling for the loop(postgres 9.1):

from django.db import transaction
with transaction.commit_on_success():
    for item in items:
        MyModel.objects.create(name=item.name)

in fact it's not the same, as 'native' database bulk insert, but it allows you to avoid/descrease transport/orms operations/sql query analyse costs

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

Sorting arrays in NumPy by column

From the Python documentation wiki, I think you can do:

a = ([[1, 2, 3], [4, 5, 6], [0, 0, 1]]); 
a = sorted(a, key=lambda a_entry: a_entry[1]) 
print a

The output is:

[[[0, 0, 1], [1, 2, 3], [4, 5, 6]]]

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

put your CA & root certificate in /usr/share/ca-certificate or /usr/local/share/ca-certificate. Then

dpkg-reconfigure ca-certificates

or even reinstall ca-certificate package with apt-get.

After doing this your certificate is collected into system's DB: /etc/ssl/certs/ca-certificates.crt

Then everything should be fine.

Static constant string (class member)

Inside class definitions you can only declare static members. They have to be defined outside of the class. For compile-time integral constants the standard makes the exception that you can "initialize" members. It's still not a definition, though. Taking the address would not work without definition, for example.

I'd like to mention that I don't see the benefit of using std::string over const char[] for constants. std::string is nice and all but it requires dynamic initialization. So, if you write something like

const std::string foo = "hello";

at namespace scope the constructor of foo will be run right before execution of main starts and this constructor will create a copy of the constant "hello" in the heap memory. Unless you really need RECTANGLE to be a std::string you could just as well write

// class definition with incomplete static member could be in a header file
class A {
    static const char RECTANGLE[];
};

// this needs to be placed in a single translation unit only
const char A::RECTANGLE[] = "rectangle";

There! No heap allocation, no copying, no dynamic initialization.

Cheers, s.

Count characters in textarea

Try this one.

<textarea maxlength="410" name="about_me" onkeydown="CountLeft(this.form.about_me, this.form.left);" onkeyup="CountLeft(this.form.about_me,this.form.left); "></textarea>

<input maxlength="3" name="left" readonly="" size="3" type="text" value="410" /> characters left

<script>
function CountLeft(field, count) 
{
    var max = "410";
    if (field.value.length > max)
    {
        field.value = field.value.substring(0, max);
    }
    else
    {
        count.value = max - field.value.length;
    }
}
</script>

How can I check the syntax of Python script without executing it?

import sys
filename = sys.argv[1]
source = open(filename, 'r').read() + '\n'
compile(source, filename, 'exec')

Save this as checker.py and run python checker.py yourpyfile.py.

How to use DISTINCT and ORDER BY in same SELECT statement?

If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:

SELECT [Category] FROM [MonitoringJob] 
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.

Passing arguments to angularjs filters

You can simply use | filter:yourFunction:arg

<div ng-repeat="group in groups | filter:weDontLike:group">...</div>

And in js

$scope.weDontLike = function(group) {
//here your condition/criteria
return !!group 
}

Checking if a variable is not nil and not zero in ruby

You could initialize discount to 0 as long as your code is guaranteed not to try and use it before it is initialized. That would remove one check I suppose, I can't think of anything else.

Java, How to specify absolute value and square roots

Use the static methods in the Math class for both - there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there's no operator for raising a value to a particular power - use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));

Changing date format in R

After reading your data in via a textConnection, the following seems to work:

dat <- read.table(textConnection(txt), header = TRUE)
dat$date <- strptime(dat$date, format= "%d/%m/%Y")
format(dat$date, format="%Y-%m-%d")

> format(dat$date, format="%Y-%m-%d")
 [1] "2011-08-31" "2011-07-31" "2011-06-30" "2011-05-31" "2011-04-30" "2011-03-31"
 [7] "2011-02-28" "2011-01-31" "2010-12-31" "2010-11-30" "2010-10-31" "2010-09-30"
[13] "2010-08-31" "2010-07-31" "2010-06-30" "2010-05-31" "2010-04-30" "2010-03-31"
[19] "2010-02-28" "2010-01-31" "2009-12-31" "2009-11-30" "2009-10-31"

> str(dat)
'data.frame':   23 obs. of  2 variables:
 $ date    : POSIXlt, format: "2011-08-31" "2011-07-31" "2011-06-30" ...
 $ midpoint: num  0.838 0.846 0.815 0.797 0.788 ...

Invalid length for a Base-64 char array

    string stringToDecrypt = CypherText.Replace(" ", "+");
    int len = stringToDecrypt.Length;
    byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); 

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

CSS On hover show another element

we just can show same label div on hovering like this

<style>
#b {
    display: none;
}

#content:hover~#b{
    display: block;
}

</style>

Is it better practice to use String.format over string Concatenation in Java?

I think we can go with MessageFormat.format as it should be good at both readability and also performance aspects.

I used the same program which one used by Icaro in his above answer and I enhanced it with appending code for using MessageFormat to explain the performance numbers.

  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = "Hi " + i + "; Hi to you " + i * 2;
    }
    long end = System.currentTimeMillis();
    System.out.println("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
  }

Concatenation = 69 millisecond

Format = 1435 millisecond

MessageFormat = 200 millisecond

UPDATES:

As per SonarLint Report, Printf-style format strings should be used correctly (squid:S3457)

Because printf-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that result in the wrong strings being created. This rule statically validates the correlation of printf-style format strings to their arguments when calling the format(...) methods of java.util.Formatter, java.lang.String, java.io.PrintStream, MessageFormat, and java.io.PrintWriter classes and the printf(...) methods of java.io.PrintStream or java.io.PrintWriter classes.

I replace the printf-style with the curly-brackets and I got something interesting results as below.

Concatenation = 69 millisecond
Format = 1107 millisecond
Format:curly-brackets = 416 millisecond
MessageFormat = 215 millisecond
MessageFormat:curly-brackets = 2517 millisecond

My Conclusion:
As I highlighted above, using String.format with curly-brackets should be a good choice to get benefits of good readability and also performance.

How to allow only numbers in textbox in mvc4 razor

function NumValidate(e) {
    var evt = (e) ? e : window.event;
    var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        alert('Only Number ');
        return false;
    }    return true;
}  function NumValidateWithDecimal(e) {

var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;

if (!(charCode == 8 || charCode == 46 || charCode == 110 || charCode == 13 || charCode == 9) && (charCode < 48 || charCode > 57)) {
    alert('Only Number With desimal e.g.: 0.0');
    return false;
}
else {
    return true;
} } function onlyAlphabets(e) {
try {
    if (window.event) {
        var charCode = window.event.keyCode;
    }
    else if (e) {
        var charCode = e.which;
    }
    else { return true; }

    if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 46) || (charCode == 32))
        return true;
    else
        alert("Only text And White Space And . Allow");
    return false;

}
catch (err) {
    alert(err.Description);
}} function checkAlphaNumeric(e) {

if (window.event) {
    var charCode = window.event.keyCode;
}
else if (e) {
    var charCode = e.which;
}
else { return true; }

if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode == 32) || (charCode >= 97 && charCode <= 122)) {
    return true;
} else {
    alert('Only Text And Number');
    return false;
}}