Programs & Examples On #Gwt

GWT (formerly the Google Web Toolkit) is a development toolkit for building and optimizing complex browser-based applications. Its goal is to enable productive development of high-performance web applications without requiring the developer to be an expert in browser quirks, XMLHttpRequest, and JavaScript. GWT is used by many products at Google, including the new versions of AdWords and Groups. It's open source and completely free (Apache 2.0 licensed).

How do I speed up the gwt compiler?

For GWT 2.x I just discovered that if you use

<set-property name="user.agent" value="ie6"/>
<extend-property values="ie8,gecko1_8" name="user.agent"/>

You can even specify more than one permutation.

How to see if an object is an array without using reflection?

You can create a utility class to check if the class represents any Collection, Map or Array

  public static boolean isCollection(Class<?> rawPropertyType) {
        return Collection.class.isAssignableFrom(rawPropertyType) || 
               Map.class.isAssignableFrom(rawPropertyType) || 
               rawPropertyType.isArray();
 }

Send an Array with an HTTP Get

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.

You have to write the query adding "[]" to foo like this:

foo[]=val1&foo[]=val2&foo[]=val3

I want to vertical-align text in select box

The nearest general solution i know uses box-align property, as described here. Working example is here (i can test it only on Chrome, believe that has equivalent for other browsers too).

CSS:

select{
  display:-webkit-box;
  display:-moz-box;
  display:box;
  height: 30px;;
}
select:nth-child(1){
  -webkit-box-align:start;
  -moz-box-align:start;
  box-align:start;
}
select:nth-child(2){
  -webkit-box-align:center;
  -moz-box-align:center;
  box-align:center;
}
select:nth-child(3){
  -webkit-box-align:end;
  -moz-box-align:end;
  box-align:end;
}

How do I pass a class as a parameter in Java?

public void callingMethod(Class neededClass) {
    //Cast the class to the class you need
    //and call your method in the class
    ((ClassBeingCalled)neededClass).methodOfClass();
}

To call the method, you call it this way:

callingMethod(ClassBeingCalled.class);

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I was facing the same issue. In my case, I had a dependency of httpclient with an older version while sendgrid required a newer version of httpclient. Just make sure that the version of httpclient is correct in your dependencies and it would work fine.

Interface/enum listing standard mime-type constants

From https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/MediaType.html :

staticjava.lang.String APPLICATION_ATOM_XML             "application/atom+xml"
staticMediaType        APPLICATION_ATOM_XML_TYPE        "application/atom+xml"
staticjava.lang.String APPLICATION_FORM_URLENCODED      "application/x-www-form-urlencoded"
staticMediaType        APPLICATION_FORM_URLENCODED_TYPE "application/x-www-form-urlencoded"
staticjava.lang.String APPLICATION_JSON                 "application/json"
staticMediaType        APPLICATION_JSON_TYPE            "application/json"
staticjava.lang.String APPLICATION_OCTET_STREAM         "application/octet-stream"
staticMediaType        APPLICATION_OCTET_STREAM_TYPE    "application/octet-stream"
staticjava.lang.String APPLICATION_SVG_XML              "application/svg+xml"
staticMediaType        APPLICATION_SVG_XML_TYPE         "application/svg+xml"
staticjava.lang.String APPLICATION_XHTML_XML            "application/xhtml+xml"
staticMediaType        APPLICATION_XHTML_XML_TYPE       "application/xhtml+xml"
staticjava.lang.String APPLICATION_XML                  "application/xml"
staticMediaType        APPLICATION_XML_TYPE             "application/xml"
staticjava.lang.String MEDIA_TYPE_WILDCARD              The value of a type or subtype wildcard: "*"
staticjava.lang.String MULTIPART_FORM_DATA              "multipart/form-data"
staticMediaType        MULTIPART_FORM_DATA_TYPE         "multipart/form-data"
staticjava.lang.String TEXT_HTML                        "text/html"
staticMediaType        TEXT_HTML_TYPE                   "text/html"
staticjava.lang.String TEXT_PLAIN                       "text/plain"
staticMediaType        TEXT_PLAIN_TYPE                  "text/plain"
staticjava.lang.String TEXT_XML                         "text/xml"
staticMediaType        TEXT_XML_TYPE                    "text/xml"
staticjava.lang.String WILDCARD                         "*/*"
staticMediaType        WILDCARD_TYPE                    "*/*"

ClassNotFoundException: org.slf4j.LoggerFactory

i know this is an old Question , but i faced this problem recently and i looked for it in google , and i came across this documentation here from slf4j website .

as it describes the following :

This error is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path.

Placing one (and only one) of slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.

SINCE 1.6.0 As of SLF4J version 1.6, in the absence of a binding, SLF4J will default to a no-operation (NOP) logger implementation.

Hope that will help someone .

Spring MVC Controller redirect using URL parameters instead of in response

You can have processForm() return a View object instead, and have it return the concrete type RedirectView which has a parameter for setExposeModelAttributes().

When you return a view name prefixed with "redirect:", Spring MVC transforms this to a RedirectView object anyway, it just does so with setExposeModelAttributes to true (which I think is an odd value to default to).

Flutter - The method was called on null

You have a CryptoListPresenter _presenter but you are never initializing it. You should either be doing that when you declare it or in your initState() (or another appropriate but called-before-you-need-it method).

One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.

EDIT:

I see diegoveloper beat me to answering this, and that the OP asked a follow up.

@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);, or

CryptoListPresenter _presenter;

@override
void initState() {
  _presenter = new CryptoListPresenter(...);
}

Sort hash by key, return hash in Ruby

No, it is not (Ruby 1.9.x)

require 'benchmark'

h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
many = 100_000

Benchmark.bm do |b|
  GC.start

  b.report("hash sort") do
    many.times do
      Hash[h.sort]
    end
  end

  GC.start

  b.report("keys sort") do
    many.times do
      nh = {}
      h.keys.sort.each do |k|
        nh[k] = h[k]
      end
    end
  end
end

       user     system      total        real
hash sort  0.400000   0.000000   0.400000 (  0.405588)
keys sort  0.250000   0.010000   0.260000 (  0.260303)

For big hashes difference will grow up to 10x and more

Linking a UNC / Network drive on an html page

Setup IIS on the network server and change the path to http://server/path/to/file.txt

EDIT: Make sure you enable directory browsing in IIS

Laravel: How do I parse this json data in view blade?

The catch all for me is taking an object, encoding it, and then passing the string into a javascript script tag. To do this you have to do some replacements.

First replace every \ with a double slash \\ and then every quote" with a \".

$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
return View::make('pages.javascript')
  ->with('payload', $payload)

Then in the blade template

@if(isset($payload))
<script>
  window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif

This basically allows you to take an object on the php side, and then have an object on the javascript side.

How do I display a wordpress page content?

@Sydney Try putting wp_reset_query() before you call the loop. This will display the content of your page.

<?php
    wp_reset_query(); // necessary to reset query
    while ( have_posts() ) : the_post();
        the_content();
    endwhile; // End of the loop.
?>

EDIT: Try this if you have some other loops that you previously ran. Place wp_reset_query(); where you find it most suitable, but before you call this loop.

Unicode character in PHP string

As mentioned by others, PHP 7 introduces support for the \u Unicode syntax directly.

As also mentioned by others, the only way to obtain a string value from any sensible Unicode character description in PHP, is by converting it from something else (e.g. JSON parsing, HTML parsing or some other form). But this comes at a run-time performance cost.

However, there is one other option. You can encode the character directly in PHP with \x binary escaping. The \x escape syntax is also supported in PHP 5.

This is especially useful if you prefer not to enter the character directly in a string through its natural form. For example, if it is an invisible control character, or other hard to detect whitespace.

First, a proof example:

// Unicode Character 'HAIR SPACE' (U+200A)
$htmlEntityChar = "&#8202;";
$realChar = html_entity_decode($htmlEntityChar);
$phpChar = "\xE2\x80\x8A";
echo 'Proof: ';
var_dump($realChar === $phpChar); // bool(true)

Note that, as mentioned by Pacerier in another answer, this binary code is unique to a specific character encoding. In the above example, \xE2\x80\x8A is the binary coding for U+200A in UTF-8.

The next question is, how do you get from U+200A to \xE2\x80\x8A?

Below is a PHP script to generate the escape sequence for any character, based on either a JSON string, HTML entity, or any other method once you have it as a native string.

function str_encode_utf8binary($str) {
    /** @author Krinkle 2018 */
    $output = '';
    foreach (str_split($str) as $octet) {
        $ordInt = ord($octet);
        // Convert from int (base 10) to hex (base 16), for PHP \x syntax
        $ordHex = base_convert($ordInt, 10, 16);
        $output .= '\x' . $ordHex;
    }
    return $output;
}

function str_convert_html_to_utf8binary($str) {
    return str_encode_utf8binary(html_entity_decode($str));
}
function str_convert_json_to_utf8binary($str) {
    return str_encode_utf8binary(json_decode($str));
}

// Example for raw string: Unicode Character 'INFINITY' (U+221E)
echo str_encode_utf8binary('8') . "\n";
// \xe2\x88\x9e

// Example for HTML: Unicode Character 'HAIR SPACE' (U+200A)
echo str_convert_html_to_utf8binary('&#8202;') . "\n";
// \xe2\x80\x8a

// Example for JSON: Unicode Character 'HAIR SPACE' (U+200A)
echo str_convert_json_to_utf8binary('"\u200a"') . "\n";
// \xe2\x80\x8a

jquery multiple checkboxes array

A global function that can be reused:

function getCheckedGroupBoxes(groupName) {

    var checkedAry= [];
    $.each($("input[name='" + groupName + "']:checked"), function () {
        checkedAry.push($(this).attr("id"));
    });

     return checkedAry;

}

where the groupName is the name of the group of the checkboxes, in you example :'options[]'

Build android release apk on Phonegap 3.x CLI

In PhoneGap 3.4.0 you can call:

cordova build android --release

If you have set up the 'ant.properties' file in 'platforms/android' directory like the following:

key.store=/Path/to/KeyStore/myapp-release-key.keystore
key.alias=myapp

Then you will be prompted for your keystore password and the output file (myapp-release.apk) ends up in the 'platforms/android/ant-build' directory already signed and aligned and ready to deploy.

Apache Proxy: No protocol handler was valid

In my case, all modules were correctly set up (https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension is a good starter) & I had the redirection working for a base url, let's say /mysite/ but I got the errors for any child ULR, let's say /mysite/login/

http://reverse-proxy.dns.com/mysite/ was properly redirected to the remote servers while http://reverse-proxy.dns.com/mysite/login/ failed at the Apache2 reverse proxying with OP's error message.

The issue was the ending / character in the proxypass directive "/mysite/". Working configuration for child URL is :

<Proxy balancer://mysite_cluster>
    BalancerMember http://192.x.x.10:8080/mysite
    BalancerMember http://192.x.x.11:8080/mysite
</Proxy>
<VirtualHost *:80>
    [...]
    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass "/mysite" "balancer://mysite_cluster"
    ProxyPassReverse "/mysite" "balancer://mysite_cluster"       
</VirtualHost>

Trailing / truly are tricky.

MySQL COUNT DISTINCT

 Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

.NET: Simplest way to send POST with data and read response

Given other answers are a few years old, currently here are my thoughts that may be helpful:

Simplest way

private async Task<string> PostAsync(Uri uri, HttpContent dataOut)
{
    var client = new HttpClient();
    var response = await client.PostAsync(uri, dataOut);
    return await response.Content.ReadAsStringAsync();
    // For non strings you can use other Content.ReadAs...() method variations
}

A More Practical Example

Often we are dealing with known types and JSON, so you can further extend this idea with any number of implementations, such as:

