Programs & Examples On #Simulink

Simulink® is an environment developed by The MathWorks for multidomain simulation and Model-Based Design for dynamic and embedded systems.

Bootstrap: adding gaps between divs

Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your custom.css (you shouldn't edit the core stylesheet anyway) file and add something like .gap. However, .col-md-offset-* does the job most of the times for me, allowing me to precisely leave a gap between the divs.

As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like .top-buffer { margin-top:20px; }. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.

Regular expression for only characters a-z, A-Z

This /[^a-z]/g solves the problem.

_x000D_
_x000D_
function pangram(str) {
    let regExp = /[^a-z]/g;
    let letters = str.toLowerCase().replace(regExp, '');
    document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2@# %hfr efg uor7 489(*&^% knt lhtkjj ngnm!@#$%^&*()_');
_x000D_
<h4 id="letters"></h4>
_x000D_
_x000D_
_x000D_

Should I use encodeURI or encodeURIComponent for encoding URLs?

It depends on what you are actually wanting to do.

encodeURI assumes that the input is a complete URI that might have some characters which need encoding in it.

encodeURIComponent will encode everything with special meaning, so you use it for components of URIs such as

var world = "A string with symbols & characters that have special meaning?";
var uri = 'http://example.com/foo?hello=' + encodeURIComponent(world);

Button text toggle in jquery

$(".pushme").click(function () {
  var button = $(this);
  button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")           
});

This ternary operator has an implicit return. If the expression before ? is true it returns "DON'T PUSH ME", else returns "PUSH ME"

This if-else statement:

if (condition) { return A }
else { return B }

has the equivalent ternary expression:

condition ? A : B

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

How and where are Annotations used in Java?

Frameworks like Hibernate were lots of configuration/mapping is required uses Annotations heavily.

Take a look at Hibernate Annotations

Print execution time of a shell command

Adding to @mob's answer:

Appending %N to date +%s gives us nanosecond accuracy:

start=`date +%s%N`;<command>;end=`date +%s%N`;echo `expr $end - $start`

How to check the multiple permission at single request in Android M?

I had the same issue and stumbled on this library.

Basically you can ask for multiple permissions sequentially, plus you can add listeners to popup a snackbar if the user denies your permission.

dexter_sample

Singleton with Arguments in Java

"A singleton with parameters is not a singleton" statement is not completely correct. We need to analyze this from the application perspective rather than from the code perspective.

We build singleton class to create a single instance of an object in one application run. By having a constructor with parameter, you can build flexibility into your code to change some attributes of your singleton object every time you run you application. This is not a violation of Singleton pattern. It looks like a violation if you see this from code perspective.

Design Patterns are there to help us write flexible and extendable code, not to hinder us writing good code.

Installing specific package versions with pip

This below command worked for me

Python version - 2.7

package - python-jenkins

command - $ pip install 'python-jenkins>=1.1.1'

Remove all child elements of a DOM node in JavaScript

This is a pure javascript i am not using jQuery but works in all browser even IE and it is verry simple to understand

   <div id="my_div">
    <p>Paragraph one</p>
    <p>Paragraph two</p>
    <p>Paragraph three</p>
   </div>
   <button id ="my_button>Remove nodes ?</button>

   document.getElementById("my_button").addEventListener("click",function(){

  let parent_node =document.getElemetById("my_div"); //Div which contains paagraphs

  //Let find numbers of child inside the div then remove all
  for(var i =0; i < parent_node.childNodes.length; i++) {
     //To avoid a problem which may happen if there is no childNodes[i] 
     try{
       if(parent_node.childNodes[i]){
         parent_node.removeChild(parent_node.childNodes[i]);
       }
     }catch(e){
     }
  }

})

or you may simpli do this which is a quick way to do

document.getElementById("my_button").addEventListener("click",function(){

 let parent_node =document.getElemetById("my_div");
 parent_node.innerHTML ="";

})

How can I use JavaScript in Java?

Java includes a scripting language extension package starting with version 6.

See the Rhino project documentation for embedding a JavaScript interpreter in Java.

[Edit]

Here is a small example of how you can expose Java objects to your interpreted script:

public class JS {
  public static void main(String args[]) throws Exception {
    ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
    Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("stdout", System.out);
    js.eval("stdout.println(Math.cos(Math.PI));");
    // Prints "-1.0" to the standard output stream.
  }
}

Forward declaration of a typedef in C++

Because to declare a type, its size needs to be known. You can forward declare a pointer to the type, or typedef a pointer to the type.

If you really want to, you can use the pimpl idiom to keep the includes down. But if you want to use a type, rather than a pointer, the compiler has to know its size.

Edit: j_random_hacker adds an important qualification to this answer, basically that the size needs to be know to use the type, but a forward declaration can be made if we only need to know the type exists, in order to create pointers or references to the type. Since the OP didn't show code, but complained it wouldn't compile, I assumed (probably correctly) that the OP was trying to use the type, not just refer to it.

NoClassDefFoundError on Maven dependency

I was able to work around it by running mvn install:install-file with -Dpackaging=class. Then adding entry to POM as described here:

How to set Internet options for Android emulator?

for the records since this is an old post and since nobody mentioned it, check if you forgot (as I did) to set the android.permission.INTERNET flag in AndroidManifest.xml as, i.e.:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.webviewdemo">
<uses-permission android:name="android.permission.INTERNET"/>
    <application android:icon="@drawable/icon">
        <activity android:name=".WebViewDemo" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Java: how to import a jar file from command line

you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".

How to install wget in macOS?

You need to do

./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl

Instead of this

./configure --with-ssl=openssl

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

Insert Update trigger how to determine if insert or update

Declare @Type varchar(50)='';
IF EXISTS (SELECT * FROM inserted) and  EXISTS (SELECT * FROM deleted)
BEGIN
    SELECT @Type = 'UPDATE'
END
ELSE IF EXISTS(SELECT * FROM inserted)
BEGIN
    SELECT @Type = 'INSERT'
END
ElSE IF EXISTS(SELECT * FROM deleted)
BEGIN
    SELECT @Type = 'DELETE'
END

Get user profile picture by Id

you can get it with using this url : you will get the picture HD (max size)

https://graph.facebook.com/{userID}?fields=picture.width(720).height(720)&redirect=false

don't forget redirect=false or it will return an error

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

I faced the same error :

"An error occurred while updating the entries. See the inner exception for details”

Simply Delete and Recreate the *.edmx file. Its worked for me. the error will gone

Convert UTC datetime string to local datetime

Here's a resilient method that doesn't depend on any external libraries:

from datetime import datetime
import time

def datetime_from_utc_to_local(utc_datetime):
    now_timestamp = time.time()
    offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)
    return utc_datetime + offset

This avoids the timing issues in DelboyJay's example. And the lesser timing issues in Erik van Oosten's amendment.

As an interesting footnote, the timezone offset computed above can differ from the following seemingly equivalent expression, probably due to daylight savings rule changes:

offset = datetime.fromtimestamp(0) - datetime.utcfromtimestamp(0) # NO!

Update: This snippet has the weakness of using the UTC offset of the present time, which may differ from the UTC offset of the input datetime. See comments on this answer for another solution.

To get around the different times, grab the epoch time from the time passed in. Here's what I do:

def utc2local (utc):
    epoch = time.mktime(utc.timetuple())
    offset = datetime.fromtimestamp (epoch) - datetime.utcfromtimestamp (epoch)
    return utc + offset

Simple parse JSON from URL on Android and display in listview

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following


Async task has three primary methods:

  1. onPreExecute() - most commonly used for setting up and starting a progress dialog

  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

Then we need to set up the connection and how we want to handle the response:

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

Iterating over ResultSet and adding its value in an ArrayList

Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet to List, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator:

jOOQ 3.8 or less

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(r -> Arrays.stream(r.intoArray()))
   .collect(Collectors.toList());

jOOQ 3.9

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(Record::intoStream)
   .collect(Collectors.toList());

(Disclaimer, I work for the company behind jOOQ)

CSS table-cell equal width

Here is a working fiddle with indeterminate number of cells: http://jsfiddle.net/r9yrM/1/

You can fix a width to each parent div (the table), otherwise it'll be 100% as usual.

The trick is to use table-layout: fixed; and some width on each cell to trigger it, here 2%. That will trigger the other table algorightm, the one where browsers try very hard to respect the dimensions indicated.
Please test with Chrome (and IE8- if needed). It's OK with a recent Safari but I can't remember the compatibility of this trick with them.

CSS (relevant instructions):

div {
    display: table;
    width: 250px;
    table-layout: fixed;
}

div > div {
    display: table-cell;
    width: 2%; /* or 100% according to OP comment. See edit about Safari 6 below */
}

EDIT (2013): Beware of Safari 6 on OS X, it has table-layout: fixed; wrong (or maybe just different, very different from other browsers. I didn't proof-read CSS2.1 REC table layout ;) ). Be prepared to different results.

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

As I understand the browser, Chrome at least, it doesn't disable the source mapping by default. That means your application's users will trigger this source-mapping request by default.

You can remove the source mapping by deleting the //@ sourceMappingURL=jquery.min.map from your JavaScript file.

Solr vs. ElasticSearch

Update

Now that the question scope has been corrected, I might add something in this regard as well:

There are many comparisons between Apache Solr and ElasticSearch available, so I'll reference those I found most useful myself, i.e. covering the most important aspects:

  • Bob Yoplait already linked kimchy's answer to ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?, which summarizes the reasons why he went ahead and created ElasticSearch, which in his opinion provides a much superior distributed model and ease of use in comparison to Solr.

  • Ryan Sonnek's Realtime Search: Solr vs Elasticsearch provides an insightful analysis/comparison and explains why he switched from Solr to ElasticSeach, despite being a happy Solr user already - he summarizes this as follows:

    Solr may be the weapon of choice when building standard search applications, but Elasticsearch takes it to the next level with an architecture for creating modern realtime search applications. Percolation is an exciting and innovative feature that singlehandedly blows Solr right out of the water. Elasticsearch is scalable, speedy and a dream to integrate with. Adios Solr, it was nice knowing you. [emphasis mine]

  • The Wikipedia article on ElasticSearch quotes a comparison from the reputed German iX magazine, listing advantages and disadvantages, which pretty much summarize what has been said above already:

    Advantages:

    • ElasticSearch is distributed. No separate project required. Replicas are near real-time too, which is called "Push replication".
    • ElasticSearch fully supports the near real-time search of Apache Lucene.
    • Handling multitenancy is not a special configuration, where with Solr a more advanced setup is necessary.
    • ElasticSearch introduces the concept of the Gateway, which makes full backups easier.

    Disadvantages:

    • Only one main developer [not applicable anymore according to the current elasticsearch GitHub organization, besides having a pretty active committer base in the first place]
    • No autowarming feature [not applicable anymore according to the new Index Warmup API]

Initial Answer

They are completely different technologies addressing completely different use cases, thus cannot be compared at all in any meaningful way:

  • Apache Solr - Apache Solr offers Lucene's capabilities in an easy to use, fast search server with additional features like faceting, scalability and much more

  • Amazon ElastiCache - Amazon ElastiCache is a web service that makes it easy to deploy, operate, and scale an in-memory cache in the cloud.

    • Please note that Amazon ElastiCache is protocol-compliant with Memcached, a widely adopted memory object caching system, so code, applications, and popular tools that you use today with existing Memcached environments will work seamlessly with the service (see Memcached for details).

[emphasis mine]

Maybe this has been confused with the following two related technologies one way or another:

  • ElasticSearch - It is an Open Source (Apache 2), Distributed, RESTful, Search Engine built on top of Apache Lucene.

  • Amazon CloudSearch - Amazon CloudSearch is a fully-managed search service in the cloud that allows customers to easily integrate fast and highly scalable search functionality into their applications.

The Solr and ElasticSearch offerings sound strikingly similar at first sight, and both use the same backend search engine, namely Apache Lucene.

While Solr is older, quite versatile and mature and widely used accordingly, ElasticSearch has been developed specifically to address Solr shortcomings with scalability requirements in modern cloud environments, which are hard(er) to address with Solr.

As such it would probably be most useful to compare ElasticSearch with the recently introduced Amazon CloudSearch (see the introductory post Start Searching in One Hour for Less Than $100 / Month), because both claim to cover the same use cases in principle.

What is a regular expression which will match a valid domain name without a subdomain?

Here is complete code with example:

<?php
function is_domain($url)
{
    $parse = parse_url($url);
    if (isset($parse['host'])) {
        $domain = $parse['host'];
    } else {
        $domain = $url;
    }

    return preg_match('/^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$/', $domain);
}

echo is_domain('example.com'); //true
echo is_domain('https://example.com'); //true
echo is_domain('https://.example.com'); //false
echo is_domain('https://localhost'); //false

Bash script to check running process

A simple script version of one of Andor's above suggestions:

!/bin/bash

pgrep $1 && echo Running

If the above script is called test.sh then, in order to test, type: test.sh NameOfProcessToCheck

e.g. test.sh php

PHP Undefined Index

if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

How to grant remote access to MySQL for a whole subnet?

Just a note of a peculiarity I faced:
Consider:

db server:  192.168.0.101
web server: 192.168.0.102

If you have a user defined in mysql.user as 'user'@'192.168.0.102' with password1 and another 'user'@'192.168.0.%' with password2,

then,

if you try to connect to the db server from the web server as 'user' with password2,

it will result in an 'Access denied' error because the single IP 'user'@'192.168.0.102' authentication is used over the wildcard 'user'@'192.168.0.%' authentication.

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

2 column div layout: right column with fixed width, left fluid

Best to avoid placing the right column before the left, simply use a negative right-margin.

And be "responsive" by including an @media setting so the right column falls under the left on narrow screens.

<div style="background: #f1f2ea;">
  <div id="container">
    <div id="content">
        <strong>Column 1 - content</strong>
    </div>
  </div>
  <div id="sidebar">
    <strong>Column 2 - sidebar</strong>
  </div>
<div style="clear:both"></div>

<style type="text/css">
#container {
    margin-right: -300px;
    float:left;
    width:100%;
}
#content {
    margin-right: 320px; /* 20px added for center margin */
}
#sidebar {
    width:300px;
    float:left
}
@media (max-width: 480px) {
    #container {
        margin-right:0px;
        margin-bottom:20px;
    }
    #content {
        margin-right:0px;
        width:100%;
    }
    #sidebar {
        clear:left;
    }
}
</style>

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

