Programs & Examples On #Findstr

findstr is a Windows command that searches for patterns of text in one or more files using regular expressions.

What are the undocumented features and limitations of the Windows FINDSTR command?

I'd like to report a bug regarding the section Source of data to search in the first answer when using en dash (–) or em dash (—) within the filename.

More specifically, if you are about to use the first option - filenames specified as arguments, the file won't be found. As soon as you use either option 2 - stdin via redirection or 3 - data stream from a pipe, findstr will find the file.

For example, this simple batch script:

echo off
chcp 1250 > nul
set INTEXTFILE1=filename with – dash.txt
set INTEXTFILE2=filename with — dash.txt

rem 3 way of findstr use with en dashed filename
echo.
echo Filename with en dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE1%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE1%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE1%" | findstr .
echo.
echo.
rem The same set of operations with em dashed filename
echo Filename with em dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE2%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE2%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE2%" | findstr .
echo.

pause

will print:

Filename with en dash:

  1. As argument
    FINDSTR: Cannot open filename with - dash.txt

  2. As stdin via redirection
    I am the file with an en dash.

  3. As datastream from a pipe
    I am the file with an en dash.

Filename with em dash:

  1. As argument
    FINDSTR: Cannot open filename with - dash.txt

  2. As stdin via redirection
    I am the file with an em dash.

  3. As datastream from a pipe
    I am the file with an em dash.

Hope it helps.

M.

How do I catch an Ajax query post error?

$.post('someUri', { }, 
  function(data){ doSomeStuff })
 .fail(function(error) { alert(error.responseJSON) });

How can I reference a commit in an issue comment on GitHub?

Answer above is missing an example which might not be obvious (it wasn't to me).

Url could be broken down into parts

https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
                  \_____/\________/       \_______________________________________/
                   |        |                              |
            Account name    |                      Hash of revision
                        Project name              

Hash can be found here (you can click it and will get the url from browser).

enter image description here

Hope this saves you some time.

What is the difference between HTML tags and elements?

HTML tag is just opening or closing entity. For example:

<p> and </p> are called HTML tags

HTML element encompasses opening tag, closing tag, content (optional for content-less tags) Eg:

<p>This is the content</p> : This complete thing is called a HTML element

How to change MySQL column definition?

Syntax to change column name in MySql:

alter table table_name change old_column_name new_column_name data_type(size);

Example:

alter table test change LowSal Low_Sal integer(4);

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax. Having fig is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')). You certainly don't have to use the returned figure object but many people do use it later so it's common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:

fig, ax = plt.subplots()

is more concise than this:

fig = plt.figure()
ax = fig.add_subplot(111)

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:

sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh

open new terminal and validate environment is clean from old RVM settings (should be no output):

env | grep rvm

if there was output, try to open new terminal, if it does not help then restart your computer.

install RVM:

\curl -L https://get.rvm.io | 
  bash -s stable --ruby --autolibs=enable --auto-dotfiles

If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.

post ajax data to PHP and return data

So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:

$id = $_POST['id'];

function getVotes($id){
    // call your database here
    $query = ("SELECT votes FROM poll WHERE ID = $id");
    $result = @mysql_query($query);
    $row = mysql_fetch_row($result);

    return $row->votes;
}
$votes = getVotes($id);
echo $votes;

This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.

Using sed to split a string with a delimiter

This should do it:

cat ~/Desktop/myfile.txt | sed s/:/\\n/g

php string to int

If you want to leave only numbers - use preg_replace like: (int)preg_replace("/[^\d]+/","",$b).

How do I format a date in Jinja2?

You can use it like this in jinja template {{ row.session_start_date_time.strftime('%d-%m-%Y %H:%M:%S')}}

In this code the field name is row.session_start_date_time.

what is reverse() in Django

reverse() | Django documentation


Let's suppose that in your urls.py you have defined this:

url(r'^foo$', some_view, name='url_name'),

In a template you can then refer to this url as:

<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>

<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>

This will be rendered as:

<a href="/foo/">link which calls some_view</a>

Now say you want to do something similar in your views.py - e.g. you are handling some other url (not /foo/) in some other view (not some_view) and you want to redirect the user to /foo/ (often the case on successful form submission).

You could just do:

return HttpResponseRedirect('/foo/')

But what if you want to change the url in future? You'd have to update your urls.py and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.

Instead, you can say:

from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))

This looks through all urls defined in your project for the url defined with the name url_name and returns the actual url /foo/.

This means that you refer to the url only by its name attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py.

Use "ENTER" key on softkeyboard instead of clicking button

may be you could add a attribute to your EditText like this:

android:imeOptions="actionSearch"

How to maintain a Unique List in Java?

I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?

If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.

Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.

How to find the extension of a file in C#?

You will not be able to restrict the file type that the user uploads at the client side[*]. You'll only be able to do this at the server side. If a user uploads an incorrect file you will only be able to recognise that once the file is uploaded uploaded. There is no reliable and safe way to stop a user uploading whatever file format they want.

[*] yes, you can do all kinds of clever stuff to detect the file extension before starting the upload, but don't rely on it. Someone will get around it and upload whatever they like sooner or later.

Troubleshooting "Illegal mix of collations" error in mysql

One another source of the issue with collations is mysql.proc table. Check collations of your storage procedures and functions:

SELECT
  p.db, p.db_collation, p.type, COUNT(*) cnt
FROM mysql.proc p
GROUP BY p.db, p.db_collation, p.type;

Also pay attention to mysql.proc.collation_connection and mysql.proc.character_set_client columns.

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

MySQL foreach alternative for procedure

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: mysql-storedprocedures.pdf

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

Remove all special characters, punctuation and spaces from string

The most generic approach is using the 'categories' of the unicodedata table which classifies every single character. E.g. the following code filters only printable characters based on their category:

import unicodedata
# strip of crap characters (based on the Unicode database
# categorization:
# http://www.sql-und-xml.de/unicode-database/#kategorien

PRINTABLE = set(('Lu', 'Ll', 'Nd', 'Zs'))

def filter_non_printable(s):
    result = []
    ws_last = False
    for c in s:
        c = unicodedata.category(c) in PRINTABLE and c or u'#'
        result.append(c)
    return u''.join(result).replace(u'#', u' ')

Look at the given URL above for all related categories. You also can of course filter by the punctuation categories.

Cast IList to List

If you have an IList containing interfaces, you can cast it like this:

List to IList

List<Foo> Foos = new List<Foo>(); 
IList<IFoo> IFoos = Foos.ToList<IFoo>();

IList to List

IList<IFoo> IFoos = new List<IFoo>();
List<Foo> Foos = new List<Foo>(IFoos.Select(x => (Foo)x));

This assumes Foo has IFoo interfaced.

How to pass a textbox value from view to a controller in MVC 4?

Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter

@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton

Python group by

The following function will quickly (no sorting required) group tuples of any length by a key having any index:

# given a sequence of tuples like [(3,'c',6),(7,'a',2),(88,'c',4),(45,'a',0)],
# returns a dict grouping tuples by idx-th element - with idx=1 we have:
# if merge is True {'c':(3,6,88,4),     'a':(7,2,45,0)}
# if merge is False {'c':((3,6),(88,4)), 'a':((7,2),(45,0))}
def group_by(seqs,idx=0,merge=True):
    d = dict()
    for seq in seqs:
        k = seq[idx]
        v = d.get(k,tuple()) + (seq[:idx]+seq[idx+1:] if merge else (seq[:idx]+seq[idx+1:],))
        d.update({k:v})
    return d

In the case of your question, the index of key you want to group by is 1, therefore:

group_by(input,1)

gives

{'ETH': ('5238761','5349618','962142','7795297','7341464','5594916','1550003'),
 'KAT': ('11013331', '9843236'),
 'NOT': ('9085267', '11788544')}

which is not exactly the output you asked for, but might as well suit your needs.

Cannot serve WCF services in IIS on Windows 8

you can add this code to web.config in asp mvc

   <system.webServer>
    <staticContent>
      <remove fileExtension=".srt" />
      <mimeMap fileExtension=".srt" mimeType="text/srt" />
      <remove fileExtension=".vtt" />
      <mimeMap fileExtension=".vtt" mimeType="text/vtt" />
    </staticContent>
  </system.webServer>

you can change file extension with your file extension

DataGridView AutoFit and Fill

Try doing,

 AutoSizeColumnMode = Fill;

Swift: Display HTML data in a label or textView

IF YOU HAVE A STRING WITH HTML CODE INSIDE YOU CAN USE:

extension String {
var utfData: Data? {
        return self.data(using: .utf8)
    }

    var htmlAttributedString: NSAttributedString? {
        guard let data = self.utfData else {
            return nil
        }
        do {
            return try NSAttributedString(data: data,
                                          options: [
                                            .documentType: NSAttributedString.DocumentType.html,
                                            .characterEncoding: String.Encoding.utf8.rawValue
                ], documentAttributes: nil)
        } catch {
            print(error.localizedDescription)
            return nil
        }
    }

    var htmlString: String {
        return htmlAttributedString?.string ?? self 
    }
}

AND IN YOUR CODE YOU USE:

label.text = "something".htmlString

Sort an Array by keys based on another Array?