public async Task<T> PostJsonAsync<T>(Uri uri, object dtoOut)
{
    var content = new StringContent(JsonConvert.SerializeObject(dtoOut));
    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

    var results = await PostAsync(uri, content); // from previous block of code

    return JsonConvert.DeserializeObject<T>(results); // using Newtonsoft.Json
}

An example of how this could be called:

var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);

Pull new updates from original GitHub repository into forked GitHub repository

If you want to do it without cli, you can do it fully on Github website.

  1. Go to your fork repository.
  2. Click on New pull request.
  3. Make sure to set your fork as the base repository, and the original (upstream) repository as head repository. Usually you only want to sync the master branch.
  4. Create new pull request.
  5. Select the arrow to the right of the merging button, and make sure to choose rebase instead of merge. Then click the button. This way, it will not produce unnecessary merge commit.
  6. Done.

How to call an action after click() in Jquery?

setTimeout may help out here

$("#message_link").click(function(){
   setTimeout(function() {
       if (some_conditions...){
           $("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\"  /></div>");
       }
   }, 100);
});

That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

Check if a string is a valid date using DateTime.TryParse

[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
    string[] formats = { "MM/dd/yyyy" };
    DateTime parsedDateTime;
    return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
                                   DateTimeStyles.None, out parsedDateTime);
}

Simply specify the date time formats that you wish to accept in the array named formats.

How to concatenate a std::string and an int?

#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
   std::stringstream ss;
   ss << t;
   return ss.str();
}

Then your usage would look something like this

   std::string szName = "John";
   int numAge = 23;
   szName += to_string<int>(numAge);
   cout << szName << endl;

Googled [and tested :p ]

What is the fastest way to compare two sets in Java?

public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof Set))
            return false;

        Set<String> a = this;
        Set<String> b = o;
        Set<String> thedifference_a_b = new HashSet<String>(a);


        thedifference_a_b.removeAll(b);
        if(thedifference_a_b.isEmpty() == false) return false;

        Set<String> thedifference_b_a = new HashSet<String>(b);
        thedifference_b_a.removeAll(a);

        if(thedifference_b_a.isEmpty() == false) return false;

        return true;
    }

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

How to find index of list item in Swift?

Swift 2.1

var array = ["0","1","2","3"]

if let index = array.indexOf("1") {
   array.removeAtIndex(index)
}

print(array) // ["0","2","3"]

Swift 3

var array = ["0","1","2","3"]

if let index = array.index(of: "1") {
    array.remove(at: index)
}
array.remove(at: 1)

Show Youtube video source into HTML5 video tag?

The easiest answer is given by W3schools. https://www.w3schools.com/html/html_youtube.asp

  1. Upload your video to Youtube
  2. Note the Video ID
  3. Now write this code in your HTML5.
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>

how to run vibrate continuously in iphone?

Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:

 AudioServicesAddSystemSoundCompletion (
        kSystemSoundID_Vibrate,
        NULL,
        NULL,
        MyAudioServicesSystemSoundCompletionProc,
        NULL
    );
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Then you define your callback function to replay the vibrate sound again:

#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
   SystemSoundID  ssID,
   void           *clientData
);

#pragma mark AudioService callback function implementation

// Callback that gets called after we finish buzzing, so we 
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
   SystemSoundID  ssID,
   void           *clientData
) {
  if (iShouldKeepBuzzing) { // Your logic here...
      AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 
  } else {
      //Unregister, so we don't get called again...
      AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
  }  
}

How to check if current thread is not main thread

Summarizing the solutions, I think that's the best one:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M 
    ? Looper.getMainLooper().isCurrentThread()
    : Thread.currentThread() == Looper.getMainLooper().getThread();

And, if you wish to run something on the UI thread, you can use this:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       //this runs on the UI thread
    }
});

jQuery .live() vs .on() method for adding a click event after loading dynamic html

I used 'live' in my project but one of my friend suggested that i should use 'on' instead of live. And when i tried to use that i experienced a problem like you had.

On my pages i create buttons table rows and many dom stuff dynamically. but when i use on the magic disappeared.

The other solutions like use it like a child just calls your functions every time on every click. But i find a way to make it happen again and here is the solution.

Write your code as:

function caller(){
    $('.ObjectYouWntToCall').on("click", function() {...magic...});
}

Call caller(); after you create your object in the page like this.

$('<dom class="ObjectYouWntToCall">bla... bla...<dom>').appendTo("#whereeveryouwant");
caller();

By this way your function is called when it is supposed to not every click on the page.

How to change MySQL timezone in a database connection using Java?

JDBC uses a so-called "connection URL", so you can escape "+" by "%2B", that is

useTimezone=true&serverTimezone=GMT%2B8

how to delete installed library form react native project

  1. If it is a library based only on javascript, than you can just run npm uninstall --save package_name or npm uninstall --save-dev package_name
  2. If you've installed a library with native content that requires linking, and you've linked it with npm then you can do: npm unlink package_name then follow step 1
  3. If you've installed a library with native content manually, then just undo all the steps you took to add the library in the first place. Then follow step 1.

note rnpm as is deprecated

How to drop columns using Rails migration

For older versions of Rails

ruby script/generate migration RemoveFieldNameFromTableName field_name:datatype

For Rails 3 and up

rails generate migration RemoveFieldNameFromTableName field_name:datatype

SQL Server JOIN missing NULL values

you can just map like that

select * from tableA a
join tableB b on isnull(a.colID,'') = isnull(b.colId,'')

Is Unit Testing worth the effort?

When you manually test software, you normally have a small set of tests/actions that you use. Eventually you'll automatically morph your input data or actions so that you navigate yourself around known issues. Unit tests should be there to remind you that things do not work correctly.

I recommend writing tests before code, adding new tests/data to evolve the functionality of the main code!

json_decode to array

Please try this

<?php
$json_string = 'http://www.domain.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>

ASP.NET Web Site or ASP.NET Web Application?

Websites - No solution file will be created. If we want to create websites no need for visual studio.

Web Application - A solution file will be created. If we want to create web application should need the visual studio. It will create a single .dll file in bin folder.

How to convert date format to DD-MM-YYYY in C#

you could do like this:

return inObj == DBNull.Value ? "" : (Convert.ToDateTime(inObj)).ToString("MM/dd/yyyy").ToString();

Django model "doesn't declare an explicit app_label"

I got this error on importing models in tests, i.e. given this Django project structure:

|-- myproject
    |-- manage.py
    |-- myproject
    |-- myapp
        |-- models.py  # defines model: MyModel
        |-- tests
            |-- test_models.py

in file test_models.py I imported MyModel in this way:

from models import MyModel

The problem was fixed if it is imported in this way:

from myapp.models import MyModel

Hope this helps!

PS: Maybe this is a bit late, but I not found in others answers how to solve this problem in my code and I want to share my solution.

How to make rounded percentages add up to 100%

Here's a Ruby gem that implements the Largest Remainder method: https://github.com/jethroo/lare_round

To use:

a =  Array.new(3){ BigDecimal('0.3334') }
# => [#<BigDecimal:887b6c8,'0.3334E0',9(18)>, #<BigDecimal:887b600,'0.3334E0',9(18)>, #<BigDecimal:887b4c0,'0.3334E0',9(18)>]
a = LareRound.round(a,2)
# => [#<BigDecimal:8867330,'0.34E0',9(36)>, #<BigDecimal:8867290,'0.33E0',9(36)>, #<BigDecimal:88671f0,'0.33E0',9(36)>]
a.reduce(:+).to_f
# => 1.0

Use of ~ (tilde) in R programming Language

R defines a ~ (tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:

library(datasets)
lm( myFormula, data=iris)

help("~") or help("formula") will teach you more.

@Spacedman has covered the basics. Let's discuss how it works.

First, being an operator, note that it is essentially a shortcut to a function (with two arguments):

> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs

That can be helpful to know for use in e.g. apply family commands.

Second, you can manipulate the formula as text:

oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )

Third, you can manipulate it as a list:

myFormula[[2]]
myFormula[[3]]

Finally, there are some helpful tricks with formulae (see help("formula") for more):

myFormula <- Species ~ . 

For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.

How to join entries in a set into one string?

The join is called on the string:

print ", ".join(set_3)

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

Git Checkout warning: unable to unlink files, permission denied

You can change the write permissions to get it done.

sudo chmod -R ug+w . 

This command will give 'w' permissions to all the folders in the current directory.

Laravel requires the Mcrypt PHP extension

OSX with brew

$ brew install mcrypt php70-mcrypt

I am running PHP 7.0.x, so change "php70" to your version, if you are using a different version.
As stated in other answers, you can see your php version with $ php -v.

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

Work with a time span in Javascript

Here a .NET C# similar implementation of a timespan class that supports days, hours, minutes and seconds. This implementation also supports negative timespans.

const MILLIS_PER_SECOND = 1000;
const MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60;   //     60,000
const MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60;     //  3,600,000
const MILLIS_PER_DAY = MILLIS_PER_HOUR * 24;        // 86,400,000

export class TimeSpan {
    private _millis: number;

    private static interval(value: number, scale: number): TimeSpan {
        if (Number.isNaN(value)) {
            throw new Error("value can't be NaN");
        }

        const tmp = value * scale;
        const millis = TimeSpan.round(tmp + (value >= 0 ? 0.5 : -0.5));
        if ((millis > TimeSpan.maxValue.totalMilliseconds) || (millis < TimeSpan.minValue.totalMilliseconds)) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }

        return new TimeSpan(millis);
    }

    private static round(n: number): number {
        if (n < 0) {
            return Math.ceil(n);
        } else if (n > 0) {
            return Math.floor(n);
        }

        return 0;
    }

    private static timeToMilliseconds(hour: number, minute: number, second: number): number {
        const totalSeconds = (hour * 3600) + (minute * 60) + second;
        if (totalSeconds > TimeSpan.maxValue.totalSeconds || totalSeconds < TimeSpan.minValue.totalSeconds) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }

        return totalSeconds * MILLIS_PER_SECOND;
    }

    public static get zero(): TimeSpan {
        return new TimeSpan(0);
    }

    public static get maxValue(): TimeSpan {
        return new TimeSpan(Number.MAX_SAFE_INTEGER);
    }

    public static get minValue(): TimeSpan {
        return new TimeSpan(Number.MIN_SAFE_INTEGER);
    }

    public static fromDays(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_DAY);
    }

    public static fromHours(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_HOUR);
    }

    public static fromMilliseconds(value: number): TimeSpan {
        return TimeSpan.interval(value, 1);
    }

    public static fromMinutes(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_MINUTE);
    }

    public static fromSeconds(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_SECOND);
    }

    public static fromTime(hours: number, minutes: number, seconds: number): TimeSpan;
    public static fromTime(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan;
    public static fromTime(daysOrHours: number, hoursOrMinutes: number, minutesOrSeconds: number, seconds?: number, milliseconds?: number): TimeSpan {
        if (milliseconds != undefined) {
            return this.fromTimeStartingFromDays(daysOrHours, hoursOrMinutes, minutesOrSeconds, seconds, milliseconds);
        } else {
            return this.fromTimeStartingFromHours(daysOrHours, hoursOrMinutes, minutesOrSeconds);
        }
    }

    private static fromTimeStartingFromHours(hours: number, minutes: number, seconds: number): TimeSpan {
        const millis = TimeSpan.timeToMilliseconds(hours, minutes, seconds);
        return new TimeSpan(millis);
    }

    private static fromTimeStartingFromDays(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan {
        const totalMilliSeconds = (days * MILLIS_PER_DAY) +
            (hours * MILLIS_PER_HOUR) +
            (minutes * MILLIS_PER_MINUTE) +
            (seconds * MILLIS_PER_SECOND) +
            milliseconds;

        if (totalMilliSeconds > TimeSpan.maxValue.totalMilliseconds || totalMilliSeconds < TimeSpan.minValue.totalMilliseconds) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }
        return new TimeSpan(totalMilliSeconds);
    }

    constructor(millis: number) {
        this._millis = millis;
    }

    public get days(): number {
        return TimeSpan.round(this._millis / MILLIS_PER_DAY);
    }

    public get hours(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_HOUR) % 24);
    }

    public get minutes(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_MINUTE) % 60);
    }

    public get seconds(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_SECOND) % 60);
    }

    public get milliseconds(): number {
        return TimeSpan.round(this._millis % 1000);
    }

    public get totalDays(): number {
        return this._millis / MILLIS_PER_DAY;
    }

    public get totalHours(): number {
        return this._millis / MILLIS_PER_HOUR;
    }

    public get totalMinutes(): number {
        return this._millis / MILLIS_PER_MINUTE;
    }

    public get totalSeconds(): number {
        return this._millis / MILLIS_PER_SECOND;
    }

    public get totalMilliseconds(): number {
        return this._millis;
    }

    public add(ts: TimeSpan): TimeSpan {
        const result = this._millis + ts.totalMilliseconds;
        return new TimeSpan(result);
    }

    public subtract(ts: TimeSpan): TimeSpan {
        const result = this._millis - ts.totalMilliseconds;
        return new TimeSpan(result);
    }
}

