Programs & Examples On #Sql server 2005 express

Use this tag for questions specific to scaled down, free edition of SQL Server 2005.

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Enable Mixed authentication mode while installing MSSQL server. Also provide password for sa user.

How to install SQL Server 2005 Express in Windows 8

Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.

After you run the install file SQLExpr.exe look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)

After that, find the file sqlncli_x64.msi in the setup folder, and run it.

Now you are ready the run the setup.exe file and install SQL server 2005 without errors

enter image description here

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

As i know, you can't do it in a sentence.

But you can build an stored procedure that do the deletes you want in whatever table in a transaction, what is almost the same.

How to change identity column values programmatically?

Very nice question, first we need to on the IDENTITY_INSERT for the specific table, after that run the insert query (Must specify the column name).

Note: After edit the the identity column, don't forget to off the IDENTITY_INSERT. If you not done, you cannot able to Edit the identity column for any other table.

SET IDENTITY_INSERT Emp_tb_gb_Menu ON
     INSERT Emp_tb_gb_Menu(MenuID) VALUES (68)
SET IDENTITY_INSERT Emp_tb_gb_Menu OFF

http://allinworld99.blogspot.com/2016/07/how-to-edit-identity-field-in-sql.html

How can I join on a stored procedure?

I hope your stored procedure is not doing a cursor loop!

If not, take the query from your stored procedure and integrate that query within the query you are posting here:

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
        u.UnitNumber,
        p.PropertyName
        ,dt.TenantBalance
FROM tblTenant t
    LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
    LEFT JOIN tblProperty   p ON u.PropertyID = p.ID
    LEFT JOIN (SELECT ID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance
                   FROM tblTransaction
                   GROUP BY tenant.ID
              ) dt ON t.ID=dt.ID
ORDER BY p.PropertyName, t.CarPlateNumber

If you are doing something more than a query in your stored procedure, create a temp table and execute the stored procedure into this temp table and then join to that in your query.

create procedure test_proc
as
  select 1 as x, 2 as y
  union select 3,4 
  union select 5,6 
  union select 7,8 
  union select 9,10
  return 0
go 

create table #testing
(
  value1   int
  ,value2  int
)

INSERT INTO #testing
exec test_proc


select
  *
  FROM #testing

Compiling LaTex bib source

You have to run 'bibtex':

latex paper.tex
bibtex paper
latex paper.tex
latex paper.tex
dvipdf paper.dvi

Get controller and action name from within controller?

This seems to work nicely for me (so far), also works if you are using attribute routing.

public class BaseController : Controller
{
    protected string CurrentAction { get; private set; }
    protected string CurrentController { get; private set; }

    protected override void Initialize(RequestContext requestContext)
    {
        this.PopulateControllerActionInfo(requestContext);
    }

    private void PopulateControllerActionInfo(RequestContext requestContext)
    {
        RouteData routedata = requestContext.RouteData;

        object routes;

        if (routedata.Values.TryGetValue("MS_DirectRouteMatches", out routes))
        {
            routedata = (routes as List<RouteData>)?.FirstOrDefault();
        }

        if (routedata == null)
            return;

        Func<string, string> getValue = (s) =>
        {
            object o;
            return routedata.Values.TryGetValue(s, out o) ? o.ToString() : String.Empty;
        };

        this.CurrentAction = getValue("action");
        this.CurrentController = getValue("controller");
    }
}

How to create a readonly textbox in ASP.NET MVC3 Razor

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })

You are welcome to make an HTML Helper for this, but this is simply just an HTML attribute like any other. Would you make an HTML Helper for a text box that has other attributes?

Count number of objects in list

length(x)

Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.

lengths(x)

Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.

"Cannot instantiate the type..."

java.util.Queue is an interface so you cannot instantiate it directly. You can instantiate a concrete subclass, such as LinkedList:

Queue<T> q = new LinkedList<T>;

How to check if a specific key is present in a hash or not?

In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is:

YourHash.has_key? :yourkey

Are there such things as variables within an Excel formula?

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

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

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

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

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

How to get height and width of device display in angular2 using typescript?

For those who want to get height and width of device even when the display is resized (dynamically & in real-time):

  • Step 1:

In that Component do: import { HostListener } from "@angular/core";

  • Step 2:

In the component's class body write:

@HostListener('window:resize', ['$event'])
onResize(event?) {
   this.screenHeight = window.innerHeight;
   this.screenWidth = window.innerWidth;
}
  • Step 3:

In the component's constructor call the onResize method to initialize the variables. Also, don't forget to declare them first.

constructor() {
  this.onResize();
}    

Complete code:

import { Component, OnInit } from "@angular/core";
import { HostListener } from "@angular/core";

@Component({
  selector: "app-login",
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class FooComponent implements OnInit {
    screenHeight: number;
    screenWidth: number;

    constructor() {
        this.getScreenSize();
    }

    @HostListener('window:resize', ['$event'])
    getScreenSize(event?) {
          this.screenHeight = window.innerHeight;
          this.screenWidth = window.innerWidth;
          console.log(this.screenHeight, this.screenWidth);
    }

}

How to exclude records with certain values in sql select

One way:

SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
    SELECT * FROM StoreClients sc2 
    WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)

Default SecurityProtocol in .NET 4.5

There are two possible scenario,

  1. If you application run on .net framework 4.5 or less than that and you can easily deploy new code to the production then you can use of below solution.

    You can add below line of code before making api call,

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5

  2. If you cannot deploy new code and you want to resolve with the same code which is present in the production, then you have two options.

Option 1 :

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001


then create a file with extension .reg and install.

Note : This setting will apply at registry level and is applicable to all application present on that machine and if you want to restrict to only single application then you can use Option 2

Option 2 : This can be done by changing some configuration setting in config file. You can add either of one in your config file.

<runtime>
    <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
  </runtime>

or

<runtime>
  <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
</runtime>

How to downgrade or install an older version of Cocoapods

Actually, you don't need to downgrade – if you need to use older version in some projects, just specify the version that you need to use after pod command.

pod _0.37.2_ setup

How to get system time in Java without creating a new Date

You can use System.currentTimeMillis().

At least in OpenJDK, Date uses this under the covers.

The call in System is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.

Angular: Can't find Promise, Map, Set and Iterator

I am training with a angular2 tutorial(hero).
After installing @types/core-js commented in theses answers, I got a "Duplicate identifier" error.
In my case, it was solved as removing lib line in tsconfig.json.

//"lib": [ "es2015", "dom" ]

Pass a String from one Activity to another Activity in Android

Most likely as others have said you want to attach it to your Intent with putExtra. But I want to throw out there that depending on what your use case is, it may be better to have one activity that switches between two fragments. The data is stored in the activity and never has to be passed.

How do you debug PHP scripts?

Xdebug and the DBGp plugin for Notepad++ for heavy duty bug hunting, FirePHP for lightweight stuff. Quick and dirty? Nothing beats dBug.

How to run a script at a certain time on Linux?

The at command exists specifically for this purpose (unlike cron which is intended for scheduling recurring tasks).

at $(cat file) </path/to/script

Efficient evaluation of a function at every cell of a NumPy array

I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.

One can write his own customised ufunc in C, which surely is more efficient, or by invoking np.frompyfunc, which is built-in factory method. After testing, this is more efficient than np.vectorize:

f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)

%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms

I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post

How do I replicate a \t tab space in HTML?

You can enter the tab character (U+0009 CHARACTER TABULATION, commonly known as TAB or HT) using the character reference &#9;. It is equivalent to the tab character as such. Thus, from the HTML viewpoint, there is no need to “escape” it using the character reference; but you may do so e.g. if your editing program does not let you enter the character conveniently.

On the other hand, the tab character is in most contexts equivalent to a normal space in HTML. It does not “tabulate”, it’s just a word space.

The tab character has, however, special handling in pre elements and (although this not that well described in specifications) in textarea and xmp element (in the latter, character references cannot be used, only the tab character as such). This is described somewhat misleadingly in HTML specifications, e.g. in HTML 4.01: “[Inside the pre element, ] the horizontal tab character (decimal 9 in [ISO10646] and [ISO88591] ) is usually interpreted by visual user agents as the smallest non-zero number of spaces necessary to line characters up along tab stops that are every 8 characters. We strongly discourage using horizontal tabs in preformatted text since it is common practice, when editing, to set the tab-spacing to other values, leading to misaligned documents.”

The warnings are unnecessary except as regards to the potential mismatch of tabbing in your authoring software and HTML rendering in browsers. The real reason for avoiding horizontal tab is that it a coarse and simplistic tool as compared with tables for presenting tabular material. And in displaying computer source programs, it is better to use just spaces inside pre, since the default tab stops at every 8 characters are quite unsuitable for any normal code indentation style.

In addition, in CSS, you can specify white-space: pre (or, with slightly more limited browser support, white-space: pre-wrap) to make a normal HTML element, like div or p, rendered like pre, so that all whitespace is preserved and horizontal tab has the “tabbing” effect.

In CSS Text Module Level 3 (Last Call working draft, i.e. proceeding towards maturity), there is also the tab-size property, which can be used to set the distance between tab stops, e.g. tab-size: 3. It’s supported by newest versions of most browsers, but not IE (not even IE 11).

jQuery - setting the selected value of a select control via its text description

Heres an easy option. Just set your list option then set its text as selected value:

$("#ddlScheduleFrequency option").selected(text("Select One..."));

Linq style "For Each"

Using the ToList() extension method is your best option:

someValues.ToList().ForEach(x => list.Add(x + 1));

There is no extension method in the BCL that implements ForEach directly.


Although there's no extension method in the BCL that does this, there is still an option in the System namespace... if you add Reactive Extensions to your project:

using System.Reactive.Linq;

someValues.ToObservable().Subscribe(x => list.Add(x + 1));

This has the same end result as the above use of ToList, but is (in theory) more efficient, because it streams the values directly to the delegate.

How to create nested directories using Mkdir in Golang?

os.Mkdir is used to create a single directory. To create a folder path, instead try using:

os.MkdirAll(folderPath, os.ModePerm)

Go documentation

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Edit:

Updated to correctly use os.ModePerm instead.
For concatenation of file paths, use package path/filepath as described in @Chris' answer.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Input placeholders for Internet Explorer

NOTE: the author of this polyfill claims it "works in pretty much any browser you can imagine" but according to the comments that's not true for IE11, however IE11 has native support, as do most modern browsers

Placeholders.js is the best placeholder polyfill I've seen, is lightweight, doesn't depend on JQuery, covers other older browsers (not just IE), and has options for hide-on-input and run-once placeholders.

Auto generate function documentation in Visual Studio

///

is the shortcut for getting the Method Description comment block. But make sure you have written the function name and signature before adding it. First write the Function name and signature.

Then above the function name just type ///

and you will get it automatically

enter image description here

Convert True/False value read from file to boolean

you can use distutils.util.strtobool

>>> from distutils.util import strtobool

>>> strtobool('True')
1
>>> strtobool('False')
0

True values are y, yes, t, true, on and 1; False values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

XPath: Get parent node from child node

This works in my case. I hope you can extract meaning out of it.

//div[text()='building1' and @class='wrap']/ancestor::tr/td/div/div[@class='x-grid-row-checker']

DB2 Query to retrieve all table names for a given schema

This should work:

select * from syscat.tables

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

How do I convert ticks to minutes?

A single tick represents one hundred nanoseconds or one ten-millionth of a second. FROM MSDN.

So 28 000 000 000 * 1/10 000 000 = 2 800 sec. 2 800 sec /60 = 46.6666min

