Programs & Examples On #Ebay lms

Ebay's Large Merchant Services.

JQuery DatePicker ReadOnly

<sj:datepicker id="datepickerid" name="datepickername" displayFormat="%{formatDateJsp}" readonly="true"/>

Works for me.

How to initialize an array of custom objects

The simplest way to initialize an array

Create array

$array = @()

Create your header

$line = "" | select name,age,phone

Fill the line

$line.name = "Leandro"
$line.age = "39"
$line.phone = "555-555555"

Add line to $array

$array += $line

Result

$array

name                                                     age                                                      phone
----                                                     ---                                                      -----
Leandro                                                  39                                                       555-555555

Disable html5 video autoplay

You can set autoplay=""

<video width="640" height="480" controls="controls" type="video/mp4" autoplay="">
<source src="http://example.com/mytestfile.mp4">
Your browser does not support the video tag.
</video>

ps. for enabling you can use autoplay or autoplay="autoplay"

Change the project theme in Android Studio?

Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles

Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.enter image description here

Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

  • Theme.Holo for a "dark" theme.
  • Theme.Holo.Light for a "light" theme.

When using the Support Library, you must instead use the Theme.AppCompat themes:

  • Theme.AppCompat for the "dark" theme.
  • Theme.AppCompat.Light for the "light" theme.
  • Theme.AppCompat.Light.DarkActionBar for the light theme with a dark action bar.

Source http://forums.udacity.com/questions/100200635/choosing-theme-in-android-studio-08x

'typeid' versus 'typeof' in C++

typeid provides the type of the data at runtime, when asked for. Typedef is a compile time construct that defines a new type as stated after that. There is no typeof in C++ Output appears as (shown as inscribed comments):

std::cout << typeid(t).name() << std::endl;  // i
std::cout << typeid(person).name() << std::endl;   // 6Person
std::cout << typeid(employee).name() << std::endl; // 8Employee
std::cout << typeid(ptr).name() << std::endl;      // P6Person
std::cout << typeid(*ptr).name() << std::endl;     //8Employee

PowerShell: how to grep command output?

For a more flexible and lazy solution, you could match all properties of the objects. Most of the time, this should get you the behavior you want, and you can always be more specific when it doesn't. Here's a grep function that works based on this principle:

Function Select-ObjectPropertyValues {
    param(
    [Parameter(Mandatory=$true,Position=0)]
    [String]
    $Pattern,
    [Parameter(ValueFromPipeline)]
    $input)

    $input | Where-Object {($_.PSObject.Properties | Where-Object {$_.Value -match $Pattern} | Measure-Object).count -gt 0} | Write-Output
}

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

It depends which version of C# you're using, from version 3.0 onwards you can use...

List<string> nameslist = new List<string> { "one", "two", "three" };

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

How to read an http input stream

a complete code for reading from a webservice in two ways

public void buttonclick(View view) {
    // the name of your webservice where reactance is your method
    new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}

public class GetMethodDemo extends AsyncTask<String, Void, String> {
    //see also: 
    // https://developer.android.com/reference/java/net/HttpURLConnection.html
    //writing to see:    https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
    String server_response;
    @Override
    protected String doInBackground(String... strings) {
        URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();
            Log.v("bufferv ", server_response);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.e("Response", "" + server_response);
   //assume there is a field with id editText
        EditText editText = (EditText) findViewById(R.id.editText);
        editText.setText(server_response);
    }
}

Rails 4 LIKE query - ActiveRecord adds quotes

Try

 def self.search(search, page = 1 )
    paginate :per_page => 5, :page => page,
      :conditions => ["name LIKE  ? OR postal_code like ?", "%#{search}%","%#{search}%"],   order => 'name'
  end

See the docs on AREL conditions for more info.

JSON.stringify output to div in pretty print way

If your <pre> tag is showing a single-line of JSON because that's how the string is provided already (via an api or some function/page out of your control), you can reformat it like this:

HTML:

<pre id="json">{"some":"JSON string"}</pre>

JavaScript:

    (function() {
        var element = document.getElementById("json");
        var obj = JSON.parse(element.innerText);
        element.innerHTML = JSON.stringify(obj, undefined, 2);
    })();

or jQuery:

    $(formatJson);

    function formatJson() {
        var element = $("#json");
        var obj = JSON.parse(element.text());
        element.html(JSON.stringify(obj, undefined, 2));
    }

Git Ignores and Maven targets

add following lines in gitignore, from all undesirable files

/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

CodeIgniter 404 Page Not Found, but why?

Your folder/file structure seems a little odd to me. I can't quite figure out how you've got this laid out.

Hello I am using CodeIgniter for two applications (a public and an admin app).

This sounds to me like you've got two separate CI installations. If this is the case, I'd recommend against it. Why not just handle all admin stuff in an admin controller? If you do want two separate CI installations, make sure they are definitely distinct entities and that the two aren't conflicting with one another. This line:

$system_folder = "../system";
$application_folder = "../application/admin"; (this line exists of course twice)

And the place you said this exists (/admin/index.php...or did you mean /admin/application/config?) has me scratching my head. You have admin/application/admin and a system folder at the top level?

python list by value not by reference

As mentioned by phihag in his answer,

b = a[:]

will work for your case since slicing a list creates a new memory id of the list (meaning you are no longer referencing the same object in your memory and the changes you make to one will not be reflected in the other.)

However, there is a slight problem. If your list is multidimensional, as in lists within lists, simply slicing will not solve this problem. Changes made in the higher dimensions, i.e. the lists within the original list, will be shared between the two.

Do not fret, there is a solution. The module copy has a nifty copying technique that takes care of this issue.

from copy import deepcopy

b = deepcopy(a)

will copy a list with a new memory id no matter how many levels of lists it contains!

how to compare two string dates in javascript?

You can use "Date.parse()" to properly compare the dates, but since in most of the comments people are trying to split the string and then trying to add up the digits and compare with obviously wrong logic -not completely.

Here's the trick. If you are breaking the string then compare the parts in nested format.

Compare year with year, month with month and day with day.

<pre><code>

var parts1 = "26/07/2020".split('/');
var parts2 = "26/07/2020".split('/');

var latest = false;

if (parseInt(parts1[2]) > parseInt(parts2[2])) {
    latest = true;
} else if (parseInt(parts1[2]) == parseInt(parts2[2])) {
    if (parseInt(parts1[1]) > parseInt(parts2[1])) {
        latest = true;
    } else if (parseInt(parts1[1]) == parseInt(parts2[1])) {
        if (parseInt(parts1[0]) >= parseInt(parts2[0])) {
            latest = true;
        } 
    }
}

return latest;

</code></pre>

Preventing form resubmission

Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:

Prevent Back button from showing POST confirmation alert

Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.

Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.

Mongoose.js: Find user by username LIKE value

Just complementing @PeterBechP 's answer.

Don't forget to scape the special chars. https://stackoverflow.com/a/6969486

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

var name = 'Peter+with+special+chars';

model.findOne({name: new RegExp('^'+escapeRegExp(name)+'$', "i")}, function(err, doc) {
  //Do your action here..
});

Why do we use Base64?

One example of when I found it convenient was when trying to embed binary data in XML. Some of the binary data was being misinterpreted by the SAX parser because that data could be literally anything, including XML special characters. Base64 encoding the data on the transmitting end and decoding it on the receiving end fixed that problem.

How to use pagination on HTML tables?

It is a very simple and effective utility build in jquery to implement pagination on html table http://tablesorter.com/docs/example-pager.html

Download the plugin from http://tablesorter.com/addons/pager/jquery.tablesorter.pager.js

After adding this plugin add following code in head script

$(document).ready(function() { 
    $("table") 
    .tablesorter({widthFixed: true, widgets: ['zebra']}) 
    .tablesorterPager({container: $("#pager")}); 
}); 

Get file from project folder java

These lines worked in my case,

ClassLoader classLoader = getClass().getClassLoader();
File fi = new File(classLoader.getResource("test.txt").getFile());

provided test.txt file inside src

error: package javax.servlet does not exist

In my case, migrating a Spring 3.1 app up to 3.2.7, my solution was similar to Matthias's but a bit different -- thus why I'm documenting it here:

In my POM I found this dependency and changed it from 6.0 to 7.0:

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

Then later in the POM I upgraded this plugin from 6.0 to 7.0:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    ...
                    <configuration>
                        ...
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

How to get a value from a Pandas DataFrame and not the index and object type

import pandas as pd

dataset = pd.read_csv("data.csv")
values = list(x for x in dataset["column name"])

>>> values[0]
'item_0'

edit:

actually, you can just index the dataset like any old array.

import pandas as pd

dataset = pd.read_csv("data.csv")
first_value = dataset["column name"][0]

>>> print(first_value)
'item_0'

setBackground vs setBackgroundDrawable (Android)

i know this is an old question but i have a similar situation ,and my solution was

button.setBackgroundResource( R.drawable.ic_button );
Drawable d = button.getBackground();

and then you can play with the "Drawable", applying color filters, etc

Difference between OpenJDK and Adoptium/AdoptOpenJDK

In short:

  • OpenJDK has multiple meanings and can refer to:
    • free and open source implementation of the Java Platform, Standard Edition (Java SE)
    • open source repository — the Java source code aka OpenJDK project
    • prebuilt OpenJDK binaries maintained by Oracle
    • prebuilt OpenJDK binaries maintained by the OpenJDK community
  • AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)

Explanation:

Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.

OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.

OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.

Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.

AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.

OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.

Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".

Donald Smith, Java product manager at Oracle writes:

Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.


OpenJDK Providers and Comparison