First Suggestion

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key) {
        if(array_key_exists($key,$array)) {
            $ordered[$key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $ordered + $array;
}

Second Suggestion

$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);

I wanted to point out that both of these suggestions are awesome. However, they are apples and oranges. The difference? One is non-associative friendly and the other is associative friendly. If you are using 2 fully associative arrays then the array merge/flip will actually merge and overwrite the other associative array. In my case that is not the results I was looking for. I used a settings.ini file to create my sort order array. The data array I was sorting did not need to written over by my associative sorting counterpart. Thus array merge would destroy my data array. Both are great methods, both need to be archived in any developers toolbox. Based on your needs you may find you actually need both concepts in your archives.

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

How to import Swagger APIs into Postman?

  • Click on the orange button ("choose files")
  • Browse to the Swagger doc (swagger.yaml)
  • After selecting the file, a new collection gets created in POSTMAN. It will contain folders based on your endpoints.

You can also get some sample swagger files online to verify this(if you have errors in your swagger doc).

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

Razor MVC Populating Javascript array with Model Array

This is possible, you just need to loop through the razor collection

<script type="text/javascript">

    var myArray = [];

    @foreach (var d in Model.data)
    {
        @:myArray.push("@d");
    }

    alert(myArray);

</script>

Hope this helps

Revert to Eclipse default settings

go to windows>preferences>Java>Editor>Syntax Coloring go all the way down and click on Restore Defaults & Apply and Close

Error: EACCES: permission denied

Remove dist folder and this solve my problem!!

Determining complexity for recursive functions (Big O notation)

I see that for the accepted answer (recursivefn5), some folks are having issues with the explanation. so I'd try to clarify to the best of my knowledge.

  1. The for loop runs for n/2 times because at each iteration, we are increasing i (the counter) by a factor of 2. so say n = 10, the for loop will run 10/2 = 5 times i.e when i is 0,2,4,6 and 8 respectively.

  2. In the same regard, the recursive call is reduced by a factor of 5 for every time it is called i.e it runs for n/5 times. Again assume n = 10, the recursive call runs for 10/5 = 2 times i.e when n is 10 and 5 and then it hits the base case and terminates.

  3. Calculating the total run time, the for loop runs n/2 times for every time we call the recursive function. since the recursive fxn runs n/5 times (in 2 above),the for loop runs for (n/2) * (n/5) = (n^2)/10 times, which translates to an overall Big O runtime of O(n^2) - ignoring the constant (1/10)...

how to get param in method post spring mvc?

It also works if you change the content type

    <form method="POST"
    action="http://localhost:8080/cms/customer/create_customer"
    id="frmRegister" name="frmRegister"
    enctype="application/x-www-form-urlencoded">

In the controller also add the header value as follows:

    @RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")

How to deal with missing src/test/java source folder in Android/Maven project?

This is a bug in the Android Connector for M2E (m2e-android) that was recently fixed:

https://github.com/rgladwell/m2e-android/commit/2b490f900153cd34fff1cec47fe5aeffabe44d87

This fix has been merged and will be available with the next release. In the meantime you can test the new fix by installing from the following update site:

http://rgladwell.github.com/m2e-android/updates/master/

What does ENABLE_BITCODE do in xcode 7?

Update

Apple has clarified that slicing occurs independent of enabling bitcode. I've observed this in practice as well where a non-bitcode enabled app will only be downloaded as the architecture appropriate for the target device.

Original

More specifically:

Bitcode. Archive your app for submission to the App Store in an intermediate representation, which is compiled into 64- or 32-bit executables for the target devices when delivered.

Slicing. Artwork incorporated into the Asset Catalog and tagged for a platform allows the App Store to deliver only what is needed for installation.

The way I read this, if you support bitcode, downloaders of your app will only get the compiled architecture needed for their own device.

How to convert int to Integer

I had a similar problem . For this you can use a Hashmap which takes "string" and "object" as shown in code below:

/** stores the image database icons */
public static int[] imageIconDatabase = { R.drawable.ball,
        R.drawable.catmouse, R.drawable.cube, R.drawable.fresh,
        R.drawable.guitar, R.drawable.orange, R.drawable.teapot,
        R.drawable.india, R.drawable.thailand, R.drawable.netherlands,
        R.drawable.srilanka, R.drawable.pakistan,

};
private void initializeImageList() {
    // TODO Auto-generated method stub
    for (int i = 0; i < imageIconDatabase.length; i++) {
        map = new HashMap<String, Object>();

        map.put("Name", imageNameDatabase[i]);
        map.put("Icon", imageIconDatabase[i]);
    }

}

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

You are using setTimeout wrong way. The (one of) function signature is setTimeout(callback, delay). So you can easily specify what code should be run after what delay.

var codeAddress = (function() {
    var index = 0;
    var delay = 100;

    function GeocodeCallback(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
            console.log(results);
        }
        else alert("Geocode was not successful for the following reason: " + status);
    };

    return function(vPostCode) {
        if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
        index++;
    };
})();

This way, every codeAddress() call will result in geocoder.geocode() being called 100ms later after previous call.

I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay variable.

Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)

How to remove jar file from local maven repository which was added with install:install-file?

Delete every things (jar, pom.xml, etc) under your local ~/.m2/repository/phonegap/1.1.0/ directory if you are using a linux OS.

curl: (35) SSL connect error

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2

You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.

How to bind Events on Ajax loaded Content?

For ASP.NET try this:

<script type="text/javascript">
    Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Use the jquery numeric value. Below function allows for decimal and numeric values.
Example: $("#inputId").numeric({ allow: "." });

Python pandas: how to specify data types when reading an Excel file?

If you are able to read the excel file correctly and only the integer values are not showing up. you can specify like this.

df = pd.read_excel('my.xlsx',sheetname='Sheet1', engine="openpyxl", dtype=str)

this should change your integer values into a string and show in dataframe

Have Excel formulas that return 0, make the result blank

=if(b2 = "", "", b2)

This worked for me

Is there a way to remove unused imports and declarations from Angular 2+?

To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file

"compilerOptions": {
    "noUnusedLocals": true,
    "noUnusedParameters": true
}

have the typescript compiler installed, ifnot install it with:

npm install -g typescript

and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.

I would also recomend using typescript hero extension for organizing your imports.

Uncaught TypeError: Cannot set property 'value' of null

The problem is that you haven't got any element with the id u so that you are calling something that doesn't exist.
To fix that you have to add an id to the element.

<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />


And I've seen too you have added a value for the input, so it means the input is not empty and it will contain text. As result placeholder won't be displayed.

Finally there is a warning that W3Validator will say because of the "/" in the end. :

For the current document, the validator interprets strings like according to legacy rules that break the expectations of most authors and thus cause confusing warnings and error messages from the validator. This interpretation is triggered by HTML 4 documents or other SGML-based HTML documents. To avoid the messages, simply remove the "/" character in such contexts. NB: If you expect <FOO /> to be interpreted as an XML-compatible "self-closing" tag, then you need to use XHTML or HTML5.

In conclusion it says you have to remove the slash. Simply write this:

<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item...">

Check last modified date of file in C#

Just use File.GetLastWriteTime. There's a sample on that page showing how to use it.

Using the Jersey client to do a POST operation

Not done this yet myself, but a quick bit of Google-Fu reveals a tech tip on blogs.oracle.com with examples of exactly what you ask for.

Example taken from the blog post:

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
    .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
    .post(ClientResponse.class, formData);

That any help?

Open text file and program shortcut in a Windows batch file

"location of notepad file" > notepad Filename

C:\Users\Desktop\Anaconda> notepad myfile

works for me! :)

Commit only part of a file in Git

It's been 10 years since this question was asked. And I hope this answer will be useful to someone. As mentioned in the answer here, where GUI is not an option, Andrew Shadura's crecord extension helps bring a ncurses window in which we can select the lines to commit.

Set up the extension as follows:

git clone https://github.com/andrewshadura/git-crecord
cd git-crecord
./setup.py install
ln -s $PWD/git-crecord ~/.local/bin/git-crecord

cd to your git repo and invoke it as follows:

git crecord

This would bring up the ncurses interface which can be used as shown below. Pressing the following keys in the ncurses window will do certain actions:

f       hunk toggle fold (arrow keys can also be used)
space   toggle hunk selection
a       toggle commit or amend
c       confirm and open commit window

Screencast showing a sample usageExample

Access cell value of datatable

If you need a weak reference to the cell value:

object field = d.Rows[0][3]

or

object field = d.Rows[0].ItemArray[3]

Should do it

If you need a strongly typed reference (string in your case) you can use the DataRowExtensions.Field extension method:

string field = d.Rows[0].Field<string>(3);

(make sure System.Data is in listed in the namespaces in this case)

Indexes are 0 based so we first access the first row (0) and then the 4th column in this row (3)

Set angular scope variable in markup

ng-init does not work when you are assigning variables inside loop. Use {{myVariable=whatever;""}}

The trailing "" stops the Angular expression being evaluated to any text.

Then you can simply call {{myVariable}} to output your variable value.

I found this very useful when iterating multiple nested arrays and I wanted to keep my current iteration info in one variable instead of querying it multiple times.

Just get column names from hive table

you could also do show columns in $table or see Hive, how do I retrieve all the database's tables columns for access to hive metadata

Groovy / grails how to determine a data type?

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

SET NOCOUNT ON usage

  • SET NOCOUNT ON- It will show "Command(s) completed successfully".
  • SET NOCOUNT OFF- it will show "(No. Of row(s) affected)".

Why aren't variable-length arrays part of the C++ standard?

There are situations where allocating heap memory is very expensive compared to the operations performed. An example is matrix math. If you work with smallish matrices say 5 to 10 elements and do a lot of arithmetics the malloc overhead will be really significant. At the same time making the size a compile time constant does seem very wasteful and inflexible.

I think that C++ is so unsafe in itself that the argument to "try to not add more unsafe features" is not very strong. On the other hand, as C++ is arguably the most runtime efficient programming language features which makes it more so are always useful: People who write performance critical programs will to a large extent use C++, and they need as much performance as possible. Moving stuff from heap to stack is one such possibility. Reducing the number of heap blocks is another. Allowing VLAs as object members would one way to achieve this. I'm working on such a suggestion. It is a bit complicated to implement, admittedly, but it seems quite doable.

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

The best code is no code at all:

The fundamental nature of coding is that our task, as programmers, is to recognize that every decision we make is a trade-off. […] Start with brevity. Increase the other dimensions as required by testing.

Consequently, less code is better code: Prefer "" to string.Empty or String.Empty. Those two are six times longer with no added benefit — certainly no added clarity, as they express the exact same information.

"Unknown class <MyClass> in Interface Builder file" error at runtime

In my case I got this error because I'd tried to save some work by creating a new project and then deleting several of the source files and copying over the source files of the same name from the working project. I also copied my MainStoryBoard file which was looking for my RootViewController. However, when I had deleted the original RootViewController and then added in the RootViewController from the previous product, evidently the Add Files operation failed to "check" the target box as suggested above. By merely visting all of the newley imported ".m" files and making sure that the target membership box was checked, all was well. I think what was happening was that the storyboard file was looking for a class that had been "excluded" from the link because the target membership was unchecked. Making sure the required files for the target are so designated in the target membership in the file inspector did the trick. Thanks Pat! (see above)

How to link an input button to a file select window?

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here's a working fiddle.

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.

how to change a selections options based on another select option selected?

I don't quote understand what you are trying to achieve, but you need an event listener. Something like:

$('#type').change(function() {
   alert('Value changed to ' + $(this).attr('value'));
});

This will give you the value of the selected option tag.

What is the Gradle artifact dependency graph command?

If you want to see dependencies on project and all subprojects use in your top-level build.gradle:

subprojects {
    task listAllDependencies(type: DependencyReportTask) {}
}

Then call gradle:

gradle listAllDependencies

What's the difference between event.stopPropagation and event.preventDefault?

_x000D_
_x000D_
$("#but").click(function(event){_x000D_
console.log("hello");_x000D_
  event.preventDefault();_x000D_
 });_x000D_