How to use

Create a new TimeSpan object

From zero

    const ts = TimeSpan.zero;

From milliseconds

    const milliseconds = 10000; // 1 second

    // by using the constructor
    const ts1 = new TimeSpan(milliseconds);

    // or as an alternative you can use the static factory method
    const ts2 = TimeSpan.fromMilliseconds(milliseconds);

From seconds

    const seconds = 86400; // 1 day
    const ts = TimeSpan.fromSeconds(seconds);

From minutes

    const minutes = 1440; // 1 day
    const ts = TimeSpan.fromMinutes(minutes);

From hours

    const hours = 24; // 1 day
    const ts = TimeSpan.fromHours(hours);

From days

    const days = 1; // 1 day
    const ts = TimeSpan.fromDays(days);

From time with given hours, minutes and seconds

    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const ts = TimeSpan.fromTime(hours, minutes, seconds);

From time2 with given days, hours, minutes, seconds and milliseconds

    const days = 1;
    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const milliseconds = 1;
    const ts = TimeSpan.fromTime(days, hours, minutes, seconds, milliseconds);

From maximal safe integer

    const ts = TimeSpan.maxValue;

From minimal safe integer

    const ts = TimeSpan.minValue;

From minimal safe integer

    const ts = TimeSpan.minValue;

Add

    const ts1 = TimeSpan.fromDays(1);
    const ts2 = TimeSpan.fromHours(1);
    const ts = ts1.add(ts2);

    console.log(ts.days);               // 1
    console.log(ts.hours);              // 1
    console.log(ts.minutes);            // 0
    console.log(ts.seconds);            // 0
    console.log(ts.milliseconds);           // 0

Subtract

    const ts1 = TimeSpan.fromDays(1);
    const ts2 = TimeSpan.fromHours(1);
    const ts = ts1.subtract(ts2);

    console.log(ts.days);               // 0
    console.log(ts.hours);              // 23
    console.log(ts.minutes);            // 0
    console.log(ts.seconds);            // 0
    console.log(ts.milliseconds);           // 0

Getting the intervals

    const days = 1;
    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const milliseconds = 1;
    const ts = TimeSpan.fromTime2(days, hours, minutes, seconds, milliseconds);

    console.log(ts.days);               // 1
    console.log(ts.hours);              // 1
    console.log(ts.minutes);            // 1
    console.log(ts.seconds);            // 1
    console.log(ts.milliseconds);           // 1

    console.log(ts.totalDays)           // 1.0423726967592593;
    console.log(ts.totalHours)          // 25.016944722222224;
    console.log(ts.totalMinutes)            // 1501.0166833333333;
    console.log(ts.totalSeconds)            // 90061.001;
    console.log(ts.totalMilliseconds);      // 90061001;

See also here: https://github.com/erdas/timespan

How to call a PHP function on the click of a button

You can simply do this. In php, you can determine button click by use of

if(isset($_Post['button_tag_name']){
echo "Button Clicked";
}

Therefore you should modify you code as follows:


<?php

if(isset($_Post['select']){
 echo "select button clicked and select method should be executed";
}
if(isset($_Post['insert']){
 echo "insert button clicked and insert method should be executed";
}
           
        ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <body>
        <form action="functioncalling.php">
            <input type="text" name="txt" />
            <input type="submit" name="insert" value="insert" onclick="insert()" />
            <input type="submit" name="select" value="select" onclick="select()" />
        </form>

<script>
//This will be processed on the client side
function insert(){
  window.alert("You click insert button");
}

function select(){
  window.alert("You click insert button");
}
</script>
</body>
</html>


        

How to get difference between two dates in Year/Month/Week/Day?

This is actually quite tricky. A different total number of days can result in the same result. For example:

  • 19th June 2008 to 19th June 2010 = 2 years, but also 365 * 2 days

  • 19th June 2006 to 19th June 2008 = 2 years, but also 365 + 366 days due to leap years

You may well want to subtract years until you get to the point where you've got two dates which are less than a year apart. Then subtract months until you get to the point where you've got two dates which are less than a month apart.

Further confusion: subtracting (or adding) months is tricky when you might start with a date of "30th March" - what's a month earlier than that?

Even further confusion (may not be relevant): even a day isn't always 24 hours. Daylight saving anyone?

Even further confusion (almost certainly not relevant): even a minute isn't always 60 seconds. Leap seconds are highly confusing...

I don't have the time to work out the exact right way of doing this right now - this answer is mostly to raise the fact that it's not nearly as simple as it might sound.

EDIT: Unfortunately I'm not going to have enough time to answer this fully. I would suggest you start off by defining a struct representing a Period:

public struct Period
{
    private readonly int days;
    public int Days { get { return days; } }
    private readonly int months;
    public int Months { get { return months; } }
    private readonly int years;
    public int Years { get { return years; } }

    public Period(int years, int months, int days)
    {
        this.years = years;
        this.months = months;
        this.days = days;
    }

    public Period WithDays(int newDays)
    {
        return new Period(years, months, newDays);
    }

    public Period WithMonths(int newMonths)
    {
        return new Period(years, newMonths, days);
    }

    public Period WithYears(int newYears)
    {
        return new Period(newYears, months, days);
    }

    public static DateTime operator +(DateTime date, Period period)
    {
        // TODO: Implement this!
    }

    public static Period Difference(DateTime first, DateTime second)
    {
        // TODO: Implement this!
    }
}

I suggest you implement the + operator first, which should inform the Difference method - you should make sure that first + (Period.Difference(first, second)) == second for all first/second values.

Start with writing a whole slew of unit tests - initially "easy" cases, then move on to tricky ones involving leap years. I know the normal approach is to write one test at a time, but I'd personally brainstorm a bunch of them before you start any implementation work.

Allow yourself a day to implement this properly. It's tricky stuff.

Note that I've omitted weeks here - that value at least is easy, because it's always 7 days. So given a (positive) period, you'd have:

int years = period.Years;
int months = period.Months;
int weeks = period.Days / 7;
int daysWithinWeek = period.Days % 7;

(I suggest you avoid even thinking about negative periods - make sure everything is positive, all the time.)

How can I force gradle to redownload dependencies?

Seems change is changed to isChange for gradle version 6.3, kotlin version 1.3.70, Groovy 2.5.10

The working configuration is

implementation("com.sample:commons:1.0.0-SNAPSHOT") {
        isChanging = true
    }

Also, run this command to fetch the latest

./gradlew assemble  --refresh-dependencies

ERROR in Cannot find module 'node-sass'

npm install node-sass will do the job in most of the cases, as it will add missing sass npm dependency module doesn't exist or it will overwrite previous crashed version.

For Mac Users use sudo in front of above commands.

On Windows machines npm rebuild node-sass --force may not work for some users because it's essentially saying, "please force npm to rebuild the sass node module for me". It will not work because that module doesn't exist.

Whenever you did npm install to the initial installation, the sass module did not get installed, which is why this problem occurs.

Try reinstalling `node-sass` on node 0.12?

i had the same problem today at work.

npm rebuild node-sass

done the job for me

Checking if a website is up via Python

The HTTPConnection object from the httplib module in the standard library will probably do the trick for you. BTW, if you start doing anything advanced with HTTP in Python, be sure to check out httplib2; it's a great library.

GenyMotion Unable to start the Genymotion virtual device

In my case, the only option was to remove the VM and download it again. No re-configuration of the host-only adapter did not help, I used different addressing of DHCP. Virtual Box I updated to version 4.3.4 and Genymotion to 2.0.2

How to tell Jackson to ignore a field during serialization if its value is null?

This Will work in Spring boot 2.0.3+ and Jackson 2.0+

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
    // your class variable and 
    // methods
}

Add a common Legend for combined ggplots

Roland's answer needs updating. See: https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

This method has been updated for ggplot2 v1.0.0.

library(ggplot2)
library(gridExtra)
library(grid)


grid_arrange_shared_legend <- function(...) {
    plots <- list(...)
    g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
    legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
    lheight <- sum(legend$height)
    grid.arrange(
        do.call(arrangeGrob, lapply(plots, function(x)
            x + theme(legend.position="none"))),
        legend,
        ncol = 1,
        heights = unit.c(unit(1, "npc") - lheight, lheight))
}

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(cut, price, data=dsamp, colour=clarity)
p3 <- qplot(color, price, data=dsamp, colour=clarity)
p4 <- qplot(depth, price, data=dsamp, colour=clarity)
grid_arrange_shared_legend(p1, p2, p3, p4)

Note the lack of ggplot_gtable and ggplot_build. ggplotGrob is used instead. This example is a bit more convoluted than the above solution but it still solved it for me.

Error sending json in POST to web API service

In the HTTP request you need to set Content-Type to: Content-Type: application/json

So if you're using fiddler client add Content-Type: application/json to the request header

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Contrary to Martin's answer, casting to int (or ignoring the warning) isn't always safe even if you know your array doesn't have more than 2^31-1 elements. Not when compiling for 64-bit.

For example:

NSArray *array = @[@"a", @"b", @"c"];

int i = (int) [array indexOfObject:@"d"];
// indexOfObject returned NSNotFound, which is NSIntegerMax, which is LONG_MAX in 64 bit.
// We cast this to int and got -1.
// But -1 != NSNotFound. Trouble ahead!

if (i == NSNotFound) {
    // thought we'd get here, but we don't
    NSLog(@"it's not here");
}
else {
    // this is what actually happens
    NSLog(@"it's here: %d", i);

    // **** crash horribly ****
    NSLog(@"the object is %@", array[i]);
}

Cassandra cqlsh - connection refused

Make sure that you also set "seeds" to the address which you provided at "listen_address"

How to create a thread?

Your example fails because Thread methods take either one or zero arguments. To create a thread without passing arguments, your code looks like this:

void Start()
{
    // do stuff
}

void Test()
{
    new Thread(new ThreadStart(Start)).Start();
}

If you want to pass data to the thread, you need to encapsulate your data into a single object, whether that is a custom class of your own design, or a dictionary object or something else. You then need to use the ParameterizedThreadStart delegate, like so:

void Start(object data)
{
    MyClass myData = (MyClass)myData;
    // do stuff
}

void Test(MyClass data)
{
    new Thread(new ParameterizedThreadStart(Start)).Start(data);
}

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

If your web application is configured to impersonate a client, then using a trusted connection will potentially have a negative performance impact. This is because each client must use a different connection pool (with the client's credentials).

Most web applications don't use impersonation / delegation, and hence don't have this problem.

See this MSDN article for more information.

Chrome refuses to execute an AJAX script due to wrong MIME type

If your proxy server or container adds the following header when serving the .js file, it will force some browsers such as Chrome to perform strict checking of MIME types:

X-Content-Type-Options: nosniff

Remove this header to prevent Chrome performing the MIME check.

Change type of varchar field to integer: "cannot be cast automatically to type integer"

If you are working on development environment(or on for production env. it may be backup your data) then first to clear the data from the DB field or set the value as 0.

UPDATE table_mame SET field_name= 0;

After that to run the below query and after successfully run the query, to the schemamigration and after that run the migrate script.

ALTER TABLE table_mame ALTER COLUMN field_name TYPE numeric(10,0) USING field_name::numeric;

I think it will help you.

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.

I have created a demo JS fiddle to demonstrate how this works:

Here is the code of the JS fiddle:

HTML:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a href="http://jquery.com">Default click action is prevented, only on the third click it would be enabled</a>
<div id="log"></div>

Javascript:

<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
  event.preventDefault();

  $( "<div>" )
    .append( "default " + event.type + " prevented "+counter )
    .appendTo( "#log" );

    if(counter == 2)
    {
        $( "<div>" )
    .append( "now enable click" )
    .appendTo( "#log" );

    $(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
    }
    else
    {
        $( "<div>" )
    .append( "still disabled" )
    .appendTo( "#log" );
    }
    counter++;
});
});
</script>

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