----------------------------------------------------------------------------------------
|     Provider      | Free Builds | Free Binary   | Extended | Commercial | Permissive |
|                   | from Source | Distributions | Updates  | Support    | License    |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK      |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Amazon – Corretto |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Azul Zulu         |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| BellSoft Liberica |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| IBM               |    No       |    No         |   Yes    |   Yes      |   Yes      |
| jClarity          |    No       |    No         |   Yes    |   Yes      |   Yes      |
| OpenJDK           |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Oracle JDK        |    No       |    Yes        |   No**   |   Yes      |   No       |
| Oracle OpenJDK    |    Yes      |    Yes        |   No     |   No       |   Yes      |
| ojdkbuild         |    Yes      |    Yes        |   No     |   No       |   Yes      |
| RedHat            |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
| SapMachine        |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
----------------------------------------------------------------------------------------

Free Builds from Source - the distribution source code is publicly available and one can assemble its own build

Free Binary Distributions - the distribution binaries are publicly available for download and usage

Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle

Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)

Permissive License - the distribution license is non-protective, e.g. Apache 2.0


Which Java Distribution Should I Use?

In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.

What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.

Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).

If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.


Additional information

Time to look beyond Oracle's JDK by Stephen Colebourne

Java Is Still Free by Java Champions community (published on September 17, 2018)

Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)

Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)

How do I escape a single quote ( ' ) in JavaScript?

You should always consider what the browser will see by the end. In this case, it will see this:

<img src='something' onmouseover='change(' ex1')' />

In other words, the "onmouseover" attribute is just change(, and there's another "attribute" called ex1')' with no value.

The truth is, HTML does not use \ for an escape character. But it does recognise &quot; and &apos; as escaped quote and apostrophe, respectively.

Armed with this knowledge, use this:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(&quot;ex1&quot;)' />";

... That being said, you could just use JavaScript quotes:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";

How to group pandas DataFrame entries by date in a non-unique column

This should work:

data.groupby(lambda x: data['date'][x].year)

How do you create a Marker with a custom icon for google maps API v3?

LatLng hello = new LatLng(X, Y);          // whereX & Y are coordinates

Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                R.drawable.university);   // where university is the icon name that is used as a marker.

mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
       }
   }
   quote wrapper div{
       div for individual quote{
          quote
       }
   }
 }

How to get named excel sheets while exporting from SSRS

Necromancing, just in case all the links go dark:

  1. Add a group to your report
    Also, be advised to set the sort order of the group expression here, so the tabs will be alphabetically sorted (or however you want it sorted).

    1. Add a group to your report

    • 'Zeilengruppe' means 'Target group'
    • 'Gruppeneigenschaften' means 'Group properties'
  2. Set the page break in the group properties 2. Set the page break in the group properties

    • 'Seitenumbruche' means 'Page break'
    • 'Zwischen den einzelnen Instanzen einer Gruppe' means 'Between the individual instances of a group'
  3. Now you need to set the PageName of the Tablix Member (group), NOT the PageName of the Tablix itselfs.
    If you got the right object, if will say "Tablix Member" (Tablix-Element in German) in the title box of the properties grid. If it's the wrong object, it will say only "table/tablix" (without member) in the property grid's title box.

  4. Note: If you get the tablix instead of the tablix member, it will put the same tab name in every tab, followed by a (tabNum)! If that happens, you now know what the problem is. Tablix Member

MultiTabExcelFile

How should I declare default values for instance variables in Python?

Using class members for default values of instance variables is not a good idea, and it's the first time I've seen this idea mentioned at all. It works in your example, but it may fail in a lot of cases. E.g., if the value is mutable, mutating it on an unmodified instance will alter the default:

>>> class c:
...     l = []
... 
>>> x = c()
>>> y = c()
>>> x.l
[]
>>> y.l
[]
>>> x.l.append(10)
>>> y.l
[10]
>>> c.l
[10]

Angular 2 filter/search list

HTML

<input [(ngModel)] = "searchTerm" (ngModelChange) = "search()"/>
<div *ngFor = "let item of items">{{item.name}}</div>

Component

search(): void {
    let term = this.searchTerm;
    this.items = this.itemsCopy.filter(function(tag) {
        return tag.name.indexOf(term) >= 0;
    }); 
}

Note that this.itemsCopy is equal to this.items and should be set before doing the search.

how to get file path from sd card in android

You can get the path of sdcard from this code:

File extStore = Environment.getExternalStorageDirectory();

Then specify the foldername and file name

for e.g:

"/LazyList/"+serialno.get(position).trim()+".jpg"

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

One additional step I needed to take was to switch my URL from http://localhost to http://127.0.0.0

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

Remove Last Comma from a string

function removeLastComma(str) {
   return str.replace(/,(\s+)?$/, '');   
}

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

Confirm deletion in modal / dialog using Twitter Bootstrap?

You can try more reusable my solution with callback function. In this function you can use POST request or some logic. Used libraries: JQuery 3> and Bootstrap 3>.

https://jsfiddle.net/axnikitenko/gazbyv8v/

Html code for test:

...
<body>
    <a href='#' id="remove-btn-a-id" class="btn btn-default">Test Remove Action</a>
</body>
...

Javascript:

$(function () {
    function remove() {
        alert('Remove Action Start!');
    }
    // Example of initializing component data
    this.cmpModalRemove = new ModalConfirmationComponent('remove-data', remove,
        'remove-btn-a-id', {
            txtModalHeader: 'Header Text For Remove', txtModalBody: 'Body For Text Remove',
            txtBtnConfirm: 'Confirm', txtBtnCancel: 'Cancel'
        });
    this.cmpModalRemove.initialize();
});

//----------------------------------------------------------------------------------------------------------------------
// COMPONENT SCRIPT
//----------------------------------------------------------------------------------------------------------------------
/**
 * Script processing data for confirmation dialog.
 * Used libraries: JQuery 3> and Bootstrap 3>.
 *
 * @param name unique component name at page scope
 * @param callback function which processing confirm click
 * @param actionBtnId button for open modal dialog
 * @param text localization data, structure:
 *              > txtModalHeader - text at header of modal dialog
 *              > txtModalBody - text at body of modal dialog
 *              > txtBtnConfirm - text at button for confirm action
 *              > txtBtnCancel - text at button for cancel action
 *
 * @constructor
 * @author Aleksey Nikitenko
 */
function ModalConfirmationComponent(name, callback, actionBtnId, text) {
    this.name = name;
    this.callback = callback;
    // Text data
    this.txtModalHeader =   text.txtModalHeader;
    this.txtModalBody =     text.txtModalBody;
    this.txtBtnConfirm =    text.txtBtnConfirm;
    this.txtBtnCancel =     text.txtBtnCancel;
    // Elements
    this.elmActionBtn = $('#' + actionBtnId);
    this.elmModalDiv = undefined;
    this.elmConfirmBtn = undefined;
}

/**
 * Initialize needed data for current component object.
 * Generate html code and assign actions for needed UI
 * elements.
 */
ModalConfirmationComponent.prototype.initialize = function () {
    // Generate modal html and assign with action button
    $('body').append(this.getHtmlModal());
    this.elmActionBtn.attr('data-toggle', 'modal');
    this.elmActionBtn.attr('data-target', '#'+this.getModalDivId());
    // Initialize needed elements
    this.elmModalDiv =  $('#'+this.getModalDivId());
    this.elmConfirmBtn = $('#'+this.getConfirmBtnId());
    // Assign click function for confirm button
    var object = this;
    this.elmConfirmBtn.click(function() {
        object.elmModalDiv.modal('toggle'); // hide modal
        object.callback(); // run callback function
    });
};

//----------------------------------------------------------------------------------------------------------------------
// HTML GENERATORS
//----------------------------------------------------------------------------------------------------------------------
/**
 * Methods needed for get html code of modal div.
 *
 * @returns {string} html code
 */
ModalConfirmationComponent.prototype.getHtmlModal = function () {
    var result = '<div class="modal fade" id="' + this.getModalDivId() + '"';
    result +=' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
    result += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
    result += this.txtModalHeader + '</div><div class="modal-body">' + this.txtModalBody + '</div>';
    result += '<div class="modal-footer">';
    result += '<button type="button" class="btn btn-default" data-dismiss="modal">';
    result += this.txtBtnCancel + '</button>';
    result += '<button id="'+this.getConfirmBtnId()+'" type="button" class="btn btn-danger">';
    result += this.txtBtnConfirm + '</button>';
    return result+'</div></div></div></div>';
};

//----------------------------------------------------------------------------------------------------------------------
// UTILITY
//----------------------------------------------------------------------------------------------------------------------
/**
 * Get id element with name prefix for this component.
 *
 * @returns {string} element id
 */
ModalConfirmationComponent.prototype.getModalDivId = function () {
    return this.name + '-modal-id';
};

/**
 * Get id element with name prefix for this component.
 *
 * @returns {string} element id
 */
ModalConfirmationComponent.prototype.getConfirmBtnId = function () {
    return this.name + '-confirm-btn-id';
};

ignoring any 'bin' directory on a git project

Adding **/bin/ to the .gitignore file did the trick for me (Note: bin folder wasn't added to index).

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

Convert javascript array to string

var arr = new Array();

var blkstr = $.each([1, 2, 3], function(idx2,val2) {                    
    arr.push(idx2 + ":" + val2);
    return arr;
}).join(', ');

console.log(blkstr);

OR

var arr = new Array();

$.each([1, 2, 3], function(idx2,val2) {                    
    arr.push(idx2 + ":" + val2);

});

console.log(arr.join(', '));

Generate 'n' unique random numbers within a range

If you just need sampling without replacement:

>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]

random.sample takes a population and a sample size k and returns k random members of the population.

If you have to control for the case where k is larger than len(population), you need to be prepared to catch a ValueError:

>>> try:
...   random.sample(range(1, 2), 3)
... except ValueError:
...   print('Sample size exceeded population size.')
... 
Sample size exceeded population size

What is this Javascript "require"?

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

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

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

example.js

module.exports = "some code";

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

We will name the other file otherFile.js

In this file, you write:

otherFile.js

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

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

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

let string = "some code";

  • or -

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

Note:

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

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

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

express.js

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

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

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

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


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

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

< one-way binding

= two-way binding

& function binding

@ pass only strings

How to Get a Sublist in C#

Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.

Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.

CreateProcess error=2, The system cannot find the file specified

