Programs & Examples On #Designated initializer

In Cocoa programming, a designated initializer is the method through which all of the instance's initial parameters can be set. A designated initializer is typically executed implicitly when not called explicitly. In C programming, designated initializers refer to a certain way of struct/union/array initialization, which allows the programmer to to initialize an element by using its name or index.

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

<project>

    <!-- ... -->

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

T-SQL - function with default parameters

you have to call it like this

SELECT dbo.CheckIfSFExists(23, default)

From Technet:

When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called in order to retrieve the default value. This behaviour is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. An exception to this behaviour is when invoking a scalar function by using the EXECUTE statement. When using EXECUTE, the DEFAULT keyword is not required.

How to split a String by space

Since it's been a while since these answers were posted, here's another more current way to do what's asked:

List<String> output = new ArrayList<>();
try (Scanner sc = new Scanner(inputString)) {
    while (sc.hasNext()) output.add(sc.next());
}

Now you have a list of strings (which is arguably better than an array); if you do need an array, you can do output.toArray(new String[0]);

Apache Prefork vs Worker MPM

Apache's Multi-Processing Modules (MPMs) are responsible for binding to network ports on the machine, accepting requests, and dispatching children to handle the requests (http://httpd.apache.org/docs/2.2/mpm.html).

They're like any other Apache module, except that just one and only one MPM must be loaded into the server at any time. MPMs are chosen during configuration and compiled into the server by using the argument --with-mpm=NAME with the configure script where NAME is the name of the desired MPM.

Apache will use a default MPM for each operating system unless a different one is choosen at compile-time (for instance on Windows mpm_winnt is used by default). Here's the list of operating systems and their default MPMs:

  • BeOS beos
  • Netware mpm_netware
  • OS/2 mpmt_os2
  • Unix/Linux prefork (update for Apache version = 2.4: prefork, worker, or event, depending on platform capabilities)
  • Windows mpm_winnt

To check what modules are compiled into the server use the command-line option -l (here is the documentation). For instance on a Windows installation you might get something like:

> httpd -l
Compiled in modules:
  core.c
  mod_win32.c
  mpm_winnt.c
  http_core.c
  mod_so.c

As of version 2.2 this is the list of available core features and MPM modules:

  • core - Core Apache HTTP Server features that are always available
  • mpm_common - A collection of directives that are implemented by more than one multi-processing module (MPM)
  • beos - This Multi-Processing Module is optimized for BeOS.
  • event - An experimental variant of the standard worker MPM
  • mpm_netware Multi-Processing Module implementing an exclusively threaded web server optimized for Novell NetWare
  • mpmt_os2 Hybrid multi-process, multi-threaded MPM for OS/2
  • prefork Implements a non-threaded, pre-forking web server
  • mpm_winnt - This Multi-Processing Module is optimized for Windows NT.
  • worker - Multi-Processing Module implementing a hybrid multi-threaded multi-process web server

Now, to the difference between prefork and worker.

The prefork MPM

implements a non-threaded, pre-forking web server that handles requests in a manner similar to Apache 1.3. It is appropriate for sites that need to avoid threading for compatibility with non-thread-safe libraries. It is also the best MPM for isolating each request, so that a problem with a single request will not affect any other.

The worker MPM implements a hybrid multi-process multi-threaded server and gives better performance, hence it should be preferred unless one is using other modules that contain non-thread-safe libraries (see also this discussion or this on Serverfault).

Detecting the character encoding of an HTTP POST request

Try setting the charset on your Content-Type:

httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );

Concatenating Files And Insert New Line In Between Files

This works in Bash:

for f in *.txt; do cat $f; echo; done

In contrast to answers with >> (append), the output of this command can be piped into other programs.

Examples:

  • for f in File*.txt; do cat $f; echo; done > finalfile.txt
  • (for ... done) > finalfile.txt (parens are optional)
  • for ... done | less (piping into less)
  • for ... done | head -n -1 (this strips off the trailing blank line)

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

As we recently posted on the React blog, in the vast majority of cases you don't need getDerivedStateFromProps at all.

If you just want to compute some derived data, either:

  1. Do it right inside render
  2. Or, if re-calculating it is expensive, use a memoization helper like memoize-one.

Here's the simplest "after" example:

import memoize from "memoize-one";

class ExampleComponent extends React.Component {
  getDerivedData = memoize(computeDerivedState);

  render() {
    const derivedData = this.getDerivedData(this.props.someValue);
    // ...
  }
}

Check out this section of the blog post to learn more.

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

href image link download on click

<a download="custom-filename.jpg" href="/path/to/image" title="ImageName">
    <img alt="ImageName" src="/path/to/image">
</a>

It's not yet fully supported caniuse, but you can use with modernizr (under Non-core detects) to check the support of the browser.

Border Radius of Table is not working

To use border radius I have a border radius of 20px in the table, and then put the border radius on the first child of the table header (th) and the last child of the table header.

table {
  border-collapse: collapse;
  border-radius:20px;
  padding: 10px;
}

table th:first-child {
  /* border-radius = top left, top right, bottom right, bottom left */
    border-radius: 20px 0 0 0; /* curves the top left */
    padding-left: 15px;
}

table th:last-child {
    border-radius: 0 20px 0 0; /* curves the top right */
}

This however will not work if this is done with table data (td) because it will add a curve onto each table row. This is not a problem if you only have 2 rows in your table but any additional ones will add curves onto the inner rows too. You only want these curves on the outside of the table. So for this, add an id to your last row. Then you can apply the curves to them.

/* curves the first tableData in the last row */

#lastRow td:first-child {
    border-radius: 0 0 0 20px; /* bottom left curve */
}

/* curves the last tableData in the last row */

#lastRow td:last-child {
    border-radius: 0 0 20px 0; /* bottom right curve */
}

How can I set the value of a DropDownList using jQuery?

Best answer for the question:

$("#comboboxid").val(yourvalue).trigger("chosen:updated");

e.g:

$("#CityID").val(20).trigger("chosen:updated");

or

$("#CityID").val("chicago").trigger("chosen:updated");

How to bind a List to a ComboBox?

public MainWindow(){
    List<person> personList = new List<person>();

    personList.Add(new person { name = "rob", age = 32 } );
    personList.Add(new person { name = "annie", age = 24 } );
    personList.Add(new person { name = "paul", age = 19 } );

    comboBox1.DataSource = personList;
    comboBox1.DisplayMember = "name";

    comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged);
}


void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    person selectedPerson = comboBox1.SelectedItem as person;
    messageBox.Show(selectedPerson.name, "caption goes here");
}

boom.

How do I restrict an input to only accept numbers?

   <input type="text" name="profileChildCount" id="profileChildCount" ng-model="profile.ChildCount" numeric-only maxlength="1" />

you can use numeric-only attribute .

How to implement "select all" check box in HTML?

<html>

<head>
<script type="text/javascript">

    function do_this(){

        var checkboxes = document.getElementsByName('approve[]');
        var button = document.getElementById('toggle');

        if(button.value == 'select'){
            for (var i in checkboxes){
                checkboxes[i].checked = 'FALSE';
            }
            button.value = 'deselect'
        }else{
            for (var i in checkboxes){
                checkboxes[i].checked = '';
            }
            button.value = 'select';
        }
    }
</script>
</head>

<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />

<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>

</html>

DataGridView checkbox column - value and functionality

If you try it on CellContentClick Event

Use:

dataGridView1.EndEdit();  //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());

Get domain name

 protected void Page_Init(object sender, EventArgs e)
 {
   String hostdet = Request.ServerVariables["HTTP_HOST"].ToString();
 }

PowerShell script to return members of multiple security groups

This will give you a list of a single group, and the members of each group.

param
(   
    [Parameter(Mandatory=$true,position=0)]
    [String]$GroupName
)

import-module activedirectory

# optional, add a wild card..
# $groups = $groups + "*"

$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name

ForEach ($Group in $Groups)
   {write-host " "
    write-host "$($group.name)"
    write-host "----------------------------"

    Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname

 }
write-host "Export Complete"

If you want the friendly name, or other details, add them to the end of the select-object query.

C# Equivalent of SQL Server DataTypes

SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework Decimal structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. Click Here's a link! for detail

https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

How can I execute a PHP function in a form action?

Is it really a function call on the action attribute? or it should be on the onSUbmit attribute, because by convention action attribute needs a page/URL.

I think you should use AJAX with that,

There are plenty PHP AJAX Frameworks to choose from

http://www.phplivex.com/example/submitting-html-forms-with-ajax

http://www.xajax-project.org/en/docs-tutorials/learn-xajax-in-10-minutes/

ETC.

Or the classic way

http://www.w3schools.com/php/php_ajax_php.asp

I hope these links help

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

If you are just interested in the use of Access-Control-Allow-Origin:*

You can do that with this .htaccess file at the site root.

Header set Access-Control-Allow-Origin "*"

Some useful information here: http://enable-cors.org/server_apache.html

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

You have more static resources that the cache has room for. You can do one of the following:

  • Increase the size of the cache
  • Decrease the TTL for the cache
  • Disable caching

For more details see the documentation for these configuration options.

How to pass parameters to a Script tag?

If you are using jquery you might want to consider their data method.

I have used something similar to what you are trying in your response but like this:

<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>

You could also create a function that lets you grab the GET params directly (this is what I frequently use):