_x000D_
_x000D_
$("#foo").click(function(){_x000D_
 alert("parent click event fired !");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo">_x000D_
  <button id="but">button</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

HTML5 live streaming

Use ffmpeg + ffserver. It works!!! You can get a config file for ffserver from ffmpeg.org and accordingly set the values.

How to convert string date to Timestamp in java?

tl;dr

java.sql.Timestamp                  
.valueOf(                           // Class-method parses SQL-style formatted date-time strings.
    "2007-11-11 12:13:14"
)                                   // Returns a `Timestamp` object.
.toInstant()                        // Converts from terrible legacy classes to modern *java.time* class.

java.sql.Timestamp.valueOf parses SQL format

If you can use the full four digits for the year, your input string of 2007-11-11 12:13:14 would be in standard SQL format assuming this value is meant to be in UTC time zone.

The java.sql.Timestamp class has a valueOf method to directly parse such strings.

String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;

java.time

In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString method. In contrast, the java.time classes by default use the standard ISO 8601 formats.

System.out.println( "Output: " + ts.toInstant().toString() );

Best Free Text Editor Supporting *More Than* 4GB Files?

Why do you want to load a 4+ GB file into memory? Even if you find a text editor that can do that, does your machine have 4 GB of memory? And unless it has a lot more than 4 GB in physical memory, your machine will slow down a lot and go swap file crazy.

So why do you want a 4+ GB file? If you want to transform it, or do a search and replace, you may be better off writing a small quick program to do it.

New line in JavaScript alert box

List of Special Character codes in JavaScript:

Code    Outputs
\'  single quote
\"  double quote
\\  backslash
\n  new line
\r  carriage return
\t  tab
\b  backspace
\f  form feed

Difference between \b and \B in regex

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

Source: http://www.regular-expressions.info/wordboundaries.html

How to make a radio button unchecked by clicking it?

You could use the checked property of a radio button to uncheck it.

Something like this:

<script>
 function uncheck()
 {
  document.getElementById('myRadio').checked = false;        
 }
 function check()
 {
  document.getElementById('myRadio').checked = true;        
 }
</script>
<input id="myRadio" type="radio" checked="checked"/>
<button onclick="uncheck();">Uncheck</button>
<button onclick="check();">Check</button>

?See it in action here: http://jsfiddle.net/wgYNa/

How to make asynchronous HTTP requests in PHP

The swoole extension. https://github.com/matyhtf/swoole Asynchronous & concurrent networking framework for PHP.

$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);

$client->on("connect", function($cli) {
    $cli->send("hello world\n");
});

$client->on("receive", function($cli, $data){
    echo "Receive: $data\n";
});

$client->on("error", function($cli){
    echo "connect fail\n";
});

$client->on("close", function($cli){
    echo "close\n";
});

$client->connect('127.0.0.1', 9501, 0.5);

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

I came across an "inverted" issue — I was getting good results with categorical_crossentropy (with 2 classes) and poor with binary_crossentropy. It seems that problem was with wrong activation function. The correct settings were:

  • for binary_crossentropy: sigmoid activation, scalar target
  • for categorical_crossentropy: softmax activation, one-hot encoded target

How to save DataFrame directly to Hive?

For Hive external tables I use this function in PySpark:

def save_table(sparkSession, dataframe, database, table_name, save_format="PARQUET"):
    print("Saving result in {}.{}".format(database, table_name))
    output_schema = "," \
        .join(["{} {}".format(x.name.lower(), x.dataType) for x in list(dataframe.schema)]) \
        .replace("StringType", "STRING") \
        .replace("IntegerType", "INT") \
        .replace("DateType", "DATE") \
        .replace("LongType", "INT") \
        .replace("TimestampType", "INT") \
        .replace("BooleanType", "BOOLEAN") \
        .replace("FloatType", "FLOAT")\
        .replace("DoubleType","FLOAT")
    output_schema = re.sub(r'DecimalType[(][0-9]+,[0-9]+[)]', 'FLOAT', output_schema)

    sparkSession.sql("DROP TABLE IF EXISTS {}.{}".format(database, table_name))

    query = "CREATE EXTERNAL TABLE IF NOT EXISTS {}.{} ({}) STORED AS {} LOCATION '/user/hive/{}/{}'" \
        .format(database, table_name, output_schema, save_format, database, table_name)
    sparkSession.sql(query)
    dataframe.write.insertInto('{}.{}'.format(database, table_name),overwrite = True)

Add disabled attribute to input element using Javascript

If you're using jQuery then there are a few different ways to set the disabled attribute.

var $element = $(...);
    $element.prop('disabled', true);
    $element.attr('disabled', true); 

    // The following do not require jQuery
    $element.get(0).disabled = true;
    $element.get(0).setAttribute('disabled', true);
    $element[0].disabled = true;
    $element[0].setAttribute('disabled', true);

FloatingActionButton example with Support Library

If you already added all libraries and it still doesn't work use:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_add" 
/>

instead of:

<android.support.design.widget.FloatingActionButton
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   app:srcCompat="@drawable/ic_add"
 />

And all will work fine :)

stop service in android

This code works for me: check this link
This is my code when i stop and start service in activity

case R.id.buttonStart:
  Log.d(TAG, "onClick: starting srvice");
  startService(new Intent(this, MyService.class));
  break;
case R.id.buttonStop:
  Log.d(TAG, "onClick: stopping srvice");
  stopService(new Intent(this, MyService.class));
  break;
}
}
 }

And in service class:

  @Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    player.stop();
}

HAPPY CODING!

Axios get access to response header fields

According to official docs:

This may help if you want the HTTP headers that the server responded with. All header names are lower cased and can be accessed using the bracket notation. Example: response.headers['content-type'] will give something like: headers: {},

Parsing JSON giving "unexpected token o" error

I was seeing this unexpected token o error because my (incomplete) code had run previously (live reload!) and set the particular keyed local storage value to [object Object] instead of {}. It wasn't until I changed keys, that things started working as expected. Alternatively, you can follow these instructions to delete the incorrectly set localStorage value.

How to set a default entity property value with Hibernate

Use @ColumnDefault() annotation. This is hibernate only though.

jQuery Mobile: Stick footer to bottom of page

The following lines work just fine...

var headerHeight = $( '#header' ).height();
var footerHeight = $( '#footer' ).height();
var footerTop = $( '#footer' ).offset().top;
var height = ( footerTop - ( headerHeight + footerHeight ) );
$( '#content' ).height( height );

Intel's HAXM equivalent for AMD on Windows OS

https://android-developers.googleblog.com/2018/07/android-emulator-amd-processor-hyper-v.html

Important

If you have an AMD processor in your computer you need the following setup requirements to be in place: AMD Processor - Recommended: AMD® Ryzen™ processors Android Studio 3.2 Beta or higher - download via Android Studio Preview page Android Emulator v27.3.8+ - download via Android Studio SDK Manager x86 Android Virtual Device (AVD) - Create AVD Windows 10 with April 2018 Update Enable via Windows Features: "Windows Hypervisor Platform"

Join two data frames, select all columns from one and some columns from the other

Here is the code snippet that does the inner join and select the columns from both dataframe and alias the same column to different column name.

emp_df  = spark.read.csv('Employees.csv', header =True);
dept_df = spark.read.csv('dept.csv', header =True)


emp_dept_df = emp_df.join(dept_df,'DeptID').select(emp_df['*'], dept_df['Name'].alias('DName'))
emp_df.show()
dept_df.show()
emp_dept_df.show()
Output  for 'emp_df.show()':

+---+---------+------+------+
| ID|     Name|Salary|DeptID|
+---+---------+------+------+
|  1|     John| 20000|     1|
|  2|    Rohit| 15000|     2|
|  3|    Parth| 14600|     3|
|  4|  Rishabh| 20500|     1|
|  5|    Daisy| 34000|     2|
|  6|    Annie| 23000|     1|
|  7| Sushmita| 50000|     3|
|  8| Kaivalya| 20000|     1|
|  9|    Varun| 70000|     3|
| 10|Shambhavi| 21500|     2|
| 11|  Johnson| 25500|     3|
| 12|     Riya| 17000|     2|
| 13|    Krish| 17000|     1|
| 14| Akanksha| 20000|     2|
| 15|   Rutuja| 21000|     3|
+---+---------+------+------+

Output  for 'dept_df.show()':
+------+----------+
|DeptID|      Name|
+------+----------+
|     1|     Sales|
|     2|Accounting|
|     3| Marketing|
+------+----------+

Join Output:
+---+---------+------+------+----------+
| ID|     Name|Salary|DeptID|     DName|
+---+---------+------+------+----------+
|  1|     John| 20000|     1|     Sales|
|  2|    Rohit| 15000|     2|Accounting|
|  3|    Parth| 14600|     3| Marketing|
|  4|  Rishabh| 20500|     1|     Sales|
|  5|    Daisy| 34000|     2|Accounting|
|  6|    Annie| 23000|     1|     Sales|
|  7| Sushmita| 50000|     3| Marketing|
|  8| Kaivalya| 20000|     1|     Sales|
|  9|    Varun| 70000|     3| Marketing|
| 10|Shambhavi| 21500|     2|Accounting|
| 11|  Johnson| 25500|     3| Marketing|
| 12|     Riya| 17000|     2|Accounting|
| 13|    Krish| 17000|     1|     Sales|
| 14| Akanksha| 20000|     2|Accounting|
| 15|   Rutuja| 21000|     3| Marketing|
+---+---------+------+------+----------+

How to check if a number is between two values?

Tests whether windowsize is greater than 500 and lesser than 600 meaning that neither values 500 or 600 itself will result in the condition becoming true.

if (windowsize > 500 && windowsize < 600) {
  // ...
}

Referencing system.management.automation.dll in Visual Studio

If you don't want to install the Windows SDK you can get the dll by running the following command in powershell:

Copy ([PSObject].Assembly.Location) C:\

JavaScript math, round to two decimal places

To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.



    var testNum = 134.9567654;
    var decPl = 2;
    var testRes = roundDec(testNum,decPl);  
    alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);

    function roundDec(nbr,dec_places){
        var mult = Math.pow(10,dec_places);
        return Math.round(nbr * mult) / mult;
    }

Order data frame rows according to vector with specific order

Try match:

df <- data.frame(name=letters[1:4], value=c(rep(TRUE, 2), rep(FALSE, 2)))
target <- c("b", "c", "a", "d")
df[match(target, df$name),]

  name value
2    b  TRUE
3    c FALSE
1    a  TRUE
4    d FALSE

It will work as long as your target contains exactly the same elements as df$name, and neither contain duplicate values.

From ?match:

match returns a vector of the positions of (first) matches of its first argument 
in its second.

Therefore match finds the row numbers that matches target's elements, and then we return df in that order.

Practical uses for the "internal" keyword in C#

One use of the internal keyword is to limit access to concrete implementations from the user of your assembly.

If you have a factory or some other central location for constructing objects the user of your assembly need only deal with the public interface or abstract base class.

Also, internal constructors allow you to control where and when an otherwise public class is instantiated.

Converting Float to Dollars and Cents

Personally, I like this much better (which, granted, is just a different way of writing the currently selected "best answer"):

money = float(1234.5)
print('$' + format(money, ',.2f'))

Or, if you REALLY don't like "adding" multiple strings to combine them, you could do this instead:

money = float(1234.5)
print('${0}'.format(format(money, ',.2f')))

I just think both of these styles are a bit easier to read. :-)

(of course, you can still incorporate an If-Else to handle negative values as Eric suggests too)

Difference between a theta join, equijoin and natural join

While the answers explaining the exact differences are fine, I want to show how the relational algebra is transformed to SQL and what the actual value of the 3 concepts is.

The key concept in your question is the idea of a join. To understand a join you need to understand a Cartesian Product (the example is based on SQL where the equivalent is called a cross join as onedaywhen points out);

This isn't very useful in practice. Consider this example.

Product(PName, Price)
====================
Laptop,   1500
Car,      20000
Airplane, 3000000


Component(PName, CName, Cost)
=============================
Laptop, CPU,    500
Laptop, hdd,    300
Laptop, case,   700
Car,    wheels, 1000