This error is mainly due to processor architecture incompatibility with Framework installed ei x86 vs x64 The solution: Go to solution explorer>project properties>Compile tab>Advanced Compile Options There you have to change Target CPU from X64 to X86 Save new setting and recompile your solution. I tried it and it worked very fine. Hope this will help you out. Malek

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

In My Aws Windows I Solved it and steps are

  1. Open "C:\ProgramData\MySQL\MySQL Server 8.0"
  2. Open My.ini
  3. Find "[mysql]"
  4. After "no-beep=" Brake Line and insert "default-character-set=utf8"
  5. Find "[mysqld]"
  6. Insert "collation-server = utf8_unicode_ci"
  7. Insert "character-set-server = utf8"

example

...
# socket=MYSQL

port=3306

[mysql]
no-beep=
default-character-set=utf8
# default-character-set=

# SERVER SECTION
# ----------------------------------------------------------------------
# 
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.=
# 
# server_type=2
[mysqld]

collation-server = utf8_unicode_ci
character-set-server = utf8
# The next three options are mutually exclusive to SERVER_PORT below.
# skip-networking=
# enable-named-pipe=
# shared-memory=
...

mysql screenshot

Python how to exit main function

You can use sys.exit() to exit from the middle of the main function.

However, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__ - then you can use return as normal.

How to install SimpleJson Package for Python

If you have Python 2.6 installed then you already have simplejson - just import json; it's the same thing.

Why can't I use a list as a dict key in python?

dict keys need to be hashable. Lists are Mutable and they do not provide a valid hash method.

AngularJS - How to use $routeParams in generating the templateUrl?

Alright, think I got it...

Little background first: The reason I needed this was to stick Angular on top of Node Express and have Jade process my partials for me.

So here's whatchya gotta do... (drink beer and spend 20+ hours on it first!!!)...

When you set up your module, save the $routeProvider globally:

// app.js:
var routeProvider
    , app = angular.module('Isomorph', ['ngResource']).config(function($routeProvider){

        routeProvider = $routeProvider;
        $routeProvider
            .when('/', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/home', {templateUrl: '/', controller: 'AppCtrl'})
            .when('/login', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/SAMPLE', {templateUrl: '/SAMPLE', controller: 'SAMPLECtrl'})
            .when('/map', {templateUrl: '/map', controller: 'MapCtrl'})
            .when('/chat', {templateUrl: '/chat', controller: 'ChatCtrl'})
            .when('/blog', {templateUrl: '/blog', controller: 'BlogCtrl'})
            .when('/files', {templateUrl: '/files', controller: 'FilesCtrl'})
            .when('/tasks', {templateUrl: '/tasks', controller: 'TasksCtrl'})
            .when('/tasks/new', {templateUrl: '/tasks/new', controller: 'NewTaskCtrl'})
            .when('/tasks/:id', {templateUrl: '/tasks', controller: 'ViewTaskCtrl'})
            .when('/tasks/:id/edit', {templateUrl: '/tasks', controller: 'EditTaskCtrl'})
            .when('/tasks/:id/delete', {templateUrl: '/tasks', controller: 'DeleteTaskCtrl'})
        .otherwise({redirectTo: '/login'});

});

// ctrls.js
...
app.controller('EditTaskCtrl', function($scope, $routeParams, $location, $http){

    var idParam = $routeParams.id;
    routeProvider.when('/tasks/:id/edit/', {templateUrl: '/tasks/' + idParam + '/edit'});
    $location.path('/tasks/' + idParam + '/edit/');

});
...

That may be more info than what was needed...

  • Basically, you'll wanna store your Module's $routeProvider var globally, eg as routeProvider so that it can be accessed by your Controllers.

  • Then you can just use routeProvider and create a NEW route (you can't 'RESET a route' / 'REpromise'; you must create a new one), I just added a slash (/) at the end so that it is as semantic as the first.

  • Then (inside your Controller), set the templateUrl to the view you want to hit.

  • Take out the controller property of the .when() object, lest you get an infinite request loop.

  • And finally (still inside the Controller), use $location.path() to redirect to the route that was just created.

If you're interested in how to slap an Angular app onto an Express app, you can fork my repo here: https://github.com/cScarlson/isomorph.

And this method also allows for you to keep the AngularJS Bidirectional Data-Bindings in case you want to bind your HTML to your database using WebSockets: otherwise without this method, your Angular data-bindings will just output {{model.param}}.

If you clone this at this time, you'll need mongoDB on your machine to run it.

Hope this solves this issue!

Cody

Don't drink your bathwater.

Efficient way of having a function only execute once in a loop

If I understand the updated question correctly, something like this should work

def function1():
    print "function1 called"

def function2():
    print "function2 called"

def function3():
    print "function3 called"

called_functions = set()
while True:
    n = raw_input("choose a function: 1,2 or 3 ")
    func = {"1": function1,
            "2": function2,
            "3": function3}.get(n)

    if func in called_functions:
        print "That function has already been called"
    else:
        called_functions.add(func)
        func()

Java: JSON -> Protobuf & back conversion

I don't much like an idea of writing binary protobuf to database, because it can one day become not backward-compatible with newer versions and break the system that way.

Converting protobuf to JSON for storage and then back to protobuf on load is much more likely to create compatibility problems, because:

  • If the process which performs the conversion is not built with the latest version of the protobuf schema, then converting will silently drop any fields that the process doesn't know about. This is true both of the storing and loading ends.
  • Even with the most recent schema available, JSON <-> Protobuf conversion may be lossy in the presence of imprecise floating-point values and similar corner cases.
  • Protobufs actually have (slightly) stronger backwards-compatibility guarantees than JSON. Like with JSON, if you add a new field, old clients will ignore it. Unlike with JSON, Protobufs allow declaring a default value, which can make it somewhat easier for new clients to deal with old data that is otherwise missing the field. This is only a slight advantage, but otherwise Protobuf and JSON have equivalent backwards-compatibility properties, therefore you are not gaining any backwards-compatibility advantages from storing in JSON.

With all that said, there are many libraries out there for converting protobufs to JSON, usually built on the Protobuf reflection interface (not to be confused with the Java reflection interface; Protobuf reflection is offered by the com.google.protobuf.Message interface).

Div with horizontal scrolling only

overflow-x: scroll;
overflow-y: hidden;

EDIT:

It works for me:

<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
    <div style='width:400px;height:250px'></div>
</div>

Any implementation of Ordered Set in Java?

Every Set has an iterator(). A normal HashSet's iterator is quite random, a TreeSet does it by sort order, a LinkedHashSet iterator iterates by insert order.

You can't replace an element in a LinkedHashSet, however. You can remove one and add another, but the new element will not be in the place of the original. In a LinkedHashMap, you can replace a value for an existing key, and then the values will still be in the original order.

Also, you can't insert at a certain position.

Maybe you'd better use an ArrayList with an explicit check to avoid inserting duplicates.

What are good ways to prevent SQL injection?

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Can you 'exit' a loop in PHP?

As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.

For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.

$person = "Rasmus Lerdorf";
$found = false;

foreach($organization as $oKey=>$department)
{
   foreach($department as $dKey=>$group)
   {
      foreach($group as $gKey=>$employee)
      {
         if ($employee['fullname'] == $person)
         {
            $found = true;
            break 3;
         }
      } // group
   } // department
} // organization

How to send email to multiple recipients using python smtplib?

So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.

email.MIMEText sets up the "To:" header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)

SMTP.sendmail, on the other hand, sets up the "envelope" of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.

So, what you need to do is COMBINE the two replies you received. Set msg['To'] to a single string, but pass the raw list to sendmail:

emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails ) 
....
s.sendmail( msg['From'], emails, msg.as_string())

Best practice to return errors in ASP.NET Web API

Use the built in "InternalServerError" method (available in ApiController):

return InternalServerError();
//or...
return InternalServerError(new YourException("your message"));

How to pass object with NSNotificationCenter

Swift 5

func post() {
    NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"), 
        object: nil, 
        userInfo:["key0": "value", "key1": 1234])
}

func addObservers() {
    NotificationCenter.default.addObserver(self, 
        selector: #selector(someMethod), 
        name: Notification.Name("SomeNotificationName"), 
        object: nil)
}

@objc func someMethod(_ notification: Notification) {
    let info0 = notification.userInfo?["key0"]
    let info1 = notification.userInfo?["key1"]
}

Bonus (that you should definitely do!) :

Replace Notification.Name("SomeNotificationName") with .someNotificationName:

extension Notification.Name {
    static let someNotificationName = Notification.Name("SomeNotificationName")
}

Replace "key0" and "key1" with Notification.Key.key0 and Notification.Key.key1:

extension Notification {
  enum Key: String {
    case key0
    case key1
  }
}

Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:

npx mocha <args>

Note: the optional args are forwarded to the command being executed (mocha in this case)

this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).

Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.

You can read more on npx here


Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...

you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:

node node_modules/.bin/mocha

npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:

"scripts": {
  "test": "mocha"
}

and invoke it with

npm test

Android: where are downloaded files saved?

Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard (or some variation of that name) which is usually symlinked to to a directory in /storage like /storage/sdcard0 or /storage/0 sometimes the emulated storage is mounted to /sdcard and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Since the filesystems and sdcard support varies among devices.

see similar question for more info how to access downloads folder in android?

Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard

Unable to import path from django.urls

As error shows that path can not be imported.

enter image description here

So here we will use the url instead of path as shown below:-

first import the url package then replace the path with url

from django.conf.urls import url
urlpatterns = [
    url('admin/', admin.site.urls),
]

for more information you can take the reference of this link.

CSS get height of screen resolution

You can get the window height quite easily in pure CSS, using the units "vh", each corresponding to 1% of the window height. On the example below, let's begin to centralize block.foo by adding a margin-top half the size of the screen.

.foo{
    margin-top: 50vh;
}

But that only works for 'window' size. With a dab of javascript, you could make it more versatile.

$(':root').css("--windowHeight", $( window ).height() );

That code will create a CSS variable named "--windowHeight" that carries the height of the window. To use it, just add the rule:

.foo{
    margin-top: calc( var(--windowHeight) / 2 );
}

And why is it more versatile than simply using "vh" units? Because you can get the height of any element. Now if you want to centralize a block.foo in any container.bar, you could:

$(':root').css("--containerHeight", $( .bar ).height() );
$(':root').css("--blockHeight", $( .foo ).height() );

.foo{
    margin-top: calc( var(--containerHeight) / 2 - var(--blockHeight) / 2);
}

And finally, for it to respond to changes on the window size, you could use (in this example, the container is 50% the window height):

$( window ).resize(function() {
    $(':root').css("--containerHeight", $( .bar ).height()*0.5 );
});