I fixed this error on my RDS instance by rebooting it from the AWS management console. HTH

[edit: lol downvotes]

PHP Foreach Arrays and objects

Use

//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
  echo $value->sm_id;
}

OR

//$arr should be array as you mentioned as below
foreach($arr as $value){
  echo $value->sm_id;
}

SQL - Select first 10 rows only?

The ANSI SQL answer is FETCH FIRST.

SELECT a.names,
         COUNT(b.post_title) AS num
    FROM wp_celebnames a
    JOIN wp_posts b ON INSTR(b.post_title, a.names) > 0
    WHERE b.post_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
GROUP BY a.names
ORDER BY num DESC
FETCH FIRST 10 ROWS ONLY

If you want ties to be included, do FETCH FIRST 10 ROWS WITH TIES instead.

To skip a specified number of rows, use OFFSET, e.g.

...
ORDER BY num DESC
OFFSET 20
FETCH FIRST 10 ROWS ONLY

Will skip the first 20 rows, and then fetch 10 rows.

Supported by newer versions of Oracle, PostgreSQL, MS SQL Server, Mimer SQL and DB2 etc.

Sublime Text 3 how to change the font size of the file sidebar?

Sublime Text -> Preferences -> Setting:

Sublime Text -> Preferences -> setting

Write your style in right screen:

Write your style in right screen

How to do "If Clicked Else .."

You should avoid using global vars, and prefer using .data()

So, you'd do:

jQuery('#id').click(function(){
  $(this).data('clicked', true);
});

Then, to check if it was clicked and perform an action:

if(jQuery('#id').data('clicked')) {
    //clicked element, do-some-stuff
} else {
    //run function2
}

Hope this helps. Cheers

How to convert a string to ASCII

.NET stores all strings as a sequence of UTF-16 code units. (This is close enough to "Unicode characters" for most purposes.)

Fortunately for you, Unicode was designed such that ASCII values map to the same number in Unicode, so after you've converted each character to an integer, you can just check whether it's in the ASCII range. Note that you can use an implicit conversion from char to int - there's no need to call a conversion method:

string text = "Here's some text including a \u00ff non-ASCII character";
foreach (char c in text)
{
    int unicode = c;
    Console.WriteLine(unicode < 128 ? "ASCII: {0}" : "Non-ASCII: {0}", unicode);
}

Converting XML to JSON using Python?

xmltodict (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this "standard". It is Expat-based, so it's very fast and doesn't need to load the whole XML tree in memory.

Once you have that data structure, you can serialize it to JSON:

import xmltodict, json

o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'

Maven: How to rename the war file for the project?

You can use the following in the web module that produces the war:

<build>
  <finalName>bird</finalName>
 . . .
</build>

This leads to a file called bird.war to be created when goal "war:war" is used.

How to Bulk Insert from XLSX file extension?

Create a linked server to your document

http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm

Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.

You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.

Found shared references to a collection org.hibernate.HibernateException

I too got the same issue, someone used BeanUtils.copyProperties(source, target). Here both source and target, are using the same collection as attribute.

So i just used the deep copy as below..

How to Clone Collection in Java - Deep copy of ArrayList and HashSet

Get first and last date of current month with JavaScript or jQuery

Very simple, no library required:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

Some browsers will treat two digit years as being in the 20th century, so that:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Depend on a branch or tag using a git URL in a package.json?

On latest version of NPM you can just do:

npm install gitAuthor/gitRepo#tag

If the repo is a valid NPM package it will be auto-aliased in package.json as:

{ "NPMPackageName": "gitAuthor/gitRepo#tag" }

If you could add this to @justingordon 's answer there is no need for manual aliasing now !

Newtonsoft JSON Deserialize

As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:

var definition = new { Name = "" };

string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);

Console.WriteLine(customer1.Name);
// James

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

Add this in the head:

<link rel="stylesheet" type="text/css" href="/path/to/easyscrolltable.css">
<script src="/path/to/easyscrolltable.js"></script>

Javascript:

$('table.ytable').EasyScrollableTable({
    'top'  : 1,  
    'left' : 1,  
    'class': '',
    'width': '100%',
    'height': 'auto',
    'footer': false,
    'hover': true
});

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

If you are doing this in a DB upgrade statement, perhaps the simplest way is to just catch the exception thrown if you are attempting to add a field that may already exist.

try {
   db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN foo TEXT default null");
} catch (SQLiteException ex) {
   Log.w(TAG, "Altering " + TABLE_NAME + ": " + ex.getMessage());
}

Should I use JSLint or JSHint JavaScript validation?

[EDIT]
This answer has been edited. I'm leaving the original answer below for context (otherwise the comments wouldn't make sense).

When this question was originally asked, JSLint was the main linting tool for JavaScript. JSHint was a new fork of JSLint, but had not yet diverged much from the original.

Since then, JSLint has remained pretty much static, while JSHint has changed a great deal - it has thrown away many of JSLint's more antagonistic rules, has added a whole load of new rules, and has generally become more flexible. Also, another tool ESLint is now available, which is even more flexible and has more rule options.

In my original answer, I said that you should not force yourself to stick to JSLint's rules; as long as you understood why it was throwing a warning, you could make a judgement for yourself about whether to change the code to resolve the warning or not.

With the ultra-strict ruleset of JSLint from 2011, this was reasonable advice -- I've seen very few JavaScript codesets that could pass a JSLint test. However with the more pragmatic rules available in today's JSHint and ESLint tools, it is a much more realistic proposition to try to get your code passing through them with zero warnings.

There may still occasionally be cases where a linter will complain about something that you've done intentionally -- for example, you know that you should always use === but just this one time you have a good reason to use ==. But even then, with ESLint you have the option to specify eslint-disable around the line in question so you can still have a passing lint test with zero warnings, with the rest of your code obeying the rule. (just don't do that kind of thing too often!)


[ORIGINAL ANSWER FOLLOWS]

By all means use JSLint. But don't get hung up on the results and on fixing everything that it warns about. It will help you improve your code, and it will help you find potential bugs, but not everything that JSLint complains about turns out to be a real problem, so don't feel like you have to complete the process with zero warnings.

Pretty much any Javascript code with any significant length or complexity will produce warnings in JSLint, no matter how well written it is. If you don't believe me, try running some popular libraries like JQuery through it.