The Cartesian product Product x Component will be - bellow or sql fiddle. You can see there are 12 rows = 3 x 4. Obviously, rows like "Laptop" with "wheels" have no meaning, this is why in practice the Cartesian product is rarely used.

|    PNAME |   PRICE |  CNAME | COST |
--------------------------------------
|   Laptop |    1500 |    CPU |  500 |
|   Laptop |    1500 |    hdd |  300 |
|   Laptop |    1500 |   case |  700 |
|   Laptop |    1500 | wheels | 1000 |
|      Car |   20000 |    CPU |  500 |
|      Car |   20000 |    hdd |  300 |
|      Car |   20000 |   case |  700 |
|      Car |   20000 | wheels | 1000 |
| Airplane | 3000000 |    CPU |  500 |
| Airplane | 3000000 |    hdd |  300 |
| Airplane | 3000000 |   case |  700 |
| Airplane | 3000000 | wheels | 1000 |

JOINs are here to add more value to these products. What we really want is to "join" the product with its associated components, because each component belongs to a product. The way to do this is with a join:

Product JOIN Component ON Pname

The associated SQL query would be like this (you can play with all the examples here)

SELECT *
FROM Product
JOIN Component
  ON Product.Pname = Component.Pname

and the result:

|  PNAME | PRICE |  CNAME | COST |
----------------------------------
| Laptop |  1500 |    CPU |  500 |
| Laptop |  1500 |    hdd |  300 |
| Laptop |  1500 |   case |  700 |
|    Car | 20000 | wheels | 1000 |

Notice that the result has only 4 rows, because the Laptop has 3 components, the Car has 1 and the Airplane none. This is much more useful.

Getting back to your questions, all the joins you ask about are variations of the JOIN I just showed:

Natural Join = the join (the ON clause) is made on all columns with the same name; it removes duplicate columns from the result, as opposed to all other joins; most DBMS (database systems created by various vendors such as Microsoft's SQL Server, Oracle's MySQL etc. ) don't even bother supporting this, it is just bad practice (or purposely chose not to implement it). Imagine that a developer comes and changes the name of the second column in Product from Price to Cost. Then all the natural joins would be done on PName AND on Cost, resulting in 0 rows since no numbers match.

Theta Join = this is the general join everybody uses because it allows you to specify the condition (the ON clause in SQL). You can join on pretty much any condition you like, for example on Products that have the first 2 letters similar, or that have a different price. In practice, this is rarely the case - in 95% of the cases you will join on an equality condition, which leads us to:

Equi Join = the most common one used in practice. The example above is an equi join. Databases are optimized for this type of joins! The oposite of an equi join is a non-equi join, i.e. when you join on a condition other than "=". Databases are not optimized for this! Both of them are subsets of the general theta join. The natural join is also a theta join but the condition (the theta) is implicit.

Source of information: university + certified SQL Server developer + recently completed the MOO "Introduction to databases" from Stanford so I dare say I have relational algebra fresh in mind.

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,

input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}

Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.

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

In my case setting the StartUp project in init helps. You can do this by executing

dotnet ef migrations add init -s ../StartUpProjectName

How do I request and receive user input in a .bat and use it to run a certain program?

Here is a working example:

@echo off
:ask
@echo echo Would you like to use developer mode?(Y/N)
set INPUT=
set /P INPUT=Type input: %=%
If /I "%INPUT%"=="y" goto yes 
If /I "%INPUT%"=="n" goto no
goto ask
:yes
@echo you select yes
goto exit
:no
@echo you select no
goto exit
:exit
@pause

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

You are not creating datetime index properly,

format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

Eclipse - Unable to install breakpoint due to missing line number attributes

I ran into this problem as well. I am using an ant build script. I am working on a legacy application so I am using jdk version 1.4.2. This used to work so I started looking around. I noticed that under the Debug configuration on the JRE tab the version of Java had been set to 1.7. Once I changed it back to 1.4 it worked.

I hope this helps.

Iterator Loop vs index loop

It always depends on what you need.

You should use operator[] when you need direct access to elements in the vector (when you need to index a specific element in the vector). There is nothing wrong in using it over iterators. However, you must decide for yourself which (operator[] or iterators) suits best your needs.

Using iterators would enable you to switch to other container types without much change in your code. In other words, using iterators would make your code more generic, and does not depend on a particular type of container.

Recursive directory listing in DOS

dir /s /b /a:d>output.txt will port it to a text file

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

ES2015 Classes

In the ES2015 specification, you can use the class syntax which is just sugar over the prototype system.

class Person {
  constructor(name) {
    this.name = name;
  }
  toString() {
    return `My name is ${ this.name }.`;
  }
}

class Employee extends Person {
  constructor(name, hours) {
    super(name);
    this.hours = hours;
  }
  toString() {
    return `${ super.toString() } I work ${ this.hours } hours.`;
  }
}

Benefits

The main benefit is that static analysis tools find it easier to target this syntax. It is also easier for others coming from class-based languages to use the language as a polyglot.

Caveats

Be wary of its current limitations. To achieve private properties, one must resort to using Symbols or WeakMaps. In future releases, classes will most likely be expanded to include these missing features.

Support

Browser support isn't very good at the moment (supported by nearly everyone except IE), but you can use these features now with a transpiler like Babel.

Resources

Posting form to different MVC post action depending on the clicked submit button

This sounds to me like what you have is one command with 2 outputs, I would opt for making the change in both client and server for this.

At the client, use JS to build up the URL you want to post to (use JQuery for simplicity) i.e.

<script type="text/javascript">
    $(function() {
        // this code detects a button click and sets an `option` attribute
        // in the form to be the `name` attribute of whichever button was clicked
        $('form input[type=submit]').click(function() {
            var $form = $('form');
            form.removeAttr('option');
            form.attr('option', $(this).attr('name'));
        });
        // this code updates the URL before the form is submitted
        $("form").submit(function(e) { 
            var option = $(this).attr("option");
            if (option) {
                e.preventDefault();
                var currentUrl = $(this).attr("action");
                $(this).attr('action', currentUrl + "/" + option).submit();     
            }
        });
    });
</script>
...
<input type="submit" ... />
<input type="submit" name="excel" ... />

Now at the server side we can add a new route to handle the excel request

routes.MapRoute(
    name: "ExcelExport",
    url: "SearchDisplay/Submit/excel",
    defaults: new
    {
        controller = "SearchDisplay",
        action = "SubmitExcel",
    });

You can setup 2 distinct actions

public ActionResult SubmitExcel(SearchCostPage model)
{
   ...
}

public ActionResult Submit(SearchCostPage model)
{
   ...
}

Or you can use the ActionName attribute as an alias

public ActionResult Submit(SearchCostPage model)
{
   ...
}

[ActionName("SubmitExcel")]
public ActionResult Submit(SearchCostPage model)
{
   ...
}

How to add new elements to an array?

If one really want to resize an array you could do something like this:

String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr)); 
// Output is: [a, b, c]

arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";

System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]

How to use Oracle's LISTAGG function with a unique filter?

I needed this peace of code as a subquery with some data filter before aggregation based on the outer most query but I wasn't able to do this using the chosen answer code because this filter should go in the inner most select (third level query) and the filter params was in the outer most select (first level query), which gave me the error ORA-00904: "TB_OUTERMOST"."COL": invalid identifier as the ANSI SQL states that table references (correlation names) are scoped to just one level deep.

I needed a solution with no levels of subquery and this one below worked great for me:

with

demotable as
(
  select 1 group_id, 'David'   name from dual union all
  select 1 group_id, 'John'    name from dual union all
  select 1 group_id, 'Alan'    name from dual union all
  select 1 group_id, 'David'   name from dual union all
  select 2 group_id, 'Julie'   name from dual union all
  select 2 group_id, 'Charlie' name from dual
)

select distinct 
  group_id, 
  listagg(name, ',') within group (order by name) over (partition by group_id) names
from demotable
-- where any filter I want
group by group_id, name
order by group_id;

How to remove foreign key constraint in sql server?

ALTER TABLE table
DROP FOREIGN KEY fk_key

EDIT: didn't notice you were using sql-server, my bad

ALTER TABLE table
DROP CONSTRAINT fk_key

Uninstall Eclipse under OSX?

I just had a similar problem, with the GWT-PlugIn not showing up in the interface. Deleting the eclipse folder did not solve it, GWT was still there! Deleting workspace didn't work! But deleting the .eclipse folder in the home directory did! I'm working under WIndows 7 here, but it should be the same with OSX. But you may have to make the folder visible first. Under linux based system, folders starting with a dot are invisible by default.

This folder was probably the reason I had problems in the first place. If I remember right, I switched from basic Eclipse to EE, but didn't delete this folder.

In my opinion, an uninstall skript would do Eclipse quite good.

Rendering React Components from Array of Objects

There are couple of way which can be used.

const stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)

Solution 1

<p>{callList.join(', ')}</p>

Solution 2

<ol>    
  { callList && callList.map(item => <li>{item}</li>) }
</ol>

Edit kind-antonelli-z8372

Of course there are other ways also available.

Convert UTF-8 encoded NSData to NSString

I humbly submit a category to make this less annoying:

@interface NSData (EasyUTF8)

// Safely decode the bytes into a UTF8 string
- (NSString *)asUTF8String;

@end

and

@implementation NSData (EasyUTF8)

- (NSString *)asUTF8String {
    return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];    
}

@end

(Note that if you're not using ARC you'll need an autorelease there.)

Now instead of the appallingly verbose:

NSData *data = ...
[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

You can do:

NSData *data = ...
[data asUTF8String];

How can I concatenate strings in VBA?

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

"1" + "2" => "12"
"1" + 2   => 3
1 + "2"   => 3
"a" + 2   => type mismatch

This is simply a subtle source of potential bugs and therefore should be avoided. & always means "string concatenation", even if its arguments are non-strings:

"1" & "2" => "12"
"1" &  2  => "12"
 1  & "2" => "12"
 1  &  2  => "12"
"a" &  2  => "a2"

How to delete all files from a specific folder?

You can do something like:

Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
    File.Delete(f.FullName);

How to get a list column names and datatypes of a table in PostgreSQL?

To make this topic 'more complete'.

I required the column names and data types on a SELECT statement (not a table).

If you want to do this on a SELECT statement instead of an actual existing table, you can do the following:

DROP TABLE IF EXISTS abc;
CREATE TEMPORARY TABLE abc AS
-- your select statement here!
SELECT 
    *
FROM foo
-- end your select statement
;

select column_name, data_type 
from information_schema.columns 
where table_name = 'abc';
DROP IF EXISTS abc;

Short explanation, it makes a (temp) table of your select statement, which you can 'call' upon via the query provided by (among others) @a_horse_with_no_name and @selva.

Hope this helps.

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

Convert Data URI to File then append to FormData

Thanks! @steovi for this solution.

I have added support to ES6 version and changed from unescape to dataURI(unescape is deprecated).

converterDataURItoBlob(dataURI) {
    let byteString;
    let mimeString;
    let ia;

    if (dataURI.split(',')[0].indexOf('base64') >= 0) {
      byteString = atob(dataURI.split(',')[1]);
    } else {
      byteString = encodeURI(dataURI.split(',')[1]);
    }
    // separate out the mime component
    mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type:mimeString});
}