What does "select count(1) from table_name" on any database tables mean?

Here is a link that will help answer your questions. In short:

count(*) is the correct way to write it and count(1) is OPTIMIZED TO BE count(*) internally -- since

a) count the rows where 1 is not null is less efficient than
b) count the rows

How do I authenticate a WebClient request?

Public Function getWeb(ByRef sURL As String) As String
    Dim myWebClient As New System.Net.WebClient()

    Try
        Dim myCredentialCache As New System.Net.CredentialCache()
        Dim myURI As New Uri(sURL)
        myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
        myWebClient.Encoding = System.Text.Encoding.UTF8
        myWebClient.Credentials = myCredentialCache
        Return myWebClient.DownloadString(myURI)
    Catch ex As Exception
        Return "Exception " & ex.ToString()
    End Try
End Function

What Does This Mean in PHP -> or =>

->

calls/sets object variables. Ex:

$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);

=> Sets key/value pairs for arrays. Ex:

$array = array(
    'foo' => 'bar'
);
var_dump($array);

Ant build failed: "Target "build..xml" does not exist"

Is this a problem Only when you run ant -d or ant -verbose, but works other times?

I noticed this error message line:

Could not load definitions from resource org/apache/tools/ant/antlib.xml. It could not be found.

The org/apache/tools/ant/antlib.xml file is embedded in the ant.jar. The ant command is really a shell script called ant or a batch script called ant.bat. If the environment variable ANT_HOME is not set, it will figure out where it's located by looking to see where the ant command itself is located.

Sometimes I've seen this where someone will move the ant shell/batch script to put it in their path, and have ANT_HOME either not set, or set incorrectly.

What platform are you on? Is this Windows or Unix/Linux/MacOS? If you're on Windows, check to see if %ANT_HOME% is set. If it is, make sure it's the right directory. Make sure you have set your PATH to include %ANT_HOME%/bin.

If you're on Unix, don't copy the ant shell script to an executable directory. Instead, make a symbolic link. I have a directory called /usr/local/bin where I put the command I want to override the commands in /bin and /usr/bin. My Ant is installed in /opt/ant-1.9.2, and I have a symbolic link from /opt/ant-1.9.2 to /opt/ant. Then, I have symbolic links from all commands in /opt/ant/bin to /usr/local/bin. The Ant shell script can detect the symbolic links and find the correct Ant HOME location.

Next, go to your Ant installation directory and look under the lib directory to make sure ant.jar is there, and that it contains org/apache/tools/ant/antlib.xml. You can use the jar tvf ant.jar command. The only thing I can emphasize is that you do have everything setup correctly. You have your Ant shell script in your PATH either because you included the bin directory of your Ant's HOME directory in your classpath, or (if you're on Unix/Linux/MacOS), you have that file symbolically linked to a directory in your PATH.

Make sure your JAVA_HOME is set correctly (on Unix, you can use the symbolic link trick to have the java command set it for you), and that you're using Java 1.5 or higher. Java 1.4 will no longer work with newer versions of Ant.

Also run ant -version and see what you get. You might get the same error as before which leads me to think you have something wrong.

Let me know what you find, and your OS, and I can give you directions on reinstalling Ant.

How to install plugin for Eclipse from .zip

My .zip file was formatted correctly (I think) but it wasn't working. Even unchecking "Group items by category" didn't work

To install it I did so:

  • unzip the .zip archive
  • Help -> Install New Software...
  • Add... -> Archive...
  • I selected the "content.jar" file

At this point Eclipse read the plugin correctly, I went ahead, accepted the conditions and then asked me to restart the IDE.

How to make several plots on a single page using matplotlib?

The answer from las3rjock, which somehow is the answer accepted by the OP, is incorrect--the code doesn't run, nor is it valid matplotlib syntax; that answer provides no runnable code and lacks any information or suggestion that the OP might find useful in writing their own code to solve the problem in the OP.

Given that it's the accepted answer and has already received several up-votes, I suppose a little deconstruction is in order.

First, calling subplot does not give you multiple plots; subplot is called to create a single plot, as well as to create multiple plots. In addition, "changing plt.figure(i)" is not correct.

plt.figure() (in which plt or PLT is usually matplotlib's pyplot library imported and rebound as a global variable, plt or sometimes PLT, like so:

from matplotlib import pyplot as PLT

fig = PLT.figure()

the line just above creates a matplotlib figure instance; this object's add_subplot method is then called for every plotting window (informally think of an x & y axis comprising a single subplot). You create (whether just one or for several on a page), like so

fig.add_subplot(111)

this syntax is equivalent to

fig.add_subplot(1,1,1)

choose the one that makes sense to you.

Below I've listed the code to plot two plots on a page, one above the other. The formatting is done via the argument passed to add_subplot. Notice the argument is (211) for the first plot and (212) for the second.

from matplotlib import pyplot as PLT

fig = PLT.figure()

ax1 = fig.add_subplot(211)
ax1.plot([(1, 2), (3, 4)], [(4, 3), (2, 3)])

ax2 = fig.add_subplot(212)
ax2.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)])

PLT.show()

Each of these two arguments is a complete specification for correctly placing the respective plot windows on the page.

211 (which again, could also be written in 3-tuple form as (2,1,1) means two rows and one column of plot windows; the third digit specifies the ordering of that particular subplot window relative to the other subplot windows--in this case, this is the first plot (which places it on row 1) hence plot number 1, row 1 col 1.

The argument passed to the second call to add_subplot, differs from the first only by the trailing digit (a 2 instead of a 1, because this plot is the second plot (row 2, col 1).

An example with more plots: if instead you wanted four plots on a page, in a 2x2 matrix configuration, you would call the add_subplot method four times, passing in these four arguments (221), (222), (223), and (224), to create four plots on a page at 10, 2, 8, and 4 o'clock, respectively and in this order.

Notice that each of the four arguments contains two leadings 2's--that encodes the 2 x 2 configuration, ie, two rows and two columns.

The third (right-most) digit in each of the four arguments encodes the ordering of that particular plot window in the 2 x 2 matrix--ie, row 1 col 1 (1), row 1 col 2 (2), row 2 col 1 (3), row 2 col 2 (4).

What is the equivalent to getch() & getche() in Linux?

You can use the curses.h library in linux as mentioned in the other answer.

You can install it in Ubuntu by:

sudo apt-get update

sudo apt-get install ncurses-dev

I took the installation part from here.

Detect if HTML5 Video element is playing

My answer at How to tell if a <video> element is currently playing?:

MediaElement does not have a property that tells about if its playing or not. But you could define a custom property for it.

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function(){
        return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
    }
})

Now you can use it on video or audio elements like this:

if(document.querySelector('video').playing){
    // Do anything you want to
}

Retrieve the commit log for a specific line in a file?

This will call git blame for every meaningful revision to show line $LINE of file $FILE:

git log --format=format:%H $FILE | xargs -L 1 git blame $FILE -L $LINE,$LINE

As usual, the blame shows the revision number in the beginning of each line. You can append

| sort | uniq -c

to get aggregated results, something like a list of commits that changed this line. (Not quite, if code only has been moved around, this might show the same commit ID twice for different contents of the line. For a more detailed analysis you'd have to do a lagged comparison of the git blame results for adjacent commits. Anyone?)

OS detecting makefile

That's the job that GNU's automake/autoconf are designed to solve. You might want to investigate them.

Alternatively you can set environment variables on your different platforms and make you Makefile conditional against them.

How to return a complex JSON response with Node.js?

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

HTML 5 Video "autoplay" not automatically starting in CHROME

You need to add playsinline autoplay muted loop, chrome do not allow a video to autostart if it is not muted, also right now I dont know why it is not working in all android devices, im trying to look if it's a version specific, If I found something I'll let you know

Chrome issue: After some research i have found that it doesnt work on chrome sometimes because in responsive you can activate the data saver, and it blocks any video to autostart

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

Delete package-lock.json it works for me

then npm install

How to setup Tomcat server in Netbeans?

If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.

How can I check a C# variable is an empty string "" or null?

Since .NET 2.0 you can use:

// Indicates whether the specified string is null or an Empty string.
string.IsNullOrEmpty(string value);

Additionally, since .NET 4.0 there's a new method that goes a bit farther:

// Indicates whether a specified string is null, empty, or consists only of white-space characters.
string.IsNullOrWhiteSpace(string value);

Embed Google Map code in HTML with marker

The element that you posted looks like it's just copy-pasted from the Google Maps embed feature.

If you'd like to drop markers for the locations that you have, you'll need to write some JavaScript to do so. I'm learning how to do this as well.

Check out the following: https://developers.google.com/maps/documentation/javascript/overlays

It has several examples and code samples that can be easily re-used and adapted to fit your current problem.

How do I specify local .gem files in my Gemfile?

This isn't strictly an answer to your question about installing .gem packages, but you can specify all kinds of locations on a gem-by-gem basis by editing your Gemfile.

Specifying a :path attribute will install the gem from that path on your local machine.

gem "foreman", path: "/Users/pje/my_foreman_fork"

Alternately, specifying a :git attribute will install the gem from a remote git repository.

gem "foreman", git: "git://github.com/pje/foreman.git"

# ...or at a specific SHA-1 ref
gem "foreman", git: "git://github.com/pje/foreman.git", ref: "bf648a070c"

# ...or branch
gem "foreman", git: "git://github.com/pje/foreman.git", branch: "jruby"

# ...or tag
gem "foreman", git: "git://github.com/pje/foreman.git", tag: "v0.45.0"

(As @JHurrah mentioned in his comment.)

count number of lines in terminal output

Putting the comment of EaterOfCode here as an answer.

grep itself also has the -c flag which just returns the count

So the command and output could look like this.

$ grep -Rl "curl" ./ -c
24

EDIT:

Although this answer might be shorter and thus might seem better than the accepted answer (that is using wc). I do not agree with this anymore. I feel like remembering that you can count lines by piping to wc -l is much more useful as you can use it with other programs than grep as well.

How to show an alert box in PHP?

change your output from

 echo '<script language="javascript>';

to

 echo '<script type="text/javascript">';

you forgot double quotes... and use the type tag

How to compile without warnings being treated as errors?

-Wall and -Werror compiler options can cause it, please check if those are used in compiler settings.

'\r': command not found - .bashrc / .bash_profile

In EditPlus you do this from the Document ? File Format (CR/LF) ? Change File Format... menu and then choose the Unix / Mac OS X radio button.

'setInterval' vs 'setTimeout'

setInterval repeats the call, setTimeout only runs it once.

Send a SMS via intent

Create the intent like this:

Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address","your desired phoneNumber");         
smsIntent.putExtra("sms_body","your desired message");
smsIntent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(smsIntent);

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

Using "setInterval" & "clearInterval" fixes the problem:

function drawMarkers(map, markers) {
    var _this = this,
        geocoder = new google.maps.Geocoder(),
        geocode_filetrs;

    _this.key = 0;

    _this.interval = setInterval(function() {
        _this.markerData = markers[_this.key];

        geocoder.geocode({ address: _this.markerData.address }, yourCallback(_this.markerData));

        _this.key++;

        if ( ! markers[_this.key]) {
            clearInterval(_this.interval);
        }

    }, 300);
}

Switch in Laravel 5 - Blade

IN LARAVEL 5.2 AND UP:

Write your usual code between the opening and closing PHP statements.

@php
switch (x) {
    case 1:
        //code to be executed
        break;
    default:
        //code to be executed
}
@endphp

How to open a web server port on EC2 instance

Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".

Go to the "Network & Security" -> Security Group settings in the left hand navigation

enter image description here Find the Security Group that your instance is apart of Click on Inbound Rules enter image description here Use the drop down and add HTTP (port 80) enter image description here Click Apply and enjoy

jQuery - how to check if an element exists?

I use this:

if ($('.div1').size() || $('.div2').size()) {
    console.log('ok');
}

AttributeError: 'list' object has no attribute 'encode'

You need to do encode on tmp[0], not on tmp.

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

How to get am pm from the date time string using moment js

You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week, DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

_x000D_
_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

How to set a Javascript object values dynamically?

myObj[prop] = value;

That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.

PHP XML Extension: Not installed

You're close

sudo apt-get install php-xml

Then you need to restart apache so it takes effect

sudo service apache2 restart

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

enter image description here

First of all you have to find an image of the back button. I used a nice app called Extractor that extracts all the graphics from iPhone. In iOS7 I managed to retrieve the image called UINavigationBarBackIndicatorDefault and it was in black colour, since I needed a red tint I change the colour to red using Gimp.

EDIT:

As was mentioned by btate in his comment, there is no need to change the color with the image editor. The following code should do the trick:

imageView.tint = [UIColor redColor];
imageView.image = [[UIImage imageNamed:@"UINavigationBarBackIndicatorDefault"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

Then I created a view that contains an imageView with that arrow, a label with the custom text and on top of the view I have a button with an action. Then I added a simple animation (fading and translation).

The following code simulates the behaviour of the back button including animation.

-(void)viewWillAppear:(BOOL)animated{
        UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UINavigationBarBackIndicatorDefault"]];
        [imageView setTintColor:[UIColor redColor]];
        UILabel *label=[[UILabel alloc] init];
        [label setTextColor:[UIColor redColor]];
        [label setText:@"Blog"];
        [label sizeToFit];

        int space=6;
        label.frame=CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+space, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, label.frame.size.width+imageView.frame.size.width+space, imageView.frame.size.height)];

        view.bounds=CGRectMake(view.bounds.origin.x+8, view.bounds.origin.y-1, view.bounds.size.width, view.bounds.size.height);
        [view addSubview:imageView];
        [view addSubview:label];

        UIButton *button=[[UIButton alloc] initWithFrame:view.frame];
        [button addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];

        [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            label.alpha = 0.0;
            CGRect orig=label.frame;
            label.frame=CGRectMake(label.frame.origin.x+25, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
            label.alpha = 1.0;
            label.frame=orig;
        } completion:nil];

        UIBarButtonItem *backButton =[[UIBarButtonItem alloc] initWithCustomView:view];
}

- (void) handleBack:(id)sender{
}

EDIT:

Instead of adding the button, in my opinion the better approach is to use a gesture recognizer.

UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleBack:)];
[view addGestureRecognizer:tap];
[view setUserInteractionEnabled:YES];