Or you can do it programmaticly with TimeSpan:

    static void Main()
    {
        TimeSpan ts = TimeSpan.FromTicks(28000000000);
        double minutesFromTs = ts.TotalMinutes;
        Console.WriteLine(minutesFromTs);
        Console.Read();
    }

Both give me 46 min and not 480 min...

How to map atan2() to degrees 0-360

The R packages geosphere will calculate bearingRhumb, which is a constant bearing line given an origin point and easting/northing. The easting and northing must be in a matrix or vector. The origin point for a wind rose is 0,0. The following code seems to readily resolve the issue:

windE<-wind$uasE
windN<-wind$vasN
wind_matrix<-cbind(windE, windN)
wind$wind_dir<-bearingRhumb(c(0,0), wind_matrix)
wind$wind_dir<-round(wind$wind_dir, 0)

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

iPhone/iPad browser simulator?

You can run safari in Xcode's simulator and it should accurately emulate iPads and iPhones. Another thing on the market that I've heard good reviews for is Ripple for chrome.

Calculate distance between two points in google maps V3

To calculate distance on Google Maps, you can use Directions API. That will be one of the easiest way to do it. To get data from Google Server, you can use Retrofit or Volley. Both has their own advantage. Take a look at following code where I have used retrofit to implement it:

private void build_retrofit_and_get_response(String type) {

    String url = "https://maps.googleapis.com/maps/";

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitMaps service = retrofit.create(RetrofitMaps.class);

    Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);

    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Response<Example> response, Retrofit retrofit) {

            try {
                //Remove previous line from map
                if (line != null) {
                    line.remove();
                }
                // This loop will go through all the results and add marker on each location.
                for (int i = 0; i < response.body().getRoutes().size(); i++) {
                    String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
                    String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
                    ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
                    String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
                    List<LatLng> list = decodePoly(encodedString);
                    line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(20)
                                    .color(Color.RED)
                                    .geodesic(true)
                    );
                }
            } catch (Exception e) {
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.d("onFailure", t.toString());
        }
    });

}

Above is the code of function build_retrofit_and_get_response for calculating distance. Below is corresponding Retrofit Interface:

package com.androidtutorialpoint.googlemapsdistancecalculator;


import com.androidtutorialpoint.googlemapsdistancecalculator.POJO.Example;

import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;

public interface RetrofitMaps {


/*
 * Retrofit get annotation with our URL
 * And our method that will return us details of student.
 */
@GET("api/directions/json?key=AIzaSyC22GfkHu9FdgT9SwdCWMwKX1a4aohGifM")
Call<Example> getDistanceDuration(@Query("units") String units, @Query("origin") String origin, @Query("destination") String destination, @Query("mode") String mode);

}

I hope this explains your query. All the best :)

Source: Google Maps Distance Calculator

How to get current available GPUs in tensorflow?

The following works in tensorflow 2:

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    print("Name:", gpu.name, "  Type:", gpu.device_type)

From 2.1, you can drop experimental:

    gpus = tf.config.list_physical_devices('GPU')

https://www.tensorflow.org/api_docs/python/tf/config/list_physical_devices

The server committed a protocol violation. Section=ResponseStatusLine ERROR

Sometimes this error occurs when UserAgent request parameter is empty (in github.com api in my case).

Setting this parameter to custom not empty string solved my problem.

What is the fastest factorial function in JavaScript?

I came across this post. Inspired by all contributions here I came up with my own version, which has two features that I haven't seen discussed before: 1) A check to ensure the argument is a non-negative integer 2) Making a unit out of the cache and the function to make it one self contained bit of code. For fun, I tried to make it as compact as possible. Some may find that elegant, others may think it terribly obscure. Anyway, here it is:

var fact;
(fact = function(n){
    if ((n = parseInt(n)) < 0 || isNaN(n)) throw "Must be non-negative number";
    var cache = fact.cache, i = cache.length - 1;
    while (i < n) cache.push(cache[i++] * i);
    return cache[n];
}).cache = [1];

You can either pre fill the cache, or allow it to be filled as the calls go by. But the initial element (for fact(0) must be present or it will break.

Enjoy :)

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-XX:MaxPermSize=256m
-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

Download xcode 10.2 from below link https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2/Xcode_10.2.xip

Edit: Minimum System Version* to 10.13.6 in Info.plist at below paths

  1. Xcode.app/Contents/Info.plist
  2. Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/Info.plist

Replace: Xcode.app/Contents/Developer/usr/bin/xcodebuild from Xcode 10

****OR*****

you can install disk image of 12.2 in your existing xcode to run on 12.2 devices Download disk image from here https://github.com/xushuduo/Xcode-iOS-Developer-Disk-Image/releases/download/12.2/12.2.16E5191d.zip

And paste at Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

Note: Restart the Xcode

What is the C# equivalent of NaN or IsNumeric?

VB has the IsNumeric function. You could reference Microsoft.VisualBasic.dll and use it.

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

Binding ng-model inside ng-repeat loop in AngularJS

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).

Fiddle.

For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

Uncaught TypeError: Cannot set property 'onclick' of null

Try to put all your <script ...></script> tags before the </body> tag. Perhaps the js is trying to access an object of the DOM before it's built up.

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.

  <configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <requestLimits>
               <headerLimits>
                  <add header="Content-type" sizeLimit="100" />
               </headerLimits>
            </requestLimits>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

How to validate an e-mail address in swift?

Here is an extension in Swift 3

extension String {
    func isValidEmail() -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
    }
}

Just use it like this:

if yourEmailString.isValidEmail() {
    //code for valid email address
} else {
    //code for not valid email address
}

Image is not showing in browser?

You put inside img tag physical path you your image. Instead of that you should put virtual path (according to root of web application) to your image. This value depends on location of your image and your html page.

for example if you have:

/yourDir
-page.html
-66.jpg

in your page.html it should be something like that:

<img  src="66.jpg" width="400" height="400" ></img>

second scenario:

/images
-66.jpg
/html
page.html

So your img should look like:

<img  src="../images/66.jpg" width="400" height="400" ></img>

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

Git reset --hard and push to remote repository

The whole git resetting business looked far to complicating for me.

So I did something along the lines to get my src folder in the state i had a few commits ago

# reset the local state
git reset <somecommit> --hard 
# copy the relevant part e.g. src (exclude is only needed if you specify .)
tar cvfz /tmp/current.tgz --exclude .git  src
# get the current state of git
git pull
# remove what you don't like anymore
rm -rf src
# restore from the tar file
tar xvfz /tmp/current.tgz
# commit everything back to git
git commit -a
# now you can properly push
git push

This way the state of affairs in the src is kept in a tar file and git is forced to accept this state without too much fiddling basically the src directory is replaced with the state it had several commits ago.

check if file exists in php

if (!file_exists('http://example.com/images/thumbnail_1286954822.jpg')) {   
$filefound = '0';
}

How do I catch an Ajax query post error?

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

How to get a path to a resource in a Java JAR file

private static final String FILE_LOCATION = "com/input/file/somefile.txt";

//Method Body


InputStream invalidCharacterInputStream = URLClassLoader.getSystemResourceAsStream(FILE_LOCATION);

Getting this from getSystemResourceAsStream is the best option. By getting the inputstream rather than the file or the URL, works in a JAR file and as stand alone.

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

Make sure you format the string like this or it wont work

 $content = "BEGIN:VCALENDAR\n".
            "VERSION:2.0\n".
            "PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n".
            "BEGIN:VEVENT\n".
            "UID:".uniqid()."\n".
            "DTSTAMP:".$time."\n".
            "DTSTART:".$time."\n".
            "DTEND:".$time."\n".
            "SUMMARY:".$summary."\n".
            "END:VEVENT\n".
            "END:VCALENDAR";

Unzipping files

If you need to support other formats as well or just need good performance, you can use this WebAssembly library

it's promised based, it uses WebWorkers for threading and API is actually simple ES module

How to know that a string starts/ends with a specific string in jQuery?

For startswith, you can use indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

and you can do the maths based on string length to determine 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

You can use the .tostring() method with datetime format specifiers to format to whatever you need:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013

Adding Google Play services version to your app's manifest?

Just add the library reference, go to Propertes -> Android, then add the library.

enter image description here

then add into you AndroidManifest.xml

   <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

Unsuccessful append to an empty NumPy array

numpy.append is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:

import numpy

old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]

I think you might be able to achieve your goal by doing something like:

result = numpy.zeros((10,))
result[0:2] = [1, 2]

# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]

Update:

If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:

import numpy as np

a = np.array([0., 1.])
b = np.array([2., 3.])

temp = []
while True:
    rnd = random.randint(0, 100)
    if rnd > 50:
        temp.append(a)
    else:
        temp.append(b)
    if rnd == 0:
         break

 result = np.array(temp)

In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.

new update

The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b) the shapes of a and b need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.

How can I start and check my MySQL log?

Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html

How to create Toast in Flutter?

SnackBar is definitely the right class to use, as pointed out by Darky.

snackbar

One tricky thing about showSnackBar is getting to the ScaffoldState, if you're trying to call showSnackBar within the build method where you construct your Scaffold.

You might see an error like this, which includes some text explaining how to solve the problem.

--¦ EXCEPTION CAUGHT BY GESTURE ¦-------------------------------------------------------------------
The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This
usually happens when the context provided is from the same StatefulWidget as that whose build
function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that
is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of():
  https://docs.flutter.io/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a
new context from which you can obtain the Scaffold. In this solution, you would have an outer widget
that creates the Scaffold populated by instances of your new inner widgets, and then in these inner
widgets you would use Scaffold.of().
A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, then use the
key.currentState property to obtain the ScaffoldState rather than using the Scaffold.of() function.
The context used was:
  MyHomePage
When the exception was thrown, this was the stack:
#0      Scaffold.of (package:flutter/src/material/scaffold.dart:444:5)
#1      MyHomePage.build.<anonymous closure> (/Users/jackson/Library/Developer/CoreSimulator/Devices/7072C907-DBAD-44FE-8F40-0257442C51D9/data/Containers/Data/Application/77FEC1A4-1453-442C-8208-96E0323DEFB2/tmp/so_scratch2Tkq9Jb/so_scratch2/lib/main.dart:23:24)
#2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:323:14)
#3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:375:30)
#4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
#5      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:149:9)
#6      TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:119:7)
#7      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
#8      BindingBase&SchedulerBinding&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:147:20)
#9      BindingBase&SchedulerBinding&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
#10     BindingBase&SchedulerBinding&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
#11     BindingBase&SchedulerBinding&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
#12     BindingBase&SchedulerBinding&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
#13     _invoke1 (file:///b/build/slave/Mac_Engine/build/src/flutter/lib/ui/hooks.dart:100)
#14     _dispatchPointerDataPacket (file:///b/build/slave/Mac_Engine/build/src/flutter/lib/ui/hooks.dart:58)
Handler: onTap
Recognizer:
  TapGestureRecognizer#69dbc(debugOwner: GestureDetector, state: ready)
----------------------------------------------------------------------------------------------------

You can either pass a GlobalKey to your Scaffold constructor:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final key = new GlobalKey<ScaffoldState>();
    return new Scaffold(
      key: key,
      floatingActionButton: new Builder(
        builder: (BuildContext context) {
          return new FloatingActionButton(
            onPressed: () {
              key.currentState.showSnackBar(new SnackBar(
                content: new Text("Sending Message"),
              ));
            },
            tooltip: 'Increment',
            child: new Icon(Icons.add),
          );
        }
      ),
    );
  }
}