How to return a specific element of an array?

You code should look like this:

public int getElement(int[] arrayOfInts, int index) {
    return arrayOfInts[index];
}

Main points here are method return type, it should match with array elements type and if you are working from main() - this method must be static also.

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Get integer value of the current year in Java

If you want the year of any date object, I used the following method:

public static int getYearFromDate(Date date) {
    int result = -1;
    if (date != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        result = cal.get(Calendar.YEAR);
    }
    return result;
}

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

Removing all line breaks and adding them after certain text

You can also try this in Notepad++

  • Highlight the lines you want to join (ctrl + a to select all)
  • Choose Edit -> Line Operations -> Join Lines

Need to perform Wildcard (*,?, etc) search on a string using Regex

From http://www.codeproject.com/KB/recipes/wildcardtoregex.aspx:

public static string WildcardToRegex(string pattern)
{
    return "^" + Regex.Escape(pattern)
                      .Replace(@"\*", ".*")
                      .Replace(@"\?", ".")
               + "$";
}

So something like foo*.xls? will get transformed to ^foo.*\.xls.$.

Python argparse command line flags without arguments

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag

Regular expression to match DNS hostname or IP Address?

Regarding IP addresses, it appears that there is some debate on whether to include leading zeros. It was once the common practice and is generally accepted, so I would argue that they should be flagged as valid regardless of the current preference. There is also some ambiguity over whether text before and after the string should be validated and, again, I think it should. 1.2.3.4 is a valid IP but 1.2.3.4.5 is not and neither the 1.2.3.4 portion nor the 2.3.4.5 portion should result in a match. Some of the concerns can be handled with this expression:

grep -E '(^|[^[:alnum:]+)(([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.){3}([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])([^[:alnum:]]|$)' 

The unfortunate part here is the fact that the regex portion that validates an octet is repeated as is true in many offered solutions. Although this is better than for instances of the pattern, the repetition can be eliminated entirely if subroutines are supported in the regex being used. The next example enables those functions with the -P switch of grep and also takes advantage of lookahead and lookbehind functionality. (The function name I selected is 'o' for octet. I could have used 'octet' as the name but wanted to be terse.)

grep -P '(?<![\d\w\.])(?<o>([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(\.\g<o>){3}(?![\d\w\.])'

The handling of the dot might actually create a false negatives if IP addresses are in a file with text in the form of sentences since the a period could follow without it being part of the dotted notation. A variant of the above would fix that:

grep -P '(?<![\d\w\.])(?<x>([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(\.\g<x>){3}(?!([\d\w]|\.\d))'

Center image in table td in CSS

Another option is the use <th> instead of <td>. <th> defaults to center; <td> defaults to left.

How to filter by IP address in Wireshark?

Filtering IP Address in Wireshark:

(1)single IP filtering:

ip.addr==X.X.X.X

ip.src==X.X.X.X

ip.dst==X.X.X.X

(2)Multiple IP filtering based on logical conditions:

OR condition:

(ip.src==192.168.2.25)||(ip.dst==192.168.2.25)

AND condition:

(ip.src==192.168.2.25) && (ip.dst==74.125.236.16)

Angular4 - No value accessor for form control

For me it was due to "multiple" attribute on select input control as Angular has different ValueAccessor for this type of control.

const countryControl = new FormControl();

And inside template use like this

    <select multiple name="countries" [formControl]="countryControl">
      <option *ngFor="let country of countries" [ngValue]="country">
       {{ country.name }}
      </option>
    </select>

More details ref Official Docs

What is the max size of VARCHAR2 in PL/SQL and SQL?

As per official documentation link shared by Andre Kirpitch, Oracle 10g gives a maximum size of 4000 bytes or characters for varchar2. If you are using a higher version of oracle (for example Oracle 12c), you can get a maximum size upto 32767 bytes or characters for varchar2. To utilize the extended datatype feature of oracle 12, you need to start oracle in upgrade mode. Follow the below steps in command prompt:

1) Login as sysdba (sqlplus / as sysdba)

2) SHUTDOWN IMMEDIATE;

3) STARTUP UPGRADE;

4) ALTER SYSTEM SET max_string_size=extended;

5) Oracle\product\12.1.0.2\rdbms\admin\utl32k.sql

6) SHUTDOWN IMMEDIATE;

7) STARTUP;

How do you get/set media volume (not ringtone volume) in Android?

Instead of AudioManager.STREAM_RING you shoul use AudioManager.STREAM_MUSIC This question has already discussed here.

Simulating Slow Internet Connection

If you're running windows, fiddler is a great tool. It has a setting to simulate modem speed, and for someone who wants more control has a plugin to add latency to each request.

I prefer using a tool like this to putting latency code in my application as it is a much more realistic simulation, as well as not making me design or code the actual bits. The best code is code I don't have to write.

ADDED: This article at Pavel Donchev's blog on Software Technologies shows how to create custom simulated speeds: Limiting your Internet connection speed with Fiddler.

How can I use async/await at the top level?

To give some further info on top of current answers:

The contents of a node.js file are currently concatenated, in a string-like way, to form a function body.

For example if you have a file test.js:

// Amazing test file!
console.log('Test!');

Then node.js will secretly concatenate a function that looks like:

function(require, __dirname, ... perhaps more top-level properties) {
  // Amazing test file!
  console.log('Test!');
}

The major thing to note, is that the resulting function is NOT an async function. So you cannot use the term await directly inside of it!

But say you need to work with promises in this file, then there are two possible methods:

  1. Don't use await directly inside the function
  2. Don't use await

Option 1 requires us to create a new scope (and this scope can be async, because we have control over it):

// Amazing test file!
// Create a new async function (a new scope) and immediately call it!
(async () => {
  await new Promise(...);
  console.log('Test!');
})();

Option 2 requires us to use the object-oriented promise API (the less pretty but equally functional paradigm of working with promises)

// Amazing test file!
// Create some sort of promise...
let myPromise = new Promise(...);

// Now use the object-oriented API
myPromise.then(() => console.log('Test!'));

It would be interesting to see node add support for top-level await!

Table scroll with HTML and CSS

_x000D_
_x000D_
  .outer {_x000D_
    overflow-y: auto;_x000D_
    height: 300px;_x000D_
  }_x000D_
_x000D_
  .outer {_x000D_
    width: 100%;_x000D_
    -layout: fixed;_x000D_
  }_x000D_
_x000D_
  .outer th {_x000D_
    text-align: left;_x000D_
    top: 0;_x000D_
    position: sticky;_x000D_
    background-color: white;_x000D_
  }
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
    <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
    <title>MYCRUD</title>_x000D_
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container-fluid col-md-11">_x000D_
  <div class="row">_x000D_
_x000D_
    <div class="col-lg-12">_x000D_
_x000D_
   _x000D_
        <div class="card-body">_x000D_
          <div class="outer">_x000D_
_x000D_
            <table class="table table-hover bg-light">_x000D_
              <thead>_x000D_
                <tr>_x000D_
                  <th scope="col">ID</th>_x000D_
                  <th scope="col">Marca</th>_x000D_
                  <th scope="col">Editar</th>_x000D_
                  <th scope="col">Eliminar</th>_x000D_
                </tr>_x000D_
              </thead>_x000D_
              <tbody>_x000D_
_x000D_
                _x000D_
                  <tr>_x000D_
                    <td>4</td>_x000D_
                    <td>Toyota</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>3</td>_x000D_
                    <td>Honda </td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>5</td>_x000D_
                    <td>Myo</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>6</td>_x000D_
                    <td>Acer</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>7</td>_x000D_
                    <td>HP</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>8</td>_x000D_
                    <td>DELL</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>9</td>_x000D_
                    <td>LOGITECH</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                              </tbody>_x000D_
            </table>_x000D_
          </div>_x000D_
_x000D_
        </div>_x000D_
_x000D_
     _x000D_
_x000D_
_x000D_
_x000D_
_x000D_
    </div>_x000D_
_x000D_
  </div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to convert a Bitmap to Drawable in android?

And you can try this:

public static Bitmap mirrorBitmap(Bitmap bInput)
    {
        Bitmap  bOutput;
        Matrix matrix = new Matrix();
        matrix.preScale(-1.0f, 1.0f);
        bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);
        return bOutput;
    }

How to hide first section header in UITableView (grouped style)

Update[9/19/17]: Old answer doesn't work for me anymore in iOS 11. Thanks Apple. The following did:

self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
self.tableView.estimatedSectionHeaderHeight = 20.0f;
self.tableView.contentInset = UIEdgeInsetsMake(-18.0, 0.0f, 0.0f, 0.0);

Previous Answer:

As posted in the comments by Chris Ostomo the following worked for me:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN; // to get rid of empty section header
}

How to get the last five characters of a string using Substring() in C#?

Substring. This method extracts strings. It requires the location of the substring (a start index, a length). It then returns a new string with the characters in that range.

See a small example :

string input = "OneTwoThree";
// Get first three characters.
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub);

Output : Substring: One

How to read strings from a Scanner in a Java console application?

Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();

Calling nextInt() was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine() after that does the work.

How do I add a ToolTip to a control?

Here is your article for doing it with code

private void Form1_Load(object sender, System.EventArgs e)
{
     // Create the ToolTip and associate with the Form container.
     ToolTip toolTip1 = new ToolTip();

     // Set up the delays for the ToolTip.
     toolTip1.AutoPopDelay = 5000;
     toolTip1.InitialDelay = 1000;
     toolTip1.ReshowDelay = 500;
     // Force the ToolTip text to be displayed whether or not the form is active.
     toolTip1.ShowAlways = true;

     // Set up the ToolTip text for the Button and Checkbox.
     toolTip1.SetToolTip(this.button1, "My button1");
     toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}

When to use malloc for char pointers

malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL), you can do arithmetic within the brackets of malloc but you shouldnt because you should use calloc which has the definition of void calloc(count, size)which means how many items you want to store ie count and size of data ie int , char etc.

Convert and format a Date in JSP

The example above showing the import with ...sun.com/jsp/jstl/format is incorrect (meaning it didn't work for me).

Instead try the below -this import statement is valid

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jstl/core-rt" prefix="c-rt" %><%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<html>
  <head>
    <title>Format Date</title>
  </head>

  <body>
    <c-rt:set var="now" value="<%=new java.util.Date()%>" />

    <table border="1" cellpadding="0" cellspacing="0"
    style="border-collapse: collapse" bordercolor="#111111"
    width="63%" id="AutoNumber2">
      <tr>
        <td width="100%" colspan="2" bgcolor="#0000FF">
          <p align="center">
            <b>
              <font color="#FFFFFF" size="4">Formatting: 
              <fmt:formatDate value="${now}" type="both"
              timeStyle="long" dateStyle="long" />
              </font>
            </b>
          </p>
        </td>
      </tr>

Run a PHP file in a cron job using CPanel

This cron line worked for me on hostgator VPS using cpanel.

/usr/bin/php -q /home/username/public_html/scriptname.php

android:drawableLeft margin and/or padding

If the size of drawable resouce is fixed, you can do like this:

<Button
    android:background="@drawable/rounded_button_green"
    style="?android:attr/selectableItemBackground"
    android:layout_height="wrap_content"
    app:layout_widthPercent="70%"
    android:drawableRight="@drawable/ic_clear_black_24dp"
    android:paddingRight="10dp"
    android:paddingLeft="34dp"
    tools:text="example" />

The key here is that:

    android:drawableRight="@drawable/ic_clear_black_24dp"
    android:paddingRight="10dp"
    android:paddingLeft="34dp"

That is, the size of drawable resource plus paddingRight is the paddingLeft.

You can see the result in this example

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

How to directly move camera to current location in Google Maps Android API v2?

make sure you have these permissions:

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

Then make some activity and register a LocationListener

package com.example.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class LocationActivity extends SherlockFragmentActivity implements LocationListener     {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER        
}

@Override
public void onLocationChanged(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
    map.animateCamera(cameraUpdate);
    locationManager.removeUpdates(this);
}

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

@Override
public void onProviderEnabled(String provider) { }

@Override
public void onProviderDisabled(String provider) { }
}