My recomendation is to keep the getRuntime().exec because exec uses the ProcessBuilder.

Try

 p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

How to make html table vertically scrollable

The best way to do this is strictly separate your table into two different tables - header and body:

<div class="header">
  <table><tr><!-- th here --></tr></table>
</div>

<div class="body">
  <table><tr><!-- td here --></tr></table>
</div>

.body {
  height: 100px;
  overflow: auto
}

If your table has a big width (more than screen width), then you have to add scroll events for horizontal scrolling header and body synchroniously.

You should never touch table tags (table, tbody, thead, tfoot, tr) with CSS properties display and overflow. Dealing with DIV wrappers is much more preferable.

replace \n and \r\n with <br /> in java

That should work, but don't kill yourself trying to figure it out. Just use 2 passes.

str  = str.replaceAll("(\r\n)", "<br />");
str  = str.replaceAll("(\n)", "<br />");

Disclaimer: this is not very efficient.

How do you keep parents of floated elements from collapsing?

Rather than putting overflow:auto on the parent, put overflow:hidden

The first CSS I write for any webpage is always:

div {
  overflow:hidden;
}

Then I never have to worry about it.

Where is database .bak file saved from SQL Server Management Studio?

Should be in

Program Files>Microsoft SQL Server>MSSQL 1.0>MSSQL>BACKUP>

In my case it is

C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup

If you use the gui or T-SQL you can specify where you want it T-SQL example

BACKUP DATABASE [YourDB] TO  DISK = N'SomePath\YourDB.bak' 
WITH NOFORMAT, NOINIT,  NAME = N'YourDB Full Database Backup', 
SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

With T-SQL you can also get the location of the backup, see here Getting the physical device name and backup time for a SQL Server database

SELECT          physical_device_name,
                backup_start_date,
                backup_finish_date,
                backup_size/1024.0 AS BackupSizeKB
FROM msdb.dbo.backupset b
JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id
WHERE database_name = 'YourDB'
ORDER BY backup_finish_date DESC

Get index of a row of a pandas dataframe as an integer

To answer the original question on how to get the index as an integer for the desired selection, the following will work :

df[df['A']==5].index.item()

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

I had similar issue with <input type="range" /> and I solved it with

-webkit-tap-highlight-color: transparent;

_x000D_
_x000D_
input[type="range"]{
  -webkit-tap-highlight-color: transparent;
}
_x000D_
 <input type="range" id="volume" name="demo"
         min="0" max="11">
  <label for="volume">Demo</label>
_x000D_
_x000D_
_x000D_

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Android Push Notifications: Icon not displaying in notification, white square shown instead

For SDK >= 23, please add setLargeIcon

notification = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(context.getResources(), R.drawable.lg_logo))
            .setContentTitle(title)
            .setStyle(new Notification.BigTextStyle().bigText(msg))
            .setAutoCancel(true)
            .setContentText(msg)
            .setContentIntent(contentIntent)
            .setSound(sound)
            .build();

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

The MySQL dependency should be like the following syntax in the pom.xml file.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

Make sure the syntax, groupId, artifactId, Version has included in the dependancy.

How do I join two lists in Java?

In Java 8 (the other way):

List<?> newList = 
Stream.of(list1, list2).flatMap(List::stream).collect(Collectors.toList());

How to fix "Attempted relative import in non-package" even with __init__.py

If your use case is for running tests, and it seams that it is, then you can do the following. Instead of running your test script as python core_test.py use a testing framework such as pytest. Then on the command line you can enter

$$ py.test

That will run the tests in your directory. This gets around the issue of __name__ being __main__ that was pointed out by @BrenBarn. Next, put an empty __init__.py file into your test directory, this will make the test directory part of your package. Then you will be able to do

from ..components.core import GameLoopEvents

However, if you run your test script as a main program then things will fail once again. So just use the test runner. Maybe this also works with other test runners such as nosetests but i haven't checked it. Hope this helps.

Logcat not displaying my log calls

When using Eclipse, in the DDMS perspective, make sure the correct device (propably emulator-xxxx) is selected and highlighted. Only then will you get the logcat output in the logcat view.

Also, the Android plugin is a bit quircky, and sometimes only shows the last line in the logcat view. If this happens, try to clear the log. After that, you should get all the log entries again (works for me anyway).

SQL Row_Number() function in Where Clause

SELECT  employee_id
FROM    (
        SELECT  employee_id, ROW_NUMBER() OVER (ORDER BY employee_id) AS rn
        FROM    V_EMPLOYEE
        ) q
WHERE   rn > 0
ORDER BY
        Employee_ID

Note that this filter is redundant: ROW_NUMBER() starts from 1 and is always greater than 0.

JavaScript dictionary with names

The main problem I see with what you have is that it's difficult to loop through, for populating a table.

Simply use an array of arrays:

var myMappings = [
    ["Name", "10%"], // Note the quotes around "10%"
    ["Phone", "10%"],
    // etc..
];

... which simplifies access:

myMappings[0][0]; // column name
myMappings[0][1]; // column width

Alternatively:

var myMappings = {
    names: ["Name", "Phone", etc...],
    widths: ["10%", "10%", etc...]
};

And access with:

myMappings.names[0];
myMappings.widths[0];

add a temporary column with a value

You mean staticly define a value, like this:

SELECT field1, 
       field2,
       'example' AS newfield
  FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

How do I find out my MySQL URL, host, port and username?

Here are the default settings

default-username is root
default-password is null/empty //mean nothing
default-url is localhost or 127.0.0.1 for apache and
localhost/phpmyadmin for mysql // if you are using xampp/wamp/mamp
default-port = 3306

Twitter Bootstrap Datepicker within modal window

As mccannf said in his comment:

I recommend you look at your bootstrap CSS and JS. Your modal is being set at a very high z-index value (99999). Just compare my jsfiddle above with yours

CSS list-style-image size

I achieved it by placing the image tag before the li's:


HTML

<img src="https://www.pinclipart.com/picdir/big/1-17498_plain-right-white-arrow-clip-art-at-clipart.png" class="listImage">

CSS

     .listImage{
      float:left;
      margin:2px;
      width:25px
     }
     .li{
      margin-left:29px;
     }

How to use relative paths without including the context root name?

This is a derivative of @Ralph suggestion that I've been using. Add the c:url to the top of your JSP.

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

Then just reference the root variable in your page:

<link rel="stylesheet" href="${root}templates/style/main.css">

Gem Command not found

check that rvm is a function type rvm | head -1

Copy folder recursively in Node.js

Mallikarjun M, thank you!

fs-extra did the thing and it can even return a Promise if you do not provide a callback! :)

const path = require('path')
const fs = require('fs-extra')

let source = path.resolve( __dirname, 'folderA')
let destination = path.resolve( __dirname, 'folderB')

fs.copy(source, destination)
  .then(() => console.log('Copy completed!'))
  .catch( err => {
    console.log('An error occurred while copying the folder.')
    return console.error(err)
  })

Max length for client ip address

As described in the IPv6 Wikipedia article,

IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:)

A typical IPv6 address:

2001:0db8:85a3:0000:0000:8a2e:0370:7334

This is 39 characters long. IPv6 addresses are 128 bits long, so you could conceivably use a binary(16) column, but I think I'd stick with an alphanumeric representation.

How do I create documentation with Pydoc?

As RocketDonkey suggested, your module itself needs to have some docstrings.

For example, in myModule/__init__.py:

"""
The mod module
"""

You'd also want to generate documentation for each file in myModule/*.py using

pydoc myModule.thefilename

to make sure the generated files match the ones that are referenced from the main module documentation file.

How to get the background color of an HTML element?

It depends which style from the div you need. Is this a background style which was defined in CSS or background style which was added through javascript(inline) to the current node?

In case of CSS style, you should use computed style. Like you do in getStyle().

With inline style you should use node.style reference: x.style.backgroundColor;

Also notice, that you pick the style by using camelCase/non hyphen reference, so not background-color, but backgroundColor;

Java recursive Fibonacci sequence

You can also simplify your function, as follows:

public int fibonacci(int n)  {
    if (n < 2) return n;

    return fibonacci(n - 1) + fibonacci(n - 2);
}

How can I filter a date of a DateTimeField in Django?

Such lookups are implemented in django.views.generic.date_based as follows:

{'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min),
                            datetime.datetime.combine(date, datetime.time.max))} 

Because it is quite verbose there are plans to improve the syntax using __date operator. Check "#9596 Comparing a DateTimeField to a date is too hard" for more details.

How To Pass GET Parameters To Laravel From With GET Method ?

Router

Route::get('search/{id}', ['as' => 'search', 'uses' => 'SearchController@search']);

Controller

class SearchController extends BaseController {

    public function search(Request $request){

        $id= $request->id ; // or any params

        ...
    }
}

How do you set EditText to only accept numeric values in Android?

I don't know what the correct answer was in '13, but today it is:

myEditText.setKeyListener(DigitsKeyListener.getInstance(null, false, true)); // positive decimal numbers

You get everything, including the onscreen keyboard is a numeric keypad.

ALMOST everything. Espresso, in its infinite wisdom, lets typeText("...") inexplicably bypass the filter and enter garbage...

Html.Raw() in ASP.NET MVC Razor view

You shouldn't be calling .ToString().

As the error message clearly states, you're writing a conditional in which one half is an IHtmlString and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.


There is never a reason to call Html.Raw(...).ToString().
Html.Raw returns an HtmlString instance that wraps the original string.
The Razor page output knows not to escape HtmlString instances.

However, calling HtmlString.ToString() just returns the original string value again; it doesn't accomplish anything.

Are string.Equals() and == operator really same?

In addition to Jon Skeet's answer, I'd like to explain why most of the time when using == you actually get the answer true on different string instances with the same value:

string a = "Hell";
string b = "Hello";
a = a + "o";
Console.WriteLine(a == b);