Or you can use a Builder to create a BuildContext that is a child of the Scaffold.

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      floatingActionButton: new Builder(
        builder: (BuildContext context) {
          return new FloatingActionButton(
            onPressed: () {
              Scaffold.of(context).showSnackBar(new SnackBar(
                content: new Text("Sending Message"),
              ));
            },
            tooltip: 'Increment',
            child: new Icon(Icons.add),
          );
        }
      ),
    );
  }
}

Finally, you could split your widget into multiple classes, which is the best long-term approach.

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

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

Recursive mkdir() system call on Unix

Here's my shot at a more general solution:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

typedef int (*dirhandler_t)( const char*, void* );
/// calls itfunc for each directory in path (except for . and ..)
int iterate_path( const char* path, dirhandler_t itfunc, void* udata )
{
    int rv = 0;
    char tmp[ 256 ];
    char *p = tmp;
    char *lp = tmp;
    size_t len;
    size_t sublen;
    int ignore_entry;

    strncpy( tmp, path, 255 );

    tmp[ 255 ] = '\0';
    len = strlen( tmp );

    if( 0 == len ||
        (1 == len && '/' == tmp[ 0 ]) )
        return 0;

    if( tmp[ len - 1 ] == '/' )
        tmp[ len - 1 ] = 0;

    while( (p = strchr( p, '/' )) != NULL )
    {
        ignore_entry = 0;
        *p = '\0';
        lp = strrchr( tmp, '/' );

        if( NULL == lp ) { lp = tmp; }
        else { lp++; }

        sublen = strlen( lp );

        if( 0 == sublen )   /* ignore things like '//' */
            ignore_entry = 1;
        else if( 1 == sublen &&  /* ignore things like '/./' */
                 '.' == lp[ 0 ] )
            ignore_entry = 1;
        else if( 2 == sublen &&    /* also ignore things like '/../' */
                 '.' == lp[ 0 ] &&
                 '.' == lp[ 1 ] )
            ignore_entry = 1;

        if( ! ignore_entry )
        {
            if( (rv = itfunc( tmp, udata )) != 0 )
                return rv;
        }

        *p = '/';
        p++;
        lp = p;
    }

    if( strcmp( lp, "." ) && strcmp( lp, ".." ) )
        return itfunc( tmp, udata );

    return 0;
}

mode_t get_file_mode( const char* path )
{
    struct stat statbuf;
    memset( &statbuf, 0, sizeof( statbuf ) );

    if( NULL == path ) { return 0; }

    if( 0 != stat( path, &statbuf ) )
    {
        fprintf( stderr, "failed to stat '%s': %s\n",
                 path, strerror( errno ) );
        return 0;
    }

    return statbuf.st_mode;
}

static int mymkdir( const char* path, void* udata )
{
    (void)udata;
    int rv = mkdir( path, S_IRWXU );
    int errnum = errno;

    if( 0 != rv )
    {
        if( EEXIST == errno &&
            S_ISDIR( get_file_mode( path ) ) )  /* it's all good, the directory already exists */
            return 0;

        fprintf( stderr, "mkdir( %s ) failed: %s\n",
                 path, strerror( errnum ) );
    }
//     else
//     {
//         fprintf( stderr, "created directory: %s\n", path );
//     }

    return rv;
}

int mkdir_with_leading( const char* path )
{
    return iterate_path( path, mymkdir, NULL );
}

int main( int argc, const char** argv )
{
    size_t i;
    int rv;

    if( argc < 2 )
    {
        fprintf( stderr, "usage: %s <path> [<path>...]\n",
                 argv[ 0 ] );
        exit( 1 );
    }

    for( i = 1; i < argc; i++ )
    {
        rv = mkdir_with_leading( argv[ i ] );
        if( 0 != rv )
            return rv;
    }

    return 0;
}

Passing a URL with brackets to curl

Globbing uses brackets, hence the need to escape them with a slash \. Alternatively, the following command-line switch will disable globbing:

--globoff (or the short-option version: -g)

Ex:

curl --globoff https://www.google.com?test[]=1

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

There can be many possible reasons for this failure.

Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.

I will recommend you to check the session timeout for shh from ssh_config file. Try to increase the session timeout and see if it fails again

What is key=lambda

A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print f()
foo

It is often used in functions such as sorted() that take a callable as a parameter (often the key keyword parameter). You could provide an existing function instead of a lambda there too, as long as it is a callable object.

Take the sorted() function as an example. It'll return the given iterable in sorted order:

>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']

but that sorts uppercased words before words that are lowercased. Using the key keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:

>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']

We had to create a separate function for that, we could not inline the def lowercased() line into the sorted() expression:

>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
  File "<stdin>", line 1
    sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
                                                           ^
SyntaxError: invalid syntax

A lambda on the other hand, can be specified directly, inline in the sorted() expression:

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']

Lambdas are limited to one expression only, the result of which is the return value.

There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.

How to update /etc/hosts file in Docker image during "docker build"

You can do with the following command at the time of running docker

docker run [OPTIONS] --add-host example.com:127.0.0.1 <your-image-name>:<your tag>

Here I am mapping example.com to localhost 127.0.0.1 and its working.

How to prevent Browser cache for php site

I had problem with caching my css files. Setting headers in PHP didn't help me (perhaps because the headers would need to be set in the stylesheet file instead of the page linking to it?).

I found the solution on this page: https://css-tricks.com/can-we-prevent-css-caching/

The solution:

Append timestamp as the query part of the URI for the linked file.
(Can be used for css, js, images etc.)

For development:

<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">

For production (where caching is mostly a good thing):

<link rel="stylesheet" type="text/css" href="style.css?version=3.2">
(and rewrite manually when it is required)

Or combination of these two:

<?php
    define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">

EDIT:

Or prettier combination of those two:

<?php
    // Init
    define( "DEBUGGING", true ); // or false in production enviroment
    // Functions
    function get_cache_prevent_string( $always = false ) {
        return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
    }
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">

PHP - Indirect modification of overloaded property

This is occurring due to how PHP treats overloaded properties in that they are not modifiable or passed by reference.

See the manual for more information regarding overloading.

To work around this problem you can either use a __set function or create a createObject method.

Below is a __get and __set that provides a workaround to a similar situation to yours, you can simply modify the __set to suite your needs.

Note the __get never actually returns a variable. and rather once you have set a variable in your object it no longer is overloaded.

/**
 * Get a variable in the event.
 *
 * @param  mixed  $key  Variable name.
 *
 * @return  mixed|null
 */
public function __get($key)
{
    throw new \LogicException(sprintf(
        "Call to undefined event property %s",
        $key
    ));
}

/**
 * Set a variable in the event.
 *
 * @param  string  $key  Name of variable
 *
 * @param  mixed  $value  Value to variable
 *
 * @return  boolean  True
 */
public function __set($key, $value)
{
    if (stripos($key, '_') === 0 && isset($this->$key)) {
        throw new \LogicException(sprintf(
            "%s is a read-only event property", 
            $key
        ));
    }
    $this->$key = $value;
    return true;
}

Which will allow for:

$object = new obj();
$object->a = array();
$object->a[] = "b";
$object->v = new obj();
$object->v->a = "b";

How do I write stderr to a file while using "tee" with a pipe?

why not simply:

./aaa.sh 2>&1 | tee -a log

This simply redirects stderr to stdout, so tee echoes both to log and to screen. Maybe I'm missing something, because some of the other solutions seem really complicated.

Note: Since bash version 4 you may use |& as an abbreviation for 2>&1 |:

./aaa.sh |& tee -a log

Find unique lines

Use as follows:

sort < filea | uniq > fileb

Write / add data in JSON file using Node.js

Please try the following program. You might be expecting this output.

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

Save this program in a javascript file, say, square.js.

Then run the program from command prompt using the command node square.js

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

Happy Coding.

How does a Breadth-First Search work when looking for Shortest Path?

I have wasted 3 days
ultimately solved a graph question
used for
finding shortest distance
using BFS

Want to share the experience.

When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges

#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)

#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path

#3
It does not matter what queue you use
   deque/queue(c++) or
   your own queue implementation (in c language)
   A circular queue is unnecessary

#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.

#5
Wikipedia BFS will work, and is sufficient.
    https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode

I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
they are not the issue.
(Try to spend time looking for other issues, if you dint find any issues with above 5).


More explanation from the comment below:

      A
     /  \
  B       C
 /\       /\
D  E     F  G

Assume above is your graph
graph goes downwards
For A, the adjacents are B & C
For B, the adjacents are D & E
For C, the adjacents are F & G

say, start node is A

  1. when you reach A, to, B & C the shortest distance to B & C from A is 1

  2. when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)

similarly, A->E is 2 (A->B->E)

also, A->F & A->G is 2

So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
example,
if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
if distance between each is 6, then A->E is 12 (A->B->E = 6+6)

yes, bfs may take any path
but we are calculating for all paths

if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
again if there are multiple paths from I to J, we only take shortest one
example,
assume,
A -> I we have distance 5
(STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
so A->J is now 13
we repeat now above (STEP) for J -> K and so on, till we get to Z

Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck


Double % formatting question for printf in Java

Yes, %d means decimal, but it means decimal number system, not decimal point.

Further, as a complement to the former post, you can also control the number of decimal points to show. Try this,

System.out.printf("%.2f %.1f",d,f); // prints 1.20 1.2

For more please refer to the API docs.

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Please Try, if use "extends AppCompatActivity" and present actionbar.

 ActionBar eksinbar=getSupportActionBar();
if (eksinbar != null) {
    eksinbar.setDisplayHomeAsUpEnabled(true);
    eksinbar.setHomeAsUpIndicator(R.mipmap.imagexxx);
}

Find index of a value in an array

int keyIndex = Array.FindIndex(words, w => w.IsKey);

That actually gets you the integer index and not the object, regardless of what custom class you have created

How to get to Model or Viewbag Variables in a Script Tag

When you're doing this

var model = @Html.Raw(Json.Encode(Model));

You're probably getting a JSON string, and not a JavaScript object.

You need to parse it in to an object:

var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);

Java GC (Allocation Failure)

"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.

GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

NSURLErrorDomain error codes description

The NSURLErrorDomain error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes

However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.

How do I enumerate the properties of a JavaScript object?

Use a for..in loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.

var myObject = {foo: 'bar'};

for (var name in myObject) {
  alert(name);
}

// results in a single alert of 'foo'

Object.prototype.baz = 'quux';

for (var name in myObject) {
  alert(name);
}

// results in two alerts, one for 'foo' and one for 'baz'

To avoid including inherited properties in your enumeration, check hasOwnProperty():

for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    alert(name);
  }
}

Edit: I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There is danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.

It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.

This is why JavaScript provides hasOwnProperty(), and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using hasOwnProperty().

jQuery - multiple $(document).ready ...?

Both will get called, first come first served. Take a look here.

$(document).ready(function(){
    $("#page-title").html("Document-ready was called!");
  });

$(document).ready(function(){
    $("#page-title").html("Document-ready 2 was called!");
  });

Output:

Document-ready 2 was called!

Search in lists of lists by given index

the above all look good

but do you want to keep the result?

if so...

you can use the following

result = [element for element in data if element[1] == search]

then a simple

len(result)

lets you know if anything was found (and now you can do stuff with the results)

of course this does not handle elements which are length less than one (which you should be checking unless you know they always are greater than length 1, and in that case should you be using a tuple? (tuples are immutable))

if you know all items are a set length you can also do:

any(second == search for _, second in data)