function $_GET(q,s) {
    s = s || window.location.search;
    var re = new RegExp('&'+q+'=([^&]*)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}

// Grab the GET param
var param_a = $_GET('param_a');

Callback functions in Java

yet i see there is most preferred way which was what i was looking for.. it's basically derived from these answers but i had to manipulate it to more more redundant and efficient.. and i think everybody looking for what i come up with

To the point::

first make an Interface that simple

public interface myCallback {
    void onSuccess();
    void onError(String err);
}

now to make this callback run when ever you wish to do to handle the results - more likely after async call and you wanna run some stuff which depends on these reuslts

// import the Interface class here

public class App {

    public static void main(String[] args) {
        // call your method
        doSomething("list your Params", new myCallback(){
            @Override
            public void onSuccess() {
                // no errors
                System.out.println("Done");
            }

            @Override
            public void onError(String err) {
                // error happen
                System.out.println(err);
            }
        });
    }

    private void doSomething(String param, // some params..
                             myCallback callback) {
        // now call onSuccess whenever you want if results are ready
        if(results_success)
            callback.onSuccess();
        else
            callback.onError(someError);
    }

}

doSomething is the function that takes some time you wanna add a callback to it to notify you when the results came, add the call back interface as a parameter to this method

hope my point is clear, enjoy ;)

How do I remove an object from an array with JavaScript?

Use delete-keyword.

delete obj[1];

EDIT: see: Deleting array elements in JavaScript - delete vs splice delete will undefine the offset but not completly remove the entry. Splice would be correct like David said.

Can I serve multiple clients using just Flask app.run() as standalone?

Using the simple app.run() from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason.

Spawning threads and managing them yourself is probably not going to get you very far either, because of the Python GIL.

That said, you do still have some good options. Gunicorn is a solid, easy-to-use WSGI server that will let you spawn multiple workers (separate processes, so no GIL worries), and even comes with asynchronous workers that will speed up your app (and make it more secure) with little to no work on your part (especially with Flask).

Still, even Gunicorn should probably not be directly publicly exposed. In production, it should be used behind a more robust HTTP server; nginx tends to go well with Gunicorn and Flask.

Stopping python using ctrl+c

If it is running in the Python shell use Ctrl + Z, otherwise locate the python process and kill it.

Decrementing for loops

You need to give the range a -1 step

 for i in range(10,0,-1):
    print i

IntelliJ does not show 'Class' when we right click and select 'New'

The directory or one of the parent directories must be marked as Source Root (In this case, it appears in blue).

If this is not the case, right click your root source directory -> Mark As -> Source Root.

python how to "negate" value : if true return false, if false return true

In python, not is a boolean operator which gets the opposite of a value:

>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False

And True == 1 and False == 0 (if you need to convert it to an integer, you can use int())

SQL Server - Convert date field to UTC

As mentioned here previously, there is no build-in way to perform time zone rules aware date conversion in SQL Server (at least as of SQL Server 2012).

You have essentially three choices to do this right:

  1. Perform the conversion outside of SQL Server and store results in the database
  2. Introduce time zone offset rules in a standalone table and create stored procedures or UDFs to reference the rules table to perform conversions. You can find one take on this approach over at SQL Server Central (registration required)
  3. You can create a SQL CLR UDF; I will describe the approach here

While SQL Server does not offer tools to perform time zone rules aware date conversion, the .NET framework does, and as long as you can use SQL CLR, you can take advantage of that.

In Visual Studio 2012, make sure you have the data tools installed (otherwise, SQL Server project won't show up as an option), and create a new SQL Server project.

Then, add a new SQL CLR C# User Defined Function, call it "ConvertToUtc". VS will generate boiler plate for you that should look something like this:

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString ConvertToUtc()
    {
        // Put your code here
        return new SqlString (string.Empty);
    }
}

We want to make several changes here. For one, we want to return a SqlDateTime rather than a SqlString. Secondly, we want to do something useful. :)

Your revised code should look like this:

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlDateTime ConvertToUtc(SqlDateTime sqlLocalDate)
    {
        // convert to UTC and use explicit conversion
        // to return a SqlDateTime
        return TimeZone.CurrentTimeZone.ToUniversalTime(sqlLocalDate.Value);
    }
}

At this point, we are ready to try it out. The simplest way is to use the built-in Publish facility in Visual Studio. Right-click on the database project and select "Publish". Set up your database connection and name, and then either click "Publish" to push the code into the database or click "Generate Script" if you'd like to store the script for posterity (or to push the bits into production).

Once you have the UDF in the database, you can see it in action:

declare @dt as datetime
set @dt = '12/1/2013 1:00 pm'
select dbo.ConvertToUtc(@dt)

how to refresh my datagridview after I add new data

If you using formview or something similar you can databind the gridview on the iteminserted event of the formview too. Like below

protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
    {
        GridView1.DataBind();
    }

You can do this on the data source iteminserted too.

How to design RESTful search/filtering?

If you use the request body in a GET request, you're breaking the REST principle, because your GET request won't be able to be cached, because cache system uses only the URL.

What's worse, your URL can't be bookmarked, because the URL doesn't contain all the information needed to redirect the user to this page.

Use URL or Query parameters instead of request body parameters, e.g.:

/myapp?var1=xxxx&var2=xxxx
/myapp;var1=xxxx/resource;var2=xxxx 

In fact, the HTTP RFC 7231 says that:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

For more information take a look here.

jQuery: select an element's class and id at the same time?

You can do:

$("#country.save")...

OR

$("a#country.save")...

OR

$("a.save#country")...

as you prefer.

So yes you can specify a selector that has to match ID and class (and potentially tag name and anything else you want to throw in).

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

Insert PHP code In WordPress Page and Post

When I was trying to accomplish something very similar, I ended up doing something along these lines:

wp-content/themes/resources/functions.php

add_action('init', 'my_php_function');
function my_php_function() {
    if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
        // add desired php code here
    }
}

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

As said by Faiyaz, to get default backup location for the instance, you cannot get it into msdb, but you have to look into Registry. You can get it in T-SQL in using xp_instance_regread stored procedure like this:

EXEC  master.dbo.xp_instance_regread 
      N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQLServer',N'BackupDirectory'

The double backslash (\\) is because the spaces into that key name part (Microsoft SQL Server). The "MSSQL12.MSSQLSERVER" part is for default instance name for SQL 2014. You have to adapt to put your own instance name (look into Registry).

Add directives from directive in AngularJS

Try storing the state in a attribute on the element itself, such as superDirectiveStatus="true"

For example:

angular.module('app')
  .directive('superDirective', function ($compile, $injector) {
    return {
      restrict: 'A',
      replace: true,
      link: function compile(scope, element, attrs) {
        if (element.attr('datepicker')) { // check
          return;
        }
        var status = element.attr('superDirectiveStatus');
        if( status !== "true" ){
             element.attr('datepicker', 'someValue');
             element.attr('datepicker-language', 'en');
             // some more
             element.attr('superDirectiveStatus','true');
             $compile(element)(scope);

        }

      }
    };
  });

I hope this helps you.

How to get a unix script to run every 15 seconds?

Use nanosleep(2). It uses structure timespec that is used to specify intervals of time with nanosecond precision.

struct timespec {
           time_t tv_sec;        /* seconds */
           long   tv_nsec;       /* nanoseconds */
       };

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

The following method works (tested in Chrome) by using a box-shadow with a spread of 1px instead of a "real" border.

_x000D_
_x000D_
    table {
        border-collapse: collapse;
        border-radius: 30px;
        border-style: hidden; /* hide standard table (collapsed) border */
        box-shadow: 0 0 0 1px #666; /* this draws the table border  */ 
    }

    td {
        border: 1px solid #ccc;
    }
_x000D_
<table>
  <thead>
    <tr>
      <th>Foo</th>
      <th>Bar</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Baz</td>
      <td>Qux</td>
    </tr>
    <tr>
      <td>Life is short</td>
      <td rowspan="3">and</td>
    </tr>
    <tr>
      <td>Love</td>
    </tr>
    <tr>
      <td>is always over</td>
    </tr>
    <tr>
      <td>In the</td>
      <td>Morning</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

JavaScript: Class.method vs. Class.prototype.method

For visual learners, when defining the function without .prototype

ExampleClass = function(){};
ExampleClass.method = function(customString){
             console.log((customString !== undefined)? 
                          customString : 
                          "called from func def.");}
ExampleClass.method(); // >> output: `called from func def.`  

var someInstance = new ExampleClass();
someInstance.method('Called from instance');
    // >> error! `someInstance.method is not a function`  

With same code, if .prototype is added,

ExampleClass.prototype.method = function(customString){
             console.log((customString !== undefined)? 
                          customString : 
                          "called from func def.");}
ExampleClass.method();  
      // > error! `ExampleClass.method is not a function.`  

var someInstance = new ExampleClass();
someInstance.method('Called from instance');
                 // > output: `Called from instance`

To make it clearer,

ExampleClass = function(){};
ExampleClass.directM = function(){}  //M for method
ExampleClass.prototype.protoM = function(){}

var instanceOfExample = new ExampleClass();

ExampleClass.directM();     ? works
instanceOfExample.directM();   x Error!

ExampleClass.protoM();     x Error!
instanceOfExample.protoM();  ? works

****Note for the example above, someInstance.method() won't be executed as,
ExampleClass.method() causes error & execution cannot continue.
But for the sake of illustration & easy understanding, I've kept this sequence.****

Results generated from chrome developer console & JS Bin
Click on the jsbin link above to step through the code.
Toggle commented section with ctrl+/

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

JavaScript: Global variables after Ajax requests

AJAX stands for Asynchronous JavaScript and XML. Thus, the post to the server happens out-of-sync with the rest of the function. Try some code like this instead (it just breaks the shorthand $.post out into the longer $.ajax call and adds the async option).

var it_works = false;

$.ajax({
  type: 'POST',
  async: false,
  url: "some_file.php",
  data: "",
  success: function() {it_works = true;}
});

alert(it_works);

Hope this helps!

Define global variable with webpack

Use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

new webpack.DefinePlugin(definitions)

Example:

plugins: [
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true)
  })
  //...
]

Usage:

console.log(`Environment is in production: ${PRODUCTION}`);

Convert SQL Server result set into string

The answer from brad.v is incorrect! It won't give you a concatenated string.

Here's the correct code, almost like brad.v's but with one important change:

DECLARE @results VarChar(1000)
  SELECT @results = CASE
     WHEN @results IS NULL THEN CONVERT( VarChar(20), [StudentId])
     ELSE @results + ', ' + CONVERT( VarChar(20), [StudentId])
  END