map.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

How do I disable the resizable property of a textarea?

This can be done in HTML easily:

<textarea name="textinput" draggable="false"></textarea>

This works for me. The default value is true for the draggable attribute.

Find unique lines

You could also print out the unique value in "file" using the cat command by piping to sort and uniq

cat file | sort | uniq -u

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Maven uses batch files to do its business. With any batch script, you must call another script using the call command so it knows to return back to your script after the called script completes. Try prepending call to all commands.

Another thing you could try is using the start command which should work similarly.

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

Should IBOutlets be strong or weak under ARC?

While the documentation recommends using weak on properties for subviews, since iOS 6 it seems to be fine to use strong (the default ownership qualifier) instead. That's caused by the change in UIViewController that views are not unloaded anymore.

  • Before iOS 6, if you kept strong links to subviews of the controller's view around, if the view controller's main view got unloaded, those would hold onto the subviews as long as the view controller is around.
  • Since iOS 6, views are not unloaded anymore, but loaded once and then stick around as long as their controller is there. So strong properties won't matter. They also won't create strong reference cycles, since they point down the strong reference graph.

That said, I am torn between using

@property (nonatomic, weak) IBOutlet UIButton *button;

and

@property (nonatomic) IBOutlet UIButton *button;

in iOS 6 and after:

  • Using weak clearly states that the controller doesn't want ownership of the button.

  • But omitting weak doesn't hurt in iOS 6 without view unloading, and is shorter. Some may point out that is also faster, but I have yet to encounter an app that is too slow because of weak IBOutlets.

  • Not using weak may be perceived as an error.

Bottom line: Since iOS 6 we can't get this wrong anymore as long as we don't use view unloading. Time to party. ;)

Laravel - Forbidden You don't have permission to access / on this server

For my case was encountering this issue with Laravel 6.x and managed to sort it out by installing an SSL Certificate. Tried playing around with .htaccess but never worked. I'm using the default Laravel 6.x .htaccess file which has the following contents

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

.attr('checked','checked') does not work

It works, but

$('input[name="myname"][checked]').val()

will return the value of the first element with attribute checked. And the a radio button still has this attribute (and it comes before the b button). Selecting b does not remove the checked attribute from a.

You can use jQuery's :checked:

$('input[name="myname"]:checked').val()

DEMO


Further notes:

  • Using $('b').attr('checked',true); is enough.
  • As others mentioned, don't use inline event handlers, use jQuery to add the event handler.

How to parse a string into a nullable int

I realise this is an old topic, but can't you simply:

(Nullable<int>)int.Parse(stringVal);

?

WordPress query single post by slug

From the WordPress Codex:

<?php
$the_slug = 'my_slug';
$args = array(
  'name'        => $the_slug,
  'post_type'   => 'post',
  'post_status' => 'publish',
  'numberposts' => 1
);
$my_posts = get_posts($args);
if( $my_posts ) :
  echo 'ID on the first post found ' . $my_posts[0]->ID;
endif;
?>

WordPress Codex Get Posts

Laravel Fluent Query Builder Join with subquery

I am on Laravel 7.25 and I don't know if it supports on previous versions or not but Its pretty good.

Syntax for the function:

public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)

Example:

Showing/Getting the user ID and the total number of posts by them left joining two tables users and posts.

        return DB::table('users')
            ->joinSub('select user_id,count(id) noOfPosts from posts group by user_id', 'totalPosts', 'users.id', '=', 'totalPosts.user_id', 'left')
            ->select('users.name', 'totalPosts.noOfPosts')
            ->get();

Alternative:

If you don't wanna mention 'left' for leftjoin then you can use another prebuilt function

    public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
    {
        return $this->joinSub($query, $as, $first, $operator, $second, 'left');
    }

And yeah, it actually calls the same function but it passes the join type itself. You can apply the same logic for other joins i.e. righJoinSub(...) etc.

Pass a data.frame column name to a function

If you are trying to build this function within an R package or simply want to reduce complexity, you can do the following:

test_func <- function(df, column) {
  if (column %in% colnames(df)) {
    return(max(df[, column, with=FALSE])) 
  } else {
    stop(cat(column, "not in data.frame columns."))
  }
}

The argument with=FALSE "disables the ability to refer to columns as if they are variables, thereby restoring the “data.frame mode” (per CRAN documentation). The if statement is a quick way to catch if the column name provided is within the data.frame. Could also use tryCatch error handling here.

How can I get a Dialog style activity window to fill the screen?

This answer is a workaround for those who use "Theme.AppCompat.Dialog" or any other "Theme.AppCompat.Dialog" descendants like "Theme.AppCompat.Light.Dialog", "Theme.AppCompat.DayNight.Dialog", etc. I myself has to use AppCompat dialog because i use AppCompatActivity as extends for all my activities. There will be a problem that make the dialog has padding on every sides(top, right, bottom and left) if we use the accepted answer.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

On your Activity's style, add these code

<style name="DialogActivityTheme" parent="Theme.AppCompat.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowBackground">@null</item>
</style>

As you may notice, the problem that generate padding to our dialog is "android:windowBackground", so here i make the window background to null.

What is private bytes, virtual bytes, working set?

You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.

A previous reply to this question has given a great explanation of what the various types are.

You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.

http://www.softwareverify.com/cpp/memory/index.html

Disclaimer: I designed Memory Validator.

generate days from date range

For Oracle, my solution is:

select trunc(sysdate-dayincrement, 'DD') 
  from dual, (select level as dayincrement 
                from dual connect by level <= 30)

Sysdate can be changed to specific date and level number can be changed to give more dates.

Sqlite or MySql? How to decide?

My few cents to previous excellent replies. the site www.sqlite.org works on a sqlite database. Here is the link when the author (Richard Hipp) replies to a similar question.

What does status=canceled for a resource mean in Chrome Developer Tools?

Chrome Version 33.0.1750.154 m consistently cancels image loads if I am using the Mobile Emulation pointed at my localhost; specifically with User Agent spoofing on (vs. just Screen settings).

When I turn User Agent spoofing off; image requests aren't canceled, I see the images.

I still don't understand why; in the former case, where the request is cancelled the Request Headers (CAUTION: Provisional headers are shown) have only

  • Accept
  • Cache-Control
  • Pragma
  • Referer
  • User-Agent

In the latter case, all of those plus others like:

  • Cookie
  • Connection
  • Host
  • Accept-Encoding
  • Accept-Language

Shrug

Check if a folder exist in a directory and create them using C#

using System;
using System.IO;
using System.Windows.Forms;

namespace DirCombination 
{
    public partial class DirCombination : Form
    {
        private const string _Path = @"D:/folder1/foler2/folfer3/folder4/file.txt";
        private string _finalPath = null;
        private string _error = null;

        public DirCombination()
        {
            InitializeComponent();

            if (!FSParse(_Path))
                Console.WriteLine(_error);
            else
                Console.WriteLine(_finalPath);
        }

        private bool FSParse(string path)
        {
            try
            {
                string[] Splited = path.Replace(@"//", @"/").Replace(@"\\", @"/").Replace(@"\", "/").Split(':');
                string NewPath = Splited[0] + ":";
                if (Directory.Exists(NewPath))
                {                    
                    string[] Paths = Splited[1].Substring(1).Split('/');

                    for (int i = 0; i < Paths.Length - 1; i++)
                    {
                        NewPath += "/";
                        if (!string.IsNullOrEmpty(Paths[i]))
                        {
                            NewPath += Paths[i];
                            if (!Directory.Exists(NewPath))
                                Directory.CreateDirectory(NewPath);
                        }
                    }

                    if (!string.IsNullOrEmpty(Paths[Paths.Length - 1]))
                    {
                        NewPath += "/" + Paths[Paths.Length - 1];
                        if (!File.Exists(NewPath))
                            File.Create(NewPath);
                    }
                    _finalPath = NewPath;
                    return true;
                }
                else
                {
                    _error = "Drive is not exists!";
                    return false;
                }
            }
            catch (Exception ex)
            {
                _error = ex.Message;
                return false;
            }
        }
    }
}

Check if a process is running or not on Windows with Python

Although @zeller said it already here is an example how to use tasklist. As I was just looking for vanilla python alternatives...

import subprocess

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    # use buildin check_output right away
    output = subprocess.check_output(call).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())

and now you can do:

>>> process_exists('eclipse.exe')
True

>>> process_exists('AJKGVSJGSCSeclipse.exe')
False

To avoid calling this multiple times and have an overview of all the processes this way you could do something like:

# get info dict about all running processes
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print('%s: %s' % (name, values))

how to make a html iframe 100% width and height?

this code probable help you .

<iframe src="" onload="this.width=screen.width;this.height=screen.height;">

Safari 3rd party cookie iframe trick no longer working?

You can resolve this issue by adding header as p3p policy..i had same issue on safari so after adding header on top of the files has resolved my problem.

<?php
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
?>

jQuery: how to get which button was clicked upon form submission?

This one worked for me

$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);

}

Convert Month Number to Month Name Function in SQL

you can get the date like this. eg:- Users table

id name created_at
1  abc  2017-09-16
2  xyz  2017-06-10

you can get the monthname like this

select year(created_at), monthname(created_at) from users;

output

+-----------+-------------------------------+
| year(created_at) | monthname(created_at)  |
+-----------+-------------------------------+
|      2017        | september              |
|      2017        | june                   |

Setting up MySQL and importing dump within Dockerfile

edit: I had misunderstand the question here. My following answer explains how to run sql commands at container creation time, but not at image creation time as desired by OP.

I'm not quite fond of Kuhess's accepted answer as the sleep 5 seems a bit hackish to me as it assumes that the mysql db daemon has correctly loaded within this time frame. That's an assumption, no guarantee. Also if you use a provided mysql docker image, the image itself already takes care about starting up the server; I would not interfer with this with a custom /usr/bin/mysqld_safe.

I followed the other answers around here and copied bash and sql scripts into the folder /docker-entrypoint-initdb.d/ within the docker container as this is clearly the intended way by the mysql image provider. Everything in this folder is executed once the db daemon is ready, hence you should be able rely on it.

As an addition to the others - since no other answer explicitely mentions this: besides sql scripts you can also copy bash scripts into that folder which might give you more control.