or for len(data[0]) == 4:

any(second == search for _, second, _, _ in data)

...and I would recommend using

for element in data:
   ...

instead of

for i in range(len(data)):
   ...

(for future uses, unless you want to save or use 'i', and just so you know the '0' is not required, you only need use the full syntax if you are starting at a non zero value)

How to export datagridview to excel using vb.net?

A simple way of generating a printable report from a Datagridview is to place the datagridview on a Panel object. It is possible to draw a bitmap of the panel.

Here's how I do it.

'create the bitmap with the dimentions of the Panel Dim bmp As New Bitmap(Panel1.Width, Panel1.Height)

'draw the Panel to the bitmap "bmp" Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)

I create a multi page tiff by "breaking my datagridview items into pages. this is how i detect the start of a new page:

'i add the rows to my datagrid one at a time and then check if the scrollbar is active. 'if the scrollbar is active i save the row to a variable and then i remove it from the 'datagridview and roll back my counter integer by one(thus the next run will include this 'row.

Private Function VScrollBarVisible() As Boolean
    Dim ctrl As New Control
    For Each ctrl In DataGridView_Results.Controls
        If ctrl.GetType() Is GetType(VScrollBar) Then
            If ctrl.Visible = True Then
                Return True
            Else
                Return False
            End If
        End If
    Next
    Return Nothing
End Function

I hope this helps

How can I set focus on an element in an HTML form using JavaScript?

Do this.

If your element is something like this..

<input type="text" id="mytext"/>

Your script would be

<script>
function setFocusToTextBox(){
    document.getElementById("mytext").focus();
}
</script>

Get the selected option id with jQuery

You can get it using the :selected selector, like this:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});

Where does Git store files?

I'm on Windows and found my location by right clicking the Git Bash program in my Start menu and selecting Properties. The Shortcut tab shows the "Start in:" value. For me, it was %HOMEDRIVE%%HOMEPATH%, so I opened a CMD prompt and typed echo %HOMEDRIVE%%HOMEPATH% to see the actual location.

ActionBarActivity is deprecated

android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."

checkout changes for Android Support Library, revision 22.1.0 (April 2015)

Prefer composition over inheritance?

Subtyping is appropriate and more powerful where the invariants can be enumerated, else use function composition for extensibility.

application/x-www-form-urlencoded or multipart/form-data?

I agree with much that Manuel has said. In fact, his comments refer to this url...

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4

... which states:

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

However, for me it would come down to tool/framework support.

  • What tools and frameworks do you expect your API users to be building their apps with?
  • Do they have frameworks or components they can use that favour one method over the other?

If you get a clear idea of your users, and how they'll make use of your API, then that will help you decide. If you make the upload of files hard for your API users then they'll move away, of you'll spend a lot of time on supporting them.

Secondary to this would be the tool support YOU have for writing your API and how easy it is for your to accommodate one upload mechanism over the other.

Get current folder path

This block of code makes a path of your app directory in string type

string path="";
path=System.AppContext.BaseDirectory;

good luck

Multiple FROMs - what it means

The first answer is too complex, historic, and uninformative for my tastes.


It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,

  • Free you from having to manually remove what you don't want, by forcing you to whitelist what you do want,
  • Free resources that would otherwise be taken up because of Docker's implementation.

Let's start with the first. Very often with something like Debian you'll see.

RUN apt-get update \ 
  && apt-get dist-upgrade \
  && apt-get install <whatever> \
  && apt-get clean

We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,

RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;

It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree for an example of that).

By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean), and you would otherwise have lots of un-needed files in your final image.

See also

Pygame mouse clicking detection

I was looking for the same answer to this question and after much head scratching this is the answer I came up with:

#Python 3.4.3 with Pygame
import pygame

pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))


# Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
    # Mouse position and button clicking.
    pos = pygame.mouse.get_pos()
    pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
    # Check if the rect collided with the mouse pos
    # and if the left mouse button was pressed.
    if Rectplace.collidepoint(pos) and pressed1:
        print("You have opened a chest!")
    # Quit pygame.
            for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit(1)

How do I count unique values inside a list

Other method by using pandas

import pandas as pd

LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])

You can then export results in any format you want

TransactionRequiredException Executing an update/delete query

I Got the same error.

I just added the @Transactional annotation of javax.transaction.Transactional on the method.

How do I get the scroll position of a document?

If you are using Jquery 1.6 or above, use prop to access the value.

$(document).prop('scrollHeight')

Previous versions used to get the value from attr but not post 1.6.

How to perform element-wise multiplication of two lists?

you can multiplication using lambda

foo=[1,2,3,4]
bar=[1,2,5,55]
l=map(lambda x,y:x*y,foo,bar)

sql server #region

Another option is

if your purpose is analyse your query, Notepad+ has useful automatic wrapper for Sql.

How to set height property for SPAN

this is to make display:inline-block work in all browsers:

Quirkly enough, in IE (6/7) , if you trigger hasLayout with "zoom:1" and then set the display to inline, it behaves as an inline block.

.inline-block {
    display: inline-block;
    zoom: 1;
    *display: inline;
}

Outline effect to text

Easy! SVG to the rescue.

This is a simplified method:

_x000D_
_x000D_
svg{
  font   : bold 70px Century Gothic, Arial;
  width  : 100%;
  height : 120px;
}

text{
  fill            : none;
  stroke          : black;
  stroke-width    : .5px;
  stroke-linejoin : round;
  animation       : 2s pulsate infinite;
}

@keyframes pulsate {
  50%{ stroke-width:5px }
}
_x000D_
<svg viewBox="0 0 450 50">
  <text y="50">Scalable Title</text>
</svg>
_x000D_
_x000D_
_x000D_

Here's a more complex demo.

I want to multiply two columns in a pandas DataFrame and add the result into a new column

To make things neat, I take Hayden's solution but make a small function out of it.

def create_value(row):
    if row['Action'] == 'Sell':
        return row['Prices'] * row['Amount']
    else:
        return -row['Prices']*row['Amount']

so that when we want to apply the function to our dataframe, we can do..

df['Value'] = df.apply(lambda row: create_value(row), axis=1)

...and any modifications only need to occur in the small function itself.

Concise, Readable, and Neat!

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I would still recommend Firebug. Not only it can debug JS within your JSP files, it can enhance debugging experience with addons like JS Deminifier (if your production JS is minified), FireQuery, FireRainbow and more.

There is also Firebug lite which is nothing but a bookmarklet. It lets you do limited things but still is useful.

Chrome as a developer console built-in that would let you modify javascript.

Using these tools, you should be able to inject your own JS too.

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

Where can I find jenkins restful api reference?

Additional Solution: use Restul api wrapper libraries written in Java / python / Ruby - An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.

For documentation and links: Remote Access API

How can one pull the (private) data of one's own Android app?

Newer versions of Android Studio include the Device File Explorer which I've found to be a handy GUI method of downloading files from my development Nexus 7.

You Must make sure you have enabled USB Debugging on the device

  1. Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar to open the Device File Explorer.
  2. Select a device from the drop down list.
  3. Interact with the device content in the file explorer window. Right-click on a file or directory to create a new file or directory, save the selected file or directory to your machine, upload, delete, or synchronize. Double-click a file to open it in Android Studio.

    Android Studio saves files you open this way in a temporary directory outside of your project. If you make modifications to a file you opened using the Device File Explorer, and would like to save your changes back to the device, you must manually upload the modified version of the file to the device.

file explorer

Full Documentation

How to get table list in database, using MS SQL 2008?

Answering the question in your title, you can query sys.tables or sys.objects where type = 'U' to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:

IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
    CREATE TABLE dbo.My_Table (...)
END

You can do the same for databases with DB_ID():

IF (DB_ID('My_Database') IS NULL)
BEGIN
    CREATE DATABASE My_Database
END

If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO statements. In an application it's easy enough to send across a new command after the database is created.

The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.

If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:

CREATE DATABASE Test_DB2

IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
    EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END

EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.

How To Change DataType of a DataColumn in a DataTable?

DataTable DT = ...
// Rename column to OLD:
DT.Columns["ID"].ColumnName = "ID_OLD";
// Add column with new type:
DT.Columns.Add( "ID", typeof(int) );
// copy data from old column to new column with new type:
foreach( DataRow DR in DT.Rows )
{ DR["ID"] = Convert.ToInt32( DR["ID_OLD"] ); }
// remove "OLD" column
DT.Columns.Remove( "ID_OLD" );

Execute external program

This is not right. Here's how you should use Runtime.exec(). You might also try its more modern cousin, ProcessBuilder:

Java Runtime.getRuntime().exec() alternatives

javascript popup alert on link click

You can use the onclick attribute, just return false if you don't want continue;

<script type="text/javascript">
function confirm_alert(node) {
    return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>

java.lang.ClassNotFoundException: HttpServletRequest

I have just deleted the declaration of the servlet in the web.xml file and it works for me.

Good luck

How to select all instances of selected region in Sublime Text

Note: You should not edit the default settings, because they get reset on updates/upgrades. For customization, you should override any setting by using the user bindings.

On Mac:

  • Sublime Text 2 > Preferences > Key Bindings-Default
  • Sublime Text 3 > Preferences > Key Bindings

This opens a document that you can edit the keybindings for Sublime.

If you search "ctrl+super+g" you find this:

{ "keys": ["ctrl+super+g"], "command": "find_all_under" },

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

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

Here is the example they use:

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

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

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

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

Using ffmpeg to encode a high quality video

You need to specify the -vb option to increase the video bitrate, otherwise you get the default which produces smaller videos but with more artifacts.

Try something like this:

ffmpeg -r 25 -i %4d.png -vb 20M myvideo.mpg

Interface/enum listing standard mime-type constants

Java 7 to the rescue!

You can either pass the file or the file name and it will return the MIME type.

String mimeType = MimetypesFileTypeMap
    .getDefaultFileTypeMap()
    .getContentType(attachment.getFileName());

http://docs.oracle.com/javase/7/docs/api/javax/activation/MimetypesFileTypeMap.html

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

How to check if a number is a power of 2

for any power of 2, the following also holds.

n&(-n)==n

NOTE: fails for n=0 , so need to check for it
Reason why this works is:
-n is the 2s complement of n. -n will have every bit to the left of rightmost set bit of n flipped compared to n. For powers of 2 there is only one set bit.

Using a dictionary to count the items in a list

>>> L = ['apple','red','apple','red','red','pear']
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in L:
...   d[i] += 1
>>> d
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})

How to use 'hover' in CSS

The href is a required attribute of an anchor element, so without it, you cannot expect all browsers to handle it equally. Anyway, I read somewhere in a comment that you only want the link to be underlined when hovering, and not otherwise. You can use the following to achieve this, and it will only apply to links with the hover-class:

<a class="hover" href="">click</a>

a.hover {
    text-decoration: none;
}

a.hover:hover {
    text-decoration:underline;
}

Initializing array of structures

my_data is a struct with name as a field and data[] is arry of structs, you are initializing each index. read following:

5.20 Designated Initializers:

In a structure initializer, specify the name of a field to initialize with .fieldname =' before the element value. For example, given the following structure,

struct point { int x, y; };

the following initialization

struct point p = { .y = yvalue, .x = xvalue };

is equivalent to

struct point p = { xvalue, yvalue };

Another syntax which has the same meaning, obsolete since GCC 2.5, is fieldname:', as shown here:

struct point p = { y: yvalue, x: xvalue };

You can also write:

my_data data[] = {
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

as:

my_data data[] = {
    [0] = { .name = "Peter" },
    [1] = { .name = "James" },
    [2] = { .name = "John" },
    [3] = { .name = "Mike" }
}; 

or:

my_data data[] = {
    [0].name = "Peter",
    [1].name = "James",
    [2].name = "John",
    [3].name = "Mike"
}; 

Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:

my_data data[] = {
    [3].name = "Mike",
    [1].name = "James",
    [0].name = "Peter",
    [2].name = "John"
}; 

If you have multiple fields in your struct (for example, an int age), you can initialize all of them at once using the following:

my_data data[] = {
    [3].name = "Mike",
    [2].age = 40,
    [1].name = "James",
    [3].age = 23,
    [0].name = "Peter",
    [2].name = "John"
}; 

To understand array initialization read Strange initializer expression?

Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code

Location of hibernate.cfg.xml in project?

For anyone interested: if you are using Intellj, just simply put hibernate.cfg.xml under src/main/resources.

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

How to set selected index JComboBox by value

Why not take a collection, likely a Map such as a HashMap, and use it as the nucleus of your own combo box model class that implements the ComboBoxModel interface? Then you could access your combo box's items easily via their key Strings rather than ints.

For instance...

import java.util.HashMap;
import java.util.Map;

import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;

public class MyComboModel<K, V>   implements ComboBoxModel {
   private Map<K, V> nucleus = new HashMap<K, V>();

   // ... any constructors that you want would go here

   public void put(K key, V value) {
      nucleus.put(key, value);
   }

   public V get(K key) {
      return nucleus.get(key);
   }

   @Override
   public void addListDataListener(ListDataListener arg0) {
      // TODO Auto-generated method stub

   }

   // ... plus all the other methods required by the interface
}

What's the difference between Perl's backticks, system, and exec?

Let me quote the manuals first:

perldoc exec():

The exec function executes a system command and never returns-- use system instead of exec if you want it to return

perldoc system():

Does exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete.

In contrast to exec and system, backticks don't give you the return value but the collected STDOUT.

perldoc `String`:

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.


Alternatives:

In more complex scenarios, where you want to fetch STDOUT, STDERR or the return code, you can use well known standard modules like IPC::Open2 and IPC::Open3.

Example:

use IPC::Open2;
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

Finally, IPC::Run from the CPAN is also worth looking at…

how to convert image to byte array in java?

BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.

if you want the data from DataBufferByte, use:

public byte[] extractBytes (String ImageName) throws IOException {
 // open image
 File imgPath = new File(ImageName);
 BufferedImage bufferedImage = ImageIO.read(imgPath);

 // get DataBufferBytes from Raster
 WritableRaster raster = bufferedImage .getRaster();
 DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

 return ( data.getData() );
}

now you can process these bytes by hiding text in lsb for example, or process it the way you want.

jwt check if token expired

This is for react-native, but login will work for all types.

isTokenExpired = async () => {
    try {
        const LoginTokenValue = await AsyncStorage.getItem('LoginTokenValue');
        if (JSON.parse(LoginTokenValue).RememberMe) {
            const { exp } = JwtDecode(LoginTokenValue);
            if (exp < (new Date().getTime() + 1) / 1000) {
                this.handleSetTimeout();
                return false;
            } else {
                //Navigate inside the application
                return true;
            }
        } else {
            //Navigate to the login page
        }
    } catch (err) {
        console.log('Spalsh -> isTokenExpired -> err', err);
        //Navigate to the login page
        return false;
    }
}

String literals and escape characters in postgresql

I find it highly unlikely for Postgres to truncate your data on input - it either rejects it or stores it as is.

milen@dev:~$ psql
Welcome to psql 8.2.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

milen=> create table EscapeTest (text varchar(50));
CREATE TABLE
milen=> insert into EscapeTest (text) values ('This will be inserted \n This will not be');
WARNING:  nonstandard use of escape in a string literal
LINE 1: insert into EscapeTest (text) values ('This will be inserted...
                                              ^
HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'.
INSERT 0 1
milen=> select * from EscapeTest;
          text
------------------------
 This will be inserted
  This will not be
(1 row)

milen=>

How to send a JSON object over Request with Android?

Nothing could be simple than this. Use OkHttpLibrary

Create your json

JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);

and send it like this.

OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .url(url)
            .post(requestObject.toString())
            .build();

okhttp3.Response response = client.newCall(request).execute();

Javascript change font color

Don't use <font color=. It's a really old fashioned way to style text and some browsers even don't even support it anymore.

caniuse lists it as obsolete, and strongly recommends not using the <font> tag. The same is with MDN

Do not use this element! Though once normalized in HTML 3.2, it was deprecated in HTML 4.01, at the same time as all elements related to styling only, then obsoleted in HTML5.

Starting with HTML 4, HTML does not convey styling information anymore (outside the element or the style attribute of each element). For any new web development, styling should be written using CSS only.

The former behavior of the element can be achieved, and even better controlled using the CSS Fonts CSS properties.

If we look at when the 4.01 standard was published we see it was published in 1999

published html5 standard

where <font> was officially deprecated, meaning it is still supported but shouldn't be used anymore as it will go away in the newer standard.

And in the html5 standard released in August 2014 it was deemed obsolete and non conforming.

To achieve the desired effect use spans and css:

_x000D_
_x000D_
function givemecolor(thecolor,thetext)
{
    return '<span style="color:'+thecolor+'">'+thetext+'</span>';
}
document.write(givemecolor('green',"Hello, I'm green"));
document.write(givemecolor('red',"Hello, I'm red"));
_x000D_
body {
  background: #333;
  color: #eee;
}
_x000D_
_x000D_
_x000D_

update

This question and answer are from 2012 and now I wouldn't recommend using document.write as it needs to be executed when the document is rendered first time. I had used it back then because I assumed OP was wishing to use it in such a way. I'd recommend using a more conventional way to insert the custom elements you wish to use, at the place you wish to insert them, without relying on document rendering and when and where the script is executed.

Native:

_x000D_
_x000D_
function givemecolor(thecolor,thetext)
{
    var span = document.createElement('span');
    span.style.color = thecolor;
    span.innerText = thetext;
    return span;
}
var container = document.getElementById('textholder');
container.append(givemecolor('green', "Hello I'm green"));
container.append(givemecolor('red', "Hello I'm red"));
_x000D_
body {
 background: #333;
 color: #eee;
}
_x000D_
<h1> some title </h1>
<div id="textholder">
</div>
<p> some other text </p>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
function givemecolor(thecolor, thetext)
{
    var $span = $("<span>");
    $span.css({color:thecolor});
    $span.text(thetext);
    return $span;
}
var $container = $('#textholder');
$container.append(givemecolor('green', "Hello I'm green"));
$container.append(givemecolor('red', "Hello I'm red"));
_x000D_
body {
 background: #333;
 color: #eee;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> some title </h1>
<div id="textholder">
</div>
<p> some other text </p>
_x000D_
_x000D_
_x000D_

MongoDB relationships: embed or reference?

Actually, I'm quite curious why nobody spoke about the UML specifications. A rule of thumb is that if you have an aggregation, then you should use references. But if it is a composition, then the coupling is stronger, and you should use embedded documents.

And you will quickly understand why it is logical. If an object can exist independently of the parent, then you will want to access it even if the parent doesn't exist. As you just can't embed it in a non-existing parent, you have to make it live in it's own data structure. And if a parent exist, just link them together by adding a ref of the object in the parent.

Don't really know what is the difference between the two relationships ? Here is a link explaining them: Aggregation vs Composition in UML

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

Microsoft's SSL Diagnostics Tool may be able to help identify the issue.

UPDATE the link has been fixed now.

Django Multiple Choice Field / Checkbox Select Multiple

The profile choices need to be setup as a ManyToManyField for this to work correctly.

So... your model should be like this:

class Choices(models.Model):
  description = models.CharField(max_length=300)

class Profile(models.Model):
  user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user')
  choices = models.ManyToManyField(Choices)

Then, sync the database and load up Choices with the various options you want available.

Now, the ModelForm will build itself...

class ProfileForm(forms.ModelForm):
  Meta:
    model = Profile
    exclude = ['user']

And finally, the view:

if request.method=='POST':
  form = ProfileForm(request.POST)
  if form.is_valid():
    profile = form.save(commit=False)
    profile.user = request.user
    profile.save()
else:
  form = ProfileForm()

return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))

It should be mentioned that you could setup a profile in a couple different ways, including inheritance. That said, this should work for you as well.

Good luck.

Can Windows' built-in ZIP compression be scripted?

There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge (http://sourceforge.net/projects/unxutils). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.

This is not the perfect solution (or the one you asked for) but a decent work-a-round.

How to do what head, tail, more, less, sed do in Powershell?

If you need to query large (or small) log files on Windows, the best tool I have found is Microsoft's free Log Parser 2.2. You can call it from PowerShell if you want and it will do all the heavy lifting for you, and very fast too.

Disable scrolling in all mobile devices

After having no success trying all the answers I managed to turn my mobile scroll off by simply adding:

html,
body {
  overflow-x: hidden;
  height: 100%;
}

body {
  position: relative;
}

Its important to use % not vh for this. The height: 100% was something I had been missing all along, crazy.

What is the !! (not not) operator in JavaScript?

! is "boolean not", which essentially typecasts the value of "enable" to its boolean opposite. The second ! flips this value. So, !!enable means "not not enable," giving you the value of enable as a boolean.

Fit website background image to screen size

you can do this with this plugin http://dev.andreaseberhard.de/jquery/superbgimage/

or

   background-image:url(../IMAGES/background.jpg);

   background-repeat:no-repeat;

   background-size:cover;

with no need the prefixes of browsers. it's all ready suporterd in both of browers

How to print a percentage value in python?

Just for the sake of completeness, since I noticed no one suggested this simple approach:

>>> print("%.0f%%" % (100 * 1.0/3))
33%

Details:

  • %.0f stands for "print a float with 0 decimal places", so %.2f would print 33.33
  • %% prints a literal %. A bit cleaner than your original +'%'
  • 1.0 instead of 1 takes care of coercing the division to float, so no more 0.0

How to check if std::map contains a key without doing insert?

Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

Install Windows Service created in Visual Studio

Stealth Change in VS 2010 and .NET 4.0 and Later

No public installers with the RunInstallerAttribute.Yes attribute could be found

There is an alias change or compiler cleanup in .NET that may reveal this little tweak for your specific case.

If you have the following code …

RunInstaller(true)   // old alias  

You may need to update it to

RunInstallerAttribute(true)  // new property spelling

It is like an alias changed under the covers at compile time or at runtime and you will get this error behavior. The above explicit change to RunInstallerAttribute(true) fixed it in all of our install scenarios on all machines.

After you add project or service installer then check for the “old” RunInstaller(true) and change it to the new RunInstallerAttribute(true)

Official way to ask jQuery wait for all images to load before executing something

With jQuery, you use $(document).ready() to execute something when the DOM is loaded and $(window).on("load", handler) to execute something when all other things are loaded as well, such as the images.

The difference can be seen in the following complete HTML file, provided you have a lot of jollyrogerNN JPEG files (or other suitable ones):

<html>
    <head>
        <script src="jquery-1.7.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                alert ("done");
            });
        </script>
    </head><body>
        Hello
        <img src="jollyroger00.jpg">
        <img src="jollyroger01.jpg">
        // : 100 copies of this in total
        <img src="jollyroger99.jpg">
    </body>
</html>

With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:

$(document).ready(function() {

into:

$(window).on("load", function() {

then the alert box doesn't appear until after the images are loaded.

Hence, to wait until the entire page is ready, you could use something like:

$(window).on("load", function() {
    // weave your magic here.
});

WPF: Setting the Width (and Height) as a Percentage Value

For anybody who is getting an error like : '2*' string cannot be converted to Length.

<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" /><!--This will make any control in this column of grid take 2/5 of total width-->
        <ColumnDefinition Width="3*" /><!--This will make any control in this column of grid take 3/5 of total width-->
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition MinHeight="30" />
    </Grid.RowDefinitions>

    <TextBlock Grid.Column="0" Grid.Row="0">Your text block a:</TextBlock>
    <TextBlock Grid.Column="1" Grid.Row="0">Your text block b:</TextBlock>
</Grid>

grep from tar.gz without extracting [faster one]

If this is really slow, I suspect you're dealing with a large archive file. It's going to uncompress it once to extract the file list, and then uncompress it N times--where N is the number of files in the archive--for the grep. In addition to all the uncompressing, it's going to have to scan a fair bit into the archive each time to extract each file. One of tar's biggest drawbacks is that there is no table of contents at the beginning. There's no efficient way to get information about all the files in the archive and only read that portion of the file. It essentially has to read all of the file up to the thing you're extracting every time; it can't just jump to a filename's location right away.

The easiest thing you can do to speed this up would be to uncompress the file first (gunzip file.tar.gz) and then work on the .tar file. That might help enough by itself. It's still going to loop through the entire archive N times, though.

If you really want this to be efficient, your only option is to completely extract everything in the archive before processing it. Since your problem is speed, I suspect this is a giant file that you don't want to extract first, but if you can, this will speed things up a lot:

tar zxf file.tar.gz
for f in hopefullySomeSubdir/*; do
  grep -l "string" $f
done

Note that grep -l prints the name of any matching file, quits after the first match, and is silent if there's no match. That alone will speed up the grepping portion of your command, so even if you don't have the space to extract the entire archive, grep -l will help. If the files are huge, it will help a lot.

How to increase the Java stack size?

I assume you calculated the "depth of 1024" by the recurring lines in the stack trace?

Obviously, the stack trace array length in Throwable seems to be limited to 1024. Try the following program:

public class Test {

    public static void main(String[] args) {

        try {
            System.out.println(fact(1 << 15));
        }
        catch (StackOverflowError e) {
            System.err.println("true recursion level was " + level);
            System.err.println("reported recursion level was " +
                               e.getStackTrace().length);
        }
    }

    private static int level = 0;
    public static long fact(int n) {
        level++;
        return n < 2 ? n : n * fact(n - 1);
    }
}

How to list only files and not directories of a directory Bash?

ls -p | grep -v /

ls -p lets you show / after the folder name, which acts as a tag for you to remove.

Html helper for <input type="file" />

This is a little hacky I guess, but it results in the correct validation attributes etc being applied

@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))

Change the background color of a row in a JTable

One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:

static class MyTableModel extends DefaultTableModel {

    List<Color> rowColours = Arrays.asList(
        Color.RED,
        Color.GREEN,
        Color.CYAN
    );

    public void setRowColour(int row, Color c) {
        rowColours.set(row, c);
        fireTableRowsUpdated(row, row);
    }

    public Color getRowColour(int row) {
        return rowColours.get(row);
    }

    @Override
    public int getRowCount() {
        return 3;
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public Object getValueAt(int row, int column) {
        return String.format("%d %d", row, column);
    }
}

Note that setRowColour calls fireTableRowsUpdated; this will cause just that row of the table to be updated.

The renderer can get the model from the table:

static class MyTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        MyTableModel model = (MyTableModel) table.getModel();
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(model.getRowColour(row));
        return c;
    }
}

Changing a row's colour would be as simple as:

model.setRowColour(1, Color.YELLOW);

Chart.js - Formatting Y axis

I had the same problem, I think in Chart.js 2.x.x the approach is slightly different like below.

ticks: {
    callback: function(label, index, labels) {
        return label/1000+'k';
    }
}

More in details

var options = {
    scales: {
        yAxes: [
            {
                ticks: {
                    callback: function(label, index, labels) {
                        return label/1000+'k';
                    }
                },
                scaleLabel: {
                    display: true,
                    labelString: '1k = 1000'
                }
            }
        ]
    }
}

How to set JAVA_HOME for multiple Tomcat instances?

If you are a Windows user, put the content below in a setenv.bat file that you must create in Tomcat bin directory.

set JAVA_HOME=C:\Program Files\Java\jdk1.6.x

If you are a Linux user, put the content below in a setenv.sh file that you must create in Tomcat bin directory.

JAVA_HOME=/usr/java/jdk1.6.x

How to create a temporary directory/folder in Java?

Well, "createTempFile" actually creates the file. So why not just delete it first, and then do the mkdir on it?

Android list view inside a scroll view

Done after lots of R&D:

fragment_one.xml should looks like:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollViewParent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="400dip" >

            <ListView
                android:id="@+id/listView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <View
                android:id="@+id/customView"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="@android:color/transparent" />
        </RelativeLayout>

        <!-- Your other elements are here -->

    </LinearLayout>

</ScrollView>

Your Java class of FragmentOne.java looks like:

private ListView listView;
private View customView

onCreateView

listView = (ListView) rootView.findViewById(R.id.listView);
scrollViewParent = (ScrollView)rootView.findViewById(R.id.scrollViewParent);
customView = (View)rootView.findViewById(R.id.customView);

customView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        // Disallow ScrollView to intercept touch events.
                        scrollViewParent.requestDisallowInterceptTouchEvent(true);
                        // Disable touch on transparent view
                        return false;

                    case MotionEvent.ACTION_UP:
                        // Allow ScrollView to intercept touch events.
                        scrollViewParent.requestDisallowInterceptTouchEvent(false);
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        scrollViewParent.requestDisallowInterceptTouchEvent(true);
                        return false;

                    default:
                        return true;
                }
            }
        });

Eclipse doesn't stop at breakpoints

Breakpoints have seemed to work and not-work on the versions of Eclipse I've used the last couple years. Currently I'm using Juno and just experienced breakpoints-not-working again. The solutions above, although good ones, didn't work in my case.

Here's what worked in my case:

  1. deleted the project

  2. check it back out from svn

  3. import it into Eclipse again

  4. run "mvn eclipse:eclipse"

Since the project is also a Groovy/Http-bulder/junit-test project, I had to:

  1. convert the project from Java to Groovy

  2. add /src/test/groovy to the Java Build Path (Source folders on build path)

  3. include "**/*.groovy" on the Java Build Path for /src/test/groovy

If table exists drop table then create it, if it does not exist just create it

Well... Huh. For years nobody mentioned one subtle thing.

Despite DROP TABLE IF EXISTS `bla`; CREATE TABLE `bla` ( ... ); seems reasonable, it leads to a situation when old table is already gone and new one has not been yet created: some client may try to access subject table right at this moment.

The better way is to create brand new table and swap it with an old one (table contents are lost):

CREATE TABLE `bla__new` (id int); /* if not ok: terminate, report error */
RENAME TABLE `bla__new` to `bla`; /* if ok: terminate, report success */
RENAME TABLE `bla` to `bla__old`, `bla__new` to `bla`;
DROP TABLE IF EXISTS `bla__old`;
  • You should check the result of CREATE ... and do not continue in case of error, because failure means that other thread didn't finish the same script: either because it crashed in the middle or just didn't finish yet -- it's a good idea to inspect things by yourself.
  • Then, you should check the result of first RENAME ... and do not continue in case of success: whole operation is successfully completed; even more, running next RENAME ... can (and will) be unsafe if another thread has already started same sequence (it's better to cover this case than not to cover, see locking note below).
  • Second RENAME ... atomically replaces table definition, refer to MySQL manual for details.
  • At last, DROP ... just cleans up the old table, obviously.

Wrapping all statements with something like SELECT GET_LOCK('__upgrade', -1); ... DO RELEASE_LOCK('__upgrade'); allows to just invoke all statements sequentially without error checking, but I don't think it's a good idea: complexity increases and locking functions in MySQL aren't safe for statement-based replication.

If the table data should survive table definition upgrade... For general case it's far more complex story about comparing table definitions to find out differences and produce proper ALTER ... statement, which is not always possible automatically, e.g. when columns are renamed.

Side note 1: You can deal with views using the same approach, in this case CREATE/DROP TABLE merely transforms to CREATE/DROP VIEW while RENAME TABLE remains unchanged. In fact you can even turn table into view and vice versa.

CREATE VIEW `foo__new` as ...; /* if not ok: terminate, report error */
RENAME TABLE `foo__new` to `foo`; /* if ok: terminate, report success */
RENAME TABLE `foo` to `foo__old`, `foo__new` to `foo`;
DROP VIEW IF EXISTS `foo__old`;

Side note 2: MariaDB users should be happy with CREATE OR REPLACE TABLE/VIEW, which already cares about subject problem and it's fine points.

Regex for numbers only

While non of the above solutions was fitting my purpose, this worked for me.

var pattern = @"^(-?[1-9]+\d*([.]\d+)?)$|^(-?0[.]\d*[1-9]+)$|^0$|^0.0$";
return Regex.Match(value, pattern, RegexOptions.IgnoreCase).Success;

Example of valid values: "3", "-3", "0", "0.0", "1.0", "0.7", "690.7", "0.0001", "-555", "945465464654"

Example of not valid values: "a", "", " ", ".", "-", "001", "00.2", "000.5", ".3", "3.", " -1", "--1", "-.1", "-0", "00099", "099"

change html input type by JS?

_x000D_
_x000D_
$(".show-pass").click(function (e) {_x000D_
    e.preventDefault();_x000D_
    var type = $("#signupform-password").attr('type');_x000D_
    switch (type) {_x000D_
        case 'password':_x000D_
        {_x000D_
            $("#signupform-password").attr('type', 'text');_x000D_
            return;_x000D_
        }_x000D_
        case 'text':_x000D_
        {_x000D_
            $("#signupform-password").attr('type', 'password');_x000D_
            return;_x000D_
        }_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" name="password" class="show-pass">
_x000D_
_x000D_
_x000D_

Creating a Shopping Cart using only HTML/JavaScript

For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (http://jquery.com/), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.

Example of your code then becomes;

function AddtoCart() {
  var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;

  $row = $("#Items td:first").clone(true);
  $cells = $row.find("td");

  $cells.get(0).html( len );

  $inp1 = $cells.get(1).find("input:first");
  $inp1.attr("id", $inp1.attr("id") + len).val("");

  $inp2 = $cells.get(2).find("input:first");
  $inp2.attr("id", $inp2.attr("id") + len).val("");

  $("#Items").append($row);
    }

I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.

I would use the libraries already created specifically for js shopping carts if I were you though.

To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?

How to export data from Spark SQL to CSV

Since Spark 2.X spark-csv is integrated as native datasource. Therefore, the necessary statement simplifies to (windows)

df.write
  .option("header", "true")
  .csv("file:///C:/out.csv")

or UNIX

df.write
  .option("header", "true")
  .csv("/var/out.csv")

Notice: as the comments say, it is creating the directory by that name with the partitions in it, not a standard CSV file. This, however, is most likely what you want since otherwise your either crashing your driver (out of RAM) or you could be working with a non distributed environment.

How to check whether an object has certain method/property?

It is an old question, but I just ran into it. Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case

public static bool HasMethod(this object objectToCheck, string methodName)
{
    try
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    }
    catch(AmbiguousMatchException)
    {
        // ambiguous means there is more than one result,
        // which means: a method with that name does exist
        return true;
    }
} 

Find object in list that has attribute equal to some value (that meets any condition)

You could also implement rich comparison via __eq__ method for your Test class and use in operator. Not sure if this is the best stand-alone way, but in case if you need to compare Test instances based on value somewhere else, this could be useful.

class Test:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        """To implement 'in' operator"""
        # Comparing with int (assuming "value" is int)
        if isinstance(other, int):
            return self.value == other
        # Comparing with another Test object
        elif isinstance(other, Test):
            return self.value == other.value

import random

value = 5

test_list = [Test(random.randint(0,100)) for x in range(1000)]

if value in test_list:
    print "i found it"

HTTP status code 0 - Error Domain=NSURLErrorDomain?

On gate way timeout, status will be zero on your error call back.

.error( function( data,status,headers,config){
    console.log(status) 
 }

HTTP status codes

Convert a string representation of a hex dump to a byte array using Java?

In android ,if you are working with hex, you can try okio.

simple usage:

byte[] bytes = ByteString.decodeHex("c000060000").toByteArray();

and result will be

[-64, 0, 6, 0, 0]

jQuery Button.click() event is triggered twice

This can as well be triggered by having both input and label inside the element with click listener.

You click on the label, which triggers a click event and as well another click event on the input for the label. Both events bubble to your element.

See this pen of a fancy CSS-only toggle: https://codepen.io/stepanh/pen/WaYzzO

Note: This is not jQuery specific, native listener is triggered 2x as well as shown in the pen.

How to move files from one git repo to another (not a clone), preserving history

Having tried various approaches to move a file or folder from one Git repository to another, the only one which seems to work reliably is outlined below.

It involves cloning the repository you want to move the file or folder from, moving that file or folder to the root, rewriting Git history, cloning the target repository and pulling the file or folder with history directly into this target repository.

Stage One

  1. Make a copy of repository A as the following steps make major changes to this copy which you should not push!

    git clone --branch <branch> --origin origin --progress \
      -v <git repository A url>
    # eg. git clone --branch master --origin origin --progress \
    #   -v https://username@giturl/scm/projects/myprojects.git
    # (assuming myprojects is the repository you want to copy from)
    
  2. cd into it

    cd <git repository A directory>
    #  eg. cd /c/Working/GIT/myprojects
    
  3. Delete the link to the original repository to avoid accidentally making any remote changes (eg. by pushing)

    git remote rm origin
    
  4. Go through your history and files, removing anything that is not in directory 1. The result is the contents of directory 1 spewed out into to the base of repository A.

    git filter-branch --subdirectory-filter <directory> -- --all
    # eg. git filter-branch --subdirectory-filter subfolder1/subfolder2/FOLDER_TO_KEEP -- --all
    
  5. For single file move only: go through what's left and remove everything except the desired file. (You may need to delete files you don't want with the same name and commit.)

    git filter-branch -f --index-filter \
    'git ls-files -s | grep $'\t'FILE_TO_KEEP$ |
    GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
    git update-index --index-info && \
    mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE || echo "Nothing to do"' --prune-empty -- --all
    # eg. FILE_TO_KEEP = pom.xml to keep only the pom.xml file from FOLDER_TO_KEEP
    

Stage Two

  1. Cleanup step

    git reset --hard
    
  2. Cleanup step

    git gc --aggressive
    
  3. Cleanup step

    git prune
    

You may want to import these files into repository B within a directory not the root:

  1. Make that directory

    mkdir <base directory>             eg. mkdir FOLDER_TO_KEEP
    
  2. Move files into that directory

    git mv * <base directory>          eg. git mv * FOLDER_TO_KEEP
    
  3. Add files to that directory

    git add .
    
  4. Commit your changes and we’re ready to merge these files into the new repository

    git commit
    

Stage Three

  1. Make a copy of repository B if you don’t have one already

    git clone <git repository B url>
    # eg. git clone https://username@giturl/scm/projects/FOLDER_TO_KEEP.git
    

    (assuming FOLDER_TO_KEEP is the name of the new repository you are copying to)

  2. cd into it

    cd <git repository B directory>
    #  eg. cd /c/Working/GIT/FOLDER_TO_KEEP
    
  3. Create a remote connection to repository A as a branch in repository B

    git remote add repo-A-branch <git repository A directory>
    # (repo-A-branch can be anything - it's just an arbitrary name)
    
    # eg. git remote add repo-A-branch /c/Working/GIT/myprojects
    
  4. Pull from this branch (containing only the directory you want to move) into repository B.

    git pull repo-A-branch master --allow-unrelated-histories
    

    The pull copies both files and history. Note: You can use a merge instead of a pull, but pull works better.

  5. Finally, you probably want to clean up a bit by removing the remote connection to repository A

    git remote rm repo-A-branch
    
  6. Push and you’re all set.

    git push
    

Email and phone Number Validation in android

try this:

extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));

private boolean validateMobile()    {   

    String mobile =extMobileNo.getText().toString().trim();
    if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )

    {
            inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
        requestFocus(extMobileNo);
        return false;
    }

    else {
        inputLayoutMobile.setErrorEnabled(false);
    }

    return true;
}

private static boolean isValidMobile(String mobile)
{
    return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}

"No cached version... available for offline mode."

In my case I get the same error title could not resolve all dependencies for configuration

However suberror said, it was due to a linting jar not loaded with its url given saying status 502 received, I ran the deployment command again, this time it succeeded.

String strip() for JavaScript?

A better polyfill from the MDN that supports removal of BOM and NBSP:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string) instead. That being said, if you are targeting an older environment without native .trim() support, you are likely to have more important performance issues to deal with.

Ping site and return result in PHP

Using shell_exec:

<?php
$output = shell_exec('ping -c1 google.com');
echo "<pre>$output</pre>";
?>

IE 8: background-size fix

I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:

background: no-repeat center center fixed\0/; /* IE8 HACK */

This has solved the frozen links problem for me.

How to run JUnit test cases from the command line

If your project is Maven-based you can run all test-methods from test-class CustomTest which belongs to module 'my-module' using next command:

mvn clean test -pl :my-module -Dtest=CustomTest

Or run only 1 test-method myMethod from test-class CustomTest using next command:

mvn clean test -pl :my-module -Dtest=CustomTest#myMethod

For this ability you need Maven Surefire Plugin v.2.7.3+ and Junit 4. More details is here: http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html

how to find seconds since 1970 in java

java.time

Using the java.time framework built into Java 8 and later.

import java.time.LocalDate;
import java.time.ZoneId;

int year = 2011;
int month = 10;
int day = 1;
int date = LocalDate.of(year, month, day);

date.atStartOfDay(ZoneId.of("UTC")).toEpochSecond; # Long = 1317427200

How to handle the click event in Listview in android?

Error is coming in your code from this statement as you said

Intent intent = new Intent(context, SendMessage.class);

This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent

android.content.Intent.Intent(Context packageContext, Class<?> cls)

You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to

Intent intent = new Intent(MainActivity.this, SendMessage.class);

Also for sending your message from this MainActivity to SendMessage class please see below code

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
                startActivity(intent);
            }
        });

Please let me know if this helps you

EDIT:- If you are finding some issue to get the value of list do one thing declear your array list

ArrayList<ListEntry> members = new ArrayList<ListEntry>();

globally i.e. before oncreate and change your listener as below

 lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
                    Intent intent = new Intent(MainActivity.this, SendMessage.class);
                    intent.putExtra(EXTRA_MESSAGE, members.get(position));
                    startActivity(intent);
                }
            });