FROM Student WHERE condition = abc;

See the difference? :) brad.v please fix your answer, I can't do anything to correct it or comment on it 'cause my reputation here is zero. I guess I can remove mine after you fix yours. Thanks!

Difference between return 1, return 0, return -1 and exit?

return from main() is equivalent to exit

the program terminates immediately execution with exit status set as the value passed to return or exit

return in an inner function (not main) will terminate immediately the execution of the specific function returning the given result to the calling function.

exit from anywhere on your code will terminate program execution immediately.


status 0 means the program succeeded.

status different from 0 means the program exited due to error or anomaly.

If you exit with a status different from 0 you're supposed to print an error message to stderr so instead of using printf better something like

if(errorOccurred) {
    fprintf(stderr, "meaningful message here\n");
    return -1;
}

note that (depending on the OS you're on) there are some conventions about return codes.

Google for "exit status codes" or similar and you'll find plenty of information on SO and elsewhere.


Worth mentioning that the OS itself may terminate your program with specific exit status codes if you attempt to do some invalid operations like reading memory you have no access to.

Why do we need boxing and unboxing in C#?

When a method only takes a reference type as a parameter (say a generic method constrained to be a class via the new constraint), you will not be able to pass a reference type to it and have to box it.

This is also true for any methods that take object as a parameter - this will have to be a reference type.

How to add MVC5 to Visual Studio 2013?

You can look into Windows installed folder from here of your pc path:

C:\Program Files (x86)\Microsoft ASP.NET

View of Opened file where showing installed MVC 3, MVC 4

enter image description here

How to create a delay in Swift?

If your code is already running in a background thread, pause the thread using this method in Foundation: Thread.sleep(forTimeInterval:)

For example:

DispatchQueue.global(qos: .userInitiated).async {

    // Code is running in a background thread already so it is safe to sleep
    Thread.sleep(forTimeInterval: 4.0)
}

(See other answers for suggestions when your code is running on the main thread.)

How do I get the entity that represents the current user in Symfony2?

Best practice

According to the documentation since Symfony 2.1 simply use this shortcut :

$user = $this->getUser();

The above is still working on Symfony 3.2 and is a shortcut for this :

$user = $this->get('security.token_storage')->getToken()->getUser();

The security.token_storage service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use the getToken() method of the security.context service.

Example : And if you want directly the username :

$username = $this->getUser()->getUsername();

If wrong user class type

The user will be an object and the class of that object will depend on your user provider.

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

//*[text()='ABC'] 

returns

<street>ABC</street>
<comment>BLAH BLAH BLAH <br><br>ABC</comment>

Is Unit Testing worth the effort?

I recently went through the exact same experience in my workplace and found most of them knew the theoretical benefits but had to be sold on the benefits to them specifically, so here were the points I used (successfully):

  • They save time when performing negative testing, where you handle unexpected inputs (null pointers, out of bounds values, etc), as you can do all these in a single process.
  • They provide immediate feedback at compile time regarding the standard of the changes.
  • They are useful for testing internal data representations that may not be exposed during normal runtime.

and the big one...

  • You might not need unit testing, but when someone else comes in and modifies the code without a full understanding it can catch a lot of the silly mistakes they might make.

How to stop java process gracefully?

Thanks for you answers. Shutdown hooks seams like something that would work in my case. But I also bumped into the thing called Monitoring and Management beans:
http://java.sun.com/j2se/1.5.0/docs/guide/management/overview.html
That gives some nice possibilities, for remote monitoring, and manipulation of the java process. (Was introduced in Java 5)

Extracting double-digit months and days from a Python date

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

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

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

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

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

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

Array functions in jQuery

Have a look at https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array for documentation on JavaScript Arrays.
jQuery is a library which adds some magic to JavaScript which is a capable and featurefull scripting language. The libraries just fill in the gaps - get to know the core!

Make a div into a link

The cleanest way would be to use jQuery with the data-tags introduced in HTML. With this solution you can create a link on every tag you want. First define the tag (e.g. div) with a data-link tag:

<div data-link="http://www.google.at/">Some content in the div which is arbitrary</div>

Now you can style the div however you want. And you have to create also the style for the "link"-alike behavior:

[data-link] {
  cursor: pointer;
}

And at last put this jQuery call to the page:

$(document).ready(function() {
  $("[data-link]").click(function() {
    window.location.href = $(this).attr("data-link");
    return false;
  });
});

With this code jQuery applys a click listener to every tag on the page which has a "data-link" attribute and redirects to the URL which is in the data-link attribute.

Get HTML5 localStorage keys

You can use the localStorage.key(index) function to return the string representation, where index is the nth object you want to retrieve.

Unicode characters in URLs

Use percent-encoded form. Some (mainly old) computers running Windows XP for example do not support Unicode, but rather ISO encodings. That is the reason percent-encoded URLs were invented. Also, if you give a URL printed on paper to a user, containing characters that cannot be easily typed, that user may have a hard time typing it (or just ignore it). Percent-encoded form can even be used in many of the oldest machines that ever existed (although they don't support internet of course).

There is a downside though, as percent-encoded characters are longer than the original ones, thus possibly resulting in really long URLs. But just try to ignore it, or use a URL shortener (I would recommend goo.gl in this case, which makes a 13-character long URL). Also, if you don't want to register for a Google account, try bit.ly (bit.ly makes slightly longer URLs, with the length being 14 characters).

How find out which process is using a file in Linux?

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

It's looking for the file in the current directory.

First, go to that directory

cd /users/gcameron/Desktop/map

And then try to run it

python colorize_svg.py

Creating a UIImage from a UIColor to use as a background image for UIButton

Are you using ARC? The problem here is that you don't have a reference to the UIColor object that you're trying to apply; the CGColor is backed by that UIColor, but ARC will deallocate the UIColor before you have a chance to use the CGColor.

The clearest solution is to have a local variable pointing to your UIColor with the objc_precise_lifetime attribute.

You can read more about this exact case on this article about UIColor and short ARC lifetimes or get more details about the objc_precise_lifetime attribute.

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

From the Terminal of Visual Code Studio on Windows 10, this is what worked for me to create a new file:

type > hello.js
echo > orange.js
ni > peach.js

Getting number of days in a month

 int days = DateTime.DaysInMonth(int year,int month);

or

 int days=System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(int year,int month);

you have to pass year and month as int then days in month will be return on currespoting year and month

Difference between res.send and res.json in Express.js

The methods are identical when an object or array is passed, but res.json() will also convert non-objects, such as null and undefined, which are not valid JSON.

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options. Those options are set like so:

app.set('json spaces', 2);
app.set('json replacer', replacer);

And passed to a JSON.stringify() like so:

JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation

This is the code in the res.json() method that the send method doesn't have:

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);

The method ends up as a res.send() in the end:

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);

Changing the URL in react-router v4 without using Redirect or Link

I'm using this to redirect with React Router v4:

this.props.history.push('/foo');

Hope it work for you ;)

How to put an image in div with CSS?

you can do this:

<div class="picture1">&nbsp;</div>

and put this into your css file:

div.picture1 {
   width:100px; /*width of your image*/
   height:100px; /*height of your image*/
   background-image:url('yourimage.file');
   margin:0; /* If you want no margin */
   padding:0; /*if your want to padding */
}

otherwise, just use them as plain

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

I totally agree with both the question and Martin's answer :). Even in Java, reading javadoc with generics is much harder than it should be due to the extra noise. This is compounded in Scala where implicit parameters are used as in the questions's example code (while the implicits do very useful collection-morphing stuff).

I don't think its a problem with the language per se - I think its more a tooling issue. And while I agree with what Jörg W Mittag says, I think looking at scaladoc (or the documentation of a type in your IDE) - it should require as little brain power as possible to grok what a method is, what it takes and returns. There shouldn't be a need to hack up a bit of algebra on a bit of paper to get it :)