Some JSLint warnings are more valuable than others: learn which ones to watch out for, and which ones are less important. Every warning should be considered, but don't feel obliged to fix your code to clear any given warning; it's perfectly okay to look at the code and decide you're happy with it; there are times when things that JSlint doesn't like are actually the right thing to do.

How do I find the length of an array?

std::vector has a method size() which returns the number of elements in the vector.

(Yes, this is tongue-in-cheek answer)

What strategies and tools are useful for finding memory leaks in .NET?

Big guns - Debugging Tools for Windows

This is an amazing collection of tools. You can analyze both managed and unmanaged heaps with it and you can do it offline. This was very handy for debugging one of our ASP.NET applications that kept recycling due to memory overuse. I only had to create a full memory dump of living process running on production server, all analysis was done offline in WinDbg. (It turned out some developer was overusing in-memory Session storage.)

"If broken it is..." blog has very useful articles on the subject.

How can I convert a .jar to an .exe?

Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:

exestub.sh:

#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt  0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
    case $1 in
        -Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
        -D*)  JAVA_OPT="$JAVA_OPT $1" ;;
        *)    PROG_OPT="$PROG_OPT $1" ;;
    esac
    shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT

Then you create your runnable file from your jar:

$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable

It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>, as <myexe> is a valid zip/jar file.

AmazonS3 putObject with InputStream length example

For uploading, the S3 SDK has two putObject methods:

PutObjectRequest(String bucketName, String key, File file)

and

PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata)

The inputstream+ObjectMetadata method needs a minimum metadata of Content Length of your inputstream. If you don't, then it will buffer in-memory to get that information, this could cause OOM. Alternatively, you could do your own in-memory buffering to get the length, but then you need to get a second inputstream.

Not asked by the OP (limitations of his environment), but for someone else, such as me. I find it easier, and safer (if you have access to temp file), to write the inputstream to a temp file, and put the temp file. No in-memory buffer, and no requirement to create a second inputstream.

AmazonS3 s3Service = new AmazonS3Client(awsCredentials);
File scratchFile = File.createTempFile("prefix", "suffix");
try {
    FileUtils.copyInputStreamToFile(inputStream, scratchFile);    
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, id, scratchFile);
    PutObjectResult putObjectResult = s3Service.putObject(putObjectRequest);

} finally {
    if(scratchFile.exists()) {
        scratchFile.delete();
    }
}

php: check if an array has duplicates

You can do it like that way also: This will return true if unique else return false.

$nofollow = (count($modelIdArr) !== count(array_unique($modelIdArr))) ? true : false;

Image is not showing in browser?

Another random reason for why your images might not show up is because of something called base href="http://..." this can make it so that the images file doesn't work the way it should. Delete that line and you should be good.

In a Bash script, how can I exit the entire script if a certain condition occurs?

Instead of if construct, you can leverage the short-circuit evaluation:

#!/usr/bin/env bash

echo $[1+1]
echo $[2/0]              # division by 0 but execution of script proceeds
echo $[3+1]
(echo $[4/0]) || exit $? # script halted with code 1 returned from `echo`
echo $[5+1]

Note the pair of parentheses which is necessary because of priority of alternation operator. $? is a special variable set to exit code of most recently called command.

PHPDoc type hinting for array of objects?

In NetBeans 7.0 (may be lower too) you could declare the the return type "array with Text objects " just as @return Text and the code hinting will work:

Edit: updated the example with @Bob Fanger suggestion

/**
 * get all Tests
 *
 * @return Test|Array $tests
 */
public function getAllTexts(){
    return array(new Test(), new Test());
}

and just use it:

$tests =  $controller->getAllTests();
//$tests->         //codehinting works!
//$tests[0]->      //codehinting works!

foreach($tests as $text){
    //$test->      //codehinting works!
}

It is not perfect but it is better then just to leave it just "mixed", which brings no value.

CONS is you are allowed to tread the array as Text Object which will throw errors.

Convert SVG to image (JPEG, PNG, etc.) in the browser

I wrote this ES6 Class which does the Job.

class SvgToPngConverter {
  constructor() {
    this._init = this._init.bind(this);
    this._cleanUp = this._cleanUp.bind(this);
    this.convertFromInput = this.convertFromInput.bind(this);
  }

  _init() {
    this.canvas = document.createElement("canvas");
    this.imgPreview = document.createElement("img");
    this.imgPreview.style = "position: absolute; top: -9999px";

    document.body.appendChild(this.imgPreview);
    this.canvasCtx = this.canvas.getContext("2d");
  }

  _cleanUp() {
    document.body.removeChild(this.imgPreview);
  }

  convertFromInput(input, callback) {
    this._init();
    let _this = this;
    this.imgPreview.onload = function() {
      const img = new Image();
      _this.canvas.width = _this.imgPreview.clientWidth;
      _this.canvas.height = _this.imgPreview.clientHeight;
      img.crossOrigin = "anonymous";
      img.src = _this.imgPreview.src;
      img.onload = function() {
        _this.canvasCtx.drawImage(img, 0, 0);
        let imgData = _this.canvas.toDataURL("image/png");
        if(typeof callback == "function"){
            callback(imgData)
        }
        _this._cleanUp();
      };
    };

    this.imgPreview.src = input;
  }
}

Here is how you use it

let input = "https://restcountries.eu/data/afg.svg"
new SvgToPngConverter().convertFromInput(input, function(imgData){
    // You now have your png data in base64 (imgData). 
    // Do what ever you wish with it here.
});

If you want a vanilla JavaScript version, you could head over to Babel website and transpile the code there.

How to append to New Line in Node.js

use \r\n combination to append a new line in node js

  var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });

How to get input textfield values when enter key is pressed in react js?

Adding onKeyPress will work onChange in Text Field.

<TextField
  onKeyPress={(ev) => {
    console.log(`Pressed keyCode ${ev.key}`);
    if (ev.key === 'Enter') {
      // Do code here
      ev.preventDefault();
    }
  }}
/>

Correlation between two vectors?

For correlations you can just use the corr function (statistics toolbox)

corr(A_1(:), A_2(:))

Note that you can also just use

corr(A_1, A_2)

But the linear indexing guarantees that your vectors don't need to be transposed.

malloc for struct and pointer in C

No, you're not allocating memory for y->x twice.

Instead, you're allocating memory for the structure (which includes a pointer) plus something for that pointer to point to.

Think of it this way:

         1          2
        +-----+    +------+
y------>|  x------>|  *x  |
        |  n  |    +------+
        +-----+

So you actually need the two allocations (1 and 2) to store everything.

Additionally, your type should be struct Vector *y since it's a pointer, and you should never cast the return value from malloc in C since it can hide certain problems you don't want hidden - C is perfectly capable of implicitly converting the void* return value to any other pointer.

And, of course, you probably want to encapsulate the creation of these vectors to make management of them easier, such as with:

struct Vector {
    double *data;    // no place for x and n in readable code :-)
    size_t size;
};

struct Vector *newVector (size_t sz) {
    // Try to allocate vector structure.

    struct Vector *retVal = malloc (sizeof (struct Vector));
    if (retVal == NULL)
        return NULL;

    // Try to allocate vector data, free structure if fail.

    retVal->data = malloc (sz * sizeof (double));
    if (retVal->data == NULL) {
        free (retVal);
        return NULL;
    }

    // Set size and return.

    retVal->size = sz;
    return retVal;
}

void delVector (struct Vector *vector) {
    // Can safely assume vector is NULL or fully built.

    if (vector != NULL) {
        free (vector->data);
        free (vector);
    }
}

By encapsulating the creation like that, you ensure that vectors are either fully built or not built at all - there's no chance of them being half-built. It also allows you to totally change the underlying data structures in future without affecting clients (for example, if you wanted to make them sparse arrays to trade off space for speed).

Jquery select this + class

What you are looking for is this:

$(".subclass", this).css("visibility","visible");

Add the this after the class $(".subclass", this)

How to connect a Windows Mobile PDA to Windows 10

Unfortunately the Windows Mobile Device Center stopped working out of the box after the Creators Update for Windows 10. The application won't open and therefore it's impossible to get the sync working. In order to get it running now we need to modify the ActiveSync registry settings. Create a BAT file with the following contents and run it as administrator:

REG ADD HKLM\SYSTEM\CurrentControlSet\Services\RapiMgr /v SvcHostSplitDisable /t REG_DWORD /d 1 /f
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\WcesComm /v SvcHostSplitDisable /t REG_DWORD /d 1 /f

Restart the computer and everything should work.

How to select only date from a DATETIME field in MySQL?

Use DATE_FORMAT

select DATE_FORMAT(date,'%d') from tablename =>Date only

example:

select DATE_FORMAT(`date_column`,'%d') from `database_name`.`table_name`;

Extract the first (or last) n characters of a string

See ?substr

R> substr(a, 1, 4)
[1] "left"

Write variable to file, including name

You could do:

import inspect

mydict = {'one': 1, 'two': 2}

source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0]
print [x for x in source if x.startswith("mydict = ")]

Also: make sure not to shadow the dict builtin!

How to move from one fragment to another fragment on click of an ImageView in Android?

When you are inside an activity and need to go to a fragment use below

getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

But when you are inside a fragment and need to go to a fragment then just add a getActivity(). before, so it would become

getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

as simple as that.

The *TO_BE_REPLACED_LAYOUT_ID* can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout .

datetime datatype in java

I used this import:

import java.util.Date;

And declared my variable like this:

Date studentEnrollementDate;

Linux shell sort file according to the second column?

sort -nk2 file.txt

Accordingly you can change column number.

How to VueJS router-link active style

Just add to @Bert's solution to make it more clear:

    const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes,
  linkExactActiveClass: "active" // active class for *exact* links.
})

As one can see, this line should be removed:

linkActiveClass: "active", // active class for non-exact links.

this way, ONLY the current link is hi-lighted. This should apply to most of the cases.

David

How to make bootstrap 3 fluid layout without horizontal scrollbar

This was introduced in v3.1.0: http://getbootstrap.com/css/#grid-example-fluid

Commit #62736046 added ".container-fluid variation for full-width containers and layouts".

Can we have multiple <tbody> in same <table>?

According to this example it can be done: w3-struct-tables.

How to debug ORA-01775: looping chain of synonyms?