So your whole code will look as

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
        members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
        members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
        members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
        members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
        members.add(new ListEntry("BcxvBB","AcxvAA"));
        members.add(new ListEntry("BvBB","AcxsvAA"));
        members.add(new ListEntry("BcxvBB","AcxsvzAA"));
        members.add(new ListEntry("Bcxadv","AcsxvAA"));
        members.add(new ListEntry("BcxcxB","AcxsvAA"));
        ListView lv = (ListView)findViewById(R.id.listView1);
        Log.i("testTag","before start adapter");
        StringArrayAdapter ad = new StringArrayAdapter (members,this);
        Log.i("testTag","after start adapter");
        Log.i("testTag","set adapter");
        lv.setAdapter(ad);
        lv.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
                        Intent intent = new Intent(MainActivity.this, SendMessage.class);
                        intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
                        startActivity(intent);
                    }
                });
    }

Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.

Send email using java

The short answer - No.

The long answer - no, since the code relies on the presence of a SMTP server running on the local machine, and listening on port 25. The SMTP server (technically the MTA or Mail Transfer Agent) is responsible for communicating with the Mail User Agent (MUA, which in this case is the Java process) to receive outgoing emails.

Now, MTAs are typically responsible for receiving mails from users for a particular domain. So, for the domain gmail.com, it would be the Google mail servers that are responsible for authenticating mail user agents and hence transferring of mails to inboxes on the GMail servers. I'm not sure if GMail trusts open mail relay servers, but it is certainly not an easy task to perform authentication on behalf on Google, and then relay mail to the GMail servers.

If you read the JavaMail FAQ on using JavaMail to accessing GMail, you'll notice that the hostname and the port happen to be pointing to the GMail servers, and certainly not to localhost. If you intend to use your local machine, you'll need to perform either relaying or forwarding.

You'll probably need to understand the SMTP protocol in depth if you intend to get anywhere when it comes to SMTP. You can start with the Wikipedia article on SMTP, but any further progress will actually necessitate programming against a SMTP server.

href="tel:" and mobile numbers

I know the OP is asking about international country codes but for North America, you could use the following:

_x000D_
_x000D_
<a href="tel:+1-847-555-5555">1-847-555-5555</a>

<a href="tel:+18475555555">Click Here To Call Support 1-847-555-5555</a>
_x000D_
_x000D_
_x000D_

This might help you.

JavaScript for...in vs for

I'd use the different methods based on how I wanted to reference the items.

Use foreach if you just want the current item.

Use for if you need an indexer to do relative comparisons. (I.e. how does this compare to the previous/next item?)

I have never noticed a performance difference. I'd wait until having a performance issue before worrying about it.

How to use LINQ to select object with minimum or maximum property value

Solution with no extra packages:

var min = lst.OrderBy(i => i.StartDate).FirstOrDefault();
var max = lst.OrderBy(i => i.StartDate).LastOrDefault();

also you can wrap it into extension:

public static class LinqExtensions
{
    public static T MinBy<T, TProp>(this IEnumerable<T> source, Func<T, TProp> propSelector)
    {
        return source.OrderBy(propSelector).FirstOrDefault();
    }

    public static T MaxBy<T, TProp>(this IEnumerable<T> source, Func<T, TProp> propSelector)
    {
        return source.OrderBy(propSelector).LastOrDefault();
    }
}

and in this case:

var min = lst.MinBy(i => i.StartDate);
var max = lst.MaxBy(i => i.StartDate);

By the way... O(n^2) is not the best solution. Paul Betts gave fatster solution than my. But my is still LINQ solution and it's more simple and more short than other solutions here.

Update Row if it Exists Else Insert Logic with Entity Framework

Ladislav's answer was close but I had to made a couple of modifications to get this to work in EF6 (database-first). I extended my data context with my on AddOrUpdate method and so far this appears to be working well with detached objects:

using System.Data.Entity;

[....]

public partial class MyDBEntities {