For sure IDEs need a nice way to show all the methods for any variable/expression/type (which as with Martin's example can have all the generics inlined so its nice and easy to grok). I like Martin's idea of hiding the implicits by default too.

To take the example in scaladoc...

def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That

When looking at this in scaladoc I'd like the generic block [B, That] to be hidden by default as well as the implicit parameter (maybe they show if you hover a little icon with the mouse) - as its extra stuff to grok reading it which usually isn't that relevant. e.g. imagine if this looked like...

def map(f: A => B): That

nice and clear and obvious what it does. You might wonder what 'That' is, if you mouse over or click it it could expand the [B, That] text highlighting the 'That' for example.

Maybe a little icon could be used for the [] declaration and (implicit...) block so its clear there are little bits of the statement collapsed? Its hard to use a token for it, but I'll use a . for now...

def map.(f: A => B).: That

So by default the 'noise' of the type system is hidden from the main 80% of what folks need to look at - the method name, its parameter types and its return type in nice simple concise way - with little expandable links to the detail if you really care that much.

Mostly folks are reading scaladoc to find out what methods they can call on a type and what parameters they can pass. We're kinda overloading users with way too much detail right how IMHO.

Here's another example...

def orElse[A1 <: A, B1 >: B](that: PartialFunction[A1, B1]): PartialFunction[A1, B1]

Now if we hid the generics declaration its easier to read

def orElse(that: PartialFunction[A1, B1]): PartialFunction[A1, B1]

Then if folks hover over, say, A1 we could show the declaration of A1 being A1 <: A. Covariant and contravariant types in generics add lots of noise too which can be rendered in a much easier to grok way to users I think.

What is the default username and password in Tomcat?

If people still have problems after adding/modifying the tomcat-users.xml file and adding the relevant user/role for the version of Tomcat that they're using then please be sure that you've removed the comment tags that are surrounding this block. They will look like this in the XML file:
<!--
-->
They will be above and below the user/role section.

Visual Studio Code compile on save

You need to increase the watches limit to fix the recompile issue on save, Open terminal and enter these two commands:

sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p --system

To make the changes persistent even after restart, run this command also:

echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

You cannot use a select statement that assigns values to variables to also return data to the user The below code will work fine, because i have declared 1 local variable and that variable is used in select statement.

 Begin
    DECLARE @name nvarchar(max)
    select @name=PolicyHolderName from Table
    select @name
    END

The below code will throw error "A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations" Because we are retriving data(PolicyHolderAddress) from table, but error says data-retrieval operation is not allowed when you use some local variable as part of select statement.

 Begin
    DECLARE @name nvarchar(max)
    select 
       @name = PolicyHolderName,
       PolicyHolderAddress 
    from Table
 END

The the above code can be corrected like below,

Begin
    DECLARE @name nvarchar(max)
    DECLARE @address varchar(100)
    select 
       @name = PolicyHolderName,
       @address = PolicyHolderAddress 
    from Table
END

So either remove the data-retrieval operation or add extra local variable. This will resolve the error.

Jenkins Pipeline Wipe Out Workspace

We make sure we are working with a clean workspace by using a feature of the git plugin. You can add additional behaviors like 'Clean before checkout'. We use this as well for 'Prune stale remote-tracking branches'.

What is a segmentation fault?

In simple words: segmentation fault is the operating system sending a signal to the program saying that it has detected an illegal memory access and is prematurely terminating the program to prevent memory from being corrupted.

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

Sort a single String in Java

Question: sort a string in java

public class SortAStringInJava {
    public static void main(String[] args) {

        String str = "Protijayi";
// Method 1
        str = str.chars() // IntStream
                .sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();

        System.out.println(str);
        // Method 2
        str = Stream.of(str.split(" ")).sorted().collect(Collectors.joining());
        System.out.println(str);
    }
}

Reload child component when variables on parent component changes. Angular2

Use @Input to pass your data to child components and then use ngOnChanges (https://angular.io/api/core/OnChanges) to see if that @Input changed on the fly.

Build android release apk on Phonegap 3.x CLI

This is for Phonegap 3.0.x to 3.3.x. For PhoneGap 3.4.0 and higher see below.

Found part of the answer here, at Phonegap documentation. The full process is the following:

  1. Open a command line window, and go to /path/to/your/project/platforms/android/cordova.

  2. Run build --release. This creates an unsigned release APK at /path/to/your/project/platforms/android/bin folder, called YourAppName-release-unsigned.apk.

  3. Sign and align the APK using the instructions at android developer official docs.

Thanks to @LaurieClark for the link (http://iphonedevlog.wordpress.com/2013/08/16/using-phonegap-3-0-cli-on-mac-osx-10-to-build-ios-and-android-projects/), and the blogger who post it, because it put me on the track.

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

The SQLite command line utility has a .schema TABLENAME command that shows you the create statements.

Apache Tomcat :java.net.ConnectException: Connection refused

The meaning of this exception is explained here: https://bz.apache.org/bugzilla/show_bug.cgi?id=27829

Summary: Java dies, Tomcat shut down hook is called, exception is thrown.

So if a firewall prevents the shutdown message from reaching Tomcat, Java will eventually die first (ex during system reboot/shutdown), and the exception will appear.

There are other possibilities.

In my case, my problem had something to do with my initscript (Linux) being incorrectly installed. That implied Java was getting killed by the OS during shutdown/reboot and not as a result of the script. The solution as simple as this:

chkconfig --del initscript
chkconfig --add initscript

Before the fix I had the following in rc.d:

find /etc/rc.d | grep initscript | sort
/etc/rc.d/init.d/initscript
/etc/rc.d/rc2.d/S85initscript
/etc/rc.d/rc3.d/S85initscript
/etc/rc.d/rc4.d/S85initscript
/etc/rc.d/rc5.d/S85initscript

After the fix:

find /etc/rc.d | grep initscript | sort
/etc/rc.d/init.d/initscript
/etc/rc.d/rc0.d/K15initscript
/etc/rc.d/rc1.d/K15initscript
/etc/rc.d/rc2.d/K15initscript
/etc/rc.d/rc3.d/K15initscript
/etc/rc.d/rc4.d/K15initscript
/etc/rc.d/rc5.d/S85initscript
/etc/rc.d/rc6.d/K15initscript

Conclusion: if you get this exception, make sure Tomcat is shutdown properly, not as a result of Java being terminated. Check your firewall, shutdown scripts etc.

How to return data from promise

You have to return a promise instead of a variable. So in your function just return:

return relationsManagerResource.GetParentId(nodeId)

And later resolve the returned promise. Or you can make another deferred and resolve theParentId with it.

Android: Internet connectivity change listener

I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.

You should have a Worker with network constraint AND it will fired only if network available, i.e:

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()

And in worker you do whatever you want once connection back, you may fire the worker periodically .

i.e:

inside dowork() callback:

notifierLiveData.postValue(info)

Validating parameters to a Bash script

The man page for test (man test) provides all available operators you can use as boolean operators in bash. Use those flags in the beginning of your script (or functions) for input validation just like you would in any other programming language. For example:

if [ -z $1 ] ; then
  echo "First parameter needed!" && exit 1;
fi

if [ -z $2 ] ; then
  echo "Second parameter needed!" && exit 2;
fi

JUnit: how to avoid "no runnable methods" in test utils classes

  1. If this is your base test class for example AbstractTest and all your tests extends this then define this class as abstract
  2. If it is Util class then better remove *Test from the class rename it is MyTestUtil or Utils etc.

How to set an image's width and height without stretching it?

Do I have to add an encapsulating <div> or <span>?

I think you do. The only thing that comes to mind is padding, but for that you would have to know the image's dimensions beforehand.

php $_POST array empty upon form submission

REFERENCE: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

POST method

We are going to make some modifications so POST method will be used when sending the request...

var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}
http.send(params);

Some http headers must be set along with any POST request. So we set them in these lines...

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}

We set a handler for the 'ready state' change event. This is the same handler we used for the GET method. You can use the http.responseText here - insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.

http.send(params);

Finally, we send the parameters with the request. The given url is loaded only after this line is called. In the GET method, the parameter will be a null value. But in the POST method, the data to be send will be send as the argument of the send function. The params variable was declared in the second line as lorem=ipsum&name=binny - so we send two parameters - 'lorem' and 'name' with the values 'ipsum' and 'binny' respectively.

Multiple left-hand assignment with JavaScript

Try this:

var var1=42;
var var2;

alert(var2 = var1); //show result of assignment expression is assigned value
alert(var2); // show assignment did occur.

Note the single '=' in the first alert. This will show that the result of an assignment expression is the assigned value, and the 2nd alert will show you that assignment did occur.

It follows logically that assignment must have chained from right to left. However, since this is all atomic to the javascript (there's no threading) a particular engine may choose to actually optimize it a little differently.

Fastest way to check a string is alphanumeric in Java

Use String.matches(), like:

String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));

That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.

Adding link a href to an element using css

You don't need CSS for this.

     <img src="abc"/>

now with link:

     <a href="#myLink"><img src="abc"/></a>

Or with jquery, later on, you can use the wrap property, see these questions answer:

how to add a link to an image using jquery?

Call Class Method From Another Class

update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

class A(object):
    def method1(self, a, b, c):
        # foo

method = A.method1

method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

a = A()
method = a.method1
method(1, 2)

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
  3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

Some examples:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
    def method1(self, a, b):
        return a + b

    @staticmethod
    def method2(a, b):
        return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

t = Test1()  # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2)        # form two (the common one) essentially reduces to form one

Test1.method2(1, 2)  #the static method can be called with just arguments
t.method2(1, 2)      # on an instance or the class

Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
t.method3(1, 2)      # that it's called on (the subclass if called on a subclass) 
                     # but will not have access to the instance it's called on 
                     # (if it is called on an instance)

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

Brew doctor says: "Warning: /usr/local/include isn't writable."

What worked for me was

$ sudo chown -R yourname:admin /usr/local/bin

Default parameters with C++ constructors

Either approach works. But if you have a long list of optional parameters make a default constructor and then have your set function return a reference to this. Then chain the settors.

class Thingy2
{
public:
    enum Color{red,gree,blue};
    Thingy2();

    Thingy2 & color(Color);
    Color color()const;

    Thingy2 & length(double);
    double length()const;
    Thingy2 & width(double);
    double width()const;
    Thingy2 & height(double);
    double height()const;

    Thingy2 & rotationX(double);
    double rotationX()const;
    Thingy2 & rotatationY(double);
    double rotatationY()const;
    Thingy2 & rotationZ(double);
    double rotationZ()const;
}

main()
{
    // gets default rotations
    Thingy2 * foo=new Thingy2().color(ret)
        .length(1).width(4).height(9)
    // gets default color and sizes
    Thingy2 * bar=new Thingy2()
        .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);
    // everything specified.
    Thingy2 * thing=new Thingy2().color(ret)
        .length(1).width(4).height(9)
        .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);
}

Now when constructing the objects you can pick an choose which properties to override and which ones you have set are explicitly named. Much more readable :)

Also, you no longer have to remember the order of the arguments to the constructor.

Resource leak: 'in' is never closed

You should close your Scanner when you're done with it:

in.close();

MySQL: Set user variable from result of query

Use this way so that result will not be displayed while running stored procedure.

The query:

SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;

Java Class.cast() vs. cast operator

Class.cast() is rarely ever used in Java code. If it is used then usually with types that are only known at runtime (i.e. via their respective Class objects and by some type parameter). It is only really useful in code that uses generics (that's also the reason it wasn't introduced earlier).