A developer accidentally wrote code that generated and ran the following SQL statement CREATE OR REPLACE PUBLIC SYNONYM "DUAL" FOR "DUAL"; which caused select * from dba_synonyms where table_name = 'DUAL'; to return PUBLIC DUAL SOME_USER DUAL rather than PUBLIC DUAL SYS DUAL.

We were able to fix it (thanks to How to recreate public synonym "DUAL"?) by running

ALTER SYSTEM SET "_SYSTEM_TRIG_ENABLED"=FALSE SCOPE=MEMORY;
CREATE OR REPLACE PUBLIC SYNONYM DUAL FOR SYS.DUAL;
ALTER SYSTEM SET "_SYSTEM_TRIG_ENABLED"=true SCOPE=MEMORY;

Subtract minute from DateTime in SQL Server 2005

I spent a while trying to do the same thing, trying to subtract the hours:minutes from datetime - here's how I did it:

convert( varchar, cast((RouteMileage / @average_speed) as integer))+ ':' +  convert( varchar, cast((((RouteMileage / @average_speed) - cast((RouteMileage / @average_speed) as integer)) * 60) as integer)) As TravelTime,

dateadd( n, -60 * CAST( (RouteMileage / @average_speed) AS DECIMAL(7,2)), @entry_date) As DepartureTime 

OUTPUT:

DeliveryDate                TravelTime             DepartureTime
2012-06-02 12:00:00.000       25:49         2012-06-01 10:11:00.000

change text of button and disable button in iOS

If you want to change the title as a response to being tapped you can try this inside the IBAction method of the button in your view controller delegate. This toggles a voice chat on and off. Setting up the voice chat is not covered here!

- (IBAction)startChat:(id)sender {
UIButton *chatButton = (UIButton*)sender;
if (!voiceChat.active) {
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Voice Chat"
                                                                   message:@"Voice Chat will become live. Please be careful with feedback if your friend is nearby."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
    [voiceChat start];
    voiceChat.active = YES;
    [chatButton setTitle:@"Stop Chat" forState:UIControlStateNormal];
}
else {
    [voiceChat stop];
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Voice Chat"
                                                                   message:@"Voice Chat is closed"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
    voiceChat.active = NO;
    [chatButton setTitle:@"Chat" forState:UIControlStateNormal];
}

}

voiceChat is specific to voice chat of course, but you can use your ow local boolean property to control the switch.

CSS background image URL failing to load

Source location should be the URL (relative to the css file or full web location), not a file system full path, for example:

background: url("http://localhost/media/css/static/img/sprites/buttons-v3-10.png");
background: url("static/img/sprites/buttons-v3-10.png");

Alternatively, you can try to use file:/// protocol prefix.

How to perform update operations on columns of type JSONB in Postgres 9.4

For those that run into this issue and want a very quick fix (and are stuck on 9.4.5 or earlier), here is a potential solution:

Creation of test table

CREATE TABLE test(id serial, data jsonb);
INSERT INTO test(data) values ('{"name": "my-name", "tags": ["tag1", "tag2"]}');

Update statement to change jsonb value

UPDATE test 
SET data = replace(data::TEXT,': "my-name"',': "my-other-name"')::jsonb 
WHERE id = 1;

Ultimately, the accepted answer is correct in that you cannot modify an individual piece of a jsonb object (in 9.4.5 or earlier); however, you can cast the jsonb column to a string (::TEXT) and then manipulate the string and cast back to the jsonb form (::jsonb).

There are two important caveats

  1. this will replace all values equaling "my-name" in the json (in the case you have multiple objects with the same value)
  2. this is not as efficient as jsonb_set would be if you are using 9.5

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

use this syntax: alter table table_name modify column col_name varchar (10000);

Simple int to char[] conversion

You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!

But you probably meant "i want to stringify a number", so ignore this response :-)

Command to find information about CPUs on a UNIX machine

Firstly, it probably depends which version of Solaris you're running, but also what hardware you have.

On SPARC at least, you have psrinfo to show you processor information, which run on its own will show you the number of CPUs the machine sees. psrinfo -p shows you the number of physical processors installed. From that you can deduce the number of threads/cores per physical processors.

prtdiag will display a fair bit of info about the hardware in your machine. It looks like on a V240 you do get memory channel info from prtdiag, but you don't on a T2000. I guess that's an architecture issue between UltraSPARC IIIi and UltraSPARC T1.

Convert month name to month number in SQL Server

You can use below code