  public void AddOrUpdate(MyDBEntities ctx, DbSet set, Object obj, long ID) {
      if (ID != 0) {
          set.Attach(obj);
          ctx.Entry(obj).State = EntityState.Modified;
      }
      else {
          set.Add(obj);
      }
  }
[....]

How to print SQL statement in codeigniter model

I read all answers here, but cannot get

echo $this->db->get_compiled_select();

to work, It gave me error like,

Call to protected method CI_DB_active_record::_compile_select() from context 'Welcome'in controllers on line xx

So i removed protected from the below line from file \system\database\DB_active_rec.php and it worked

protected function _compile_select($select_override = FALSE)

How to compile C++ under Ubuntu Linux?

you can use g++ --std=c++0x example.cpp -o example

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Push commits to another branch

when you pushing code to another branch just follow the below git command. Remember demo is my other branch name you can replace with your branch name.

git push origin master:demo

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

There are 3 ways to allow cross domain origin (excluding jsonp):

1) Set the header in the page directly using a templating language like PHP. Keep in mind there can be no HTML before your header or it will fail.

 <?php header("Access-Control-Allow-Origin: http://example.com"); ?>

2) Modify the server configuration file (apache.conf) and add this line. Note that "*" represents allow all. Some systems might also need the credential set. In general allow all access is a security risk and should be avoided:

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

3) To allow multiple domains on Apache web servers add the following to your config file

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(example.org|example.com)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

4) For development use only hack your browser and allow unlimited CORS using the Chrome Allow-Control-Allow-Origin extension

5) Disable CORS in Chrome: Quit Chrome completely. Open a terminal and execute the following. Just be cautious you are disabling web security:

open -a Google\ Chrome --args --disable-web-security --user-data-dir

Stack, Static, and Heap in C++

It's been said elaborately, just as "the short answer":

  • static variable (class)
    lifetime = program runtime (1)
    visibility = determined by access modifiers (private/protected/public)

  • static variable (global scope)
    lifetime = program runtime (1)
    visibility = the compilation unit it is instantiated in (2)

  • heap variable
    lifetime = defined by you (new to delete)
    visibility = defined by you (whatever you assign the pointer to)

  • stack variable
    visibility = from declaration until scope is exited
    lifetime = from declaration until declaring scope is exited


(1) more exactly: from initialization until deinitialization of the compilation unit (i.e. C / C++ file). Order of initialization of compilation units is not defined by the standard.

(2) Beware: if you instantiate a static variable in a header, each compilation unit gets its own copy.

How do I see the extensions loaded by PHP?

Running

php -m
will give you all the modules, and
php -i
will give you a lot more detailed information on what the current configuration.

How to connect to remote Oracle DB with PL/SQL Developer?

I am facing to this problem so many times till I have 32bit PL/SQL Developer and 64bit Oracle DB or Oracle Client.

The solution is:

  1. install a 32bit client.
  2. set PLSQL DEV-Tools-Preferencies-Oracle Home to new 32bit client Home
  3. set PLSQL DEV-Tools-Preferencies-OCI to new 32 bit home /bin/oci.dll For example: c:\app\admin\product\11.2.0\client_1\BIN\oci.dll
  4. Save and restart PLSQL DEV.

Edit or create a TNSNAMES.ORA file in c:\app\admin\product\11.2.0\client_1\NETWORK\admin folder like mentioned above.

Try with TNSPING in console like

C:>tnsping ORCL

If still have problem, set the TNS_ADMIN Enviroment properties value pointing to the folder where the TNSNAMES.ORA located, like: c:\app\admin\product\11.2.0\client_1\network\admin

Using python's mock patch.object to change the return value of a method called within another method

Let me clarify what you're talking about: you want to test Foo in a testcase, which calls external method uses_some_other_method. Instead of calling the actual method, you want to mock the return value.

class Foo:
    def method_1():
       results = uses_some_other_method()
    def method_n():
       results = uses_some_other_method()

Suppose the above code is in foo.py and uses_some_other_method is defined in module bar.py. Here is the unittest:

import unittest
import mock

from foo import Foo


class TestFoo(unittest.TestCase):

    def setup(self):
        self.foo = Foo()

    @mock.patch('foo.uses_some_other_method')
    def test_method_1(self, mock_method):
        mock_method.return_value = 3
        self.foo.method_1(*args, **kwargs)

        mock_method.assert_called_with(*args, **kwargs)

If you want to change the return value every time you passed in different arguments, mock provides side_effect.

How to set javascript variables using MVC4 with Razor

I've been looking into this approach:

function getServerObject(serverObject) {
  if (typeof serverObject === "undefined") {
    return null;
  }
  return serverObject;
}

var itCameFromDotNet = getServerObject(@dotNetObject);

To me this seems to make it safer on the JS side... worst case you end up with a null variable.

check if a number already exist in a list in python

If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.

s = set()
if number1 not in s:
  s.add(number1)
if number2 not in s:
  s.add(number2)
...
s = sorted(s)  #Now a list in ascending order

Html.fromHtml deprecated in Android N

update: as @Andy mentioned below Google has created HtmlCompat which can be used instead of the method below. Add this dependency implementation 'androidx.core:core:1.0.1 to the build.gradle file of your app. Make sure you use the latest version of androidx.core:core.

This allows you to use:

HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY);

You can read more about the different flags on the HtmlCompat-documentation

original answer: In Android N they introduced a new Html.fromHtml method. Html.fromHtml now requires an additional parameter, named flags. This flag gives you more control about how your HTML gets displayed.

On Android N and above you should use this new method. The older method is deprecated and may be removed in the future Android versions.

You can create your own Util-method which will use the old method on older versions and the newer method on Android N and above. If you don't add a version check your app will break on lower Android versions. You can use this method in your Util class.

@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
    if(html == null){
        // return an empty spannable if the html is null
        return new SpannableString("");
    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        // FROM_HTML_MODE_LEGACY is the behaviour that was used for versions below android N
        // we are using this flag to give a consistent behaviour
        return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
    } else {
        return Html.fromHtml(html);
    }
}

You can convert the HTML.FROM_HTML_MODE_LEGACY into an additional parameter if you want. This gives you more control about it which flag to use.

You can read more about the different flags on the Html class documentation

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Another option is to ask IDEA to behave like eclipse with eclipse shortcut keys. You can use all eclipse shortcuts by enabling this.

Here are the steps:

1- With IDEA open, press Control + `. Following options will be popped up.

enter image description here

2- Select Keymap. You will see another pop-up. Select Eclipse there.

enter image description here

3- Now press Ctrl + Shift + O. You are done!

Measuring the distance between two coordinates in PHP

Not long ago I wrote an example of the haversine formula, and published it on my website:

/**
 * Calculates the great-circle distance between two points, with
 * the Haversine formula.
 * @param float $latitudeFrom Latitude of start point in [deg decimal]
 * @param float $longitudeFrom Longitude of start point in [deg decimal]
 * @param float $latitudeTo Latitude of target point in [deg decimal]
 * @param float $longitudeTo Longitude of target point in [deg decimal]
 * @param float $earthRadius Mean earth radius in [m]
 * @return float Distance between points in [m] (same as earthRadius)
 */
function haversineGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
  // convert from degrees to radians
  $latFrom = deg2rad($latitudeFrom);
  $lonFrom = deg2rad($longitudeFrom);
  $latTo = deg2rad($latitudeTo);
  $lonTo = deg2rad($longitudeTo);

  $latDelta = $latTo - $latFrom;
  $lonDelta = $lonTo - $lonFrom;

  $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
    cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
  return $angle * $earthRadius;
}

? Note that you get the distance back in the same unit as you pass in with the parameter $earthRadius. The default value is 6371000 meters so the result will be in [m] too. To get the result in miles, you could e.g. pass 3959 miles as $earthRadius and the result would be in [mi]. In my opinion it is a good habit to stick with the SI units, if there is no particular reason to do otherwise.

Edit:

As TreyA correctly pointed out, the Haversine formula has weaknesses with antipodal points because of rounding errors (though it is stable for small distances). To get around them, you could use the Vincenty formula instead.

/**
 * Calculates the great-circle distance between two points, with
 * the Vincenty formula.
 * @param float $latitudeFrom Latitude of start point in [deg decimal]
 * @param float $longitudeFrom Longitude of start point in [deg decimal]
 * @param float $latitudeTo Latitude of target point in [deg decimal]
 * @param float $longitudeTo Longitude of target point in [deg decimal]
 * @param float $earthRadius Mean earth radius in [m]
 * @return float Distance between points in [m] (same as earthRadius)
 */
public static function vincentyGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
  // convert from degrees to radians
  $latFrom = deg2rad($latitudeFrom);
  $lonFrom = deg2rad($longitudeFrom);
  $latTo = deg2rad($latitudeTo);
  $lonTo = deg2rad($longitudeTo);

  $lonDelta = $lonTo - $lonFrom;
  $a = pow(cos($latTo) * sin($lonDelta), 2) +
    pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
  $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);

  $angle = atan2(sqrt($a), $b);
  return $angle * $earthRadius;
}

Syntax of for-loop in SQL Server

There is no for-loop, only the while-loop:

DECLARE @i int = 0

WHILE @i < 20
BEGIN
    SET @i = @i + 1
    /* do some work */
END

Detect HTTP or HTTPS then force HTTPS in JavaScript

I have just had all the script variations tested by Pui Cdm, included answers above and many others using php, htaccess, server configuration, and Javascript, the results are that the script

<script type="text/javascript">        
function showProtocall() {
        if (window.location.protocol != "https") {
            window.location = "https://" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
            window.location.reload();
        }
    }
    showProtocall();
</script> 

provided by vivek-srivastava works best and you can add further security in java script.

jQuery UI Slider (setting programmatically)

I wanted to update slider as well as the inputbox. For me following is working

a.slider('value',1520);
$("#labelAID").val(1520);

where a is object as following.

 var a= $( "<div id='slider' style='width:200px;margin-left:20px;'></div>" ).insertAfter( "#labelAID" ).slider({
            min: 0,
            max: 2000,
            range: "min",
            value: 111,
            slide: function( event, ui ) {

                $("#labelAID").val(ui.value    );
            }
        });

        $( "#labelAID" ).keyup(function() {
            a.slider( "value",$( "#labelAID" ).val()  );
        });

Running a simple shell script as a cronjob

Try,

 # cat test.sh
 #!/bin/bash
 /bin/touch file.txt

cron as:

 * * * * * /bin/sh /home/myUser/scripts/test.sh

And you can confirm this by:

 # tailf /var/log/cron

In SQL, how can you "group by" in ranges?

Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.

Here are the correct versions of both of them on SQL Server 2000.

select t.range as [score range], count(*) as [number of occurences]
from (
  select case  
    when score between 0 and 9 then ' 0- 9'
    when score between 10 and 19 then '10-19'
    else '20-99' end as range
  from scores) t
group by t.range

or

select t.range as [score range], count(*) as [number of occurrences]
from (
      select user_id,
         case when score >= 0 and score< 10 then '0-9'
         when score >= 10 and score< 20 then '10-19'
         else '20-99' end as range
     from scores) t
group by t.range

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I would recommend giving the LI a background-image and padding-left. The list-style-image attribute is flakey in cross-browser environments, and adding an extra element, such as a span, is unneccessary. So your code would end up looking something like this:

li {
  background:url(../images/bullet.png) 0 0 no-repeat;
  list-style:none;
  padding-left:10px;
}

Sum all the elements java arraylist

Using Java 8 streams:

double sum = m.stream()
    .mapToDouble(a -> a)
    .sum();

System.out.println(sum);