As you can see, a and b must be different string instances, but because strings are immutable, the runtime uses so called string interning to let both a and b reference the same string in memory. The == operator for objects checks reference, and since both a and b reference the same instance, the result is true. When you change either one of them, a new string instance is created, which is why string interning is possible.

By the way, Jon Skeet's answer is not complete. Indeed, x == y is false but that is only because he is comparing objects and objects compare by reference. If you'd write (string)x == (string)y, it will return true again. So strings have their ==-operator overloaded, which calls String.Equals underneath.

Git push error: "origin does not appear to be a git repository"

Your config file does not include any references to "origin" remote. That section looks like this:

[remote "origin"]
    url = [email protected]:repository.git
    fetch = +refs/heads/*:refs/remotes/origin/*

You need to add the remote using git remote add before you can use it.

Is it possible to get a list of files under a directory of a website? How?

Yes, you can, but you need a few tools first. You need to know a little about basic coding, FTP clients, port scanners and brute force tools, if it has a .htaccess file.

If not just try tgp.linkurl.htm or html, ie default.html, www/home/siteurl/web/, or wap /index/ default /includes/ main/ files/ images/ pics/ vids/, could be possible file locations on the server, so try all of them so www/home/siteurl/web/includes/.htaccess or default.html. You'll hit a file after a few tries then work off that. Yahoo has a site file viewer too: you can try to scan sites file indexes.

Alternatively, try brutus aet, trin00, trinity.x, or whiteshark airtool to crack the site's FTP login (but it's illegal and I do not condone that).

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

Python: Adding element to list while iterating

You can do this.

bonus_rows = []
for a in myarr:
  if somecond(a):
      bonus_rows.append(newObj())
myarr.extend( bonus_rows )

node.js, socket.io with SSL

Use a secure URL for your initial connection, i.e. instead of "http://" use "https://". If the WebSocket transport is chosen, then Socket.IO should automatically use "wss://" (SSL) for the WebSocket connection too.

Update:

You can also try creating the connection using the 'secure' option:

var socket = io.connect('https://localhost', {secure: true});

Enable SQL Server Broker taking too long

USE master;
GO
ALTER DATABASE Database_Name
    SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
GO
USE Database_Name;
GO

Curl error: Operation timed out

Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.

If you are running the script through browser, then set the set_time_limit to zero for infinite seconds.

set_time_limit(0);

Increase the curl's operation time limit using this option CURLOPT_TIMEOUT

curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds

It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

Write to Windows Application Event Log

try

   System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
   appLog.Source = "This Application's Name";
   appLog.WriteEntry("An entry to the Application event log.");

Two models in one view in ASP MVC 3

To use the tuple you need to do the following, in the view change the model to:

@model Tuple<Person,Order>

to use @html methods you need to do the following i.e:

@Html.DisplayNameFor(tuple => tuple.Item1.PersonId)

or

@Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id }) |

Item1 indicates the first parameter passed to the Tuple method and you can use Item2 to access the second model and so on.

in your controller you need to create a variable of type Tuple and then pass it to the view:

    public ActionResult Details(int id = 0)
    {
        Person person = db.Persons.Find(id);
        if (person == null)
        {
            return HttpNotFound();
        }
        var tuple = new Tuple<Person, Order>(person,new Order());

        return View(tuple);
    }

Another example : Multiple models in a view

Function stoi not declared

Are you running C++ 11? stoi was added in C++ 11, if you're running on an older version use atoi()

Update Eclipse with Android development tools v. 23

It works for me :)

If for some reason you installed an ADT preview and need to revert back to the current stable, you can't use the dialog to install "new" software since what you want is actually an older one. Instead do this:

  • Open Help > About Eclipse... on Windows or Linux. On Mac, use the app's menu > About...
  • Click the "Installation Details" button.
  • Select the "Installation History" tab.
  • Select one of the previous configurations.
  • Click the "Revert" button at the bottom.

enter image description here

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

To make life easier when entering multiple dates/times it is possible to use a custom format to remove the need to enter the colon, and the leading "hour" 0. This however requires a second field for the numerical date to be stored, as the displayed date from the custom format is in base 10.

Displaying a number as a time (no need to enter colons, but no time conversion)

For displaying the times on the sheet, and for entering them without having to type the colon set the cell format to custom and use:

0/:00

Then enter your time. For example, if you wanted to enter 62:30, then you would simply type 6230 and your custom format would visually insert a colon 2 decimal points from the right.

If you only need to display the times, stop here.

Converting number to time

If you need to be able to calculate with the times, you will need to convert them from base 10 into the time format.

This can be done with the following formula (change A2 to the relevant cell reference):

=TIME(0,TRUNC(A2/100),MOD(A2,100))

  • =TIME starts the number to time conversion
  • We don't need hours, so enter 0, at the beginning of the formula, as the format is always hh,mm,ss (to display hours and minutes instead of minutes and seconds, place the 0 at the end of the formula).
  • For the minutes, TRUNC(A2/100), discards the rightmost 2 digits.
  • For the seconds, MOD(A2,100) keeps the rightmost 2 digits and discards everything to the left.

The above formula was found and adapted from this article: PC Mag.com - Easy Date and Time Entry in Excel

Alternatively, you could skip the 0/:00 custom formatting, and just enter your time in a cell to be referenced of the edge of the visible workspace or on another sheet as you would for the custom formatting (ie: 6230 for 62:30)

Then change the display format of the cells with the formula to [m]:ss as @Sean Chessire suggested.

Here is a screen shot to show what I mean.

Excel screen shot showing time conversion formula and custom formatting

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
- debug: var=cat.stdout_lines

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

SQLException: No suitable driver found for jdbc:derby://localhost:1527

Notice: you can download it from here.

If you can't find it, then

  1. Find your project in projects selection tab

  2. Right click "Libraries"

  3. Click "Add JAR/Folder..."

  4. Choose "derbyclient.jar"

  5. Click "Open", then you will see "derbyclient.jar" under your "Libraries"

Make sure your URL, user name, password is correct, and run your code:)

Regex Named Groups in Java

For people coming to this late: Java 7 adds named groups. Matcher.group(String groupName) documentation.

Using PowerShell to remove lines from a text file if it contains a string

Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt

Mockito, JUnit and Spring

The difference in whether you have to instantiate your @InjectMocks annotated field is in the version of Mockito, not in whether you use the MockitoJunitRunner or MockitoAnnotations.initMocks. In 1.9, which will also handle some constructor injection of your @Mock fields, it will do the instantiation for you. In earlier versions, you have to instantiate it yourself.

This is how I do unit testing of my Spring beans. There is no problem. People run into confusion when they want to use Spring configuration files to actually do the injection of the mocks, which is crossing up the point of unit tests and integration tests.

And of course the unit under test is an Impl. You need to test a real concrete thing, right? Even if you declared it as an interface you would have to instantiate the real thing to test it. Now, you could get into spies, which are stub/mock wrappers around real objects, but that should be for corner cases.

Taking inputs with BufferedReader in Java

BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.

            String s= inp.readLine();
            int[] m= new int[2];
            String[] s1 = inp.readLine().split(" ");
            m[0]=Integer.parseInt(s1[0]);
            m[1]=Integer.parseInt(s1[1]);

            // Checking whether I am taking the inputs correctly
            System.out.println(s);
            System.out.println(m[0]);
            System.out.println(m[1]);

You can check also Scanner vs. BufferedReader.

How do I get the first element from an IEnumerable<T> in .net?

Well, you didn't specify which version of .Net you're using.

Assuming you have 3.5, another way is the ElementAt method:

var e = enumerable.ElementAt(0);

What is 'Context' on Android?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.

For more information, look in Introduction to Android development with Android Studio - Tutorial.

Matplotlib connect scatterplot points with line - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

Htaccess: add/remove trailing slash from URL

Right below the RewriteEngine On line, add:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R] # <- for test, for prod use [L,R=301]

to enforce a no-trailing-slash policy.

To enforce a trailing-slash policy:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R] # <- for test, for prod use [L,R=301]

EDIT: commented the R=301 parts because, as explained in a comment:

Be careful with that R=301! Having it there makes many browsers cache the .htaccess-file indefinitely: It somehow becomes irreversible if you can't clear the browser-cache on all machines that opened it. When testing, better go with simple R or R=302

After you've completed your tests, you can use R=301.

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Using python PIL to turn a RGB image into a pure black and white image

Another option (which is useful e.g. for scientific purposes when you need to work with segmentation masks) is simply apply a threshold:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Binarize (make it black and white) an image with Python."""

from PIL import Image
from scipy.misc import imsave
import numpy


def binarize_image(img_path, target_path, threshold):
    """Binarize an image."""
    image_file = Image.open(img_path)
    image = image_file.convert('L')  # convert image to monochrome
    image = numpy.array(image)
    image = binarize_array(image, threshold)
    imsave(target_path, image)


def binarize_array(numpy_array, threshold=200):
    """Binarize a numpy array."""
    for i in range(len(numpy_array)):
        for j in range(len(numpy_array[0])):
            if numpy_array[i][j] > threshold:
                numpy_array[i][j] = 255
            else:
                numpy_array[i][j] = 0
    return numpy_array


def get_parser():
    """Get parser object for script xy.py."""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__,
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("-i", "--input",
                        dest="input",
                        help="read this file",
                        metavar="FILE",
                        required=True)
    parser.add_argument("-o", "--output",
                        dest="output",
                        help="write binarized file hre",
                        metavar="FILE",
                        required=True)
    parser.add_argument("--threshold",
                        dest="threshold",
                        default=200,
                        type=int,
                        help="Threshold when to show white")
    return parser


if __name__ == "__main__":
    args = get_parser().parse_args()
    binarize_image(args.input, args.output, args.threshold)

It looks like this for ./binarize.py -i convert_image.png -o result_bin.png --threshold 200:

enter image description here

Cloning an Object in Node.js

Y'all suffering yet the solution is simple.

var obj1 = {x: 5, y:5};

var obj2 = {...obj1}; // Boom

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Create a group object and call methods like below example:

grp = df.groupby(['col1',  'col2',  'col3']) 

grp.max() 
grp.mean() 
grp.describe() 

How to generate UML diagrams (especially sequence diagrams) from Java code?

I am one of the authors, so the answer can be biased. It is open-source (Apache 2.0), but the plugin is not free. You don't have to pay (obviously) if you clone and build it locally.

On Intellij IDEA, ZenUML can generate sequence diagram from Java code. enter image description here

Check it out at https://plugins.jetbrains.com/plugin/12437-zenuml-support

Source code: https://github.com/ZenUml/jetbrains-zenuml

Instagram how to get my user id from username?

I wrote this tool for retrieving Instagram IDs by username: Instagram User ID Lookup.

It utilizes the python-instagram library to access the API and includes a link to the source code (written on Django), which illustrates various implementations of the Instagram API.

Update: Added source code for port to Ruby on Rails.

Bash Templating: How to build configuration files from templates with Bash?

I have a bash solution like mogsie but with heredoc instead of herestring to allow you to avoid escaping double quotes

eval "cat <<EOF
$(<template.txt)
EOF
" 2> /dev/null

Correct way to use StringBuilder in SQL

The aim of using StringBuilder, i.e reducing memory. Is it achieved?

No, not at all. That code is not using StringBuilder correctly. (I think you've misquoted it, though; surely there aren't quotes around id2 and table?)

Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.

Will that take memory equal to using String like below?

No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder in the code is unnecessary and optimizes it out, if it can.)

If the author of that code wants to use StringBuilder (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2 and table):

StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();

Note that I've listed some_appropriate_size in the StringBuilder constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append] each time it runs out of room).

You may have heard that string concatenation will use a StringBuilder under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder:

return "prefix " + variable1 + " middle " + variable2 + " end";

It roughly translates to:

StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();

So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.

But that's only for a single expression. Multiple StringBuilders are used for this:

String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;

That ends up becoming something like this:

String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;

...which is pretty ugly.

It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

I encountered the same error. My linker command did have the rt library included -lrt which is correct and it was working for a while. After re-installing Kubuntu it stopped working.

A separate forum thread suggested the -lrt needed to come after the project object files. Moving the -lrt to the end of the command fixed this problem for me although I don't know the details of why.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I have also got stuck into this and believe me disabling SELinux is not a good idea.

Please just use below and you are good,

sudo restorecon -R /var/www/mysite

Enjoy..

How to access nested elements of json object using getJSONArray method

This is for Nikola.

    public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
    String[] keyMain = keys.split("\\.");
    for (String keym : keyMain) {
        Iterator iterator = js1.keys();
        String key = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
                if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
                    js1.put(key, valueNew);
                    return js1;
                }
            }
            if (js1.optJSONObject(key) != null) {
                if ((key.equals(keym))) {
                    js1 = js1.getJSONObject(key);
                    break;
                }
            }
            if (js1.optJSONArray(key) != null) {
                JSONArray jArray = js1.getJSONArray(key);
                JSONObject j;
                for (int i = 0; i < jArray.length(); i++) {
                    js1 = jArray.getJSONObject(i);
                    break;
                }
            }
        }
    }
    return js1;
}


public static void main(String[] args) throws IOException, JSONException {
    String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
    JSONObject json = new JSONObject(text);
    setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
    System.out.println(json.toString(4));

}

If it's help bro,Do not forget to up for my reputation)))

Reset the database (purge all), then seed a database

You can delete everything and recreate database + seeds with both:

  1. rake db:reset: loads from schema.rb
  2. rake db:drop db:create db:migrate db:seed: loads from migrations

Make sure you have no connections to db (rails server, sql client..) or the db won't drop.

schema.rb is a snapshot of the current state of your database generated by:

rake db:schema:dump

Can I change the name of `nohup.out`?

my start.sh file:

#/bin/bash

nohup forever -c php artisan your:command >>storage/logs/yourcommand.log 2>&1 &

There is one important thing only. FIRST COMMAND MUST BE "nohup", second command must be "forever" and "-c" parameter is forever's param, "2>&1 &" area is for "nohup". After running this line then you can logout from your terminal, relogin and run "forever restartall" voilaa... You can restart and you can be sure that if script halts then forever will restart it.

I <3 forever

Android: making a fullscreen application

In onCreate call

requestWindowFeature(Window.FEATURE_NO_TITLE); // for hiding title

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);

How to log as much information as possible for a Java Exception?

The java.util.logging package is standard in Java SE. Its Logger includes an overloaded log method that accepts Throwable objects. It will log stacktraces of exceptions and their cause for you.

For example:

import java.util.logging.Level;
import java.util.logging.Logger;

[...]

Logger logger = Logger.getAnonymousLogger();
Exception e1 = new Exception();
Exception e2 = new Exception(e1);
logger.log(Level.SEVERE, "an exception was thrown", e2);

Will log:

SEVERE: an exception was thrown
java.lang.Exception: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:21)
Caused by: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:20)

Internally, this does exactly what @philipp-wendler suggests, by the way. See the source code for SimpleFormatter.java. This is just a higher level interface.

Can I export a variable to the environment from a bash script without sourcing it?

The answer is no, but for me I did the following

the script: myExport

#! \bin\bash
export $1

an alias in my .bashrc

alias myExport='source myExport' 

Still you source it, but maybe in this way it is more useable and it is interesting for someone else.

Django DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

from django.core.exceptions import ObjectDoesNotExist
......

try:
  # try something
except ObjectDoesNotExist:
  # do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

How can I remove all objects but one from the workspace in R?

How about this?

# Removes all objects except the specified & the function itself.

rme <- function(except=NULL){
  except = ifelse(is.character(except), except, deparse(substitute(except)))
  rm(list=setdiff(ls(envir=.GlobalEnv), c(except,"rme")), envir=.GlobalEnv)
}

Spring 3 MVC resources and tag <mvc:resources />

<mvc:resources mapping="/resources/**"
               location="/, classpath:/WEB-INF/public-resources/"
               cache-period="10000" />

Put the resources under: src/main/webapp/images/logo.png and then access them via /resources/images/logo.png.

In the war they will be then located at images/logo.png. So the first location (/) form mvc:resources will pick them up.

The second location (classpath:/WEB-INF/public-resources/) in mvc:resources (looks like you used some roo based template) can be to expose resources (for example js-files) form jars, if they are located in the directory WEB-INF/public-resources in the jar.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.

Solution

Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.

Set and Get Methods in java?

I want to add to other answers that setters can be used to prevent putting the object in an invalid state.

For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:

private String taxId;

public void setTaxId(String taxId) {
    this.taxId = taxId;
}

However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:

private String taxId;

public void setTaxId(String taxId) throws IllegalArgumentException {
    if (isTaxIdValid(taxId)) {
        throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
    }
    this.taxId = taxId;
}

The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.

private final TaxId taxId = new TaxId()

public void setTaxId(String taxIdString) throws IllegalArgumentException {
    taxId.set(taxIdString); //will throw exception if not valid
}

Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:

public String getTaxId() throws IllegalStateException {
    return taxId.get(); //will throw exception if not set
}

How to normalize an array in NumPy to a unit vector?

If you work with multidimensional array following fast solution is possible.

Say we have 2D array, which we want to normalize by last axis, while some rows have zero norm.

import numpy as np
arr = np.array([
    [1, 2, 3], 
    [0, 0, 0],
    [5, 6, 7]
], dtype=np.float)

lengths = np.linalg.norm(arr, axis=-1)
print(lengths)  # [ 3.74165739  0.         10.48808848]
arr[lengths > 0] = arr[lengths > 0] / lengths[lengths > 0][:, np.newaxis]
print(arr)
# [[0.26726124 0.53452248 0.80178373]
# [0.         0.         0.        ]
# [0.47673129 0.57207755 0.66742381]]

When to use RDLC over RDL reports?

If you have a reporting services infrastructure available to you, use it. You will find RDL development to be a bit more pleasant. You can preview the report, easily setup parameters, etc.

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

Get Image Height and Width as integer values?

Try like this:

list($width, $height) = getimagesize('path_to_image');

Make sure that:

  1. You specify the correct image path there
  2. The image has read access
  3. Chmod image dir to 755

Also try to prefix path with $_SERVER["DOCUMENT_ROOT"], this helps sometimes when you are not able to read files.

How to calculate age (in years) based on Date of Birth and getDate()

DECLARE @DOB datetime
set @DOB ='11/25/1985'

select floor(
( cast(convert(varchar(8),getdate(),112) as int)-
cast(convert(varchar(8),@DOB,112) as int) ) / 10000
)

source: http://beginsql.wordpress.com/2012/04/26/how-to-calculate-age-in-sql-server/

C++ Pass A String

Just cast it as a const char *. print((const char *)"Yo!") will work fine.

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

Getting list of files in documents folder

Swift 5

// Get the document directory url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    // Get the directory contents urls (including subfolders urls)
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
    print(directoryContents)

    // if you want to filter the directory contents you can do like this:
    let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
    print("mp3 urls:",mp3Files)
    let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
    print("mp3 list:", mp3FileNames)

} catch {
    print(error)
}

Allow Access-Control-Allow-Origin header using HTML5 fetch API

I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:

#(original) var request = new Request('https://davidwalsh.name/demo/arsenal.json');
#use IP instead
var request = new Request('https://0.0.0.0/demo/arsenal.json');

fetch(request).then(function(response) {
    // Convert to JSON
    return response.json();
}).then(function(j) {
    // Yay, `j` is a JavaScript object
    console.log(JSON.stringify(j));
}).catch(function(error) {
    console.log('Request failed', error)
});

Passive Link in Angular 2 - <a href=""> equivalent

I have 4 solutions for dummy anchor tag.

    1. <a style="cursor: pointer;"></a>
    2. <a href="javascript:void(0)" ></a>
    3. <a href="current_screen_path"></a>

4.If you are using bootstrap:

<button class="btn btn-link p-0" type="button" style="cursor: pointer"(click)="doSomething()">MY Link</button>

How to convert any Object to String?

"toString()" is Very useful method which returns a string representation of an object. The "toString()" method returns a string reperentation an object.It is recommended that all subclasses override this method.

Declaration: java.lang.Object.toString()

Since, you have not mentioned which object you want to convert, so I am just using any object in sample code.

Integer integerObject = 5;
String convertedStringObject = integerObject .toString();
System.out.println(convertedStringObject );

You can find the complete code here. You can test the code here.

Are there such things as variables within an Excel formula?

I know it's a little off-topic, but following up with the solution presented by Jonas Bøhmer, actually I think that MOD is the best solution to your example.

If your intention was to limit the result to one digit, MOD is the best approach to achieve it.

ie. Let's suppose that VLOOKUP(A1, B:B, 1, 0) returns 23. Your IF formula would simply make this calculation: 23 - 10 and return 13 as the result.

On the other hand, MOD(VLOOKUP(A1, B:B, 1, 0), 10) would divide 23 by 10 and show the remainder: 3.

Back to the main topic, when I need to use a formula that repeats some part, I usually put it on another cell and then hide it as some people already suggested.

How does Spring autowire by name when more than one matching bean is found?

You can use the @Qualifier annotation

From here

Fine-tuning annotation-based autowiring with qualifiers

Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:

class Main {
    private Country country;
    @Autowired
    @Qualifier("country")
    public void setCountry(Country country) {
        this.country = country;
    }
}

This will use the UK add an id to USA bean and use that if you want the USA.

Rolling back bad changes with svn in Eclipse

In Eclipse using Subversive:

Right click your project > Team > Merge

In the merge window, select the revisions you want to revert as normally but also enable checkbox "Reversed merge".

Merge as normally.

Performance differences between ArrayList and LinkedList

I want to add an additional piece of information her about the difference in performance.

We already know that due to the fact that ArrayList implementation is backed by an Object[] it's supports random access and dynamic resizing and LinkedList implementation uses references to head and tail to navigate it. It has no random access capabilities, but it supports dynamic resizing as well.

The first thing is that with an ArrayList, you can immediately access the index, whereas with a LinkedList, you have iterate down the object chain.

Secondly, inserting into ArrayList is generally slower because it has to grow once you hit its boundaries. It will have to create a new bigger array, and copy data from the original one.

But the interesting thing is that when you create an ArrayList that is already huge enough to fit all your inserts it will obviously not involve any array copying operations. Adding to it will be even faster than with LinkedList because LinkedList will have to deal with its pointers, while huge ArrayList just sets value at given index.

enter image description here

Check out for more ArrayList and LinkedList differences.

Array slices in C#

static byte[] SliceMe(byte[] source, int length)
{
    byte[] destfoo = new byte[length];
    Array.Copy(source, 0, destfoo, 0, length);
    return destfoo;
}

//

var myslice = SliceMe(sourcearray,41);

Remove stubborn underline from link

You missed text-decoration:none for the anchor tag. So code should be following.

_x000D_
_x000D_
.boxhead a {_x000D_
    text-decoration: none;_x000D_
}
_x000D_
<div class="boxhead">_x000D_
    <h2>_x000D_
        <span class="thisPage">Current Page</span>_x000D_
        <a href="myLink"><span class="otherPage">Different Page</span></a>_x000D_
    </h2>_x000D_
</div>
_x000D_
_x000D_
_x000D_

More standard properties for text-decoration

enter image description here

TypeScript getting error TS2304: cannot find name ' require'

Quick and Dirty

If you just have one file using require, or you're doing this for demo purposes you can define require at the top of your TypeScript file.

declare var require: any

TypeScript 2.x

If you are using TypeScript 2.x you no longer need to have Typings or Definitely Typed installed. Simply install the following package.

npm install @types/node --save-dev

The Future of Declaration Files (6/15/2016)

Tools like Typings and tsd will continue to work, and we’ll be working alongside those communities to ensure a smooth transition.

Verify or Edit your src/tsconfig.app.json so that it contains the following:

...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...

Make sure is the file in the src folder and no the one on the root app folder.

By default, any package under @types is already included in your build unless you've specified either of these options. Read more

TypeScript 1.x

Using typings (DefinitelyTyped's replacement) you can specify a definition directly from a GitHub repository.

Install typings

npm install typings -g --save-dev

Install the requireJS type definition from DefinitelyType's repo

typings install dt~node --save --global

Webpack

If you are using Webpack as your build tool you can include the Webpack types.

npm install --save-dev @types/webpack-env

Update your tsconfig.json with the following under compilerOptions:

"types": [
      "webpack-env"
    ]

This allows you to do require.ensure and other Webpack specific functions.

Angular CLI

With CLI you can follow the Webpack step above and add the "types" block to your tsconfig.app.json.

Alternatively, you could use the preinstalled node types. Keep in mind this will include additional types to your client-side code that are not really available.

"compilerOptions": {
    // other options
    "types": [
      "node"
    ]
  }

What's the HTML to have a horizontal space between two objects?

I guess what you want is:

&nbsp;

But this is usually not a nice way to align some content. You better put your different content in

<div>

tags and then use css for proper alignment.


You can also check out this post with useful extra info:

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Replace string in text file using PHP

This works like a charm, fast and accurate:

function replace_string_in_file($filename, $string_to_replace, $replace_with){
    $content=file_get_contents($filename);
    $content_chunks=explode($string_to_replace, $content);
    $content=implode($replace_with, $content_chunks);
    file_put_contents($filename, $content);
}

Usage:

$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);

// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool

Get name of property as a string

I modified your solution to chain over multiple properties:

public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    MemberExpression me = propertyLambda.Body as MemberExpression;
    if (me == null)
    {
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    }

    string result = string.Empty;
    do
    {
        result = me.Member.Name + "." + result;
        me = me.Expression as MemberExpression;
    } while (me != null);

    result = result.Remove(result.Length - 1); // remove the trailing "."
    return result;
}

Usage:

string name = GetPropertyName(() => someObject.SomeProperty.SomeOtherProperty);
// returns "SomeProperty.SomeOtherProperty"

GitLab git user password

I had the right public/private key, but seemed like it didn't work anyway (got same errors, prompting for the git-user password). After a computer-restart it worked though!

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

I have the same error with you, this is my case:

~# mongod
2018-07-15T05:27:08.265+0000 I JOURNAL  [initandlisten] journal dir=/data/db/journal
2018-07-15T05:27:08.265+0000 I JOURNAL  [initandlisten] recover : no journal files present, no recovery needed
2018-07-15T05:27:08.301+0000 I JOURNAL  [durability] Durability thread started
2018-07-15T05:27:08.301+0000 I JOURNAL  [journal writer] Journal writer thread started
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] MongoDB starting : pid=26796 port=27017 dbpath=/data/db 64-bit host=ubuntu-s-2vcpu-4gb-sfo2-01
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] 
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] 
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] 
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] db version v3.0.6
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] git version: 1ef45a23a4c5e3480ac919b28afcba3c615488f2
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] build info: Linux build6.ny.cbi.10gen.cc 2.6.32-431.3.1.el6.x86_64 #1 SMP Fri Jan 3 21:39:27 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] allocator: tcmalloc
2018-07-15T05:27:08.302+0000 I CONTROL  [initandlisten] options: {}
2018-07-15T05:27:08.308+0000 I NETWORK  [initandlisten] waiting for connections on port 27017

I type mongod to start the server, and I type control + c to exit to shell

then I type mongo and I got

~# mongo
MongoDB shell version: 3.0.6
connecting to: test
2018-07-15T05:05:02.738+0000 W NETWORK  Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2018-07-15T05:05:02.739+0000 E QUERY    Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed
    at connect (src/mongo/shell/mongo.js:179:14)
    at (connect):1:6 at src/mongo/shell/mongo.js:179

As you can see, my error info is same with you.

This is case mongod doesn't start with backend process, when I type control + c I quit mongod.

We can add --fork args to make the process daemon process.

#  mongod --logpath /usr/local/mongodb/log.txt --fork

you have to set --logpath if you want to use --fork

then you will success to connect to mongo

MySQL error 2006: mysql server has gone away

The unlikely scenario is you have a firewall between the client and the server that forces TCP reset into the connection.

I had that issue, and I found our corporate F5 firewall was configured to terminate inactive sessions that is idle for more than 5 mins.

Once again, this is the unlikely scenario.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

First drop your foreign key and try your above command, put add constraint instead of modify constraint. Now this is the command:

ALTER TABLE child_table_name 
  ADD CONSTRAINT fk_name 
  FOREIGN KEY (child_column_name) 
  REFERENCES parent_table_name(parent_column_name) 
  ON DELETE CASCADE;

Why does jQuery or a DOM method such as getElementById not find the element?

The element you were trying to find wasn’t in the DOM when your script ran.

The position of your DOM-reliant script can have a profound effect upon its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements which appear later in the markup because those elements have yet to be added to the DOM.

Consider the following markup; script #1 fails to find the <div> while script #2 succeeds:

_x000D_
_x000D_
<script>_x000D_
  console.log("script #1: %o", document.getElementById("test")); // null_x000D_
</script>_x000D_
<div id="test">test div</div>_x000D_
<script>_x000D_
  console.log("script #2: %o", document.getElementById("test")); // <div id="test" ..._x000D_
</script>
_x000D_
_x000D_
_x000D_

So, what should you do? You've got a few options:


Option 1: Move your script

Move your script further down the page, just before the closing body tag. Organized in this fashion, the rest of the document is parsed before your script is executed:

_x000D_
_x000D_
<body>_x000D_
  <button id="test">click me</button>_x000D_
  <script>_x000D_
    document.getElementById("test").addEventListener("click", function() {_x000D_
      console.log("clicked: %o", this);_x000D_
    });_x000D_
  </script>_x000D_
</body><!-- closing body tag -->
_x000D_
_x000D_
_x000D_

Note: Placing scripts at the bottom is generally considered a best practice.


Option 2: jQuery's ready()

Defer your script until the DOM has been completely parsed, using $(handler):

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
  $(function() {_x000D_
    $("#test").click(function() {_x000D_
      console.log("clicked: %o", this);_x000D_
    });_x000D_
  });_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

Note: You could simply bind to DOMContentLoaded or window.onload but each has its caveats. jQuery's ready() delivers a hybrid solution.


Option 3: Event Delegation

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

When an element raises an event (provided that it's a bubbling event and nothing stops its propagation), each parent in that element's ancestry receives the event as well. That allows us to attach a handler to an existing element and sample events as they bubble up from its descendants... even those added after the handler is attached. All we have to do is check the event to see whether it was raised by the desired element and, if so, run our code.

jQuery's on() performs that logic for us. We simply provide an event name, a selector for the desired descendant, and an event handler:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
  $(document).on("click", "#test", function(e) {_x000D_
    console.log("clicked: %o",  this);_x000D_
  });_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

Note: Typically, this pattern is reserved for elements which didn't exist at load-time or to avoid attaching a large amount of handlers. It's also worth pointing out that while I've attached a handler to document (for demonstrative purposes), you should select the nearest reliable ancestor.


Option 4: The defer attribute

Use the defer attribute of <script>.

[defer, a Boolean attribute,] is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

_x000D_
_x000D_
<script src="https://gh-canon.github.io/misc-demos/log-test-click.js" defer></script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

For reference, here's the code from that external script:

document.getElementById("test").addEventListener("click", function(e){
   console.log("clicked: %o", this); 
});

Note: The defer attribute certainly seems like a magic bullet but it's important to be aware of the caveats...
1. defer can only be used for external scripts, i.e.: those having a src attribute.
2. be aware of browser support, i.e.: buggy implementation in IE < 10

Sorted collection in Java

import java.util.TreeSet;

public class Ass3 {
    TreeSet<String>str=new TreeSet<String>();
    str.add("dog");
    str.add("doonkey");
    str.add("rat");
    str.add("rabbit");
    str.add("elephant");
    System.out.println(str);    
}

MySQL: Set user variable from result of query

Yes, but you need to move the variable assignment into the query:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

Test case:

CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);

Result:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

+--------+-------+
| user   | group |
+--------+-------+
| 123456 |     5 |
| 111111 |     5 |
+--------+-------+
2 rows in set (0.00 sec)

Note that for SET, either = or := can be used as the assignment operator. However inside other statements, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements.


UPDATE:

Further to comments below, you may also do the following:

SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group; 
SELECT * FROM user WHERE `group` = @group;

Can we execute a java program without a main() method?

You should also be able to accomplish a similar thing using the premain method of a Java agent.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.

Get Line Number of certain phrase in file Python

Here's what I've found to work:

f_rd = open(path, 'r')
file_lines = f_rd.readlines()
f_rd.close()

matches = [line for line in file_lines if "chars of Interest" in line]
index = file_lines.index(matches[0])

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

Out of the box Swift Mailer can't do STARTTLS, however some nice guys have written a patch for it.

I found patching it was a bit of a chore (probably went about it the wrong way), so have zipped it up ready for download here: Swift Mailer with STARTTLS

Redirecting to a page after submitting form in HTML

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

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

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

What is the difference between git clone and checkout?

One thing to notice is the lack of any "Copyout" within git. That's because you already have a full copy in your local repo - your local repo being a clone of your chosen upstream repo. So you have effectively a personal checkout of everything, without putting some 'lock' on those files in the reference repo.

Git provides the SHA1 hash values as the mechanism for verifying that the copy you have of a file / directory tree / commit / repo is exactly the same as that used by whoever is able to declare things as "Master" within the hierarchy of trust. This avoids all those 'locks' that cause most SCM systems to choke (with the usual problems of private copies, big merges, and no real control or management of source code ;-) !

How does true/false work in PHP?

This is covered in the PHP documentation for booleans and type comparison tables.

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string '0'
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE.

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

What is a user agent stylesheet?

Put the following code in your CSS file:

table {
    font-size: inherit;
}

Compare two objects in Java with possible null values

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.

Measuring execution time of a function in C++

It is a very easy-to-use method in C++11. You have to use std::chrono::high_resolution_clock from <chrono> header.

Use it like so:

#include <iostream>
#include <chrono>

void function()
{
    long long number = 0;

    for( long long i = 0; i != 2000000; ++i )
    {
       number += 5;
    }
}

int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    function();
    auto t2 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration;
    return 0;
}

This will measure the duration of the function.

NOTE: You will not always get the same timing for a function. This is because the CPU of your machine can be less or more used by other processes running on your computer, just as your mind can be more or less concentrated when you solve a math exercise. In the human mind, we can remember the solution of a math problem, but for a computer the same process will always be something new; thus, as I said, you will not always get the same result!

Simple Java Client/Server Program

you can get ip of that computer runs server program from DHCP list in that router you connected to.

How to insert values into the database table using VBA in MS access

since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.

Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario

Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer

InDate = Me.FromDateTxt

StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"

DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True

Javascript extends class

Douglas Crockford has some very good explanations of inheritance in JavaScript:

  1. prototypal inheritance: the 'natural' way to do things in JavaScript
  2. classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript

In Angular, how to redirect with $location.path as $http.post success callback

Here is the changeLocation example from this article http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase

//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
  $scope = $scope || angular.element(document).scope();
  if(forceReload || $scope.$$phase) {
    window.location = url;
  }
  else {
    //only use this if you want to replace the history stack
    //$location.path(url).replace();

    //this this if you want to change the URL and add it to the history stack
    $location.path(url);
    $scope.$apply();
  }
};

is it possible to update UIButton title/text programmatically?

Even though Caffeine Coma's issue was resolved, I would like to offer another potential cause for the title not showing up on a UIButton.

If you set an image for the UIButton using

- (void)setImage:(UIImage *)image forState:(UIControlState)state

It can cover the title. I found this out the hard way and imagine some of you end up reading this page for the same reason.

Use this method instead

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state

for the button image and the title will not be affected.

I tested this with programmatically created buttons and buttons created in a .xib

SELECT where row value contains string MySQL

This should work:

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

libpthread.so.0: error adding symbols: DSO missing from command line

I found another case and therefore I thing you are all wrong.

This is what I had:

/usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-linux/bin/ld: eggtrayicon.o: undefined reference to symbol 'XFlush'
/usr/lib64/libX11.so.6: error adding symbols: DSO missing from command line

The problem is that the command line DID NOT contain -lX11 - although the libX11.so should be added as a dependency because there were also GTK and GNOME libraries in the arguments.

So, the only explanation for me is that this message might have been intended to help you, but it didn't do it properly. This was probably simple: the library that provides the symbol was not added to the command line.

Please note three important rules concerning linkage in POSIX:

  • Dynamic libraries have defined dependencies, so only libraries from the top-dependency should be supplied in whatever order (although after the static libraries)
  • Static libraries have just undefined symbols - it's up to you to know their dependencies and supply all of them in the command line
  • The order in static libraries is always: requester first, provider follows. Otherwise you'll get undefined symbol message, just like when you forgot to add the library to the command line
  • When you specify the library with -l<name>, you never know whether it will take lib<name>.so or lib<name>.a. The dynamic library is preferred, if found, and static libraries only can be enforced by compiler option - that's all. And whether you have any problems as above, it depends on whether you had static or dynamic libraries
  • Well, sometimes the dependencies may be lacking in dynamic libraries :D

How to check if input is numeric in C++

I find myself using boost::lexical_cast for this sort of thing all the time these days. Example:

std::string input;
std::getline(std::cin,input);
int input_value;
try {
  input_value=boost::lexical_cast<int>(input));
} catch(boost::bad_lexical_cast &) {
  // Deal with bad input here
}

The pattern works just as well for your own classes too, provided they meet some simple requirements (streamability in the necessary direction, and default and copy constructors).

Adding extra zeros in front of a number using jQuery?

function addLeadingZeros (n, length)
{
    var str = (n > 0 ? n : -n) + "";
    var zeros = "";
    for (var i = length - str.length; i > 0; i--)
        zeros += "0";
    zeros += str;
    return n >= 0 ? zeros : "-" + zeros;
}

//addLeadingZeros (1, 3) =   "001"
//addLeadingZeros (12, 3) =  "012"
//addLeadingZeros (123, 3) = "123"

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

Encountered this issue in chrome. Resolved by cleaning up related cookies. Note that you don't have to cleanup ALL your cookies.

Why can't I do <img src="C:/localfile.jpg">?

You need to upload the image aswell, then link to the image on the server.

What's the difference between isset() and array_key_exists()?

Answer to an old question as no answer here seem to address the 'warning' problem (explanation follows)

Basically, in this case of checking if a key exists in an array, isset

  • tells if the expression (array) is defined, and the key is set
  • no warning or error if the var is not defined, not an array ...
  • but returns false if the value for that key is null

and array_key_exists

  • tells if a key exists in an array as the name implies
  • but gives a warning if the array parameter is not an array

So how do we check if a key exists which value may be null in a variable

  • that may or may not be an array
  • (or similarly is a multidimensional array for which the key check happens at dim 2 and dim 1 value may not be an array for the 1st dim (etc...))

without getting a warning, without missing the existing key when its value is null (what were the PHP devs thinking would also be an interesting question, but certainly not relevant on SO). And of course we don't want to use @

isset($var[$key]);            // silent but misses null values
array_key_exists($key, $var); // works but warning if $var not defined/array

It seems is_array should be involved in the equation, but it gives a warning if $var is not defined, so that could be a solution:

if (isset($var[$key]) || 
    isset($var) && is_array($var) && array_key_exists($key, $var)) ...

which is likely to be faster if the tests are mainly on non-null values. Otherwise for an array with mostly null values

if (isset($var) && is_array($var) && array_key_exists($key, $var)) ...

will do the work.

How to document a method with parameter(s)?

If you plan to use Sphinx to document your code, it is capable of producing nicely formatted HTML docs for your parameters with their 'signatures' feature. http://sphinx-doc.org/domains.html#signatures

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

What is the effect of extern "C" in C++?

extern "C" is meant to be recognized by a C++ compiler and to notify the compiler that the noted function is (or will be) compiled in C style, so that while linking, it links to the correct version of the function from C.

Hide axis and gridlines Highcharts

This has always worked well for me:

yAxes: [{
         ticks: {
                 display: false;
                },

How to sort a Ruby Hash by number value?

Already answered but still. Change your code to:

metrics.sort {|a1,a2| a2[1].to_i <=> a1[1].to_i }

Converted to strings along the way or not, this will do the job.

JSP : JSTL's <c:out> tag

c:out escapes HTML characters so that you can avoid cross-site scripting.

if person.name = <script>alert("Yo")</script>

the script will be executed in the second case, but not when using c:out

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

A reference to the dll could not be added

I had the same problem when I tried to add a dll I just coded in C++ to my new C# project. Turned out I needed to set properties of the C++ project my dll is from:

  • Configuration Properties\General\Common Language Runtime Support: /clr
  • Configuration Properties\C/C++\General\Common Language RunTime Support: /clr

Because the C# project in which I wanted to use this dll was also set like that (had the same properties set to /clr).

Detect enter press in JTextField

First add action command on JButton or JTextField by:

JButton.setActionCommand("name of command");
JTextField.setActionCommand("name of command");

Then add ActionListener to both JTextField and JButton.

JButton.addActionListener(listener);
JTextField.addActionListener(listener);

After that, On you ActionListener implementation write

@Override
public void actionPerformed(ActionEvent e)
{
    String actionCommand = e.getActionCommand();

    if(actionCommand.equals("Your actionCommand for JButton") || actionCommand.equals("Your   actionCommand for press Enter"))
    {
        //Do something
    }
}

How to create websockets server in PHP

I was in the same boat as you recently, and here is what I did:

  1. I used the phpwebsockets code as a reference for how to structure the server-side code. (You seem to already be doing this, and as you noted, the code doesn't actually work for a variety of reasons.)

  2. I used PHP.net to read the details about every socket function used in the phpwebsockets code. By doing this, I was finally able to understand how the whole system works conceptually. This was a pretty big hurdle.

  3. I read the actual WebSocket draft. I had to read this thing a bunch of times before it finally started to sink in. You will likely have to go back to this document again and again throughout the process, as it is the one definitive resource with correct, up-to-date information about the WebSocket API.

  4. I coded the proper handshake procedure based on the instructions in the draft in #3. This wasn't too bad.

  5. I kept getting a bunch of garbled text sent from the clients to the server after the handshake and I couldn't figure out why until I realized that the data is encoded and must be unmasked. The following link helped me a lot here: (original link broken) Archived copy.

    Please note that the code available at this link has a number of problems and won't work properly without further modification.

  6. I then came across the following SO thread, which clearly explains how to properly encode and decode messages being sent back and forth: How can I send and receive WebSocket messages on the server side?

    This link was really helpful. I recommend consulting it while looking at the WebSocket draft. It'll help make more sense out of what the draft is saying.

  7. I was almost done at this point, but had some issues with a WebRTC app I was making using WebSocket, so I ended up asking my own question on SO, which I eventually solved: What is this data at the end of WebRTC candidate info?

  8. At this point, I pretty much had it all working. I just had to add some additional logic for handling the closing of connections, and I was done.

That process took me about two weeks total. The good news is that I understand WebSocket really well now and I was able to make my own client and server scripts from scratch that work great. Hopefully the culmination of all that information will give you enough guidance and information to code your own WebSocket PHP script.

Good luck!


Edit: This edit is a couple of years after my original answer, and while I do still have a working solution, it's not really ready for sharing. Luckily, someone else on GitHub has almost identical code to mine (but much cleaner), so I recommend using the following code for a working PHP WebSocket solution:
https://github.com/ghedipunk/PHP-Websockets/blob/master/websockets.php


Edit #2: While I still enjoy using PHP for a lot of server-side related things, I have to admit that I've really warmed up to Node.js a lot recently, and the main reason is because it's better designed from the ground up to handle WebSocket than PHP (or any other server-side language). As such, I've found recently that it's a lot easier to set up both Apache/PHP and Node.js on your server and use Node.js for running the WebSocket server and Apache/PHP for everything else. And in the case where you're on a shared hosting environment in which you can't install/use Node.js for WebSocket, you can use a free service like Heroku to set up a Node.js WebSocket server and make cross-domain requests to it from your server. Just make sure if you do that to set your WebSocket server up to be able to handle cross-origin requests.

How to pass url arguments (query string) to a HTTP request on Angular?

In latest Angular 7/8, you can use the simplest approach:-

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

getDetails(searchParams) {
    const httpOptions = {
        headers: { 'Content-Type': 'application/json' },
        params: { ...searchParams}
    };
    return this.http.get(this.Url, httpOptions);
}

Select All as default value for Multivalue parameter

Adding to the answer from E_8.
This does not work if you have empty strings.

You can get around this by modifying your select statement in SQL or modifying your query in the SSRS dataset.

 Select distinct phonenumber
from YourTable
where phonenumber <> ''
Order by Phonenumber

Running Java Program from Command Line Linux

What is the package name of your class? If there is no package name, then most likely the solution is:

java -cp FileManagement Main

Printing 1 to 1000 without loop or conditionals

#include <iostream>
#include <iterator>
using namespace std;

int num() { static int i = 1; return i++; }
int main() { generate_n(ostream_iterator<int>(cout, "\n"), 1000, num); }

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

C#: Looping through lines of multiline string

Sometimes I think we can overcomplicate the solution just to avoid repeating one line of code. This is the reason I landed on this question in the first place.

After thinking about it for a bit I came to the conclusion that the simplest solution is to repeat the ReadLine before and inside the loop.

using (var stringReader = new StringReader(input))
{
    var line = await stringReader.ReadLineAsync();

    while (line != null)
    {
        // do something
        line = await stringReader.ReadLineAsync();
    }
}

I realize this might be considered to not follow the DRY principle, but I think it's worth considering given the simplicity.

In C - check if a char exists in a char array

use strchr function when dealing with C strings.

const char * strchr ( const char * str, int character );

Here is an example of what you want to do.

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char invalids[] = ".@<>#";
  char * pch;
  pch=strchr(invalids,'s');//is s an invalid character?
  if (pch!=NULL)
  {
    printf ("Invalid character");
  }
  else 
  {
     printf("Valid character");
  } 
  return 0;
}

Use memchr when dealing with memory blocks (as not null terminated arrays)

const void * memchr ( const void * ptr, int value, size_t num );

/* memchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char * pch;
  char invalids[] = "@<>#";
  pch = (char*) memchr (invalids, 'p', strlen(invalids));
  if (pch!=NULL)
    printf (p is an invalid character);
  else
    printf ("p valid character.\n");
  return 0;
}

http://www.cplusplus.com/reference/clibrary/cstring/memchr/

http://www.cplusplus.com/reference/clibrary/cstring/strchr/

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

  1. NSLog - add meta info (like timestamp and identifier) and allows you to output 1023 symbols. Also print message into Console. The slowest method
@import Foundation
NSLog("SomeString")
  1. print - prints all string to Xcode. Has better performance than previous
@import Foundation
print("SomeString")
  1. println (only available Swift v1) and add \n at the end of string
  2. os_log (from iOS v10) - prints 32768 symbols also prints to console. Has better performance than previous
@import os.log
os_log("SomeIntro: %@", log: .default, type: .info, "someString")
  1. Logger (from iOS v14) - prints 32768 symbols also prints to console. Has better performance than previous
@import os
let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "someCategory")
logger.log("\(s)")

Converting string to tuple without splitting characters

This only covers a simple case:

a = ‘Quattro TT’
print tuple(a)

If you use only delimiter like ‘,’, then it could work.

I used a string from configparser like so:

list_users = (‘test1’, ‘test2’, ‘test3’)
and the i get from file
tmp = config_ob.get(section_name, option_name)
>>>”(‘test1’, ‘test2’, ‘test3’)”

In this case the above solution does not work. However, this does work:

def fot_tuple(self, some_str):
     # (‘test1’, ‘test2’, ‘test3’)
     some_str = some_str.replace(‘(‘, ”)
     # ‘test1’, ‘test2’, ‘test3’)
     some_str = some_str.replace(‘)’, ”)
     # ‘test1’, ‘test2’, ‘test3’
     some_str = some_str.replace(“‘, ‘”, ‘,’)
     # ‘test1,test2,test3’
     some_str = some_str.replace(“‘”, ‘,’)
     # test1,test2,test3
     # and now i could convert to tuple
     return tuple(item for item in some_str.split(‘,’) if item.strip())

Generate MD5 hash string with T-SQL

For data up to 8000 characters use:

CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)

Demo

For binary data (without the limit of 8000 bytes) use:

CONVERT(VARCHAR(32), master.sys.fn_repl_hash_binary(@binary_data), 2)

Demo

Return a string method in C#

These answers are all way too complicated!

The way he wrote the method is fine. The problem is where he invoked the method. He did not include parentheses after the method name, so the compiler thought he was trying to get a value from a variable instead of a method.

In Visual Basic and Delphi, those parentheses are optional, but in C#, they are required. So, to correct the last line of the original post:

Console.WriteLine("{0}", x.fullNameMethod());

What is the difference between a port and a socket?

A port is an entity that is used by networking protocols to attain access to connected hosts. Ports could be application-specific or related to a certain communication medium. Different protocols use different ports to access the hosts, like HTTP uses port 80 or FTP uses port 23. You can assign user-defined port numbers in your application, but they should be above 1023.

Ports open up the connection to the required host while sockets are an endpoint in an inter-network or an inter-process communication. Sockets are assigned by APIs(Application Programming Interface) by the system.

A more subtle difference can be made saying that, when a system is rebooted ports will be present while the sockets will be destroyed.