Chrome Dev Tools - Modify javascript and reload

This is a bit of a work around, but one way you can achieve this is by adding a breakpoint at the start of the javascript file or block you want to manipulate.

Then when you reload, the debugger will pause on that breakpoint, and you can make any changes you want to the source, save the file and then run the debugger through the modified code.

But as everyone has said, next reload the changes will be gone - at least it let's you run some slightly modified JS client side.

How do I read configuration settings from Symfony2 config.yml?

I learnt a easy way from code example of http://tutorial.symblog.co.uk/

1) notice the ZendeskBlueFormBundle and file location

# myproject/app/config/config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: @ZendeskBlueFormBundle/Resources/config/config.yml }

framework:

2) notice Zendesk_BlueForm.emails.contact_email and file location

# myproject/src/Zendesk/BlueFormBundle/Resources/config/config.yml

parameters:
    # Zendesk contact email address
    Zendesk_BlueForm.emails.contact_email: [email protected]

3) notice how i get it in $client and file location of controller

# myproject/src/Zendesk/BlueFormBundle/Controller/PageController.php

    public function blueFormAction($name, $arg1, $arg2, $arg3, Request $request)
    {
    $client = new ZendeskAPI($this->container->getParameter("Zendesk_BlueForm.emails.contact_email"));
    ...
    }

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

How to place two forms on the same page?

Hope this will help you. Assumed that login form has: username and password inputs.

if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}

What is the difference between i++ and ++i?

The typical answer to this question, unfortunately posted here already, is that one does the increment "before" remaining operations and the other does the increment "after" remaining operations. Though that intuitively gets the idea across, that statement is on the face of it completely wrong. The sequence of events in time is extremely well-defined in C#, and it is emphatically not the case that the prefix (++var) and postfix (var++) versions of ++ do things in a different order with respect to other operations.

It is unsurprising that you'll see a lot of wrong answers to this question. A great many "teach yourself C#" books also get it wrong. Also, the way C# does it is different than how C does it. Many people reason as though C# and C are the same language; they are not. The design of the increment and decrement operators in C# in my opinion avoids the design flaws of these operators in C.

There are two questions that must be answered to determine what exactly the operation of prefix and postfix ++ are in C#. The first question is what is the result? and the second question is when does the side effect of the increment take place?

It is not obvious what the answer to either question is, but it is actually quite simple once you see it. Let me spell out for you precisely what x++ and ++x do for a variable x.

For the prefix form (++x):

  1. x is evaluated to produce the variable
  2. The value of the variable is copied to a temporary location
  3. The temporary value is incremented to produce a new value (not overwriting the temporary!)
  4. The new value is stored in the variable
  5. The result of the operation is the new value (i.e. the incremented value of the temporary)

For the postfix form (x++):

  1. x is evaluated to produce the variable
  2. The value of the variable is copied to a temporary location
  3. The temporary value is incremented to produce a new value (not overwriting the temporary!)
  4. The new value is stored in the variable
  5. The result of the operation is the value of the temporary

Some things to notice:

First, the order of events in time is exactly the same in both cases. Again, it is absolutely not the case that the order of events in time changes between prefix and postfix. It is entirely false to say that the evaluation happens before other evaluations or after other evaluations. The evaluations happen in exactly the same order in both cases as you can see by steps 1 through 4 being identical. The only difference is the last step - whether the result is the value of the temporary, or the new, incremented value.

You can easily demonstrate this with a simple C# console app:

public class Application
{
    public static int currentValue = 0;

    public static void Main()
    {
        Console.WriteLine("Test 1: ++x");
        (++currentValue).TestMethod();

        Console.WriteLine("\nTest 2: x++");
        (currentValue++).TestMethod();

        Console.WriteLine("\nTest 3: ++x");
        (++currentValue).TestMethod();

        Console.ReadKey();
    }
}

public static class ExtensionMethods 
{
    public static void TestMethod(this int passedInValue) 
    {
        Console.WriteLine("Current:{0} Passed-in:{1}",
            Application.currentValue,
            passedInValue);
    }
}

Here are the results...

Test 1: ++x
Current:1 Passed-in:1

Test 2: x++
Current:2 Passed-in:1

Test 3: ++x
Current:3 Passed-in:3

In the first test, you can see that both currentValue and what was passed in to the TestMethod() extension show the same value, as expected.

However, in the second case, people will try to tell you that the increment of currentValue happens after the call to TestMethod(), but as you can see from the results, it happens before the call as indicated by the 'Current:2' result.

In this case, first the value of currentValue is stored in a temporary. Next, an incremented version of that value is stored back in currentValue but without touching the temporary which still stores the original value. Finally that temporary is passed to TestMethod(). If the increment happened after the call to TestMethod() then it would write out the same, non-incremented value twice, but it does not.

It's important to note that the value returned from both the currentValue++ and ++currentValue operations are based on the temporary and not the actual value stored in the variable at the time either operation exits.

Recall in the order of operations above, the first two steps copy the then-current value of the variable into the temporary. That is what's used to calculate the return value; in the case of the prefix version, it's that temporary value incremented while in the case of the suffix version, it's that value directly/non-incremented. The variable itself is not read again after the initial storage into the temporary.

Put more simply, the postfix version returns the value that was read from the variable (i.e. the value of the temporary) while the prefix version returns the value that was written back to the variable (i.e. the incremented value of the temporary). Neither return the variable's value.

This is important to understand because the variable itself could be volatile and have changed on another thread which means the return value of those operations could differ from the current value stored in the variable.

It is surprisingly common for people to get very confused about precedence, associativity, and the order in which side effects are executed, I suspect mostly because it is so confusing in C. C# has been carefully designed to be less confusing in all these regards. For some additional analysis of these issues, including me further demonstrating the falsity of the idea that prefix and postfix operations "move stuff around in time" see:

https://ericlippert.com/2009/08/10/precedence-vs-order-redux/

which led to this SO question:

int[] arr={0}; int value = arr[arr[0]++]; Value = 1?

You might also be interested in my previous articles on the subject:

https://ericlippert.com/2008/05/23/precedence-vs-associativity-vs-order/

and

https://ericlippert.com/2007/08/14/c-and-the-pit-of-despair/

and an interesting case where C makes it hard to reason about correctness:

https://docs.microsoft.com/archive/blogs/ericlippert/bad-recursion-revisited

Also, we run into similar subtle issues when considering other operations that have side effects, such as chained simple assignments:

https://docs.microsoft.com/archive/blogs/ericlippert/chaining-simple-assignments-is-not-so-simple

And here's an interesting post on why the increment operators result in values in C# rather than in variables:

Why can't I do ++i++ in C-like languages?

How to keep :active css style after clicking an element

You can use a little bit of Javascript to add and remove CSS classes of your navitems. For starters, create a CSS class that you're going to apply to the active element, name it ie: ".activeItem". Then, put a javascript function to each of your navigation buttons' onclick event which is going to add "activeItem" class to the one activated, and remove from the others...

It should look something like this: (untested!)

/*In your stylesheet*/
.activeItem{
   background-color:#999; /*make some difference for the active item here */
}


/*In your javascript*/
var prevItem = null;
function activateItem(t){
   if(prevItem != null){
      prevItem.className = prevItem.className.replace(/{\b}?activeItem/, "");
   }
   t.className += " activeItem";
   prevItem = t;
}

<!-- And then your markup -->
<div id='nav'>
<a href='#abouts' onClick="activateItem(this)">
<div class='navitem about'>
about
</div>
</a>
<a href='#workss' onClick="activateItem(this)">
<div class='navitem works'>
works
</div>
</a>
</div>

how to get current datetime in SQL?

I want my datetime, and I want it now()!

For MySQL, anyway.

PDO error message?

Try this instead:

print_r($sth->errorInfo());

Add this before your prepare:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.

In git, what is the difference between merge --squash and rebase?

Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branchenter image description here

Merge Squash: retains the changes but omits the individual commits from history enter image description here

Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master

enter image description here

More on here

Output PowerShell variables to a text file

$computer,$Speed,$Regcheck will create an array, and run out-file ones per variable = they get seperate lines. If you construct a single string using the variables first, it will show up a single line. Like this:

"$computer,$Speed,$Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200

Python: Remove division decimal

There is a math function modf() that will break this up as well.

import math

print("math.modf(3.14159) : ", math.modf(3.14159))

will output a tuple: math.modf(3.14159) : (0.14159, 3.0)

This is useful if you want to keep both the whole part and decimal for reference like:

decimal, whole = math.modf(3.14159)

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

Using a CASE statement for each of the convert / cast functions always works for me:

Please replace tableXXXXY with your table name, and issueDate_dat with the name of your datetime field in that table:

SELECT  issueDate_dat, CONVERT(varchar, DATEPART(yyyy, issuedate_dat))  AS issueDateYYYY
, CASE WHEN (len(CONVERT(varchar, DATEPART(mm, issuedate_dat))) < 2) THEN '0' +CONVERT(varchar, DATEPART(mm, issuedate_dat)) ELSE CONVERT(varchar, DATEPART(mm, issuedate_dat)) END AS  issueDateMM
, CASE WHEN (len(CONVERT(varchar, DATEPART(dd, issuedate_dat))) <2) THEN '0' +CONVERT(varchar, DATEPART(dd, issuedate_dat)) ELSE CONVERT(varchar, DATEPART(dd, issuedate_dat)) END AS issueDateDD
FROM            tableXXXXY

Hope this was helpful. chagbert.