DECLARE @T TABLE ([Month] VARCHAR(20))
INSERT INTO @T
SELECT 'January'
UNION
SELECT 'February'
UNION
SELECT 'March'`

SELECT MONTH('01-' + [Month] + '-2010') As MonthNumeric,[Month] FROM @T
ORDER BY MonthNumeric

How to set breakpoints in inline Javascript in Google Chrome?

This is an extension of Rian Schmits' answer above. In my case, I had HTML code embedded in my JavaScript code and I couldn't see anything other than the HTML code. Maybe Chrome Debugging has changed over the years but right-clicking the Sources/Sources tab presented me with Add folder to workspace. I was able to add my entire project, which gave me access to all of my JavaScripts. You can find more detail in this link. I hope this helps somebody.

How do I convert datetime to ISO 8601 in PHP

If you try set a value in datetime-local

date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21

Angularjs ng-model doesn't work inside ng-if

The ng-if directive, like other directives creates a child scope. See the script below (or this jsfiddle)

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>_x000D_
_x000D_
<script>_x000D_
    function main($scope) {_x000D_
        $scope.testa = false;_x000D_
        $scope.testb = false;_x000D_
        $scope.testc = false;_x000D_
        $scope.obj = {test: false};_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<div ng-app >_x000D_
    <div ng-controller="main">_x000D_
        _x000D_
        Test A: {{testa}}<br />_x000D_
        Test B: {{testb}}<br />_x000D_
        Test C: {{testc}}<br />_x000D_
        {{obj.test}}_x000D_
        _x000D_
        <div>_x000D_
            testa (without ng-if): <input type="checkbox" ng-model="testa" />_x000D_
        </div>_x000D_
        <div ng-if="!testa">_x000D_
            testb (with ng-if): <input type="checkbox" ng-model="testb" /> {{testb}}_x000D_
        </div>_x000D_
        <div ng-if="!someothervar">_x000D_
            testc (with ng-if): <input type="checkbox" ng-model="testc" />_x000D_
        </div>_x000D_
        <div ng-if="!someothervar">_x000D_
            object (with ng-if): <input type="checkbox" ng-model="obj.test" />_x000D_
        </div>_x000D_
        _x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So, your checkbox changes the testb inside of the child scope, but not the outer parent scope.

Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.

Initialising an array of fixed size in python

You can use:

>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

Access host database from a docker container

Use host.docker.internal from Docker 18.03 onwards.

The transaction manager has disabled its support for remote/network transactions

In my scenario, the exception was being thrown because I was trying to create a new connection instance within a TransactionScope on an already existing connection:

Example:

void someFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
        {
            someOtherFunction(); // This function opens a new connection within this transaction, causing the exception.
        }
    }
}

void someOtherFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        db.Whatever // <- Exception.
    }
}

What is the difference between explicit and implicit cursors in Oracle?

An explicit cursor is one you declare, like:

CURSOR my_cursor IS
  SELECT table_name FROM USER_TABLES

An implicit cursor is one created to support any in-line SQL you write (either static or dynamic).

How do I convert a list into a string with spaces in Python?

you can iterate through it to do it

my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
    my_string = my_string + ' ' + a
print(my_string)

output is

 how are you

you can strip it to get

how are you

like this

my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
    my_string = my_string + ' ' + a
print(my_string.strip())

Integer expression expected error in shell script

If you are just comparing numbers, I think there's no need to change syntax, just correct those lines, lines 6 and 9 brackets.

Line 6 before: if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]

After: if [ "$age" -le "7" -o "$age" -ge "65" ]

Line 9 before: elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]

After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

How to list containers in Docker

I got the error message Cannot connect to the Docker daemon. I forgot I am running the daemon as root and needed sudo:

$ sudo docker ps

Mongodb service won't start

I solved this by executing C:\mongodb\bin\mongod.exe --repair first. Then when I ran MongoDB again by C:\mongodb\bin\mongod.exe, it successfully started.

Difference between ref and out parameters in .NET

Ref parameters aren't required to be set in the function, whereas out parameters must be bound to a value before exiting the function. Variables passed as out may also be passed to a function without being initialized.

Add to integers in a list

Here is an example where the things to add come from a dictionary

>>> L = [0, 0, 0, 0]
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
>>> for item in things_to_add:
...     L[item['idx']] += item['amount']
... 
>>> L
[0, 1, 1, 0]

Here is an example adding elements from another list

>>> L = [0, 0, 0, 0]
>>> things_to_add = [0, 1, 1, 0]
>>> for idx, amount in enumerate(things_to_add):
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

You could also achieve the above with a list comprehension and zip

L[:] = [sum(i) for i in zip(L, things_to_add)]

Here is an example adding from a list of tuples

>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

How to set NODE_ENV to production/development in OS X

Windows CMD -> set NODE_ENV=production

Windows Powershell -> $env:NODE_ENV="production"

MAC -> export NODE_ENV=production

Calling Javascript function from server side

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:test();", true);

Delete from two tables in one query

no need for JOINS:

DELETE m, um FROM messages m, usersmessages um

WHERE m.messageid = 1 

AND m.messageid = um.messageid 

Getting the document object of an iframe

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:

If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

Delete newline in Vim

set backspace=indent,eol,start

in your .vimrc will allow you to use backspace and delete on \n (newline) in insert mode.

set whichwrap+=<,>,h,l,[,]

will allow you to delete the previous LF in normal mode with X (when in col 1).

The response content cannot be parsed because the Internet Explorer engine is not available, or

Yet another method to solve: updating registry. In my case I could not alter GPO, and -UseBasicParsing breaks parts of the access to the website. Also I had a service user without log in permissions, so I could not log in as the user and run the GUI.
To fix,

  1. log in as a normal user, run IE setup.
  2. Then export this registry key: HKEY_USERS\S-1-5-21-....\SOFTWARE\Microsoft\Internet Explorer
  3. In the .reg file that is saved, replace the user sid with the service account sid
  4. Import the .reg file

In the file

How to get full REST request body using Jersey?

Try this using this single code:

import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Path("/serviceX")
public class MyClassRESTService {

    @POST
    @Path("/doSomething")   
    public void someMethod(String x) {

        System.out.println(x);
                // String x contains the body, you can process
                // it, parse it using JAXB and so on ...

    }
}

The url for try rest services ends .... /serviceX/doSomething

How do I programmatically get the GUID of an application in .NET 2.0

 string AssemblyID = Assembly.GetEntryAssembly().GetCustomAttribute<GuidAttribute>().Value;

or, VB.NET:

  Dim AssemblyID As String = Assembly.GetEntryAssembly.GetCustomAttribute(Of GuidAttribute).Value

Android webview slow

It depends on the web application being loaded. Try some of the approaches below:

Set higher render priority (deprecated from API 18+):

webview.getSettings().setRenderPriority(RenderPriority.HIGH);

Enable/disable hardware acceleration:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    // chromium, enable hardware acceleration
    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
    // older android version, disable hardware acceleration
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

Disable the cache (if you have problems with your content):

webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

I had to cast the integer equivalent to get around the fact that I'm still using .NET 4.0

System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
/* Note the property type  
   [System.Flags]
   public enum SecurityProtocolType
   {
     Ssl3 = 48,
     Tls = 192,
     Tls11 = 768,
     Tls12 = 3072,
   } 
*/

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

transform object to array with lodash

Object to Array

Of all the answers I think this one is the best:

let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))

that transforms:

{
  a: { p: 1, q: 2},
  b: { p: 3, q: 4}
}

to:

[
  { key: 'a', p: 1, q: 2 }, 
  { key: 'b', p: 3, q: 4 }
]

Array to Object

To transform back:

let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})

To transform back keeping the key in the value:

let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})

Will give:

{
  a: { key: 'a', p: 1, q: 2 },
  b: { key: 'b', p: 3, q: 4 }
}

For the last example you can also use lodash _.keyBy(arr, 'key') or _.keyBy(arr, i => i.key).

Working copy locked error in tortoise svn while committing

Windows Solution:

https://sourceforge.net/projects/win32svn/

1.Download it, then add it to system path.

2.Go to work directory execute "svn clean" and "svn update" in cmd.

Group By Multiple Columns

.GroupBy(x => (x.MaterialID, x.ProductID))

ZIP file content type for HTTP request

If you want the MIME type for a file, you can use the following code:

- (NSString *)mimeTypeForPath:(NSString *)path
{
    // get a mime type for an extension using MobileCoreServices.framework

    CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
    assert(UTI != NULL);

    NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
    assert(mimetype != NULL);

    CFRelease(UTI);

    return mimetype;
}

In the case of a ZIP file, this will return application/zip.

How to check the version before installing a package using apt-get?

on debian :

apt list --upgradable

gives the list with package, version to be upgraded, and actual version of the package.

result :

base-files/stable 8+deb8u8 amd64 [upgradable from: 8+deb8u7]
bind9-host/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]
ca-certificates/stable 20141019+deb8u3 all [upgradable from: 20141019+deb8u2]
certbot/jessie-backports 0.10.2-1~bpo8+1 all [upgradable from: 0.8.1-2~bpo8+1]
dnsutils/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]

How to order citations by appearance using BibTeX?

Change

\bibliographystyle{plain}

to

\bibliographystyle{ieeetr}

Then rebuild it a few times to replace the .aux and .bbl files that were made when you used the plain style.

Or simply delete the .aux and .bbl files and rebuild.

If you use MiKTeX you shouldn't need to download anything extra.

PHP send mail to multiple email addresses

The best way could be to save all the emails in a database.

You can try this code, assuming you have your email in a database

/*Your connection to your database comes here*/
$query="select email from yourtable";
$result =mysql_query($query);

/the above code depends on where you saved your email addresses, so make sure you replace it with your parameters/

Then you can make a comma separated string from the result,

while($row=$result->fetch_array()){
        if($rows=='')    //this prevents from inserting comma on before the first element
        $rows.=$row['email'];
        else
        $rows.=','.$row['email'];
    }

Now you can use

$to = explode(',',$rows); // to change to array

$string =implode(',',$cc); //to get back the string separated by comma

With above code you can send the email like this

mail($string, "Test", "Hi, Happy X-Mas and New Year");

Updating a dataframe column in spark

Just as maasg says you can create a new DataFrame from the result of a map applied to the old DataFrame. An example for a given DataFrame df with two rows:

val newDf = sqlContext.createDataFrame(df.map(row => 
  Row(row.getInt(0) + SOMETHING, applySomeDef(row.getAs[Double]("y")), df.schema)

Note that if the types of the columns change, you need to give it a correct schema instead of df.schema. Check out the api of org.apache.spark.sql.Row for available methods: https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/Row.html

[Update] Or using UDFs in Scala:

import org.apache.spark.sql.functions._

val toLong = udf[Long, String] (_.toLong)

val modifiedDf = df.withColumn("modifiedColumnName", toLong(df("columnName"))).drop("columnName")

and if the column name needs to stay the same you can rename it back:

modifiedDf.withColumnRenamed("modifiedColumnName", "columnName")

How do I set cell value to Date and apply default Excel date format?

To know the format string used by Excel without having to guess it: create an excel file, write a date in cell A1 and format it as you want. Then run the following lines:

FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);

Then copy-paste the resulting string, remove the backslashes (for example d/m/yy\ h\.mm;@ becomes d/m/yy h.mm;@) and use it in the http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells code:

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

Access props inside quotes in React JSX

Note: In react you can put javascript expression inside curly bracket. We can use this property in this example.
Note: give one look to below example:

class LoginForm extends React.Component {

  constructor(props) {
    super(props);

    this.state = {i:1};
  }

  handleClick() {
    this.setState(prevState => ({i : prevState.i + 1}));

    console.log(this.state.j);  
  }


  render() {

    return (
      <div>
        <p onClick={this.handleClick.bind(this)}>Click to change image</p>
        <img src={'images/back'+ this.state.i+'.jpg'}/>
      </div>
      );

  }
}

Get current folder path

Use this,

var currentDirectory = System.IO.Directory.GetCurrentDirectory(); 

You can use this as well.

var currentDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

Alternative Windows shells, besides CMD.EXE?

At the moment there are three realy powerfull cmd.exe alternatives:

cmder is an enhancement off ConEmu and Clink

All have features like Copy & Paste, Window Resize per Mouse, Splitscreen, Tabs and a lot of other usefull features.

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

How to create a scrollable Div Tag Vertically?

Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched

overflow-y: scroll;

to

overflow-y: auto;

Demo page over at: http://davidrhysthomas.co.uk/so/tableDiv.html.

xhtml below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Div in table</title>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css" />

        <style type="text/css" media="all">

        th      {border-bottom: 2px solid #ccc; }

        th,td       {padding: 0.5em 1em; 
                margin: 0;
                border-collapse: collapse;
                }

        tr td:first-child
                {border-right: 2px solid #ccc; } 

        td > div    {width: 249px;
                height: 299px;
                background-color:Gray;
                overflow-y: auto;
                max-width:230px;
                max-height:100px;
                }
        </style>

    <script type="text/javascript" src="js/jquery.js"></script>

    <script type="text/javascript">

    </script>

</head>

<body>

<div>

    <table>

        <thead>
            <tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>
        </thead>



        <tbody>
            <tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
            <tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
            <tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
            <tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
            <tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
            <tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
            <tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>
        </body>



    </table>

</div>

</body>

</html>

How do I lock the orientation to portrait mode in a iPhone Web Application?

You can specify CSS styles based on viewport orientation: Target the browser with body[orient="landscape"] or body[orient="portrait"]

http://www.evotech.net/blog/2007/07/web-development-for-the-iphone/

However...

Apple's approach to this issue is to allow the developer to change the CSS based on the orientation change but not to prevent re-orientation completely. I found a similar question elsewhere:

http://ask.metafilter.com/99784/How-can-I-lock-iPhone-orientation-in-Mobile-Safari

How do I get a UTC Timestamp in JavaScript?

EDIT: The code below does NOT work. I was always assuming that new Date().getTime() returned the number of seconds since the 1st of January 1970 IN THE CURRENT TIMEZONE. This is not the case: getTime() returns the number of seconds in UTC. So, the code below does gross over-adjusting. Thank you everybody!]

First of all, thank you for your fantastic insights. I guess my question had the wrong title... it should have been "Get the UTC Unix Timestamp for an existing date".

So, if I have a date object:

var d = new Date(2009,01,31)

I was after a function that would tell me "The UTC Unix Timestamp".

This function seems to be the real trick:

Date.prototype.getUTCUnixTime =  function (){
  return Math.floor( new Date(
    this.getUTCFullYear(),
    this.getUTCMonth(),
    this.getUTCDate(),
    this.getUTCHours(),
    this.getUTCMinutes(), 
    this.getUTCSeconds()
  ).getTime() / 1000); 
}

Note that it works on "this" This means that I can do:

var n = new Date(2008,10,10)
...
...

n.getUTCUnixTime();

And get the number of seconds since the 1st of Jan 1970 in Unix time. Right?

It's a little insane, to me, that Javascript stores everything in UTC times, but then in order to get that number I have to create a new Date object passing the individual UTC getters and then finally call getTime() for that...

Merc.

Can't find bundle for base name

If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .

‘ant’ is not recognized as an internal or external command

Need to see whether you got ant folder moved by mistake or unknowingly. It is set in environment variables.I resolved this once as mentioned below.

I removed ant folder by mistake and placed in another folder.I went to command prompt and typed "path". It has given me path as "F:\apache-ant-1.9.4\". So I moved the ant back to F drive and it resolved the issue.

Trusting all certificates with okHttp

SSLSocketFactory does not expose its X509TrustManager, which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call sslSocketFactory(SSLSocketFactory, X509TrustManager), which avoids such reflection.

Source: OkHttp documentation

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.sslSocketFactory(sslContext.getSocketFactory(),
    new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }
    });

PHP string "contains"

You can use these string functions,

strstr — Find the first occurrence of a string

stristr — Case-insensitive strstr()

strrchr — Find the last occurrence of a character in a string

strpos — Find the position of the first occurrence of a substring in a string

strpbrk — Search a string for any of a set of characters

If that doesn't help then you should use preg regular expression

preg_match — Perform a regular expression match

Get string between two strings in a string

A working LINQ solution:

string str = "super example of string key : text I want to keep - end of my string";
string res = new string(str.SkipWhile(c => c != ':')
                           .Skip(1)
                           .TakeWhile(c => c != '-')
                           .ToArray()).Trim();
Console.WriteLine(res); // text I want to keep

Inserting values into a SQL Server database using ado.net via C#

As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.

Also: I would recommend to separate the click event handler from the actual code to insert the data.

So I would rewrite your code to be something like

In your web page's code-behind file (yourpage.aspx.cs)

private void button1_Click(object sender, EventArgs e)
{
      string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";

      InsertData(connectionString,
                 textBox1.Text.Trim(),  -- first name
                 textBox2.Text.Trim(),  -- last name
                 textBox3.Text.Trim(),  -- user name
                 textBox4.Text.Trim(),  -- password
                 Convert.ToInt32(comboBox1.Text),  -- age
                 comboBox2.Text.Trim(), -- gender
                 textBox7.Text.Trim() );  -- contact
}

In some other code (e.g. a databaselayer.cs):

private void InsertData(string connectionString, string firstName, string lastname, string username, string password
                        int Age, string gender, string contact)
{
    // define INSERT query with parameters
    string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " + 
                   "VALUES (@FirstName, @Lastname, @Username, @Password, @Age, @Gender, @Contact) ";

    // create connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(query, cn))
    {
        // define parameters and their values
        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName;
        cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = lastName;
        cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = userName;
        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = password;
        cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age;
        cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = gender;
        cmd.Parameters.Add("@Contact", SqlDbType.VarChar, 50).Value = contact;

        // open connection, execute INSERT, close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

Code like this:

  • is not vulnerable to SQL injection attacks
  • performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
  • separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

IPC performance: Named Pipe vs Socket

If you do not need speed, sockets are the easiest way to go!

If what you are looking at is speed, the fastest solution is shared Memory, not named pipes.

Creating a DateTime in a specific Time Zone in c#

Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.

Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:

public struct DateTimeWithZone
{
    private readonly DateTime utcDateTime;
    private readonly TimeZoneInfo timeZone;

    public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
    {
        var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
        utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); 
        this.timeZone = timeZone;
    }

    public DateTime UniversalTime { get { return utcDateTime; } }

    public TimeZoneInfo TimeZone { get { return timeZone; } }

    public DateTime LocalTime
    { 
        get 
        { 
            return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); 
        }
    }        
}

You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.

In Maven how to exclude resources from the generated jar?

Exclude specific pattern of file during creation of maven jar using maven-jar-plugin.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <version>2.3</version>
  <configuration>
    <excludes>
      <exclude>**/*.properties</exclude>
      <exclude>**/*.xml</exclude>
      <exclude>**/*.exe</exclude>
      <exclude>**/*.java</exclude>
      <exclude>**/*.xls</exclude>
    </excludes>
  </configuration>
</plugin>

How do I change the default application icon in Java?

You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:

Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))

Do not forget to import:

import java.awt.Toolkit;

in the source code!

"Fade" borders in CSS

How to fade borders with CSS:

<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

Source: Gradient Borders

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

$("form input[type=submit]").click(function() {
    $("<input />")
        .attr('type', 'hidden')
        .attr('name', $(this).attr('name'))
        .attr('value', $(this).attr('value'))
    .appendTo(this)
});

add hidden field

How do I get a Cron like scheduler in Python?

There isn't a "pure python" way to do this because some other process would have to launch python in order to run your solution. Every platform will have one or twenty different ways to launch processes and monitor their progress. On unix platforms, cron is the old standard. On Mac OS X there is also launchd, which combines cron-like launching with watchdog functionality that can keep your process alive if that's what you want. Once python is running, then you can use the sched module to schedule tasks.

How to sort by Date with DataTables jquery plugin?

Create a hidden column "dateOrder" (for example) with the date as string with the format "yyyyMMddHHmmss" and use the property "orderData" to point to that column.

var myTable = $("#myTable").dataTable({
 columns: [
      { data: "id" },
      { data: "date", "orderData": 4 },
      { data: "name" },
      { data: "total" },
      { data: "dateOrder", visible: false }
 ] });

Writing your own square root function

The first thing comes to my mind is: this is a good place to use Binary search (inspired by this great tutorials.)

To find the square root of vaule ,we are searching the number in (1..value) where the predictor is true for the first time. The predictor we are choosing is number * number - value > 0.00001.

double square_root_of(double value)
{
     assert(value >= 1);
     double lo = 1.0;
     double hi = value;

     while( hi - lo > 0.00001)
     {
          double mid = lo + (hi - lo) / 2 ;
          std::cout << lo << "," << hi << "," << mid << std::endl;
          if( mid * mid - value > 0.00001)    //this is the predictors we are using 
          {
              hi = mid;
          } else {
              lo = mid;
          }

     }

    return lo;
 }

Git error: src refspec master does not match any

The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:

git push origin master

Which will create this new master branch for you. Little things like this are very confusing with git.

If this didn't fix your issue then it's probably a gitolite-related issue:

Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:

repo    phonegap                                                                                                                                                                           
    RW+     =   myusername otherusername                                                                                                                                               

repo    gitolite-admin                                                                                                                                                                         
    RW+     =   myusername                                                                                                                                                               

Please make sure you're setting your conf file correctly.

Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.

Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.

Returning JSON from a PHP Script

As said above:

header('Content-Type: application/json');

will make the job. but keep in mind that :

  • Ajax will have no problem to read json even if this header is not used, except if your json contains some HTML tags. In this case you need to set the header as application/json.

  • Make sure your file is not encoded in UTF8-BOM. This format add a character in the top of the file, so your header() call will fail.

How to get Printer Info in .NET?

Just for reference, here is a list of all the available properties for a printer ManagementObject.

usage: printer.Properties["PropName"].Value

Saving changes after table edit in SQL Server Management Studio

This is a risk to turning off this option. You can lose changes if you have change tracking turned on (your tables).

Chris

http://chrisbarba.wordpress.com/2009/04/15/sql-server-2008-cant-save-changes-to-tables/

git push >> fatal: no configured push destination

I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.

git add .
git commit -m "some comments"
git push --set-upstream origin master

How to check if the URL contains a given string?

Try this, it's shorter and works exactly as window.location.href:

if (document.URL.indexOf("franky") > -1) { ... }

also if you want to check the previous URL:

if (document.referrer.indexOf("franky") > -1) { ... }

Website screenshots

You can use https://grabz.it solution.

It's got a PHP API which is very flexible and can be called in different ways such as from a cronjob or a PHP web page.

In order to implement it you will need to first get an app key and secret and download the (free) SDK.

And an example for implementation. First of all initialization:

include("GrabzItClient.class.php");

// Create the GrabzItClient class
// Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account!
$grabzIt = new GrabzItClient("Sign in to view your Application Key", "Sign in to view your Application Secret");

And screenshoting example:

// To take a image screenshot
$grabzIt->URLToImage("http://www.google.com");  
// Or to take a PDF screenshot
$grabzIt->URLToPDF("http://www.google.com");
// Or to convert online videos into animated GIF's
$grabzIt->URLToAnimation("http://www.example.com/video.avi");
// Or to capture table(s)
$grabzIt->URLToTable("http://www.google.com");

Next is the saving.You can use one of the two save methods, Save if publicly accessible callback handle available and SaveTo if not. Check the documentation for details.

Getting DOM node from React child element

React.findDOMNode(this.refs.myExample) mentioned in another answer has been deprectaed.

use ReactDOM.findDOMNode from 'react-dom' instead

import ReactDOM from 'react-dom'
let myExample = ReactDOM.findDOMNode(this.refs.myExample)

Case insensitive regular expression without re.compile?

You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):

re.search(r'(?i)test', 'TeSt').group()    ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group()     ## returns 'TeSt'

Fixed positioned div within a relative parent div

Gavin,

The issue you are having is a misunderstanding of positioning. If you want it to be "fixed" relative to the parent, then you really want your #fixed to be position:absolute which will update its position relative to the parent.

This question fully describes positioning types and how to use them effectively.

In summary, your CSS should be

#wrap{ 
    position:relative;
}
#fixed{ 
    position:absolute;
    top:30px;
    left:40px;
}

How get total sum from input box values using Javascript?

I need to sum the span elements so I edited Akhil Sekharan's answer below.

var arr = document.querySelectorAll('span[id^="score"]');
var total=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].innerHTML))
            total+= parseInt(arr[i].innerHTML);
    }
console.log(total)

You can change the elements with other elements link will guide you with editing.

https://www.w3.org/TR/css3-selectors/#attribute-substrings

Can't include C++ headers like vector in Android NDK

I'm using Android Studio and as of 19th of January 2016 this did the trick for me. (This seems like something that changes every year or so)

Go to: app -> Gradle Scripts -> build.gradle (Module: app)

Then under model { ... android.ndk { ... and add a line: stl = "gnustl_shared"

Like this:

model {

    ...

    android.ndk {
        moduleName = "gl2jni"
        cppFlags.add("-Werror")
        ldLibs.addAll(["log", "GLESv2"])
        stl = "gnustl_shared"     //  <-- this is the line that I added
    }

    ...

}

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

This solution solve my problem: (from: https://msdn.microsoft.com/en-us/library/ms239722.aspx)

To permanently attach a database file (.mdf) from the Data Connections node

  1. Open the shortcut menu for Data Connections and choose Add New Connection.

    The Add Connection dialog box appears.

  2. Choose the Change button.

    The Change Data Source dialog box appears.

  3. Select Microsoft SQL Server and choose the OK button.

    The Add Connection dialog box reappears, with Microsoft SQL Server (SqlClient) displayed in the Data source text box.

  4. In the Server Name box, type or browse to the path to the local instance of SQL Server. You can type the following:

    • "." for the default instance on your computer.
    • "(LocalDB)\v11.0" for the default instance of SQL Server Express LocalDB.
    • ".\SQLEXPRESS" for the default instance of SQL Server Express.

    For information about SQL Server Express LocalDB and SQL Server Express, see Local Data Overview.

  5. Select either Use Windows Authentication or Use SQL Server Authentication.

  6. Choose Attach a database file, Browse, and open an existing .mdf file.

  7. Choose the OK button.

    The new database appears in Server Explorer. It will remain connected to SQL Server until you explicitly detach it.

Remove URL parameters without refreshing page

To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:

history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is

This will add an entry in the browser history. You could also consider replaceState if you don't wan't to add a new entry and just want to replace the old entry.

EditText, clear focus on touch outside

Just put these properties in the top most parent.

android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="true" 

Why does Math.Round(2.5) return 2 instead of 3?

This post has the answer you are looking for:

http://weblogs.asp.net/sfurman/archive/2003/03/07/3537.aspx

Basically this is what it says:

Return Value

The number nearest value with precision equal to digits. If value is halfway between two numbers, one of which is even and the other odd, then the even number is returned. If the precision of value is less than digits, then value is returned unchanged.

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. If digits is zero, this kind of rounding is sometimes called rounding toward zero.

Calculating percentile of dataset column

The quantile() function will do much of what you probably want, but since the question was ambiguous, I will provide an alternate answer that does something slightly different from quantile().

ecdf(infert$age)(infert$age)

will generate a vector of the same length as infert$age giving the proportion of infert$age that is below each observation. You can read the ecdf documentation, but the basic idea is that ecdf() will give you a function that returns the empirical cumulative distribution. Thus ecdf(X)(Y) is the value of the cumulative distribution of X at the points in Y. If you wanted to know just the probability of being below 30 (thus what percentile 30 is in the sample), you could say

ecdf(infert$age)(30)

The main difference between this approach and using the quantile() function is that quantile() requires that you put in the probabilities to get out the levels, and this requires that you put in the levels to get out the probabilities.

Passing command line arguments to R CMD BATCH

I add an answer because I think a one line solution is always good! Atop of your myRscript.R file, add the following line:

eval(parse(text=paste(commandArgs(trailingOnly = TRUE), collapse=";")))

Then submit your script with something like:

R CMD BATCH [options] '--args arguments you want to supply' myRscript.R &

For example:

R CMD BATCH --vanilla '--args N=1 l=list(a=2, b="test") name="aname"' myscript.R &

Then:

> ls()
[1] "N"    "l"    "name"

CSS3 Box Shadow on Top, Left, and Right Only

use the spread value...

box-shadow has the following values

box-shadow: x y blur spread color;

so you could use something like..

box-shadow: 0px -10px 10px -10px black;

UPDATE: i'm adding a jsfiddle

SQL left join vs multiple tables on FROM line?

Well the first and second queries may yield different results because a LEFT JOIN includes all records from the first table, even if there are no corresponding records in the right table.

Can I nest a <button> element inside an <a> using HTML5?

It is illegal in HTML5 to embed a button element inside a link.

Better to use CSS on the default and :active (pressed) states:

_x000D_
_x000D_
body{background-color:#F0F0F0} /* JUST TO MAKE THE BORDER STAND OUT */_x000D_
a.Button{padding:.1em .4em;color:#0000D0;background-color:#E0E0E0;font:normal 80% sans-serif;font-weight:700;border:2px #606060 solid;text-decoration:none}_x000D_
a.Button:not(:active){border-left-color:#FFFFFF;border-top-color:#FFFFFF}_x000D_
a.Button:active{border-right-color:#FFFFFF;border-bottom-color:#FFFFFF}
_x000D_
<p><a class="Button" href="www.stackoverflow.com">Click me<a>
_x000D_
_x000D_
_x000D_

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

Is Java a Compiled or an Interpreted programming language ?

Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program.

What is the native keyword in Java for?

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface).

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

gcc actually can do this optimization, even for floating-point numbers. For example,

double foo(double a) {
  return a*a*a*a*a*a;
}

becomes

foo(double):
    mulsd   %xmm0, %xmm0
    movapd  %xmm0, %xmm1
    mulsd   %xmm0, %xmm1
    mulsd   %xmm1, %xmm0
    ret

with -O -funsafe-math-optimizations. This reordering violates IEEE-754, though, so it requires the flag.

Signed integers, as Peter Cordes pointed out in a comment, can do this optimization without -funsafe-math-optimizations since it holds exactly when there is no overflow and if there is overflow you get undefined behavior. So you get

foo(long):
    movq    %rdi, %rax
    imulq   %rdi, %rax
    imulq   %rdi, %rax
    imulq   %rax, %rax
    ret

with just -O. For unsigned integers, it's even easier since they work mod powers of 2 and so can be reordered freely even in the face of overflow.

Sublime Text 2: How do I change the color that the row number is highlighted?

On windows 7, find

C:\Users\Simion\AppData\Roaming\Sublime Text 2\Packages\Color Scheme - Default

Find your color scheme file, open it, and find lineHighlight.
Ex:

<key>lineHighlight</key>
<string>#ccc</string>

replace #ccc with your preferred background color.

Progress Bar with HTML and CSS

Progress Bar without nested divs... for every element where the css linear-gradient works.

Here the JSFiddle http://jsfiddle.net/oj1L3y6t/2/

_x000D_
_x000D_
function show_progress(i) {_x000D_
  var progress1 = i;_x000D_
  var progress2 = progress1 + 1;_x000D_
  var progress3 = progress1 + 2;_x000D_
_x000D_
  var magic = "linear-gradient(to right, #FFC2CE " + progress1 + "% ,red " + progress2 + "% , #FFFFFF " + progress3 + "%)";_x000D_
  document.getElementById("progress-0").style.background = magic;_x000D_
_x000D_
  var magic = "linear-gradient(to right, lightblue " + progress1 + "% , lightgreen " + progress2 + "%)";_x000D_
  document.getElementById("progress-1").style.background = magic;_x000D_
_x000D_
  var magic = "linear-gradient(to right, lightblue " + progress1 + "% , #FFFFFF 100%)";_x000D_
  document.getElementById("progress-2").style.background = magic;_x000D_
_x000D_
  var magic = "linear-gradient(#FFC2CE " + progress1 + "% ,red " + progress2 + "% , #FFFFFF " + progress3 + "%)";_x000D_
  document.getElementById("progress-3").style.background = magic;_x000D_
}_x000D_
_x000D_
function timeout() {_x000D_
  t = setTimeout(function() {_x000D_
    show_progress(t)_x000D_
    timeout();_x000D_
  }, 50);_x000D_
  if (t == 78) {_x000D_
    clearTimeout(t);_x000D_
  }_x000D_
  console.log(t);_x000D_
}_x000D_
_x000D_
timeout();
_x000D_
#progress-0 {_x000D_
  border: 1px solid black;_x000D_
  width: 500px;_x000D_
  background: #999;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
#progress-1 {_x000D_
  border: 1px solid black;_x000D_
  width: 500px;_x000D_
  background: #999;_x000D_
  text-align: center;_x000D_
  margin-top: 10px;_x000D_
  border-radius: 10px;_x000D_
}_x000D_
_x000D_
#progress-2 {_x000D_
  border: 1px solid black;_x000D_
  width: 500px;_x000D_
  background: #999;_x000D_
  text-align: center;_x000D_
  margin-top: 10px;_x000D_
}_x000D_
_x000D_
#progress-3 {_x000D_
  border: 1px solid black;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #999;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  margin-top: 10px;_x000D_
  border-radius: 200px;_x000D_
}
_x000D_
<div id="progress-0">Loading</div>_x000D_
<input id="progress-1" value="Loading"></input>_x000D_
<button id="progress-2">Loading</button>_x000D_
<p id="progress-3">Loading</p>
_x000D_
_x000D_
_x000D_

Angular 5 Reactive Forms - Radio Button Group

I tried your code, you didn't assign/bind a value to your formControlName.

In HTML file:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

In the TS file:

  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
      gender: ['', Validators.required]
    });
  }

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

See the screenshot: enter image description here

To make it shorter:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female
</form>

enter image description here

Hope it helps:)

How do I create a link using javascript?

With JavaScript

  1. var a = document.createElement('a');
    a.setAttribute('href',desiredLink);
    a.innerHTML = desiredText;
    // apend the anchor to the body
    // of course you can append it almost to any other dom element
    document.getElementsByTagName('body')[0].appendChild(a);
    
  2. document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';
    

    or, as suggested by @travis :

    document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
    
  3. <script type="text/javascript">
    //note that this case can be used only inside the "body" element
    document.write('<a href="'+desiredLink+'">'+desiredText+'</a>');
    </script>
    

With JQuery

  1. $('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));
    
  2. $('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));
    
  3. var a = $('<a />');
    a.attr('href',desiredLink);
    a.text(desiredText);
    $('body').append(a);
    

In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.

Passing arguments forward to another javascript function

try this

function global_func(...args){
  for(let i of args){
    console.log(i)
  }
}


global_func('task_name', 'action', [{x: 'x'},{x: 'x'}], {x: 'x'}, ['x1','x2'], 1, null, undefined, false, true)




//task_name
//action
//(2) [{...},
//    {...}]
//    {
//        x:"x"
//    }
//(2) [
//        "x1",
//        "x2"
//    ]
//1
//null
//undefined
//false
//true
//func

List all environment variables from the command line

You can use SET in cmd

To show the current variable, just SET is enough

To show certain variable such as 'PATH', use SET PATH.

For help, type set /?.

Deserializing a JSON into a JavaScript object

If you paste the string in server-side into the html don't need to do nothing:

For plain java in jsp:

var jsonObj=<%=jsonStringInJavaServlet%>;

For jsp width struts:

var jsonObj=<s:property value="jsonStringInJavaServlet" escape="false" escapeHtml="false"/>;

How to install xgboost in Anaconda Python (Windows platform)?

  1. Download package from this website. I downloaded xgboost-0.6-cp36-cp36m-win_amd64.whl for anaconda 3 (python 3.6)
  2. Put the package in directory C:\
  3. Open anaconda 3 prompt
  4. Type cd C:\
  5. Type pip install C:\xgboost-0.6-cp36-cp36m-win_amd64.whl
  6. Type conda update scikit-learn

Import CSV file as a pandas DataFrame

Note quite as clean, but:

import csv

with open("value.txt", "r") as f:
    csv_reader = reader(f)
    num = '  '
    for row in csv_reader:
        print num, '\t'.join(row)
        if num == '  ':  
            num=0
        num=num+1

Not as compact, but it does the job:

   Date price   factor_1    factor_2
1 2012-06-11    1600.20 1.255   1.548
2 2012-06-12    1610.02 1.258   1.554
3 2012-06-13    1618.07 1.249   1.552
4 2012-06-14    1624.40 1.253   1.556
5 2012-06-15    1626.15 1.258   1.552
6 2012-06-16    1626.15 1.263   1.558
7 2012-06-17    1626.15 1.264   1.572

how do I get the bullet points of a <ul> to center with the text?

Here's how you do it.

First, decorate your list this way:

<div class="p">
<div class="text-bullet-centered">&#8277;</div>
text text text text text text text text text text text text text text text text 
text text text text text text text text text text text text text text text text 
text text text text text text text text text text text text text text text text 
text text text text text text text text text text text text text text text text 
</div>
<div class="p">
<div class="text-bullet-centered">&#8277;</div>
text text text text text text text text text text text text text text text text 
text text text text text text text text text text text text text text text text 
text text text text text text text text text text text text text text text text 
text text text text text text text text text text text text text text text text 
</div>

Add this CSS:

.p {
    position: relative;
    margin: 20px;
    margin-left: 50px;
}
.text-bullet-centered {
    position: absolute;
    left: -40px;
    top: 50%;
    transform: translate(0%,-50%);
    font-weight: bold;
}

And voila, it works. Resize a window, to see that it indeed works.

As a bonus, you can easily change font and color of bullets, which is very hard to do with normal lists.

_x000D_
_x000D_
.p {_x000D_
  position: relative;_x000D_
  margin: 20px;_x000D_
  margin-left: 50px;_x000D_
}_x000D_
_x000D_
.text-bullet-centered {_x000D_
  position: absolute;_x000D_
  left: -40px;_x000D_
  top: 50%;_x000D_
  transform: translate(0%, -50%);_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<div class="p">_x000D_
  <div class="text-bullet-centered">&#8277;</div>_x000D_
  text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
  text text text text text text text text text text text text text_x000D_
</div>_x000D_
<div class="p">_x000D_
  <div class="text-bullet-centered">&#8277;</div>_x000D_
  text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
  text text text text text text text text text text text text text_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set a DateTime database field to "Now"

In SQL you need to use GETDATE():

UPDATE table SET date = GETDATE();

There is no NOW() function.


To answer your question:

In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.

So, if your requirement is to set it all to the same date I would do something like this (untested):

DECLARE @currDate DATETIME;
SET @currDate = GETDATE();

UPDATE table SET date = @currDate;

How can I control the width of a label tag?

Using CSS, of course...

label { display: block; width: 100px; }

The width attribute is deprecated, and CSS should always be used to control these kinds of presentational styles.

How to check type of variable in Java?

None of these answers work if the variable is an uninitialized generic type

And from what I can find, it's only possible using an extremely ugly workaround, or by passing in an initialized parameter to your function, making it in-place, see here:

<T> T MyMethod(...){ if(T.class == MyClass.class){...}}

Is NOT valid because you cannot pull the type out of the T parameter directly, since it is erased at runtime time.

<T> void MyMethod(T out, ...){ if(out.getClass() == MyClass.class){...}}

This works because the caller is responsible to instantiating the variable out before calling. This will still throw an exception if out is null when called, but compared to the linked solution, this is by far the easiest way to do this

I know this is a kind of specific application, but since this is the first result on google for finding the type of a variable with java (and given that T is a kind of variable), I feel it should be included

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

I imagine that these might possibly be changed with some styling options. But as far as default values go, these are taken from my version of Excel 2010 which should have the defaults.

"Bad" Red Font: 156, 0, 6; Fill: 255, 199, 206

"Good" Green Font: 0, 97, 0; Fill: 198, 239, 206

"Neutral" Yellow Font: 156, 101, 0; Fill: 255, 235, 156

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

How do I remove the last comma from a string using PHP?

Try:

$string = "'name', 'name2', 'name3',";
$string = rtrim($string,',');

Parse json string using JSON.NET

You can use .NET 4's dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe:

string json = "{\"items\":[{\"Name\":\"AAA\",\"Age\":\"22\",\"Job\":\"PPP\"},{\"Name\":\"BBB\",\"Age\":\"25\",\"Job\":\"QQQ\"},{\"Name\":\"CCC\",\"Age\":\"38\",\"Job\":\"RRR\"}]}";

var jss = new JavaScriptSerializer();

dynamic data = jss.Deserialize<dynamic>(json);

StringBuilder sb = new StringBuilder();

sb.Append("<table>\n  <thead>\n    <tr>\n");

// Build the header based on the keys in the
//  first data item.
foreach (string key in data["items"][0].Keys) {
        sb.AppendFormat("      <th>{0}</th>\n", key);
}

sb.Append("    </tr>\n  </thead>\n  <tbody>\n");

foreach (Dictionary<string, object> item in data["items"]) {
    sb.Append("    <tr>\n");

    foreach (string val in item.Values) {
        sb.AppendFormat("      <td>{0}</td>\n", val);
    }
}

sb.Append("    </tr>\n  </tbody>\n</table>");

string myTable = sb.ToString();

At the end, myTable will hold a string that looks like this:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Job</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>AAA</td>
            <td>22</td>
            <td>PPP</td>
        <tr>
            <td>BBB</td>
            <td>25</td>
            <td>QQQ</td>
        <tr>
            <td>CCC</td>
            <td>38</td>
            <td>RRR</td>
        </tr>
    </tbody>
</table>

How to convert map to url query string?

The most robust one I saw off-the-shelf is the URLEncodedUtils class from Apache Http Compoments (HttpClient 4.0).

The method URLEncodedUtils.format() is what you need.

It doesn't use map so you can have duplicate parameter names, like,

  a=1&a=2&b=3

Not that I recommend this kind of use of parameter names.

span with onclick event inside a tag

I would use jQuery to get the results that you're looking for. You wouldn't need to use an anchor tag at that point but if you did it would look like:

<a href="page" style="text-decoration:none;display:block;">

<span onclick="hide()">Hide me</span>

</a>

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.2.min.js' /
<script type='text/javascript'>
$(document).ready(function(){
     $('span').click(function(){
           $(this).hide();
     }
}

List supported SSL/TLS versions for a specific OpenSSL build

Use this

openssl ciphers -v | awk '{print $2}' | sort | uniq

CentOS 7 and Puppet unable to install nc

Nc is a link to nmap-ncat.

It would be nice to use nmap-ncat in your puppet, because NC is a virtual name of nmap-ncat.

Puppet cannot understand the links/virtualnames

your puppet should be:

package {
  'nmap-ncat':
    ensure => installed;
}

len() of a numpy array in python

What is the len of the equivalent nested list?

len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])

With the more general concept of shape, numpy developers choose to implement __len__ as the first dimension. Python maps len(obj) onto obj.__len__.

X.shape returns a tuple, which does have a len - which is the number of dimensions, X.ndim. X.shape[i] selects the ith dimension (a straight forward application of tuple indexing).

What are the differences among grep, awk & sed?

Short definition:

grep: search for specific terms in a file

#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"

$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"

Now awk and sed are completly different than grep. awk and sed are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).

awk is mostly used for data extraction and reporting. sed is a stream editor
Each one of them has its own functionality and specialties.

Example
Sed

$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'

Awk

$ awk '{print $2}' file.txt
# this will print the second column of file.txt

Basic awk usage:
Compute sum/average/max/min/etc. what ever you may need.

$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average:    30

I recommend that you read this book: Sed & Awk: 2nd Ed.

It will help you become a proficient sed/awk user on any unix-like environment.

Make an image width 100% of parent div, but not bigger than its own width

Just specify max-width: 100% alone, that should do it.

Tomcat base URL redirection

In Tomcat 8 you can also use the rewrite-valve

RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^/(.*)$         /somethingelse/index.jsp

To setup the rewrite-valve look here:

http://tonyjunkes.com/blog/a-brief-look-at-the-rewrite-valve-in-tomcat-8/

How to squash all git commits into one?

In one line of 6 words:

git checkout --orphan new_root_branch  &&  git commit

Can I try/catch a warning?

I would only recommend using @ to suppress warnings when it's a straight forward operation (e.g. $prop = @($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.

Replace multiple strings with multiple other strings

Specific Solution

You can use a function to replace each one.

var str = "I have a cat, a dog, and a goat.";
var mapObj = {
   cat:"dog",
   dog:"goat",
   goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
  return mapObj[matched];
});

jsfiddle example

Generalizing it

If you want to dynamically maintain the regex and just add future exchanges to the map, you can do this

new RegExp(Object.keys(mapObj).join("|"),"gi"); 

to generate the regex. So then it would look like this

var mapObj = {cat:"dog",dog:"goat",goat:"cat"};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
  return mapObj[matched];
});

And to add or change any more replacements you could just edit the map. 

fiddle with dynamic regex

Making it Reusable

If you want this to be a general pattern you could pull this out to a function like this

function replaceAll(str,mapObj){
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");

    return str.replace(re, function(matched){
        return mapObj[matched.toLowerCase()];
    });
}

So then you could just pass the str and a map of the replacements you want to the function and it would return the transformed string.

fiddle with function

To ensure Object.keys works in older browsers, add a polyfill eg from MDN or Es5.

Remove Backslashes from Json Data in JavaScript

tl;dr: You don't have to remove the slashes, you have nested JSON, and hence have to decode the JSON twice: DEMO (note I used double slashes in the example, because the JSON is inside a JS string literal).


I assume that your actual JSON looks like

{"data":"{\n \"taskNames\" : [\n \"01 Jan\",\n \"02 Jan\",\n \"03 Jan\",\n \"04 Jan\",\n \"05 Jan\",\n \"06 Jan\",\n \"07 Jan\",\n \"08 Jan\",\n \"09 Jan\",\n \"10 Jan\",\n \"11 Jan\",\n \"12 Jan\",\n \"13 Jan\",\n \"14 Jan\",\n \"15 Jan\",\n \"16 Jan\",\n \"17 Jan\",\n \"18 Jan\",\n \"19 Jan\",\n \"20 Jan\",\n \"21 Jan\",\n \"22 Jan\",\n \"23 Jan\",\n \"24 Jan\",\n \"25 Jan\",\n \"26 Jan\",\n \"27 Jan\"]}"}

I.e. you have a top level object with one key, data. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. This lets the parser know that " is to be treated literally and doesn't terminate the string.

So you can either fix the server side code, so that you don't double encode the data, or you have to decode the JSON twice, e.g.

var data = JSON.parse(JSON.parse(json).data));

No route matches "/users/sign_out" devise rails 3

  devise_for :users
  devise_scope :user do
    get '/users/sign_out' => 'devise/sessions#destroy'
  end