This is what I had needed for example as I also needed to import a dump, but the dump alone was not sufficient as it did not provide which database it should import into. So in my case I have a script named db_custom_init.sh with this content:

mysql -u root -p$MYSQL_ROOT_PASSWORD -e 'create database my_database_to_import_into'
mysql -u root -p$MYSQL_ROOT_PASSWORD my_database_to_import_into < /home/db_dump.sql

and this Dockerfile copying that script:

FROM mysql/mysql-server:5.5.62
ENV MYSQL_ROOT_PASSWORD=XXXXX
COPY ./db_dump.sql /home/db_dump.sql
COPY ./db_custom_init.sh /docker-entrypoint-initdb.d/

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

The syntax is:

=GOOGLEFINANCE(ticker, [attribute], [start_date], [num_days|end_date], [interval])

Sample usage:

=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
=GOOGLEFINANCE("GOOG","price",TODAY()-30,TODAY())
=GOOGLEFINANCE(A2,A3)
=117.80*Index(GOOGLEFINANCE("CURRENCY:EURGBP", "close", DATE(2014,1,1)), 2, 2)

For instance if you'd like to convert the rate on specific date, here is some more advanced example:

=IF($C2 = "GBP", "", Index(GoogleFinance(CONCATENATE("CURRENCY:", C2, "GBP"), "close", DATE(year($A2), month($A2), day($A2)), DATE(year($A2), month($A2), day($A2)+1), "DAILY"), 2))

where $A2 is your date (e.g. 01/01/2015) and C2 is your currency (e.g. EUR).

See more samples at Docs editors Help at Google.

Is it possible to use argsort in descending order?

An elegant way could be as follows -

ids = np.flip(np.argsort(avgDists))

This will give you indices of elements sorted in descending order. Now you can use regular slicing...

top_n = ids[:n]

Changing java platform on which netbeans runs

You can change the JDK for Netbeans by modifying the config file:

  1. Open netbeans.conf file available under etc folder inside the NetBeans installation.
  2. Modify the netbeans_jdkhome variable to point to new JDK path, and then
  3. Restart your Netbeans.

Set UIButton title UILabel font size programmatically

You can use:

button.titleLabel.font = [UIFont systemFontOfSize:14.0];

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

I think you will understand it through these examples below.

Source code structure:

/src/main/webapp/subdir/sample.jsp
/src/main/webapp/sample.jsp

Context is: TestApp
So the entry point: http://yourhostname-and-port/TestApp


Forward to RELATIVE path:

Using servletRequest.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> \subdir\sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character
http://yourhostname-and-port/TestApp/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character


Forward to ABSOLUTE path:

Using servletRequest.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

How to search for an element in a golang slice

As other guys commented before you can write your own procedure with anonymous function to solve this issue.

I used two ways to solve it:

func Find(slice interface{}, f func(value interface{}) bool) int {
    s := reflect.ValueOf(slice)
    if s.Kind() == reflect.Slice {
        for index := 0; index < s.Len(); index++ {
            if f(s.Index(index).Interface()) {
                return index
            }
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 12,
    }) 
    
    idx := Find(destinationList, func(value interface{}) bool {
        return value.(UserInfo).UserId == userId
    })
    
    if idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

Second method with less computational cost:

func Search(length int, f func(index int) bool) int {
    for index := 0; index < length; index++ {
        if f(index) {
            return index
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 123,
    }) 
    
    idx := Search(len(destinationList), func(index int) bool {
        return destinationList[index].UserId == userId
    })
    
    if  idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

String or binary data would be truncated. The statement has been terminated

When you define varchar etc without a length, the default is 1.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

So, if you expect 400 bytes in the @trackingItems1 column from stock, use nvarchar(400).

Otherwise, you are trying to fit >1 character into nvarchar(1) = fail

As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better

ALTER FUNCTION [dbo].[testing1](@price int)
RETURNS
AS
   SELECT ta.item, ta.warehouse, ta.price 
   FROM   stock ta
   WHERE  ta.price >= @price;

Of course, you could just use a normal SELECT statement..

Matplotlib - How to plot a high resolution graph?

For future readers who found this question while trying to save high resolution images from matplotlib as I am, I have tried some of the answers above and elsewhere, and summed them up here.

Best result: plt.savefig('filename.pdf')

and then converting this pdf to a png on the command line so you can use it in powerpoint:

pdftoppm -png -r 300 filename.pdf filename

OR simply opening the pdf and cropping to the image you need in adobe, saving as a png and importing the picture to powerpoint

Less successful test #1: plt.savefig('filename.png', dpi=300)

This does save the image at a bit higher than the normal resolution, but it isn't high enough for publication or some presentations. Using a dpi value of up to 2000 still produced blurry images when viewed close up.

Less successful test #2: plt.savefig('filename.pdf')

This cannot be opened in Microsoft Office Professional Plus 2016 (so no powerpoint), same with Google Slides.

Less successful test #3: plt.savefig('filename.svg')

This also cannot be opened in powerpoint or Google Slides, with the same issue as above.

Less successful test #4: plt.savefig('filename.pdf')

and then converting to png on the command line:

convert -density 300 filename.pdf filename.png

but this is still too blurry when viewed close up.

Less successful test #5: plt.savefig('filename.pdf')

and opening in GIMP, and exporting as a high quality png (increased the file size from ~100 KB to ~75 MB)

Less successful test #6: plt.savefig('filename.pdf')

and then converting to jpeg on the command line:

pdfimages -j filename.pdf filename

This did not produce any errors but did not produce an output on Ubuntu even after changing around several parameters.

React - Component Full Screen (with height 100%)

While this may not be the ideal answer but try this:

style={{top:'0', bottom:'0', left:'0', right:'0', position: 'absolute'}}

It keeps the size attached to borders which is not what you want but gives you somewhat same effect.

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you are trying to populate a table from a SQL dump, make sure that the table listed in the "INSERT INTO" statements of the dump is the same one you are trying to populate. Opening "MyTable" and importing with a SQL dump will throw exactly that kind of error if the dump is trying to put entries into "MyOtherTable", which may already have entries.

Replacing a fragment with another fragment inside activity group

I've made a gist with THE perfect method to manage fragment replacement and lifecycle.

It only replace the current fragment by a new one, if it's not the same and if it's not in backstack (in this case it will pop it).

It contain several option as if you want the fragment to be saved in backstack.

=> See Gist here

Using this and a single Activity, you may want to add this to your activity:

@Override
public void onBackPressed() {
    int fragments = getSupportFragmentManager().getBackStackEntryCount();
    if (fragments == 1) {
            finish();
            return;
    }

    super.onBackPressed();
}

How do I avoid the specification of the username and password at every git push?

You have to setup a SSH private key, you can review this page, how to do the setup on Mac, if you are on linux the guide should be almost the same, on Windows you would need tool like MSYS.

How to use split?

If it is the basic JavaScript split function, look at documentation, JavaScript split() Method.

Basically, you just do this:

var array = myString.split(' -- ')

Then your two values are stored in the array - you can get the values like this:

var firstValue = array[0];
var secondValue = array[1];

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

Here is an excerpt from Python reference about open().

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

Squash my last X commits together using Git

Tried all approaches mention here. But finally my issue resolved by following this link. https://gist.github.com/longtimeago/f7055aa4c3bba8a62197

$ git fetch upstream
$ git checkout omgpull 
$ git rebase -i upstream/master

 < choose squash for all of your commits, except the first one >
 < Edit the commit message to make sense, and describe all your changes >

$ git push origin omgpull -f

Posting parameters to a url using the POST method without using a form

You could use JavaScript and XMLHTTPRequest (AJAX) to perform a POST without using a form. Check this link out. Keep in mind that you will need JavaScript enabled in your browser though.

How to fix the session_register() deprecated issue?

We just have to use @ in front of the deprecated function. No need to change anything as mentioned in above posts. For example: if(!@session_is_registered("username")){ }. Just put @ and problem is solved.

Throwing exceptions from constructors

The only time you would NOT throw exceptions from constructors is if your project has a rule against using exceptions (for instance, Google doesn't like exceptions). In that case, you wouldn't want to use exceptions in your constructor any more than anywhere else, and you'd have to have an init method of some sort instead.

how does int main() and void main() work

If you really want to understand ANSI C 89, I need to correct you in one thing; In ANSI C 89 the difference between the following functions:

int main()
int main(void)
int main(int argc, char* argv[])

is:

int main()

  • a function that expects unknown number of arguments of unknown types. Returns an integer representing the application software status.

int main(void)

  • a function that expects no arguments. Returns an integer representing the application software status.

int main(int argc, char * argv[])

  • a function that expects argc number of arguments and argv[] arguments. Returns an integer representing the application software status.

About when using each of the functions

int main(void)

  • you need to use this function when your program needs no initial parameters to run/ load (parameters received from the OS - out of the program it self).

int main(int argc, char * argv[])

  • you need to use this function when your program needs initial parameters to load (parameters received from the OS - out of the program it self).

About void main()

In ANSI C 89, when using void main and compiling the project AS -ansi -pedantic (in Ubuntu, e.g) you will receive a warning indicating that your main function is of type void and not of type int, but you will be able to run the project. Most C developers tend to use int main() on all of its variants, though void main() will also compile.

Pass row number as variable in excel sheet

Assuming your row number is in B1, you can use INDIRECT:

=INDIRECT("A" & B1)

This takes a cell reference as a string (in this case, the concatenation of A and the value of B1 - 5), and returns the value at that cell.

How do you switch pages in Xamarin.Forms?

Seems like this thread is very popular and it will be sad not to mention here that there is an alternative way - ViewModel First Navigation. Most of the MVVM frameworks out there using it, however if you want to understand what it is about, continue reading.

All the official Xamarin.Forms documentation is demonstrating a simple, yet slightly not MVVM pure solution. That is because the Page(View) should know nothing about the ViewModel and vice versa. Here is a great example of this violation:

// C# version
public partial class MyPage : ContentPage
{
    public MyPage()
    {
        InitializeComponent();
        // Violation
        this.BindingContext = new MyViewModel();
    }
}

// XAML version
<?xml version="1.0" encoding="utf-8"?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:viewmodels="clr-namespace:MyApp.ViewModel"
    x:Class="MyApp.Views.MyPage">
    <ContentPage.BindingContext>
        <!-- Violation -->
        <viewmodels:MyViewModel />
    </ContentPage.BindingContext>
</ContentPage>

If you have a 2 pages application this approach might be good for you. However if you are working on a big enterprise solution you better go with a ViewModel First Navigation approach. It is slightly more complicated but much cleaner approach that allow you to navigate between ViewModels instead of navigation between Pages(Views). One of the advantages beside clear separation of concerns is that you could easily pass parameters to the next ViewModel or execute an async initialization code right after navigation. Now to details.

(I will try to simplify all the code examples as much as possible).

1. First of all we need a place where we could register all our objects and optionally define their lifetime. For this matter we can use an IOC container, you can choose one yourself. In this example I will use Autofac(it is one of the fastest available). We can keep a reference to it in the App so it will be available globally (not a good idea, but needed for simplification):

public class DependencyResolver
{
    static IContainer container;

    public DependencyResolver(params Module[] modules)
    {
        var builder = new ContainerBuilder();

        if (modules != null)
            foreach (var module in modules)
                builder.RegisterModule(module);

        container = builder.Build();
    }

    public T Resolve<T>() => container.Resolve<T>();
    public object Resolve(Type type) => container.Resolve(type);
}

public partial class App : Application
{
    public DependencyResolver DependencyResolver { get; }

    // Pass here platform specific dependencies
    public App(Module platformIocModule)
    {
        InitializeComponent();
        DependencyResolver = new DependencyResolver(platformIocModule, new IocModule());
        MainPage = new WelcomeView();
    }

    /* The rest of the code ... */
}

2.We will need an object responsible for retrieving a Page (View) for a specific ViewModel and vice versa. The second case might be useful in case of setting the root/main page of the app. For that we should agree on a simple convention that all the ViewModels should be in ViewModels directory and Pages(Views) should be in the Views directory. In other words ViewModels should live in [MyApp].ViewModels namespace and Pages(Views) in [MyApp].Views namespace. In addition to that we should agree that WelcomeView(Page) should have a WelcomeViewModel and etc. Here is a code example of a mapper:

public class TypeMapperService
{
    public Type MapViewModelToView(Type viewModelType)
    {
        var viewName = viewModelType.FullName.Replace("Model", string.Empty);
        var viewAssemblyName = GetTypeAssemblyName(viewModelType);
        var viewTypeName = GenerateTypeName("{0}, {1}", viewName, viewAssemblyName);
        return Type.GetType(viewTypeName);
    }

    public Type MapViewToViewModel(Type viewType)
    {
        var viewModelName = viewType.FullName.Replace(".Views.", ".ViewModels.");
        var viewModelAssemblyName = GetTypeAssemblyName(viewType);
        var viewTypeModelName = GenerateTypeName("{0}Model, {1}", viewModelName, viewModelAssemblyName);
        return Type.GetType(viewTypeModelName);
    }

    string GetTypeAssemblyName(Type type) => type.GetTypeInfo().Assembly.FullName;
    string GenerateTypeName(string format, string typeName, string assemblyName) =>
        string.Format(CultureInfo.InvariantCulture, format, typeName, assemblyName);
}

3.For the case of setting a root page we will need sort of ViewModelLocator that will set the BindingContext automatically:

public static class ViewModelLocator
{
    public static readonly BindableProperty AutoWireViewModelProperty =
        BindableProperty.CreateAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), default(bool), propertyChanged: OnAutoWireViewModelChanged);

    public static bool GetAutoWireViewModel(BindableObject bindable) =>
        (bool)bindable.GetValue(AutoWireViewModelProperty);

    public static void SetAutoWireViewModel(BindableObject bindable, bool value) =>
        bindable.SetValue(AutoWireViewModelProperty, value);

    static ITypeMapperService mapper = (Application.Current as App).DependencyResolver.Resolve<ITypeMapperService>();

    static void OnAutoWireViewModelChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var view = bindable as Element;
        var viewType = view.GetType();
        var viewModelType = mapper.MapViewToViewModel(viewType);
        var viewModel =  (Application.Current as App).DependencyResolver.Resolve(viewModelType);
        view.BindingContext = viewModel;
    }
}