It is not similar to reinterpret_cast, because it will not allow you to break the type system at runtime any more than a normal cast does (i.e. you can break generic type parameters, but can't break "real" types).

The evils of the C-style cast operator generally don't apply to Java. The Java code that looks like a C-style cast is most similar to a dynamic_cast<>() with a reference type in Java (remember: Java has runtime type information).

Generally comparing the C++ casting operators with Java casting is pretty hard since in Java you can only ever cast reference and no conversion ever happens to objects (only primitive values can be converted using this syntax).

Are parameters in strings.xml possible?

If you need two variables in the XML, you can use:

%1$d text... %2$d or %1$s text... %2$s for string variables.

Example :

strings.xml

<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>

activity.java

String site = "site.tld";
String days = "11";

//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();

MySQL Database won't start in XAMPP Manager-osx

I had success with easy killing all active mysql processes in Monitor Activity tool:

1) close XAMPP control

2) open Monitor Activity

3) select filter for All processes (default is My processes)

4) search for: mysql

5) force quit all the mysql

6) relaunch XAMPP control and launch apache again

Enjoy

Set height of <div> = to height of another <div> through .css

If you're open to using javascript then you can get the property on an element like this: document.GetElementByID('rightdiv').style.getPropertyValue('max-height');

And you can set the attribute on an element like this: .setAttribute('style','max-height:'+heightVariable+';');

Note: if you're simply looking to set both element's max-height property in one line, you can do so like this:

#leftdiv,#rightdiv
{
    min-height: 600px;   
}

What is the difference between hg forget and hg remove?

The best way to put is that hg forget is identical to hg remove except that it leaves the files behind in your working copy. The files are left behind as untracked files and can now optionally be ignored with a pattern in .hgignore.

In other words, I cannot tell if you used hg forget or hg remove when I pull from you. A file that you ran hg forget on will be deleted when I update to that changeset — just as if you had used hg remove instead.

Remove files from Git commit

git checkout HEAD~ path/to/file
git commit --amend

Call two functions from same onclick

Just to offer some variety, the comma operator can be used too but some might say "noooooo!", but it works:

<input type="button" onclick="one(), two(), three(), four()"/>

http://jsbin.com/oqizir/1/edit

How to remove focus from input field in jQuery?

Use .blur().

The blur event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as <input>. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.

$("#myInputID").blur(); 

How can I align the columns of tables in Bash?

It's easier than you wonder.

If you are working with a separated by semicolon file and header too:

$ (head -n1 file.csv && sort file.csv | grep -v <header>) | column -s";" -t

If you are working with array (using tab as separator):

for((i=0;i<array_size;i++));
do

   echo stringarray[$i] $'\t' numberarray[$i] $'\t' anotherfieldarray[$i] >> tmp_file.csv

done;

cat file.csv | column -t

Assign a login to a user created without login (SQL Server)

I found that this question was still relevant but not clearly answered in my case.

Using SQL Server 2012 with an orphaned SQL_USER this was the fix;

USE databasename                      -- The database I had recently attached
EXEC sp_change_users_login 'Report'   -- Display orphaned users
EXEC sp_change_users_login 'Auto_Fix', 'UserName', NULL, 'Password'

Swap x and y axis without manually swapping values

Microsoft Excel for Mac 2011 v 14.5.9

  • Click on the chart
  • Press the "Switch Plot" button under the "Charts" tab

Paging with Oracle

Something like this should work: From Frans Bouma's Blog

SELECT * FROM
(
    SELECT a.*, rownum r__
    FROM
    (
        SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%'
        ORDER BY OrderDate DESC, ShippingDate DESC
    ) a
    WHERE rownum < ((pageNumber * pageSize) + 1 )
)
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

you can return a FileResult from your MVC action.

*********************MVC action************

    public FileResult OpenPDF(parameters)
    {
       //code to fetch your pdf byte array
       return File(pdfBytes, "application/pdf");
    }

**************js**************

Use formpost to post your data to action

    var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
    var form = document.createElement("form");
    jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
    jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
    jQuery(form).append(inputTag);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
    return false;

You need to create a form to post your data, append it your dom, post your data and remove the form your document body.

However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.

Change hover color on a button with Bootstrap customization

The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:

/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
    color: #fff;
    background-color: #0495c9;
    border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
    background-color: #00b3db;
    border-color: #285e8e; /*set the color you want here*/
}

saving a file (from stream) to disk using c#

For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.

Example (Assuming you already have a stream):

FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);    
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();

What is the HTML5 equivalent to the align attribute in table cells?

you can use this code as replacement for table align

table 
{
    margin:auto;
}

android.content.res.Resources$NotFoundException: String resource ID #0x0

You can do it. this is a easy way.

txtTopicNo.setText(10+"");

Passing ArrayList from servlet to JSP

here list attribute name set in request request.setAttribute("List",list); and ArrayList list=new ArrayList();

<%

ArrayList<Category> a=(ArrayList<Category>)request.getAttribute("List");

out.print(a);

for(int i=0;i<a.size();i++)

{
    out.println(a.get(i));

}


%>

How to pass optional arguments to a method in C++?

Use default parameters

template <typename T>
void func(T a, T b = T()) {

   std::cout << a << b;

}

int main()
{
    func(1,4); // a = 1, b = 4
    func(1);   // a = 1, b = 0

    std::string x = "Hello";
    std::string y = "World";

    func(x,y);  // a = "Hello", b ="World"
    func(x);    // a = "Hello", b = "" 

}

Note : The following are ill-formed

template <typename T>
void func(T a = T(), T b )

template <typename T>
void func(T a, T b = a )

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

A simple thing but I figured it out is: I missed adding @Log to the class.

@Log
public class YourClassName {


}

It may help someone.

WebSockets protocol vs HTTP

1) Why is the WebSockets protocol better?

WebSockets is better for situations that involve low-latency communication especially for low latency for client to server messages. For server to client data you can get fairly low latency using long-held connections and chunked transfer. However, this doesn't help with client to server latency which requires a new connection to be established for each client to server message.

Your 48 byte HTTP handshake is not realistic for real-world HTTP browser connections where there is often several kilobytes of data sent as part of the request (in both directions) including many headers and cookie data. Here is an example of a request/response to using Chrome:

Example request (2800 bytes including cookie data, 490 bytes without cookie data):

GET / HTTP/1.1
Host: www.cnn.com
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.68 Safari/537.17
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: [[[2428 byte of cookie data]]]

Example response (355 bytes):

HTTP/1.1 200 OK
Server: nginx
Date: Wed, 13 Feb 2013 18:56:27 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: CG=US:TX:Arlington; path=/
Last-Modified: Wed, 13 Feb 2013 18:55:22 GMT
Vary: Accept-Encoding
Cache-Control: max-age=60, private
Expires: Wed, 13 Feb 2013 18:56:54 GMT
Content-Encoding: gzip

Both HTTP and WebSockets have equivalent sized initial connection handshakes, but with a WebSocket connection the initial handshake is performed once and then small messages only have 6 bytes of overhead (2 for the header and 4 for the mask value). The latency overhead is not so much from the size of the headers, but from the logic to parse/handle/store those headers. In addition, the TCP connection setup latency is probably a bigger factor than the size or processing time for each request.

2) Why was it implemented instead of updating HTTP protocol?

There are efforts to re-engineer the HTTP protocol to achieve better performance and lower latency such as SPDY, HTTP 2.0 and QUIC. This will improve the situation for normal HTTP requests, but it is likely that WebSockets and/or WebRTC DataChannel will still have lower latency for client to server data transfer than HTTP protocol (or it will be used in a mode that looks a lot like WebSockets anyways).

Update:

Here is a framework for thinking about web protocols:

  • TCP: low-level, bi-directional, full-duplex, and guaranteed order transport layer. No browser support (except via plugin/Flash).
  • HTTP 1.0: request-response transport protocol layered on TCP. The client makes one full request, the server gives one full response, and then the connection is closed. The request methods (GET, POST, HEAD) have specific transactional meaning for resources on the server.
  • HTTP 1.1: maintains the request-response nature of HTTP 1.0, but allows the connection to stay open for multiple full requests/full responses (one response per request). Still has full headers in the request and response but the connection is re-used and not closed. HTTP 1.1 also added some additional request methods (OPTIONS, PUT, DELETE, TRACE, CONNECT) which also have specific transactional meanings. However, as noted in the introduction to the HTTP 2.0 draft proposal, HTTP 1.1 pipelining is not widely deployed so this greatly limits the utility of HTTP 1.1 to solve latency between browsers and servers.
  • Long-poll: sort of a "hack" to HTTP (either 1.0 or 1.1) where the server does not respond immediately (or only responds partially with headers) to the client request. After a server response, the client immediately sends a new request (using the same connection if over HTTP 1.1).
  • HTTP streaming: a variety of techniques (multipart/chunked response) that allow the server to send more than one response to a single client request. The W3C is standardizing this as Server-Sent Events using a text/event-stream MIME type. The browser API (which is fairly similar to the WebSocket API) is called the EventSource API.
  • Comet/server push: this is an umbrella term that includes both long-poll and HTTP streaming. Comet libraries usually support multiple techniques to try and maximize cross-browser and cross-server support.
  • WebSockets: a transport layer built-on TCP that uses an HTTP friendly Upgrade handshake. Unlike TCP, which is a streaming transport, WebSockets is a message based transport: messages are delimited on the wire and are re-assembled in-full before delivery to the application. WebSocket connections are bi-directional, full-duplex and long-lived. After the initial handshake request/response, there is no transactional semantics and there is very little per message overhead. The client and server may send messages at any time and must handle message receipt asynchronously.
  • SPDY: a Google initiated proposal to extend HTTP using a more efficient wire protocol but maintaining all HTTP semantics (request/response, cookies, encoding). SPDY introduces a new framing format (with length-prefixed frames) and specifies a way to layering HTTP request/response pairs onto the new framing layer. Headers can be compressed and new headers can be sent after the connection has been established. There are real world implementations of SPDY in browsers and servers.
  • HTTP 2.0: has similar goals to SPDY: reduce HTTP latency and overhead while preserving HTTP semantics. The current draft is derived from SPDY and defines an upgrade handshake and data framing that is very similar the the WebSocket standard for handshake and framing. An alternate HTTP 2.0 draft proposal (httpbis-speed-mobility) actually uses WebSockets for the transport layer and adds the SPDY multiplexing and HTTP mapping as an WebSocket extension (WebSocket extensions are negotiated during the handshake).
  • WebRTC/CU-WebRTC: proposals to allow peer-to-peer connectivity between browsers. This may enable lower average and maximum latency communication because as the underlying transport is SDP/datagram rather than TCP. This allows out-of-order delivery of packets/messages which avoids the TCP issue of latency spikes caused by dropped packets which delay delivery of all subsequent packets (to guarantee in-order delivery).
  • QUIC: is an experimental protocol aimed at reducing web latency over that of TCP. On the surface, QUIC is very similar to TCP+TLS+SPDY implemented on UDP. QUIC provides multiplexing and flow control equivalent to HTTP/2, security equivalent to TLS, and connection semantics, reliability, and congestion control equivalentto TCP. Because TCP is implemented in operating system kernels, and middlebox firmware, making significant changes to TCP is next to impossible. However, since QUIC is built on top of UDP, it suffers from no such limitations. QUIC is designed and optimised for HTTP/2 semantics.