Binary numbers in Python

You can convert between a string representation of the binary using bin() and int()

>>> bin(88)
'0b1011000'
>>> int('0b1011000', 2)
88
>>> 

>>> a=int('01100000', 2)
>>> b=int('00100110', 2)
>>> bin(a & b)
'0b100000'
>>> bin(a | b)
'0b1100110'
>>> bin(a ^ b)
'0b1000110'

How do I use the built in password reset/change views with my own templates

If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.

The b-list has a good introduction to context processors.

Edit (I seem to have been confused about what the actual question was):

You'll notice that password_reset takes a named parameter called template_name:

def password_reset(request, is_admin_site=False, 
            template_name='registration/password_reset_form.html',
            email_template_name='registration/password_reset_email.html',
            password_reset_form=PasswordResetForm, 
            token_generator=default_token_generator,
            post_reset_redirect=None):

Check password_reset for more information.

... thus, with a urls.py like:

from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset

urlpatterns = patterns('',
     (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
     ...
)

django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.

In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.

Split column at delimiter in data frame

Hadley has a very elegant solution to do this inside data frames in his reshape package, using the function colsplit.

require(reshape)
> df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
> df
  ID FOO
1 11 a|b
2 12 b|c
3 13 x|y
> df = transform(df, FOO = colsplit(FOO, split = "\\|", names = c('a', 'b')))
> df
  ID FOO.a FOO.b
1 11     a     b
2 12     b     c
3 13     x     y

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

I just ran into this and I was running under Release build configuration instead of Debug build configuration. Once I switched back to Debug my variable showed in the watch again.

How to stop C# console applications from closing automatically?

Console.ReadLine();

or

Console.ReadKey();

ReadLine() waits for ?, ReadKey() waits for any key (except for modifier keys).

Edit: stole the key symbol from Darin.

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

// range()              0..10, step=1
// range(max)           0..max, step=1
// range(min,max)       min..max, step=1
// range(min,step,max)  min..max, step=step
// Use:
// console.log(...range(3));
// Array.from(range(5))
// [...range(100)]
// for (const v of range(1,10)) { ... 

function* range(...args) {
    let [min, step, max] = {
        0: [0, 1, 10],
        1: [0, args[0] >= 0 ? 1 : -1, args[0]],
        2: [args[0], args[1] >= args[0] ? 1 : -1, args[1]],
        3: args,
    }[args.length] || [];
    if (min === undefined) throw new SyntaxError("Too many arguments");
    let x = min;
    while (step >= 0 ? x < max : x > max) {
        yield x;
        x += step
    }
}
console.log(...range());      // 0 1 2 3 4 5 6 7 8 9
console.log(...range(3));     // 0 1 2
console.log(...range(2, 5));  // 2 3 4
console.log(...range(5, 2));  // 5 4 3
console.log(...range(3, -3)); // 3 2 1 0 -1 -2
console.log(...range(-3, 3)); // -3 -2 -1 0 1 2
console.log(...range(-5, -2));// -5 -4 -3
console.log(...range(-2, -5));// -2 -3 -4

Convert JS object to JSON string

Use this,

var j={"name":"binchen"};
 var myJSON = JSON.stringify(j);

Define an <img>'s src attribute in CSS

just this as img tag is a content element

img {
    content:url(http://example.com/image.png);
}

GoogleTest: How to skip a test?

If more than one test are needed be skipped

--gtest_filter=-TestName.*:TestName.*TestCase

Styling JQuery UI Autocomplete

Based on @md-nazrul-islam reply, This is what I did with SCSS:

ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}

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

EDIT: Consider looking at and upvoting Malvineous's answer on this page. Netmasks are a much more elegant solution.


Simply use a percent sign as a wildcard in the IP address.

From http://dev.mysql.com/doc/refman/5.1/en/grant.html

You can specify wildcards in the host name. For example, user_name@'%.example.com' applies to user_name for any host in the example.com domain, and user_name@'192.168.1.%' applies to user_name for any host in the 192.168.1 class C subnet.

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

How to check Django version

If you have pip, you can also do a

pip freeze
and it will show your all component version including Django .

You can pipe it through grep to get just the Django version. That is,

josh@villaroyale:~/code/djangosite$ pip freeze | grep Django
Django==1.4.3

Count number of rows per group and add result to original data frame

One simple line in base R:

df$count = table(interaction(df[, (c("name", "type"))]))[interaction(df[, (c("name", "type"))])]

Same in two lines, for clarity/efficiency:

fact = interaction(df[, (c("name", "type"))])
df$count = table(fact)[fact]

Best way to check if column returns a null value (from database to .net application)

Use DBNull.Value.Equals on the object without converting it to a string.

Here's an example:

   if (! DBNull.Value.Equals(row[fieldName])) 
   {
      //not null
   }
   else
   {
      //null
   }

php refresh current page?

Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

ProgressDialog is deprecated.What is the alternate one to use?

In the progress dialog, user cannot do any kind of work. All the background processes are stopped during progress dialog. So, It is advisable to user progress-bar instead of progress dialog.

Replace all double quotes within String

Here's how

String details = "Hello \"world\"!";
details = details.replace("\"","\\\"");
System.out.println(details);               // Hello \"world\"!

Note that strings are immutable, thus it is not sufficient to simply do details.replace("\"","\\\""). You must reassign the variable details to the resulting string.


Using

details = details.replaceAll("\"","&quote;");

instead, results in

Hello &quote;world&quote;!

How to convert column with string type to int form in pyspark data frame?

from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))

You can run loop for each column but this is the simplest way to convert string column into integer.

How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:

DECIMAL[(M[,D])]

Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

Angular pass callback function to child component as @Input similar to AngularJS way

UPDATE

This answer was submitted when Angular 2 was still in alpha and many of the features were unavailable / undocumented. While the below will still work, this method is now entirely outdated. I strongly recommend the accepted answer over the below.

Original Answer

Yes in fact it is, however you will want to make sure that it is scoped correctly. For this I've used a property to ensure that this means what I want it to.

@Component({
  ...
  template: '<child [myCallback]="theBoundCallback"></child>',
  directives: [ChildComponent]
})
export class ParentComponent{
  public theBoundCallback: Function;

  public ngOnInit(){
    this.theBoundCallback = this.theCallback.bind(this);
  }

  public theCallback(){
    ...
  }
}

@Component({...})
export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  @Input()
  public myCallback: Function; 
  ...
}

Data access object (DAO) in Java

Don't get confused with too many explanations. DAO: From the name itself it means Accessing Data using Object. DAO is separated from other Business Logic.

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

No Spring WebApplicationInitializer types detected on classpath

tomcat-maven-plugin in test

Tomcat usually does not add classes in src/test/java to the classpath. They are missing if you run tomcat in scope test. To order tomcat to respect classes in test, use -Dmaven.tomcat.useTestClasspath=true or add

<properties>
   <maven.tomcat.useTestClasspath>true</maven.tomcat.useTestClasspath>
</properties>

To your pom.xml.

How to remove duplicate values from a multi-dimensional array in PHP

I've given this problem a lot of thought and have determined that the optimal solution should follow two rules.

  1. For scalability, modify the array in place; no copying to a new array
  2. For performance, each comparison should be made only once

With that in mind and given all of PHP's quirks, below is the solution I came up with. Unlike some of the other answers, it has the ability to remove elements based on whatever key(s) you want. The input array is expected to be numeric keys.

$count_array = count($input);
for ($i = 0; $i < $count_array; $i++) {
    if (isset($input[$i])) {
        for ($j = $i+1; $j < $count_array; $j++) {
            if (isset($input[$j])) {
                //this is where you do your comparison for dupes
                if ($input[$i]['checksum'] == $input[$j]['checksum']) {
                    unset($input[$j]);
                }
            }
        }
    }
}

The only drawback is that the keys are not in order when the iteration completes. This isn't a problem if you're subsequently using only foreach loops, but if you need to use a for loop, you can put $input = array_values($input); after the above to renumber the keys.

Changing background color of selected item in recyclerview

I got it like this

public void onClick(View v){
        v.findViewById(R.id.textView).setBackgroundColor(R.drawable.selector_row);
 }

Thanks

How to use JUnit to test asynchronous processes

How about calling SomeObject.wait and notifyAll as described here OR using Robotiums Solo.waitForCondition(...) method OR use a class i wrote to do this (see comments and test class for how to use)

Error checking for NULL in VBScript

I see lots of confusion in the comments. Null, IsNull() and vbNull are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.

To test if a variable is uninitialized, use IsEmpty(). To test if a variable is uninitialized or contains "", test on "" or Empty. To test if a variable is an object, use IsObject and to see if this object has no reference test on Is Nothing.

In your case, you first want to test if the variable is an object, and then see if that variable is Nothing, because if it isn't an object, you get the "Object Required" error when you test on Nothing.

snippet to mix and match in your code:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

How to set up Automapper in ASP.NET Core

Asp.Net Core 2.2 with AutoMapper.Extensions.Microsoft.DependencyInjection.

public class MappingProfile : Profile
{
  public MappingProfile()
  {
      CreateMap<Domain, DomainDto>();
  }
}

In Startup.cs

services.AddAutoMapper(typeof(List.Handler));

Get error message if ModelState.IsValid fails?

Ok Check and Add to Watch:

  1. Do a breakpoint at your ModelState line in your Code
  2. Add your model state to your Watch
  3. Expand ModelState "Values"
  4. Expand Values "Results View"

Now you can see a list of all SubKey with its validation state at end of value.

So search for the Invalid value.

Postman addon's like in firefox

The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).

Now I'm settled with Fiddler (Inspectors > WebView)

Does Python have a package/module management system?

It's called setuptools. You run it with the "easy_install" command.

You can find the directory at http://pypi.python.org/

Java generics: multiple generic parameters?

You can follow one of the below approaches:

1) Basic, single type :

//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

2) Multiple Types :

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.

//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Correct : Compiles fine

public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Sample Class Code :

package generics.basics;

import java.util.ArrayList;
import java.util.List;

public class GenericMethods {

/*
 Declare the generic type parameter T in this method. 

 After the qualifiers public and static, you put <T> and 
 then followed it by return type, method name, and its parameters.

 Observe : type of val is 'T' and not '<T>'

 * */
//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

/*// Q: To audience -> will this compile ? 
 * 
 * public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return 0;

}*/

 public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return null;

}

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    System.out.println(list.toString());
    fill(list, 100);
    System.out.println(list.toString());

    List<String> Strlist = new ArrayList<>();
    Strlist.add("Chirag");
    Strlist.add("Nayak");
    System.out.println(Strlist.toString());
    fill(Strlist, "GOOD BOY");
    System.out.println(Strlist.toString());


    System.out.println(multipleTypeArgument("Chirag", 100));
    System.out.println(multipleTypeArgument(100,"Nayak"));

}

}

// class definition ends

Sample Output:

[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak

How to start IIS Express Manually

From the links the others have posted, I'm not seeing an option. -- I just use powershell to kill it -- you can save this to a Stop-IisExpress.ps1 file:

get-process | where { $_.ProcessName -like "IISExpress" } | stop-process

There's no harm in it -- Visual Studio will just pop a new one up when it wants one.

Formatting struct timespec

You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.

jquery mobile background image

Just add !important tag to all css elements in Paolo's answer! Works fine for me JQM+phonegap

EXAMPLE:

body {
    background: url(../images/background.jpg) !important;

Test or check if sheet exists

I know it is an old post, but here is another simple solution that is fast.

Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean

On Error Resume Next
worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
Err.Clear: On Error GoTo 0

End Function

How can I truncate a string to the first 20 words in PHP?

To limit words, am using the following little code :

    $string = "hello world ! I love chocolate.";
    $explode = array_slice(explode(' ', $string), 0, 4);
    $implode = implode(" ",$explode);   
    echo $implode;

$implot will give : hello world ! I

Detect Safari browser

Note: always try to detect the specific behavior you're trying to fix, instead of targeting it with isSafari?

As a last resort, detect Safari with this regex:

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

It uses negative look-arounds and it excludes Chrome, Edge, and all Android browsers that include the Safari name in their user agent.

Changing font size and direction of axes text in ggplot2

Another way to deal with overlapping labels is using guide = guide_axis(n.dodge = 2).

library(dplyr)
library(tibble)
library(ggplot2)

dt <- mtcars %>% rownames_to_column("name") %>% 
  dplyr::filter(cyl == 4)

# Overlapping labels
ggplot(dt, aes(x = name, y = mpg)) + geom_point()

enter image description here

ggplot(dt, aes(x = name, y = mpg)) + geom_point() +
  scale_x_discrete(guide = guide_axis(n.dodge = 2))

enter image description here

Is module __file__ attribute absolute or relative?

Late simple example:

from os import path, getcwd, chdir

def print_my_path():
    print('cwd:     {}'.format(getcwd()))
    print('__file__:{}'.format(__file__))
    print('abspath: {}'.format(path.abspath(__file__)))

print_my_path()

chdir('..')

print_my_path()

Under Python-2.*, the second call incorrectly determines the path.abspath(__file__) based on the current directory:

cwd:     C:\codes\py
__file__:cwd_mayhem.py
abspath: C:\codes\py\cwd_mayhem.py
cwd:     C:\codes
__file__:cwd_mayhem.py
abspath: C:\codes\cwd_mayhem.py

As noted by @techtonik, in Python 3.4+, this will work fine since __file__ returns an absolute path.

How to import JSON File into a TypeScript file?

I couldn't import a different file.json too. But I resolved it like this

const swaggerDoc = require('../swagger.json')

"SMTP Error: Could not authenticate" in PHPMailer

There is no issue with your code.

Follow below two simple steps to send emails from phpmailer.

  • You have to disable 2-step verification setting for google account if you have enabled.

  • Turn ON allow access to less secure app.

how to automatically scroll down a html page?

You can use two different techniques to achieve this.

The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;).

The second is setting the link to point to a specific id in the page e.g.

<a href="mypage.html#sectionOne">section one</a>

Then if in your target page you'll have that ID the page will be scrolled automatically.

What's the difference between Git Revert, Checkout and Reset?

Let's say you had commits:

C
B
A

git revert B, will create a commit that undoes changes in B.

git revert A, will create a commit that undoes changes in A, but will not touch changes in B

Note that if changes in B are dependent on changes in A, the revert of A is not possible.

git reset --soft A, will change the commit history and repository; staging and working directory will still be at state of C.

git reset --mixed A, will change the commit history, repository, and staging; working directory will still be at state of C.

git reset --hard A, will change the commit history, repository, staging and working directory; you will go back to the state of A completely.

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

Set value of textarea in jQuery

When I had JQuery v1.4.4 in the page, neither of these worked. When injecting JQuery v1.7.1 into my page, it worked finally. So in my case, it was my JQuery version that was causing the issue.

id ==> textareaid

======================

var script1 = document.createElement("script");
script1.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
document.body.appendChild(script1);

var script2 = document.createElement("script"); 
script2.type = "text/javascript"; 
script2.innerHTML = "var $jq171 = $.noConflict();"; 
document.body.appendChild(script2);

$jq171('#textareaid').val('xxx');

Using Java generics for JPA findAll() query with WHERE clause

Hat tip to Adam Bien if you don't want to use createQuery with a String and want type safety:

 @PersistenceContext
 EntityManager em;

 public List<ConfigurationEntry> allEntries() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class);
        Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class);
        CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry);
        TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all);
        return allQuery.getResultList();
 }

http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as

How do I include inline JavaScript in Haml?

So i tried the above :javascript which works :) However HAML wraps the generated code in CDATA like so:

<script type="text/javascript">
  //<![CDATA[
    $(document).ready( function() {
       $('body').addClass( 'test' );
    } );
  //]]>
</script>

The following HAML will generate the typical tag for including (for example) typekit or google analytics code.

 %script{:type=>"text/javascript"}
  //your code goes here - dont forget the indent!

Count number of iterations in a foreach loop

Try:

$counter = 0;
foreach ($Contents as $item) {
          something 
          your code  ...
      $counter++;      
}
$total_count=$counter-1;

Android studio - Failed to find target android-18

I solved the problem by changing the compileSdkVersion in the Gradle.build file from 18 to 17.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 18
    }
}

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
}

What are the differences among grep, awk & sed?

I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....

they are very handy but you have to learn their options etc.

A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)

AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.

a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.

SQL Server tables: what is the difference between @, # and ##?

if you need a unique global temp table, create your own with a Uniqueidentifier Prefix/Suffix and drop post execution if an if object_id(.... The only drawback is using Dynamic sql and need to drop explicitly.

Carriage Return\Line feed in Java

bw.newLine(); cannot ensure compatibility with all systems.

If you are sure it is going to be opened in windows, you can format it to windows newline.

If you are already using native unix commands, try unix2dos and convert teh already generated file to windows format and then send the mail.

If you are not using unix commands and prefer to do it in java, use ``bw.write("\r\n")` and if it does not complicate your program, have a method that finds out the operating system and writes the appropriate newline.

jQuery Mobile: document ready vs. page events

This is the correct way:

To execute code that will only be available to the index page, we could use this syntax:

$(document).on('pageinit', "#index",  function() {
    ...
});

git command to move a folder inside another

I had a similar problem with git mv where I wanted to move the contents of one folder into an existing folder, and ended up with this "simple" script:

pushd common; for f in $(git ls-files); do newdir="../include/$(dirname $f)"; mkdir -p $newdir; git mv $f $newdir/$(basename "$f"); done; popd

Explanation

  • git ls-files: Find all files (in the common folder) checked into git
  • newdir="../include/$(dirname $f)"; mkdir -p $newdir;: Make a new folder inside the include folder, with the same directory structure as common
  • git mv $f $newdir/$(basename "$f"): Move the file into the newly created folder

The reason for doing this is that git seems to have problems moving files into existing folders, and it will also fail if you try to move a file into a non-existing folder (hence mkdir -p).

The nice thing about this approach is that it only touches files that are already checked in to git. By simply using git mv to move an entire folder, and the folder contains unstaged changes, git will not know what to do.

After moving the files you might want to clean the repository to remove any remaining unstaged changes - just remember to dry-run first!

git clean -fd -n

CSS styling in Django forms

You can do:

<form action="" method="post">
    <table>
        {% for field in form %}
        <tr><td>{{field}}</td></tr>
        {% endfor %}
    </table>
    <input type="submit" value="Submit">
</form>

Then you can add classes/id's to for example the <td> tag. You can of course use any others tags you want. Check Working with Django forms as an example what is available for each field in the form ({{field}} for example is just outputting the input tag, not the label and so on).

How do I show/hide a UIBarButtonItem?

Just Set barButton.customView = UIView() and see the Trick

What is Gradle in Android Studio?

Short and simple answer for that,

Gradle is a build system, which is responsible for code compilation, testing, deployment and conversion of the code into . dex files and hence running the app on the device. As Android Studio comes with Gradle system pre-installed, there is no need to install additional runtime softwares to build our project.

Save a file in json format using Notepad++

You can do using a simple notepad and save as FILENAME.json

That's all.

jQuery remove all list items from an unordered list

this worked for me with minimal code

$(my_list).remove('li');

Passing arguments to C# generic new() of templated type

If you simply want to initialise a member field or property with the constructor parameter, in C# >= 3 you can do it very easier:

public static string GetAllItems<T>(...) where T : InterfaceOrBaseClass, new() 
{ 
   ... 
   List<T> tabListItems = new List<T>(); 
   foreach (ListItem listItem in listCollection)  
   { 
       tabListItems.Add(new T{ BaseMemberItem = listItem }); // No error, BaseMemberItem owns to InterfaceOrBaseClass. 
   }  
   ... 
} 

This is the same thing Garry Shutler said, but I'd like to put an aditional note.

Of course you can use a property trick to do more stuff than just setting a field value. A property "set()" can trigger any processing needed to setup its related fields and any other need for the object itself, including a check to see if a full initialization is to take place before the object is used, simulating a full contruction (yes, it is an ugly workaround, but it overcomes M$'s new() limitation).

I can't be assure if it is a planned hole or an accidental side effect, but it works.

It is very funny how MS people adds new features to the language and seems to not do a full side effects analysis. The entire generic thing is a good evidence of this...

How to change the background-color of jumbrotron?

just and another class to jumbotron

bg-transparent

It will work perfectly

bootstrap color documentation: https://getbootstrap.com/docs/4.3/utilities/colors/

JPA: unidirectional many-to-one and cascading delete

Create a bi-directional relationship, like this:

@Entity
public class Parent implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
    private Set<Child> children;
}

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Here is an official answer to this:

If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.

Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.

You can configure Git to store your password for you. If you'd like to set that up, read all about setting up password caching.

Moment js get first and last day of current month

As simple we can use daysInMonth() and endOf()

const firstDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').startOf('month').format('D')
const lastDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').endOf('month').format('D')

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

Disabling swap files creation in vim

If you are using git, you can add *.swp to .gitignore.

Equals(=) vs. LIKE

Using = avoids wildcards and special characters conflicts in the string when you build the query at run time.

This makes the programmer's life easier by not having to escape all special wildcard characters that might slip in the LIKE clause and not producing the intended result. After all, = is the 99% use case scenario, it would be a pain to have to escape them every time.

rolls eyes at '90s

I also suspect it's a little bit slower, but I doubt it's significant if there are no wildcards in the pattern.

How do I create a HTTP Client Request with a cookie?

The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

Convert Time DataType into AM PM Format:

Here are the various ways you may pull this (depending on your needs).

Using the Time DataType:

DECLARE @Time Time = '15:04:46.217'
SELECT --'3:04PM'
       CONVERT(VarChar(7), @Time, 0),

       --' 3:04PM' --Leading Space.
       RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7),

       --' 3:04 PM' --Space before AM/PM.
       STUFF(RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' '),

       --'03:04 PM' --Leading Zero.  This answers the question above.
       STUFF(RIGHT('0' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' ')

       --'03:04 PM' --This only works in SQL Server 2012 and above.  :)
       ,FORMAT(CAST(@Time as DateTime), 'hh:mm tt')--Comment out for SS08 or less.

Using the DateTime DataType:

DECLARE @Date DateTime = '2016-03-17 15:04:46.217'
SELECT --' 3:04PM' --No space before AM/PM.
       RIGHT(CONVERT(VarChar(19), @Date, 0), 7),

       --' 3:04 PM' --Space before AM/PM.
       STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' '),

       --'3:04 PM' --No Leading Space.
       LTRIM(STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' ')),

       --'03:04 PM' --Leading Zero.
       STUFF(REPLACE(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), ' ', '0'), 6, 0, ' ')

       --'03:04 PM' --This only works in SQL Server 2012 and above.  :)
       ,FORMAT(@Date, 'hh:mm tt')--Comment line out for SS08 or less.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Also you should know that you can force TLS v1.2 for Android 4.0 devices that don't have it enabled by default:

Put this code in onCreate() of your Application file:

try {
        ProviderInstaller.installIfNeeded(getApplicationContext());
        SSLContext sslContext;
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);
        sslContext.createSSLEngine();
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
            | NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

1> File -> invalidate caches 2> Build-> Rebuild

its work for me

JUnit test for System.out.println()

You cannot directly print by using system.out.println or using logger api while using JUnit. But if you want to check any values then you simply can use

Assert.assertEquals("value", str);

It will throw below assertion error:

java.lang.AssertionError: expected [21.92] but found [value]

Your value should be 21.92, Now if you will test using this value like below your test case will pass.

 Assert.assertEquals(21.92, str);