// Usage example
<?xml version="1.0" encoding="utf-8"?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:viewmodels="clr-namespace:MyApp.ViewModel"
    viewmodels:ViewModelLocator.AutoWireViewModel="true"
    x:Class="MyApp.Views.MyPage">
</ContentPage>

4.Finally we will need a NavigationService that will support ViewModel First Navigation approach:

public class NavigationService
{
    TypeMapperService mapperService { get; }

    public NavigationService(TypeMapperService mapperService)
    {
        this.mapperService = mapperService;
    }

    protected Page CreatePage(Type viewModelType)
    {
        Type pageType = mapperService.MapViewModelToView(viewModelType);
        if (pageType == null)
        {
            throw new Exception($"Cannot locate page type for {viewModelType}");
        }

        return Activator.CreateInstance(pageType) as Page;
    }

    protected Page GetCurrentPage()
    {
        var mainPage = Application.Current.MainPage;

        if (mainPage is MasterDetailPage)
        {
            return ((MasterDetailPage)mainPage).Detail;
        }

        // TabbedPage : MultiPage<Page>
        // CarouselPage : MultiPage<ContentPage>
        if (mainPage is TabbedPage || mainPage is CarouselPage)
        {
            return ((MultiPage<Page>)mainPage).CurrentPage;
        }

        return mainPage;
    }

    public Task PushAsync(Page page, bool animated = true)
    {
        var navigationPage = Application.Current.MainPage as NavigationPage;
        return navigationPage.PushAsync(page, animated);
    }

    public Task PopAsync(bool animated = true)
    {
        var mainPage = Application.Current.MainPage as NavigationPage;
        return mainPage.Navigation.PopAsync(animated);
    }

    public Task PushModalAsync<TViewModel>(object parameter = null, bool animated = true) where TViewModel : BaseViewModel =>
        InternalPushModalAsync(typeof(TViewModel), animated, parameter);

    public Task PopModalAsync(bool animated = true)
    {
        var mainPage = GetCurrentPage();
        if (mainPage != null)
            return mainPage.Navigation.PopModalAsync(animated);

        throw new Exception("Current page is null.");
    }

    async Task InternalPushModalAsync(Type viewModelType, bool animated, object parameter)
    {
        var page = CreatePage(viewModelType);
        var currentNavigationPage = GetCurrentPage();

        if (currentNavigationPage != null)
        {
            await currentNavigationPage.Navigation.PushModalAsync(page, animated);
        }
        else
        {
            throw new Exception("Current page is null.");
        }

        await (page.BindingContext as BaseViewModel).InitializeAsync(parameter);
    }
}

As you may see there is a BaseViewModel - abstract base class for all the ViewModels where you can define methods like InitializeAsync that will get executed right after the navigation. And here is an example of navigation:

public class WelcomeViewModel : BaseViewModel
{
    public ICommand NewGameCmd { get; }
    public ICommand TopScoreCmd { get; }
    public ICommand AboutCmd { get; }

    public WelcomeViewModel(INavigationService navigation) : base(navigation)
    {
        NewGameCmd = new Command(async () => await Navigation.PushModalAsync<GameViewModel>());
        TopScoreCmd = new Command(async () => await navigation.PushModalAsync<TopScoreViewModel>());
        AboutCmd = new Command(async () => await navigation.PushModalAsync<AboutViewModel>());
    }
}

As you understand this approach is more complicated, harder to debug and might be confusing. However there are many advantages plus you actually don't have to implement it yourself since most of the MVVM frameworks support it out of the box. The code example that is demonstrated here is available on github.

There are plenty of good articles about ViewModel First Navigation approach and there is a free Enterprise Application Patterns using Xamarin.Forms eBook which is explaining this and many other interesting topics in detail.

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

maybe you have code like this before the jquery:

var $jq=jQuery.noConflict();
$jq('ul.menu').lavaLamp({
    fx: "backout", 
    speed: 700
});

and them was Conflict

you can change $ to (jQuery)

CKEditor automatically strips classes from div

if you're using ckeditor 4.x you can try

config.allowedContent = true;

if you're using ckeditor 3.x you may be having this issue.

try putting the following line in config.js

config.ignoreEmptyParagraph = false;

Can Console.Clear be used to only clear a line instead of whole console?

To clear from the current position to the end of the current line, do this:

    public static void ClearToEndOfCurrentLine()
    {
        int currentLeft = Console.CursorLeft;
        int currentTop = Console.CursorTop;
        Console.Write(new String(' ', Console.WindowWidth - currentLeft));
        Console.SetCursorPosition(currentLeft, currentTop);
    }

In Java, how do you determine if a thread is running?

Use Thread.currentThread().isAlive() to see if the thread is alive[output should be true] which means thread is still running the code inside the run() method or use Thread.currentThread.getState() method to get the exact state of the thread.

How to replace all special character into a string using C#

Yes, you can use regular expressions in C#.

Using regular expressions with C#:

using System.Text.RegularExpressions;

string your_String = "Hello@Hello&Hello(Hello)";
string my_String =  Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");

Efficiently sorting a numpy array in descending order?

For short arrays I suggest using np.argsort() by finding the indices of the sorted negatived array, which is slightly faster than reversing the sorted array:

In [37]: temp = np.random.randint(1,10, 10)

In [38]: %timeit np.sort(temp)[::-1]
100000 loops, best of 3: 4.65 µs per loop

In [39]: %timeit temp[np.argsort(-temp)]
100000 loops, best of 3: 3.91 µs per loop

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can get the script that SSMS provides by doing the following:

  1. Right-click on a database in SSMS and choose delete
  2. In the dialog, check the checkbox for "Close existing connections."
  3. Click the Script button at the top of the dialog.

The script will look something like this:

USE [master]
GO
ALTER DATABASE [YourDatabaseName] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
DROP DATABASE [YourDatabaseName]
GO

How to do a scatter plot with empty circles in Python?

In matplotlib 2.0 there is a parameter called fillstyle which allows better control on the way markers are filled. In my case I have used it with errorbars but it works for markers in general http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html

fillstyle accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]

There are two important things to keep in mind when using fillstyle,

1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to 'none' it would not take effect. So avoid using mfc in conjuntion with fillstyle

2) You might want to control the marker edge width (using markeredgewidth or mew) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.

Following is an example using errorbars:

myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue',  mec='blue')

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

Set element focus in angular way

The problem with your solution is that it does not work well when tied down to other directives that creates a new scope, e.g. ng-repeat. A better solution would be to simply create a service function that enables you to focus elements imperatively within your controllers or to focus elements declaratively in the html.

DEMO

JAVASCRIPT

Service

 .factory('focus', function($timeout, $window) {
    return function(id) {
      // timeout makes sure that it is invoked after any other event has been triggered.
      // e.g. click events that need to run before the focus or
      // inputs elements that are in a disabled state but are enabled when those events
      // are triggered.
      $timeout(function() {
        var element = $window.document.getElementById(id);
        if(element)
          element.focus();
      });
    };
  });

Directive

  .directive('eventFocus', function(focus) {
    return function(scope, elem, attr) {
      elem.on(attr.eventFocus, function() {
        focus(attr.eventFocusId);
      });

      // Removes bound events in the element itself
      // when the scope is destroyed
      scope.$on('$destroy', function() {
        elem.off(attr.eventFocus);
      });
    };
  });

Controller

.controller('Ctrl', function($scope, focus) {
    $scope.doSomething = function() {
      // do something awesome
      focus('email');
    };
  });

HTML

<input type="email" id="email" class="form-control">
<button event-focus="click" event-focus-id="email">Declarative Focus</button>
<button ng-click="doSomething()">Imperative Focus</button>

mysql update column with value from another table

Store your data in temp table

Select * into tempTable from table1

Now update the column

 UPDATE table1
    SET table1.FileName = (select FileName from tempTable where tempTable.id = table1.ID);

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

How to add new column to MYSQL table?

your table:

q1 | q2 | q3 | q4 | q5

you can also do

ALTER TABLE yourtable ADD q6 VARCHAR( 255 ) after q5