References:

How do I get a list of all subdomains of a domain?

In Windows nslookup the command is

ls -d somedomain.com > outfile.txt

which stores the subdomain list in outfile.txt

few domains these days allow this

Java double comparison epsilon

You do NOT use double to represent money. Not ever. Use java.math.BigDecimal instead.

Then you can specify how exactly to do rounding (which is sometimes dictated by law in financial applications!) and don't have to do stupid hacks like this epsilon thing.

Seriously, using floating point types to represent money is extremely unprofessional.

TextView Marquee not working

I've encountered the same problem. Amith GC's answer(the first answer checked as accepted) is right, but sometimes textview.setSelected(true); doesn't work when the text view can't get the focus all the time. So, to ensure TextView Marquee working, I had to use a custom TextView.

public class CustomTextView extends TextView {
    public CustomTextView(Context context) {
        super(context);
    }
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }


    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }


    @Override
    public boolean isFocused() {
        return true;
    }
}

And then, you can use the custom TextView as the scrolling text view in your layout .xml file like this:

<com.example.myapplication.CustomTextView
            android:id="@+id/tvScrollingMessage"
            android:text="@string/scrolling_message_main_wish_list"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit ="marquee_forever"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:scrollHorizontally="true"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/black"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:freezesText="true"/>

NOTE: in the above code snippet com.example.myapplication is an example package name and should be replaced by your own package name.

Hope this will help you. Cheers!

Loading cross-domain endpoint with AJAX

If the external site doesn't support JSONP or CORS, your only option is to use a proxy.

Build a script on your server that requests that content, then use jQuery ajax to hit the script on your server.

strcpy() error in Visual studio 2012

A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings

Right-click your C++ and chose the "Properties" item to get to the properties window.

Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".

In the "Preprocessor definitions" add

_CRT_SECURE_NO_WARNINGS

but it would be a good idea to add

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)

as to inherit predefined definitions

IMHO & for the most part this is a good approach.

SQL update trigger only when column is modified

You have two way for your question :

1- Use Update Command in your Trigger.

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS BEGIN
    SET NOCOUNT ON;
    IF UPDATE (QtyToRepair) 
    BEGIN
        UPDATE SCHEDULE 
        SET modified = GETDATE()
           , ModifiedUser = SUSER_NAME()
           , ModifiedHost = HOST_NAME()
        FROM SCHEDULE S INNER JOIN Inserted I 
        ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        WHERE S.QtyToRepair <> I.QtyToRepair
    END 
END

2- Use Join between Inserted table and deleted table

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS BEGIN
    SET NOCOUNT ON;    

    UPDATE SCHEDULE 
    SET modified = GETDATE()
       , ModifiedUser = SUSER_NAME()
       , ModifiedHost = HOST_NAME()
    FROM SCHEDULE S 
    INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
    INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber                  
    WHERE S.QtyToRepair <> I.QtyToRepair
    AND D.QtyToRepair <> I.QtyToRepair
END

When you use update command for table SCHEDULE and Set QtyToRepair Column to new value, if new value equal to old value in one or multi row, solution 1 update all updated row in Schedule table but solution 2 update only schedule rows that old value not equal to new value.

Excel: Creating a dropdown using a list in another sheet?

Excel has a very powerful feature providing for a dropdown select list in a cell, reflecting data from a named region. It'a a very easy configuration, once you have done it before. Two steps are to follow:

Create a named region,
Setup the dropdown in a cell.

There is a detailed explanation of the process HERE.

Remove columns from DataTable in C#

To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.

DataTable dt;
int desiredSize = 10;

while (dt.Columns.Count > desiredSize)
{
   dt.Columns.RemoveAt(desiredSize);
}

Using Page_Load and Page_PreRender in ASP.Net

It depends on your requirements.

Page Load : Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data. See Handling Inherited Events.

Prerender :Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost. See Handling Inherited Events.

Reference: Control Execution Lifecycle MSDN

Try to read about

ASP.NET Page Life Cycle Overview ASP.NET

Control Execution Lifecycle

Regards

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

Spring Data JPA and Exists query

It's gotten a lot easier these days!

@Repository
public interface PageRepository extends JpaRepository<Page, UUID> {

    Boolean existsByName(String name); //Checks if there are any records by name
    Boolean existsBy(); // Checks if there are any records whatsoever

}

Android Studio Gradle Configuration with name 'default' not found

Everything looks fine at first blush, but some poking around on here found an answer that could be helpful: https://stackoverflow.com/a/16905808/7944

Even the original answer writer doesn't sound super confident, but it's worth following up on. Also, you didn't say anything about your directory structure and so I'm assuming it's boring default stuff, but can't know for sure.

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

I happen to be consulting for a Fortune 500 company and it's sadly Windows 7 and no administrator privileges. Thus Node.js, Npm, Visual Studio Code, etc.. were pushed to my machine - I cannot change a lot, etc...

For this computer running Windows 7:

Below are my new settings. The one not working is commented out.

{
    "update.channel": "none",
    "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
    //"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\bash.exe"
}

javascript filter array of objects

You could utilize jQuery.filter() function to return elements from a subset of the matching elements.

_x000D_
_x000D_
var names = [_x000D_
    { name : "Joe", age:20, email: "[email protected]"},_x000D_
    { name : "Mike", age:50, email: "[email protected]"},_x000D_
    { name : "Joe", age:45, email: "[email protected]"}_x000D_
   ];_x000D_
   _x000D_
   _x000D_
var filteredNames = $(names).filter(function( idx ) {_x000D_
    return names[idx].name === "Joe" && names[idx].age < 30;_x000D_
}); _x000D_
_x000D_
$(filteredNames).each(function(){_x000D_
     $('#output').append(this.name);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="output"/>
_x000D_
_x000D_
_x000D_

how to make negative numbers into positive

abs() is for integers only. For floating point, use fabs() (or one of the fabs() line with the correct precision for whatever a actually is)

What's the difference between a null pointer and a void pointer?

Both void and null pointers point to a memory location in the end.

A null pointer points to place (in a memory segment) which is usually the 0th address of memory segment. It is almost all about how the underlying OS treat that "reserved" memory location (an implementation detail) when you try to access it to read/write or dereference. For example, that particular memory location can be marked as "non-accessible" and throws an expection when it's accessed.

A void pointer can point to anywhere and potentially represent any type (primitive, reference-type, and including null).

As someone nicely put above, null pointer represents a value whereas void* represents a type more than a value.

How to fix "Referenced assembly does not have a strong name" error?

There is a NuGet package named StrongNamer by Daniel Plaisted that seems to do the trick.

Is the simplest solution that I've found so far.

There are also a number of other NuGet packages to fix the strong naming problem such as Brutal.Dev.StrongNameSigner by Werner van Deventer, but I have not tested that one or any of the others.

How to concatenate strings in django templates?

And multiple concatenation:

from django import template
register = template.Library()


@register.simple_tag
def concat_all(*args):
    """concatenate all args"""
    return ''.join(map(str, args))

And in Template:

{% concat_all 'x' 'y' another_var as string_result %}
concatenated string: {{ string_result }}

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Used to face the same problem. The reason was in incorrect context passing to AlertDialog.Builder(here). use like AlertDialog.Builder(Homeactivity.this)

How do Python's any and all functions work?

The code in question you're asking about comes from my answer given here. It was intended to solve the problem of comparing multiple bit arrays - i.e. collections of 1 and 0.

any and all are useful when you can rely on the "truthiness" of values - i.e. their value in a boolean context. 1 is True and 0 is False, a convenience which that answer leveraged. 5 happens to also be True, so when you mix that into your possible inputs... well. Doesn't work.

You could instead do something like this:

[len(set(x)) > 1 for x in zip(*d['Drd2'])]

It lacks the aesthetics of the previous answer (I really liked the look of any(x) and not all(x)), but it gets the job done.

Auto height of div

Here is the Latest solution of the problem:

In your CSS file write the following class called .clearfix along with the pseudo selector :after

.clearfix:after {
content: "";
display: table;
clear: both;
}

Then, in your HTML, add the .clearfix class to your parent Div. For example:

<div class="clearfix">
    <div></div>
    <div></div>
</div>

It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "".

Source: http://css-snippets.com/page/2/

How to find if element with specific id exists or not

Use typeof for elements checks.

if(typeof(element) === 'undefined')
{
// then field does not exist
}

limit text length in php and provide 'Read more' link

This worked for me.

// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {

    // truncate string
    $stringCut = substr($string, 0, 500);
    $endPoint = strrpos($stringCut, ' ');

    //if the string doesn't contain any space then it will cut without word basis.
    $string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
    $string .= '... <a href="/this/story">Read More</a>';
}
echo $string;

Thanks @webbiedave

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

[^\[] Match any character that is not [.

+ Match 1 or more of the anything that is not [. Creates groups of these matches.

(?=\]) Positive lookahead ]. Matches a group ending with ] without including it in the result.

Done.

[^\[]+(?=\])

Proof.

http://regexr.com/3gobr

Similar to the solution proposed by null. But the additional \] is not required. As an additional note, it appears \ is not required to escape the [ after the ^. For readability, I would leave it in.

Does not work in the situation in which the delimiters are identical. "more or less" for example.

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

If you have just one query I don't know how to set timeout on T-SQL level.

However if you have a few queries (i.e. collecting data into temporary tables) inside stored procedure you can just control time of execution with GETDATE(), DATEDIFF() and a few INT variables storing time of execution of each part.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

Tools -> Build System -> New Build System. The type following as your OS, save as Chrome.sublime-build

Windows OS

  {
        "cmd": ["C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "$file"]
  }

MAC Os

{
   "cmd": ["open", "-a", "/Applications/Google Chrome.app", "$file"]
}

Save the file - Chrome.sublime-build in location

C:\Users\xnivirro\Downloads\Software-Installed\Sublime-2\Data\Packages\User

Sublime View in Browswer - https://github.com/adampresley/sublime-view-in-browser (Tried with Linux and it works)

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

If you use CMake you have to set WIN32 flag in add_executable

add_executable(${name} WIN32 ${source_files})

See CMake Doc for more information.

What integer hash function are good that accepts an integer hash key?

The answer depends on a lot of things like:

  • Where do you intend to employ it?
  • What are you trying to do with the hash?
  • Do you need a crytographically secure hash function?

I suggest that you take a look at the Merkle-Damgard family of hash functions like SHA-1 etc

file_get_contents behind a proxy?

To use file_get_contents() over/through a proxy that doesn't require authentication, something like this should do :

(I'm not able to test this one : my proxy requires an authentication)

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Of course, replacing the IP and port of my proxy by those which are OK for yours ;-)

If you're getting that kind of error :

Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 407 Proxy Authentication Required

It means your proxy requires an authentication.

If the proxy requires an authentication, you'll have to add a couple of lines, like this :

$auth = base64_encode('LOGIN:PASSWORD');

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
        'header'          => "Proxy-Authorization: Basic $auth",
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Same thing about IP and port, and, this time, also LOGIN and PASSWORD ;-) Check out all valid http options.

Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.

And... The page should be displayed ;-)

Find the smallest positive integer that does not occur in a given sequence

Java Solution - Inside de method solution

int N = A.length;

Set<Integer> set = new HashSet<>();
for (int a : A) {
    if (a > 0) {
        set.add(a);
    }
}

if(set.size()==0) {
    return N=1;
}

for (int i = 1; i <= N + 1; i++) {
    if (!set.contains(i)) {
        N= i;
        break;
    }
}
return N;

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

I would check the Installed value of

HKLM\SOFTWARE\[WOW6432Node]\Microsoft\Windows\CurrentVersion\Uninstall\{VCRedist_GUID} key

  • where GUID of VC++ 2012 (x86) is {33d1fd90-4274-48a1-9bc1-97e33d9c2d6f}
  • WOW6432Node will be present or not depending on the VC++ redist product

CSS selector based on element text?

I know it's not exactly what you are looking for, but maybe it'll help you.

You can try use a jQuery selector :contains(), add a class and then do a normal style for a class.

Oracle SqlPlus - saving output in a file but don't show on screen

Try this:

SET TERMOUT OFF; 
spool M:\Documents\test;
select * from employees;
/
spool off;

Efficient way to return a std::vector in c++

It's time I post an answer about RVO, me too...

If you return an object by value, the compiler often optimizes this so it doesn't get constructed twice, since it's superfluous to construct it in the function as a temporary and then copy it. This is called return value optimization: the created object will be moved instead of being copied.

Good way of getting the user's location in Android

I scoured the internet for an updated (past year) answer using the latest location pulling methods suggested by google (to use FusedLocationProviderClient). I finally landed on this:

https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates

I created a new project and copied in most of this code. Boom. It works. And I think without any deprecated lines.

Also, the simulator doesn't seem to get a GPS location, that I know of. It did get as far as reporting this in the log: "All location settings are satisfied."

And finally, in case you wanted to know (I did), you DO NOT need a google maps api key from the google developer console, if all you want is the GPS location.

Also useful is their tutorial. But I wanted a full one page tutorial/code example, and that. Their tutorial stacks but is confusing when you're new to this because you don't know what pieces you need from earlier pages.

https://developer.android.com/training/location/index.html

And finally, remember things like this:

I not only had to modify the mainActivity.Java. I also had to modify Strings.xml, androidmanifest.xml, AND the correct build.gradle. And also your activity_Main.xml (but that part was easy for me).

I needed to add dependencies like this one: implementation 'com.google.android.gms:play-services-location:11.8.0', and update the settings of my android studio SDK to include google play services. (file settings appearance system settings android SDK SDK Tools check google play services).

update: the android simulator did seem to get a location and location change events (when I changed the value in the settings of the sim). But my best and first results were on an actual device. So it's probably easiest to test on actual devices.

Forbidden You don't have permission to access /wp-login.php on this server

If you are using the iThemes Security plugin (former Better WP security) please refer to the answer provided by Mikeys4u.

Also, there is a similar thread related to this plugin on the WordPress support: https://wordpress.org/support/topic/how-to-reset-ithemes-security-plugin-to-fix-issues

Make sure you backup your database before trying any of the solutions.

How to get min, seconds and milliseconds from datetime.now() in python?

What about:

datetime.now().strftime('%M:%S.%f')[:-4]

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

EDIT

If the %f modifier doesn't work for you, you can try something like:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]

Again, I'm assuming you just want to truncate the precision.

mysql error 1364 Field doesn't have a default values

Open phpmyadmin and goto 'More' Tab and select 'Variables' submenu. Scroll down to find sql mode. Edit sql mode and remove 'STRICT_TRANS_TABLES' Save it.

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

I believe the intent was to rename System32, but so many applications hard-coded for that path, that it wasn't feasible to remove it.

SysWoW64 wasn't intended for the dlls of 64-bit systems, it's actually something like "Windows on Windows64", meaning the bits you need to run 32bit apps on a 64bit windows.

This article explains a bit:

"Windows x64 has a directory System32 that contains 64-bit DLLs (sic!). Thus native processes with a bitness of 64 find “their” DLLs where they expect them: in the System32 folder. A second directory, SysWOW64, contains the 32-bit DLLs. The file system redirector does the magic of hiding the real System32 directory for 32-bit processes and showing SysWOW64 under the name of System32."

Edit: If you're talking about an installer, you really should not hard-code the path to the system folder. Instead, let Windows take care of it for you based on whether or not your installer is running on the emulation layer.

What do parentheses surrounding an object/function/class declaration mean?

It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.

It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.

See:

http://en.wikipedia.org/wiki/Closure_%28computer_science%29

http://peter.michaux.ca/articles/javascript-namespacing

C# Dictionary get item by index

Your key is a string and your value is an int. Your code won't work because it cannot look up the random int you pass. Also, please provide full code

How to use data-binding with Fragment

You are actually encouraged to use the inflate method of your generated Binding and not the DataBindingUtil:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    MainFragmentBinding binding = MainFragmentBinding.inflate(inflater, container, false);
    //set variables in Binding
    return binding.getRoot();
}

Docs for DataBindingUtil.inflate():

Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

Detect application heap size in Android

Debug.getNativeHeapSize() will do the trick, I should think. It's been there since 1.0, though.

The Debug class has lots of great methods for tracking allocations and other performance concerns. Also, if you need to detect a low-memory situation, check out Activity.onLowMemory().

How do I escape a string inside JavaScript code inside an onClick handler?

In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string.

\xXX is for chars < 127, and \uXXXX for Unicode, so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist.

For example,

<a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a>

How to change letter spacing in a Textview?

after API >=21 there is inbuild method provided by TextView called setLetterSpacing

check this for more

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

WCF Service, the type provided as the service attribute values…could not be found

Change the following line in your Eval.svc file from:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.Eval" %> 

to:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.EvalService" %>

How to delete a workspace in Eclipse?

Click on the menu Window > Preferences and go to Workspaces like below :

| General
    | Startup and Shutdown
        | Workspaces

Select the workspace to delete and click on the Remove button.

How can I set / change DNS using the command-prompt at windows 8

Now you can change the primary dns (index=1), assuming that your interface is static (not using dhcp)

You can set your DNS servers statically even if you use DHCP to obtain your IP address.

Example under Windows 7 to add two DN servers, the command is as follows:

netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=1 netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=2

How to add elements to an empty array in PHP?

Both array_push and the method you described will work.

$customArray = array();
$customArray[] = 20;
$customArray[] = 21;

Above is correct, but below one is for further understanding

$customArray = array();
for($i=0;$i<=12;$i++){
    $cart[] = $i;  
}
echo "<pre>";
print_r($customArray);
echo "</pre>";

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

you can use added method like;

_dbContext.Entry(modelclassname).State = EntityState.Added;

but in many case if you want to use more than one model at that time this won't work because entity is already attached to another entity. So, at that time you can use ADDOrUpdate Entity Migration method which simply migrates object from one to another and as a result you wouldn't get any error.

_dbContext.Set<modelclassname>().AddOrUpdate(yourmodel);

Compile a DLL in C/C++, then call it from another program

For VB6:

You need to declare your C functions as __stdcall, otherwise you get "invalid calling convention" type errors. About other your questions:

can I take arguments by pointer/reference from the VB front-end?

Yes, use ByRef/ByVal modifiers.

Can the DLL call a theoretical function in the front-end?

Yes, use AddressOf statement. You need to pass function pointer to dll before.

Or have a function take a "function pointer" (I don't even know if that's possible) from VB and call it?)

Yes, use AddressOf statement.

update (more questions appeared :)):

to load it into VB, do I just do the usual method (what I would do to load winsock.ocx or some other runtime, but find my DLL instead) or do I put an API call into a module?

You need to decaler API function in VB6 code, like next:

Private Declare Function SHGetSpecialFolderLocation Lib "shell32" _
   (ByVal hwndOwner As Long, _
    ByVal nFolder As Long, _
    ByRef pidl As Long) As Long

NoClassDefFoundError in Java: com/google/common/base/Function

When I caught the exception java.lang.NoClassDefFoundError: com/google/common/base/Function it was caused by errors in Project Libraries.

Please check it in your project settings. For Intellij IDEA go to File - Project Structure and select Modules tab. All I needed to do to resolve this exception was re-adding the selenium library

Catch multiple exceptions at once?

How about

try
{
    WebId = Guid.Empty;
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}

using lodash .groupBy. how to add your own keys for grouped output?

Isn't it this simple?

var result = _(data)
            .groupBy(x => x.color)
            .map((value, key) => ({color: key, users: value}))
            .value();

How to create a pivot query in sql server without aggregate function

Check this out as well: using xml path and pivot

SQLFIDDLE DEMO

| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
|   Asset |  205 |  142 |  421 |
|  Equity |  365 |  214 |  163 |
|  Profit |  524 |  421 |  325 |

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period) 
            FROM demo c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT account, ' + @cols + ' from 
            (
                select account
                    , value
                    , period
                from demo
           ) x
            pivot 
            (
                 max(value)
                for period in (' + @cols + ')
            ) p '


execute(@query)

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

How to encode text to base64 in python

To compatibility with both py2 and py3

import six
import base64

def b64encode(source):
    if six.PY3:
        source = source.encode('utf-8')
    content = base64.b64encode(source).decode('utf-8')

What is the point of WORKDIR on Dockerfile?

Beware of using vars as the target directory name for WORKDIR - doing that appears to result in a "cannot normalize nothing" fatal error. IMO, it's also worth pointing out that WORKDIR behaves in the same way as mkdir -p <path> i.e. all elements of the path are created if they don't exist already.

UPDATE: I encountered the variable related problem (mentioned above) whilst running a multi-stage build - it now appears that using a variable is fine - if it (the variable) is "in scope" e.g. in the following, the 2nd WORKDIR reference fails ...

FROM <some image>
ENV varname varval
WORKDIR $varname

FROM <some other image>
WORKDIR $varname

whereas, it succeeds in this ...

FROM <some image>
ENV varname varval
WORKDIR $varname

FROM <some other image>
ENV varname varval
WORKDIR $varname

.oO(Maybe it's in the docs & I've missed it)

git status shows fatal: bad object HEAD

I solved this by renaming the branch in the file .git/refs/remotes/origin/HEAD.

twitter bootstrap 3.0 typeahead ajax example

I'm using this https://github.com/biggora/bootstrap-ajax-typeahead

The result of code using Codeigniter/PHP

<pre>

$("#produto").typeahead({
        onSelect: function(item) {
            console.log(item);
            getProductInfs(item);
        },
        ajax: {
            url: path + 'produto/getProdName/',
            timeout: 500,
            displayField: "concat",
            valueField: "idproduto",
            triggerLength: 1,
            method: "post",
            dataType: "JSON",
            preDispatch: function (query) {
                showLoadingMask(true);
                return {
                    search: query
                }
            },
            preProcess: function (data) {

                if (data.success === false) {
                    return false;
                }else{
                    return data;    
                }                
            }               
        }
    });
</pre>   

What's the -practical- difference between a Bare and non-Bare repository?

A default/non-bare Git repo contains two pieces of state:

  1. A snapshot of all of the files in the repository (this is what "working tree" means in Git jargon)
  2. A history of all changes made to all the files that have ever been in the repository (there doesn't seem to be a concise piece of Git jargon that encompasses all of this)

The snapshot is what you probably think of as your project: your code files, build files, helper scripts, and anything else you version with Git.

The history is the state that allows you to check out a different commit and get a complete snapshot of what the files in your repository looked like when that commit was added. It consists of a bunch of data structures that are internal to Git that you've probably never interacted with directly. Importantly, the history doesn't just store metadata (e.g. "User U added this many lines to File F at Time T as part of Commit C"), it also stores data (e.g. "User U added these exact lines to File F").

The key idea of a bare repository is that you don't actually need to have the snapshot. Git keeps the snapshot around because it's convenient for humans and other non-Git processes that want to interact with your code, but the snapshot is just duplicating state that's already in the history.

A bare repository is a Git repository that does not have a snapshot. It just stores the history.

Why would you want this? Well, if you're only going to interact with your files using Git (that is, you're not going to edit your files directly or use them to build an executable), you can save space by not keeping around the snapshot. In particular, if you're maintaining a centralized version of your repo on a server somewhere (i.e. you're basically hosting your own GitHub), that server should probably have a bare repo (you would still use a non-bare repo on your local machine though, since you'll presumably want to edit your snapshot).

If you want a more in-depth explanation of bare repos and another example use case, I wrote up a blog post here: https://stegosaurusdormant.com/bare-git-repo/

Mockito match any class argument

If you have no idea which Package you need to import:

import static org.mockito.ArgumentMatchers.any;
any(SomeClass.class)

OR

import org.mockito.ArgumentMatchers;
ArgumentMatchers.any(SomeClass.class)

How can I use iptables on centos 7?

I had the problem that rebooting wouldn't start iptables.

This fixed it:

yum install iptables-services
systemctl mask firewalld
systemctl enable iptables
systemctl enable ip6tables
systemctl stop firewalld
systemctl start iptables
systemctl start ip6tables

Parse JSON in JavaScript?

The standard way to parse JSON in JavaScript is JSON.parse()

The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:

_x000D_
_x000D_
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);
_x000D_
_x000D_
_x000D_


The only time you won't be able to use JSON.parse() is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse().

When processing extremely large JSON files, JSON.parse() may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet, which provide streaming JSON parsing.

jQuery once had a $.parseJSON() function, but it was deprecated with jQuery 3.0. In any case, for a long time, it was nothing more than a wrapper around JSON.parse().

Which version of C# am I using

Thanks to @fortesl and this answer

I'm using VS 2019 and it doesn't easily tell you the C# version you are using. I'm working with .Net Core 3.0, and VS 2019 using C# 8 in that environment. But "csc -langversion:?" makes this clear:

D:\>csc -langversion:?
Supported language versions:
default
1
2
3
4
5
6
7.0
7.1
7.2
7.3
8.0 (default)
latestmajor
preview
latest

Not sure what csc -version is identifying:

D:\>csc --version
Microsoft (R) Visual C# Compiler version 3.4.0-beta1-19462-14 (2f21c63b)
Copyright (C) Microsoft Corporation. All rights reserved.

Requested registry access is not allowed

You can't write to the HKCR (or HKLM) hives in Vista and newer versions of Windows unless you have administrative privileges. Therefore, you'll either need to be logged in as an Administrator before you run your utility, give it a manifest that says it requires Administrator level (which will prompt the user for Admin login info), or quit changing things in places that non-Administrators shouldn't be playing. :-)

How to install psycopg2 with "pip" on Python?

On Fedora 24: For Python 3.x

sudo dnf install postgresql-devel python3-devel

sudo dnf install redhat-rpm-config

Activate your Virtual Environment:

pip install psycopg2

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

As precised in the annotation documentation, the annotation indicates that the argument name is used as the property name without any modifications, but it can be specified to non-empty value to specify different name:

Override valueof() and toString() in Java enum

I don't think your going to get valueOf("Start Here") to work. But as far as spaces...try the following...

static private enum RandomEnum {
    R("Start There"), 
    G("Start Here"); 
    String value;
    RandomEnum(String s) {
        value = s;
    }
}

System.out.println(RandomEnum.G.value);
System.out.println(RandomEnum.valueOf("G").value);

Start Here
Start Here

Converting NumPy array into Python List structure?

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)

Python - Create list with numbers between 2 values?

Try:

range(x1,x2+1)  

That is a list in Python 2.x and behaves mostly like a list in Python 3.x. If you are running Python 3 and need a list that you can modify, then use:

list(range(x1,x2+1))

Java maximum memory on Windows XP

First, using a page-file when you have 4 GB of RAM is useless. Windows can't access more than 4GB (actually, less because of memory holes) so the page file is not used.

Second, the address space is split in 2, half for kernel, half for user mode. If you need more RAM for your applications use the /3GB option in boot.ini (make sure java.exe is marked as "large address aware" (google for more info).

Third, I think you can't allocate the full 2 GB of address space because java wastes some memory internally (for threads, JIT compiler, VM initialization, etc). Use the /3GB switch for more.

Difference between iCalendar (.ics) and the vCalendar (.vcs)

The newer iCalendar format, with more data attached, includes information about the person who created the event, so that when it is imported into Outlook (for example), changes to that event are communicated via email to the creator. This can be helpful when you need to inform others of any changes.

However, when I am just exporting an event from one of my calendars to another, I prefer to use vCalendar, since this does not require sending an email message to the creator (usually myself) if I make a change or delete something.

Cassandra cqlsh - connection refused

Try to change the rpc_address to point to the node's IP instead of 0.0.0.0 and specify the IP while connecting to the cqlsh, as if the IP is 10.0.2.64 and the rpc_port left to the default value 9160 then the following should work:

cqlsh 10.0.2.64 9160 

OR

cqlsh 10.0.2.64

Also make sure that start_rpc is set to true in /etc/cassandra/cassandra.yaml configuration file.

Can't install nuget package because of "Failed to initialize the PowerShell host"

I had the same problem with vs2013 and changing execution policy did not fix it. The only working solution I found was uninstalling Nuget from VS and installing it again. Steps are here: https://stackoverflow.com/a/32619961/3853238

How can I use JavaScript in Java?

Rhino is what you are looking for.

Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.

Update: Now Nashorn, which is more performant JavaScript Engine for Java, is available with jdk8.

How to create a directive with a dynamic template in AngularJS?

Had a similar need. $compile does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)

http://jsbin.com/ebuhuv/7/edit - my exploration test.

One thing to note (per my example), one of my requirements was that the template would change based on a type attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.