Programs & Examples On #Auto populating

How can I use JSON data to populate the options of a select box?

Take a look at JQuery view engine and just load the array into a dropdown:

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
          // Assumption is that API returned something like:["North","West","South","East"];
          $('#myselect').view(json);
    }
});

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown

How can I find last row that contains data in a specific column?

You should use the .End(xlup) but instead of using 65536 you might want to use:

sheetvar.Rows.Count

That way it works for Excel 2007 which I believe has more than 65536 rows

Inheriting constructors

If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:

class A
{
    public: 
        explicit A(int x) {}
};

class B: public A
{
     using A::A;
};

This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.

Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.

makefile execute another target

Actually you are right: it runs another instance of make. A possible solution would be:

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : clean clearscr all

clearscr:
    clear

By calling make fresh you get first the clean target, then the clearscreen which runs clear and finally all which does the job.

EDIT Aug 4

What happens in the case of parallel builds with make’s -j option? There's a way of fixing the order. From the make manual, section 4.2:

Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites

The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).

Hence the makefile becomes

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : | clean clearscr all

clearscr:
    clear

EDIT Dec 5

It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.

log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)

install:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  command1  # this line will be a subshell
  command2  # this line will be another subshell
  @command3  # Use `@` to hide the command line
  $(call log_error, "It works, yey!")

uninstall:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  ....
  $(call log_error, "Nuked!")

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

What do the icons in Eclipse mean?

This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.

Latest: JDT Icons

2019-06: JDT Icons

2019-03: JDT Icons

2018-12: JDT Icons

2018-09: JDT Icons

Photon: JDT Icons

Oxygen: JDT Icons

Neon: JDT Icons

Mars: JDT Icons

Luna: JDT Icons

Kepler: JDT Icons

Juno: JDT Icons

Indigo: JDT Icons

Helios: JDT Icons

There are also some CDT icons at the bottom of this help page.

If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.

Android Studio cannot resolve R in imported project?

File -> invalidate caches

then

Restart application

Creating a SOAP call using PHP with an XML body

First off, you have to specify you wish to use Document Literal style:

$client = new SoapClient(NULL, array(
    'location' => 'https://example.com/path/to/service',
    'uri' => 'http://example.com/wsdl',
    'trace' => 1,
    'use' => SOAP_LITERAL)
);

Then, you need to transform your data into a SoapVar; I've written a simple transform function:

function soapify(array $data)
{
        foreach ($data as &$value) {
                if (is_array($value)) {
                        $value = soapify($value);
                }
        }

        return new SoapVar($data, SOAP_ENC_OBJECT);
}

Then, you apply this transform function onto your data:

$data = soapify(array(
    'Acquirer' => array(
        'Id' => 'MyId',
        'UserId' => 'MyUserId',
        'Password' => 'MyPassword',
    ),
));

Finally, you call the service passing the Data parameter:

$method = 'Echo';

$result = $client->$method(new SoapParam($data, 'Data'));

How to convert a GUID to a string in C#?

In Visual Basic, you can call a parameterless method without the braces (()). In C#, they're mandatory. So you should write:

String guid = System.Guid.NewGuid().ToString();

Without the braces, you're assigning the method itself (instead of its result) to the variable guid, and obviously the method cannot be converted to a String, hence the error.

Oracle 'Partition By' and 'Row_Number' keyword

I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.

Laravel 5.4 create model, controller and migration in single artisan command

Just Try this command on your terminal

php artisan make:model Todo -mcr

Below the output and your Model, Controller with Resource and Migration file will create...

Model created successfully.
Created Migration: 2019_12_25_105305_create_todos_table
Controller created successfully.

Align the form to the center in Bootstrap 4

All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

A sample form

enter image description here

HTML

<div class="container-fluid h-100 bg-light text-dark">
  <div class="row justify-content-center align-items-center">
    <h1>Form</h1>    
  </div>
  <hr/>
  <div class="row justify-content-center align-items-center h-100">
    <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
      <form action="">
        <div class="form-group">
          <select class="form-control">
                    <option>Option 1</option>
                    <option>Option 2</option>
                  </select>
        </div>
        <div class="form-group">
          <input type="text" class="form-control" />
        </div>
        <div class="form-group text-center">
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 1
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 2
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
  </label>
          </div>
        </div>
        <div class="form-group">
          <div class="container">
            <div class="row">
              <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
              <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
            </div>
          </div>
        </div>

      </form>
    </div>
  </div>
</div>

Link to CodePen

https://codepen.io/anjanasilva/pen/WgLaGZ

I hope this helps someone. Thank you.

How do I make a list of data frames?

This isn't related to your question, but you want to use = and not <- within the function call. If you use <-, you'll end up creating variables y1 and y2 in whatever environment you're working in:

d1 <- data.frame(y1 <- c(1, 2, 3), y2 <- c(4, 5, 6))
y1
# [1] 1 2 3
y2
# [1] 4 5 6

This won't have the seemingly desired effect of creating column names in the data frame:

d1
#   y1....c.1..2..3. y2....c.4..5..6.
# 1                1                4
# 2                2                5
# 3                3                6

The = operator, on the other hand, will associate your vectors with arguments to data.frame.

As for your question, making a list of data frames is easy:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))
my.list <- list(d1, d2)

You access the data frames just like you would access any other list element:

my.list[[1]]
#   y1 y2
# 1  1  4
# 2  2  5
# 3  3  6

How to reset settings in Visual Studio Code?

This may be overkill, but it seemed to work for me:

#!/bin/sh

rm -rfv "$HOME/.vscode"
rm -rfv "$HOME/Library/Application Support/Code"
rm -rfv "$HOME/Library/Caches/com.microsoft.VSCode"
rm -rfv "$HOME/Library/Saved Application State/com.microsoft.VSCode.savedState"

After I ran that, and restarted VSC, it showed the the "Welcome" screen, which I took to mean that it was starting from scratch.

What's a good IDE for Python on Mac OS X?

I've searched on Google for an app like this for a while, and I've found only options with heavy and ugly interfaces.

Then I opened Mac App Store and found CodeRunner. Very nice and clean interface. Support many languages like Python, Lua, Perl, Ruby, Javascript, etc. The price is U$10, but it's worth it!

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

How can I format DateTime to web UTC format?

string foo = yourDateTime.ToUniversalTime()
                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

How to re-index all subarray elements of a multidimensional array?

Use array_values to reset keys

foreach($input as &$val) {
   $val = array_values($val);
}

http://php.net/array_values

How to send a Post body in the HttpClient request in Windows Phone 8?

This depends on what content do you have. You need to initialize your requestMessage.Content property with new HttpContent. For example:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

where content is your encoded content. You also should include correct Content-type header.

UPDATE:

Oh, it can be even nicer (from this answer):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

How can I load webpage content into a div on page load?

This is possible to do without an iframe specifically. jQuery is utilised since it's mentioned in the title.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Load remote content into object element</title>
  </head>
  <body>
    <div id="siteloader"></div>?
    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script>
      $("#siteloader").html('<object data="http://tired.com/">');
    </script>
  </body>
</html>

Recover from git reset --hard?

I ran into same issue and I was almost going insane....initially i committed the project and merged.. later when i try running git push --set-upstream origin master i was getting this error

  fatal: refusing to merge unrelated histories

so i ran git reset --hard HEAD and it deleted a 3 weeks project but these few commands below save the day:

git reset HEAD@{1}         //this command unstage changes after reset
git fsck --lost-found      //I got the dangling commit fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b
git show <dangling commit something like-> fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b>
git rebase fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b

hope this helps

how to define variable in jquery

in jquery we have to use selector($) to declare variables

var test=$("<%=ddl.ClientId%>");

here we can get the id of drop down to j query variable

When to encode space to plus (+) or %20?

http://www.example.com/some/path/to/resource?param1=value1

The part before the question mark must use % encoding (so %20 for space), after the question mark you can use either %20 or + for a space. If you need an actual + after the question mark use %2B.

How to time Java program execution speed

You get the current system time, in milliseconds:

final long startTime = System.currentTimeMillis();

Then you do what you're going to do:

for (int i = 0; i < length; i++) {
  // Do something
}

Then you see how long it took:

final long elapsedTimeMillis = System.currentTimeMillis() - startTime;

How to get all Errors from ASP.Net MVC modelState?

In addition, ModelState.Values.ErrorMessage may be empty, but ModelState.Values.Exception.Message may indicate an error.

assigning column names to a pandas series

If you have a pd.Series object x with index named 'Gene', you can use reset_index and supply the name argument:

df = x.reset_index(name='count')

Here's a demo:

x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'

df = x.reset_index(name='count')

print(df)

   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also try this.

consider today's date '28 Dec 2018'(for example)

 this.date = new Date().toISOString().slice(0,10); 

new Date() we get as: Fri Dec 28 2018 11:44:33 GMT+0530 (India Standard Time)

toISOString will convert to : 2018-12-28T06:15:27.479Z

slice(0,10) we get only first 10 characters as date which contains yyyy-mm-dd : 2018-12-28.

Error in spring application context schema

I also faced this problem and fixed it by removing version part from the XSD name.

http://www.springframework.org/schema/beans/spring-beans-4.2.xsd to http://www.springframework.org/schema/beans/spring-beans.xsd

Versions less XSD's are mapped to the current version of the framework used in the application.

SQL Server AS statement aliased column within WHERE statement

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx

T-SQL XOR Operator

From your comment:

Example: WHERE (Note is null) ^ (ID is null)

you could probably try:

where
   (case when Note is null then 1 else 0 end)
 <>(case when ID is null then 1 else 0 end)

How to get complete current url for Cakephp

I prefer this, because if I don't mention "request" word, my IDE gives warning.

<?php echo $this->request->here; ?>

API Document: class-CakeRequest


Edit: To clarify all options

Current URL: http://example.com/en/controller/action/?query=12

// Router::url(null, true)
http://example.com/en/controller/action/

// Router::url(null, false)
/en/controller/action/

// $this->request->here
/en/controller/action/

// $this->request->here()
/en/controller/action/?query=12

// $this->request->here(false)
/en/controller/action/?query=12

// $this->request->url
en/controller/action

// $_SERVER["REQUEST_URI"]
/en/controller/action/?query=12

// strtok($_SERVER["REQUEST_URI"],'?');
/en/controller/action/

VB.NET - Click Submit Button on Webbrowser page

You could try giving an ID to the form, in order to get ahold of it, and then call form.submit() from a Javascript call.

What is the way of declaring an array in JavaScript?

If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length); is appropriate.

eg-

String.prototype.repeat= function(n){
    n= n || 1;
    return Array(n+1).join(this);
}

Check if ADODB connection is open

This is an old topic, but in case anyone else is still looking...

I was having trouble after an undock event. An open db connection saved in a global object would error, even after reconnecting to the network. This was due to the TCP connection being forcibly terminated by remote host. (Error -2147467259: TCP Provider: An existing connection was forcibly closed by the remote host.)

However, the error would only show up after the first transaction was attempted. Up to that point, neither Connection.State nor Connection.Version (per solutions above) would reveal any error.

So I wrote the small sub below to force the error - hope it's useful.

Performance testing on my setup (Access 2016, SQL Svr 2008R2) was approx 0.5ms per call.

Function adoIsConnected(adoCn As ADODB.Connection) As Boolean

    '----------------------------------------------------------------
    '#PURPOSE: Checks whether the supplied db connection is alive and
    '          hasn't had it's TCP connection forcibly closed by remote
    '          host, for example, as happens during an undock event
    '#RETURNS: True if the supplied db is connected and error-free, 
    '          False otherwise
    '#AUTHOR:  Belladonna
    '----------------------------------------------------------------

    Dim i As Long
    Dim cmd As New ADODB.Command

    'Set up SQL command to return 1
    cmd.CommandText = "SELECT 1"
    cmd.ActiveConnection = adoCn

    'Run a simple query, to test the connection
    On Error Resume Next
    i = cmd.Execute.Fields(0)
    On Error GoTo 0

    'Tidy up
    Set cmd = Nothing

    'If i is 1, connection is open
    If i = 1 Then
        adoIsConnected = True
    Else
        adoIsConnected = False
    End If

End Function

How to Read from a Text File, Character by Character in C++

    //Variables
    char END_OF_FILE = '#';
    char singleCharacter;

    //Get a character from the input file
    inFile.get(singleCharacter);

    //Read the file until it reaches #
    //When read pointer reads the # it will exit loop
    //This requires that you have a # sign as last character in your text file

    while (singleCharacter != END_OF_FILE)
    {
         cout << singleCharacter;
         inFile.get(singleCharacter);
    }

   //If you need to store each character, declare a variable and store it
   //in the while loop.

How do you implement a circular buffer in C?

Can you enumerate the types needed at the time you code up the buffer, or do you need to be able to add types at run time via dynamic calls? If the former, then I would create the buffer as a heap-allocated array of n structs, where each struct consists of two elements: an enum tag identifying the data type, and a union of all the data types. What you lose in terms of extra storage for small elements, you make up in terms of not having to deal with allocation/deallocation and the resulting memory fragmentation. Then you just need to keep track of the start and end indices that define the head and tail elements of the buffer, and make sure to compute mod n when incrementing/decrementing the indices.

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

Consider Android Development:

IDE: Eclipse etc..

Library: android.app.Activity library (Class with all code)

API: Interface basically all functions with which we call

SDK: The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android (----tools - DDMS,Emulator ----platforms - Android OS versions, ----platform-tools - ADB, ----API docs)

ToolKit: Could be ADT Bundle

Framework: Big library but more of architecture-oriented

C# - Multiple generic types in one list

I have also used a non-generic version, using the new keyword:

public interface IMetadata
{
    Type DataType { get; }

    object Data { get; }
}

public interface IMetadata<TData> : IMetadata
{
    new TData Data { get; }
}

Explicit interface implementation is used to allow both Data members:

public class Metadata<TData> : IMetadata<TData>
{
    public Metadata(TData data)
    {
       Data = data;
    }

    public Type DataType
    {
        get { return typeof(TData); }
    }

    object IMetadata.Data
    {
        get { return Data; }
    }

    public TData Data { get; private set; }
}

You could derive a version targeting value types:

public interface IValueTypeMetadata : IMetadata
{

}

public interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct
{

}

public class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct
{
    public ValueTypeMetadata(TData data) : base(data)
    {}
}

This can be extended to any kind of generic constraints.

Python update a key in dict if it doesn't exist

According to the above answers setdefault() method worked for me.

old_attr_name = mydict.setdefault(key, attr_name)
if attr_name != old_attr_name:
    raise RuntimeError(f"Key '{key}' duplication: "
                       f"'{old_attr_name}' and '{attr_name}'.")

Though this solution is not generic. Just suited me in this certain case. The exact solution would be checking for the key first (as was already advised), but with setdefault() we avoid one extra lookup on the dictionary, that is, though small, but still a performance gain.

Find the maximum value in a list of tuples in Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

Delete files in subfolder using batch script

Moved from the closed topic

del /s d:\test\archive*.txt

This should get you all of your text files

Alternatively,

I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.

Please test this on your system before using it though.

@echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION

REM ---------------------------
REM   *** EDIT VARIABLES BELOW ***
REM ---------------------------

set targetFolder=
REM targetFolder is the location you want to delete from    
REM ---------------------------
REM  *** DO NOT EDIT BELOW ***
REM ---------------------------

IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
  set "Subfolders[!Index!]=%%D"
  set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!

:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in: 
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start

:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end

:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end

:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit


REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)

If you change the

set targetFolder= 

to the folder you want you won't get prompted for the folder. *Remember when putting the base path in, the format does not include a '\' on the end. e.g. d:\test c:\temp

Hope this helps

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

I imported the new Apple WWDR Certificate that expires in 2023, but I was still getting problems and my developer certificates were showing the invalid issuer error.

In keychain access, go to View -> Show Expired Certificates, then in your login keychain highlight the expired WWDR Certificate and delete it. I also had the same expired certificate in my System keychain, so I deleted it from there too.(Important)

After deleting the expired cert from the login and System keychains, I was able to build for Distribution again.

Matplotlib - How to plot a high resolution graph?

For saving the graph:

matplotlib.rcParams['savefig.dpi'] = 300

For displaying the graph when you use plt.show():

matplotlib.rcParams["figure.dpi"] = 100

Just add them at the top

Is Task.Result the same as .GetAwaiter.GetResult()?

Task.GetAwaiter().GetResult() is preferred over Task.Wait and Task.Result because it propagates exceptions rather than wrapping them in an AggregateException. However, all three methods cause the potential for deadlock and thread pool starvation issues. They should all be avoided in favor of async/await.

The quote below explains why Task.Wait and Task.Result don't simply contain the exception propagation behavior of Task.GetAwaiter().GetResult() (due to a "very high compatibility bar").

As I mentioned previously, we have a very high compatibility bar, and thus we’ve avoided breaking changes. As such, Task.Wait retains its original behavior of always wrapping. However, you may find yourself in some advanced situations where you want behavior similar to the synchronous blocking employed by Task.Wait, but where you want the original exception propagated unwrapped rather than it being encased in an AggregateException. To achieve that, you can target the Task’s awaiter directly. When you write “await task;”, the compiler translates that into usage of the Task.GetAwaiter() method, which returns an instance that has a GetResult() method. When used on a faulted Task, GetResult() will propagate the original exception (this is how “await task;” gets its behavior). You can thus use “task.GetAwaiter().GetResult()” if you want to directly invoke this propagation logic.

https://blogs.msdn.microsoft.com/pfxteam/2011/09/28/task-exception-handling-in-net-4-5/

GetResult” actually means “check the task for errors”

In general, I try my best to avoid synchronously blocking on an asynchronous task. However, there are a handful of situations where I do violate that guideline. In those rare conditions, my preferred method is GetAwaiter().GetResult() because it preserves the task exceptions instead of wrapping them in an AggregateException.

http://blog.stephencleary.com/2014/12/a-tour-of-task-part-6-results.html

Android - Handle "Enter" in an EditText

This will give you a callable function when the user presses the return key.

fun EditText.setLineBreakListener(onLineBreak: () -> Unit) {
    val lineBreak = "\n"
    doOnTextChanged { text, _, _, _ ->
        val currentText = text.toString()

        // Check if text contains a line break
        if (currentText.contains(lineBreak)) {

            // Uncommenting the lines below will remove the line break from the string
            // and set the cursor back to the end of the line

            // val cleanedString = currentText.replace(lineBreak, "")
            // setText(cleanedString)
            // setSelection(cleanedString.length)

            onLineBreak()
        }
    }
}

Usage

editText.setLineBreakListener {
    doSomething()
}

JUnit tests pass in Eclipse but fail in Maven Surefire

I had a similar problem, I ran my tests disabling the reuse of forks like this

mvn clean test -DreuseForks=false

and the problem disappeared. The downside is that the overall test execution time will be longer, that's why you may want to do this from the command line only if necessary

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

Android: upgrading DB version and adding new table

Your code looks correct. My suggestion is that the database already thinks it's upgraded. If you executed the project after incrementing the version number, but before adding the execSQL call, the database on your test device/emulator may already believe it's at version 2.

A quick way to verify this would be to change the version number to 3 -- if it upgrades after that, you know it was just because your device believed it was already upgraded.

How to change button text in Swift Xcode 6?

In Xcode 8 - Swift 3:

button.setTitle( "entertext" , for: .normal )

How to import a jar in Eclipse

In eclipse I included a compressed jar file i.e. zip file. Eclipse allowed me to add this zip file as an external jar but when I tried to access the classes in the jar they weren't showing up.

After a lot of trial and error I found that using a zip format doesn't work. When I added a jar file then it worked for me.

Show a message box from a class in c#?

Try this:

System.Windows.Forms.MessageBox.Show("Here's a message!");

C# ListView Column Width Auto

There is another useful method called AutoResizeColumn which allows you to auto size a specific column with the required parameter.

You can call it like this:

listview1.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize);
listview1.AutoResizeColumn(4, ColumnHeaderAutoResizeStyle.HeaderSize);

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

Deleting the project specific settings files (Eclipse workspace/project folder/.settings/) from the project folder also will do. Obviously, we need to do a project clean and build after deleting.

Postgresql GROUP_CONCAT equivalent?

Since 9.0 this is even easier:

SELECT id, 
       string_agg(some_column, ',')
FROM the_table
GROUP BY id

Create hyperlink to another sheet

If you need to hyperlink Sheet1 to all or corresponding sheets, then use simple vba code. If you wish to create a radio button, then assign this macro to that button ex "Home Page".

Here is it:

Sub HomePage()
'
' HomePage Macro
'


' This is common code to go to sheet 1 if do not change name for Sheet1
    'Sheets("Sheet1").Select
' OR 

' You can write you sheet name here in case if its name changes

    Sheets("Monthly Reports Home").Select
    Range("A1").Select

End Sub

Oracle Add 1 hour in SQL

select sysdate + 1/24 from dual;

sysdate is a function without arguments which returns DATE type
+ 1/24 adds 1 hour to a date

select to_char(to_date('2014-10-15 03:30:00 pm', 'YYYY-MM-DD HH:MI:SS pm') + 1/24, 'YYYY-MM-DD HH:MI:SS pm') from dual;

How to use timer in C?

Here's a solution I used (it needs #include <time.h>):

int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();

do {
  /*
   * Do something to busy the CPU just here while you drink a coffee
   * Be sure this code will not take more than `trigger` ms
   */

  clock_t difference = clock() - before;
  msec = difference * 1000 / CLOCKS_PER_SEC;
  iterations++;
} while ( msec < trigger );

printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
  msec/1000, msec%1000, iterations);

How to reset a form using jQuery with .reset() method

Your code should work. Make sure static/jquery-1.9.1.min.js exists. Also, you can try reverting to static/jquery.min.js. If that fixes the problem then you've pinpointed the problem.

Way to run Excel macros from command line or batch file?

I generally store my macros in xlam add-ins separately from my workbooks so I wanted to open a workbook and then run a macro stored separately.

Since this required a VBS Script, I wanted to make it "portable" so I could use it by passing arguments. Here is the final script, which takes 3 arguments.

  • Full Path to Workbook
  • Macro Name
  • [OPTIONAL] Path to separate workbook with Macro

I tested it like so:

"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"

"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"

runmacro.vbs:

Set args = Wscript.Arguments

ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
 macrowb= WScript.Arguments.Item(2)
End If

LaunchMacro

Sub LaunchMacro() 
  Dim xl
  Dim xlBook  

  Set xl = CreateObject("Excel.application")
  Set xlBook = xl.Workbooks.Open(ws, 0, True)
  If wscript.arguments.count > 2 Then
   Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
  End If
  'xl.Application.Visible = True ' Show Excel Window
  xl.Application.run macro
  'xl.DisplayAlerts = False  ' suppress prompts and alert messages while a macro is running
  'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
  'xl.activewindow.close
  xl.Quit

End Sub 

Performing a query on a result from another query?

I don't know if you even need to wrap it. Won't this work?

SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms    ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' 
  AND date_add('2009-06-25', INTERVAL 4 DAY)
  AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);

If your goal is to return both result sets then you'll need to store it some place temporarily.

Definitive way to trigger keypress events with jQuery

I made it work with keyup.

$("#id input").trigger('keyup');

How to delete a stash created with git stash create?

Git stash clear will clear complete stash,

cmd: git stash clear

If you want to delete a particular stash with a stash index, you can use the drop.

cmd: git stash drop 4

(4 is stash id or stash index)

remove first element from array and return the array minus the first element

Why not use ES6?

_x000D_
_x000D_
 var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
 const [, ...rest] = myarray;_x000D_
 console.log(rest)
_x000D_
_x000D_
_x000D_

Convert normal Java Array or ArrayList to Json Array in android

This is the correct syntax:

String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);

package javax.servlet.http does not exist

If you use elcipse with tomcat server, you can open setting properties by right click project -> choose Properties (or Alt+Enter), continue do same below picture. It will resolve your problem.

enter image description here

Could not autowire field in spring. why?

In spring servlet .xml :

<context:component-scan base-package="net.controller" />

(I assumed that the service impl is in the same package as the service interface "net.service")

I think you have to add the package net.service (or all of net) to the component scan. Currently spring only searches in net.controller for components and as your service impl is in net.service, it will not be instantiated by spring.

How do I create a batch file timer to execute / call another batch throughout the day

@echo off
:Start # seting a ponter
title timer  #name the cmd window to "Timer"
echo Type in an amount of time (Seconds)  
set /p A=  #wating for input from user
set B=1  

cls  
:loop  
ping localhost -n 2 >nul  #pinging your self for 1 second
set /A A=A-B  #sets the value A - 1
echo %A%  # printing A
if %A% EQU 0 goto Timesup  #if A = 0 go to ponter Timesup eles loop it
goto loop

:Timesup  #ponter Timesup
cls  #clear the screen
MSG * /v "time Is Up!"  #makes a pop up saying "time Is Up!"
goto Exit  #go to exit

:Exit 

Preferred Java way to ping an HTTP URL for availability

You could also use HttpURLConnection, which allows you to set the request method (to HEAD for example). Here's an example that shows how to send a request, read the response, and disconnect.

What is the difference between gravity and layout_gravity in Android?

The difference

android:layout_gravity is the Outside gravity of the View. Specifies the direction in which the View should touch its parent's border.

android:gravity is the Inside gravity of that View. Specifies in which direction its contents should align.

HTML/CSS Equivalents

(if you are coming from a web development background)

Android                 | CSS
————————————————————————+————————————
android:layout_gravity  | float
android:gravity         | text-align

Easy trick to help you remember

Take layout-gravity as "Lay-outside-gravity".

Getting content/message from HttpResponseMessage

If you want to cast it to specific type (e.g. within tests) you can use ReadAsAsync extension method:

object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));

or following for synchronous code:

object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;

Update: there is also generic option of ReadAsAsync<> which returns specific type instance instead of object-declared one:

YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();

Error in MySQL when setting default value for DATE or DATETIME

I've tested a fix as follow:

1). On the file "system/library/db/mysqli.php" search and comment the line: 
"$this->connection->query("SET SESSION sql_mode = 'NO_ZERO_IN_DATE,NO_ZERO_DATE,NO_ENGINE_SUBSTITUTION'");"

2) Add the following line above the one you just commented:
// Correction by Added by A.benkorich
$this->connection->query("SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY'");

Match multiline text using regular expression

str.matches(regex) behaves like Pattern.matches(regex, str) which attempts to match the entire input sequence against the pattern and returns

true if, and only if, the entire input sequence matches this matcher's pattern

Whereas matcher.find() attempts to find the next subsequence of the input sequence that matches the pattern and returns

true if, and only if, a subsequence of the input sequence matches this matcher's pattern

Thus the problem is with the regex. Try the following.

String test = "User Comments: This is \t a\ta \ntest\n\n message \n";

String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find());  //true

String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2));  //true

Thus in short, the (\\W)*(\\S)* portion in your first regex matches an empty string as * means zero or more occurrences and the real matched string is User Comments: and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W matches a non word character, ie [^a-zA-Z0-9_] and the first character is T, a word character.

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

How to push both key and value into an Array in Jquery

I think you need to define an object and then push in array

var obj = {};
obj[name] = val;
ary.push(obj);

adding comment in .properties files

Writing the properties file with multiple comments is not supported. Why ?

PropertyFile.java

public class PropertyFile extends Task {

    /* ========================================================================
     *
     * Instance variables.
     */

    // Use this to prepend a message to the properties file
    private String              comment;

    private Properties          properties;

The ant property file task is backed by a java.util.Properties class which stores comments using the store() method. Only one comment is taken from the task and that is passed on to the Properties class to save into the file.

The way to get around this is to write your own task that is backed by commons properties instead of java.util.Properties. The commons properties file is backed by a property layout which allows settings comments for individual keys in the properties file. Save the properties file with the save() method and modify the new task to accept multiple comments through <comment> elements.

Figuring out whether a number is a Double in Java

Try this:

if (items.elementAt(1) instanceof Double) {
   sum.add( i, items.elementAt(1));
}

How can I clear the Scanner buffer in Java?

Use the following command:

in.nextLine();

right after

System.out.println("Invalid input. Please Try Again.");
System.out.println();

or after the following curly bracket (where your comment regarding it, is).

This command advances the scanner to the next line (when reading from a file or string, this simply reads the next line), thus essentially flushing it, in this case. It clears the buffer and readies the scanner for a new input. It can, preferably, be used for clearing the current buffer when a user has entered an invalid input (such as a letter when asked for a number).

Documentation of the method can be found here: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

Hope this helps!

How to convert List<Integer> to int[] in Java?

int[] ret = new int[list.size()];       
Iterator<Integer> iter = list.iterator();
for (int i=0; iter.hasNext(); i++) {       
    ret[i] = iter.next();                
}                                        
return ret;                              

Check whether specific radio button is checked

1.You don't need the @ prefix for attribute names any more:

http://api.jquery.com/category/selectors/attribute-selectors/:

Note: In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the ‘@’ symbol from your selectors in order to make them work again.

2.Your selector queries radio buttons by name, but that attribute is not defined in your HTML structure.

Visual Studio Code open tab in new window

If you are using the excellent

VSCode for Mac, 2020

simply tap Apple-Shift-N (as in "new window")

Drag whatever you want there.

Parsing JSON Array within JSON Object

line 2 should be

for (int i = 0; i < jsonMainArr.size(); i++) {  // **line 2**

For line 3, I'm having to do

    JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());

How to determine whether a Pandas Column contains a particular value

Use

df[df['id']==x].index.tolist()

If x is present in id then it'll return the list of indices where it is present, else it gives an empty list.

Measure the time it takes to execute a t-sql query

One simplistic approach to measuring the "elapsed time" between events is to just grab the current date and time.

In SQL Server Management Studio

SELECT GETDATE();
SELECT /* query one */ 1 ;
SELECT GETDATE();
SELECT /* query two */ 2 ; 
SELECT GETDATE(); 

To calculate elapsed times, you could grab those date values into variables, and use the DATEDIFF function:

DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;

SET @t1 = GETDATE();
SELECT /* query one */ 1 ;
SET @t2 = GETDATE();
SELECT DATEDIFF(millisecond,@t1,@t2) AS elapsed_ms;

SET @t1 = GETDATE();
SELECT /* query two */ 2 ;
SET @t2 = GETDATE();
SELECT DATEDIFF(millisecond,@t1,@t2) AS elapsed_ms;

That's just one approach. You can also get elapsed times for queries using SQL Profiler.

Integer.toString(int i) vs String.valueOf(int i)

If you look at the source code for the String class, it actually calls Integer.toString() when you call valueOf().

That being said, Integer.toString() might be a tad faster if the method calls aren't optimized at compile time (which they probably are).

Floating elements within a div, floats outside of div. Why?

Here's more modern approach:

.parent {display: flow-root;} 

No more clearfixes.

p.s. Using overflow: hidden; hides the box-shadow so...

Work with a time span in Javascript

Moment.js provides such functionality:

http://momentjs.com/

It's well documented and nice library.

It should go along the lines "Duration" and "Humanize of API http://momentjs.com/docs/#/displaying/from/

 var d1, d2; // Timepoints
 var differenceInPlainText = moment(a).from(moment(b), true); // Add true for suffixless text

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How do I remove the blue styling of telephone numbers on iPhone/iOS?

In Joomla Yootheme works for me:

a:not([class]) {
    color: #fff !important;
}

How do I get the latest version of my code?

I understand you want to trash your local changes and pull down what's on your remote?

If all else fails, and if you're (quite understandably) scared of "reset", the simplest thing is just to clone origin into a new directory and trash your old one.

error: request for member '..' in '..' which is of non-class type

Adding to the knowledge base, I got the same error for

if(class_iter->num == *int_iter)

Even though the IDE gave me the correct members for class_iter. Obviously, the problem is that "anything"::iterator doesn't have a member called num so I need to dereference it. Which doesn't work like this:

if(*class_iter->num == *int_iter)

...apparently. I eventually solved it with this:

if((*class_iter)->num == *int_iter)

I hope this helps someone who runs across this question the way I did.

transform object to array with lodash

_.toArray(obj);

Outputs as:

[
  {
    "name": "Ivan",
    "id": 12,
    "friends": [
      2,
      44,
      12
    ],
    "works": {
      "books": [],
      "films": []
    }
  },
  {
    "name": "John",
    "id": 22,
    "friends": [
      5,
      31,
      55
    ],
    "works": {
      "books": [],
      "films": []
    }
  }
]"

How to check if any flags of a flag combination are set?

I use extension methods to write things like that :

if (letter.IsFlagSet(Letter.AB))
    ...

Here's the code :

public static class EnumExtensions
{
    private static void CheckIsEnum<T>(bool withFlags)
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException(string.Format("Type '{0}' is not an enum", typeof(T).FullName));
        if (withFlags && !Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
            throw new ArgumentException(string.Format("Type '{0}' doesn't have the 'Flags' attribute", typeof(T).FullName));
    }

    public static bool IsFlagSet<T>(this T value, T flag) where T : struct
    {
        CheckIsEnum<T>(true);
        long lValue = Convert.ToInt64(value);
        long lFlag = Convert.ToInt64(flag);
        return (lValue & lFlag) != 0;
    }

    public static IEnumerable<T> GetFlags<T>(this T value) where T : struct
    {
        CheckIsEnum<T>(true);
        foreach (T flag in Enum.GetValues(typeof(T)).Cast<T>())
        {
            if (value.IsFlagSet(flag))
                yield return flag;
        }
    }

    public static T SetFlags<T>(this T value, T flags, bool on) where T : struct
    {
        CheckIsEnum<T>(true);
        long lValue = Convert.ToInt64(value);
        long lFlag = Convert.ToInt64(flags);
        if (on)
        {
            lValue |= lFlag;
        }
        else
        {
            lValue &= (~lFlag);
        }
        return (T)Enum.ToObject(typeof(T), lValue);
    }

    public static T SetFlags<T>(this T value, T flags) where T : struct
    {
        return value.SetFlags(flags, true);
    }

    public static T ClearFlags<T>(this T value, T flags) where T : struct
    {
        return value.SetFlags(flags, false);
    }

    public static T CombineFlags<T>(this IEnumerable<T> flags) where T : struct
    {
        CheckIsEnum<T>(true);
        long lValue = 0;
        foreach (T flag in flags)
        {
            long lFlag = Convert.ToInt64(flag);
            lValue |= lFlag;
        }
        return (T)Enum.ToObject(typeof(T), lValue);
    }

    public static string GetDescription<T>(this T value) where T : struct
    {
        CheckIsEnum<T>(false);
        string name = Enum.GetName(typeof(T), value);
        if (name != null)
        {
            FieldInfo field = typeof(T).GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
    }
}

How to print the full NumPy array, without truncation?

Since NumPy version 1.16, for more details see GitHub ticket 12251.

from sys import maxsize
from numpy import set_printoptions

set_printoptions(threshold=maxsize)

What is aria-label and how should I use it?

If you wants to know how aria-label helps you practically .. then follow the steps ... you will get it by your own ..

Create a html page having below code

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <button title="Close"> X </button>
    <br />
    <br />
    <br />
    <br />
    <button aria-label="Back to the page" title="Close" > X </button>
</body>
</html>

Now, you need a virtual screen reader emulator which will run on browser to observe the difference. So, chrome browser users can install chromevox extension and mozilla users can go with fangs screen reader addin

Once done with installation, put headphones in your ears, open the html page and make focus on both button(by pressing tab) one-by-one .. and you can hear .. focusing on first x button .. will tell you only x button .. but in case of second x button .. you will hear back to the page button only..

i hope you got it well now!!

What do Push and Pop mean for Stacks?

Ok. As the other answerers explained, a stack is a last-in, first-out data structure. You add an element to the top of the stack with a Push operation. You take an element off the top with a Pop operation. The elements are removed in reverse order to the order they were put inserted (hence Last In, First Out). For example, if you push the elments 1,2,3 in that order, the number 3 will be at the top of the stack. A Pop operation will remove it (it was the last in) and leave 2 at the top of the stack.

Regarding the rest of the lecture, the lecturer tried to describe a stack-based machine that evaluates arithmetic expressions. The machine operates by continuously popping 3 elements from the top of the stack. The first two elements are operands and the third is an operator (+, -, *, /). It then applies this operator on the operands, and pushes the result onto the stack. The process continues until there is only one element on the stack, which is the value of the expression.

So, suppose we begin by pushing the values "+/*23-21*5-41" in left-to-right order onto the stack. We then pop 3 elements from the top. The last in is first out, which means the first 3 element are "1", "4", and "-" in that order. We push the number 3 (the result of 4-1) onto the stack, then pop the three topmost elements: 3, 5, *. Push the result, 15, onto the stack, and so on.

Succeeded installing but could not start apache 2.4 on my windows 7 system

if you are using windows os and believe that skype is not the suspect, then you might want to check the task manager and check the "Show processes from all users" and make sure that there is NO entry for httpd.exe. Otherwise, end its process. That solves my problem.

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

If embed no longer works for you, try with /v instead:

<iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>

Is there an embeddable Webkit component for Windows / C# development?

The Windows version of Qt 4 includes both WebKit and classes to create ActiveX components. It probably isn't an ideal solution if you aren't already using Qt though.

Running JAR file on Windows

You want to check a couple of things; if this is your own jar file, make sure you have defined a Main-class in the manifest. Since we know you can run it from the command line, the other thing to do is create a windows shortcut, and modify the properties (you'll have to look around, I don't have a Windows machine to look at) so that the command it executes on open is the java -jar command you mentioned.

The other thing: if something isn't confused, it should work anyway; check and make sure you have java associated with the .jar extension.

Why is HttpClient BaseAddress not working?

Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.

If base URI contains non-empty path, merge procedure discards it's last part (after last /). Relevant section:

5.2.3. Merge Paths

The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:

  • If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise

  • return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).

If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.

" app-release.apk" how to change this default generated apk name

First rename your module from app to i.e. SurveyApp

Second add this to your project top-level (root project) gradle. It's working with Gradle 3.0

//rename apk for all sub projects
subprojects {
    afterEvaluate { project ->
        if (project.hasProperty("android")) {
            android.applicationVariants.all { variant ->
                variant.outputs.all {
                    outputFileName = "${project.name}-${variant.name}-${variant.versionName}.apk"
                }
            }
        }
    }
}

Media query to detect if device is touchscreen

adding a class touchscreen to the body using JS or jQuery

  //allowing mobile only css
    var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));
    if(isMobile){
        jQuery("body").attr("class",'touchscreen');
    }

how to deal with google map inside of a hidden div (Updated picture)

I didn't like that the map would load only after the hidden div had become visible. In a carousel, for example, that doesn't really work.

This my solution is to add class to the hidden element to unhide it and hide it with position absolute instead, then render the map, and remove the class after map load.

Tested in Bootstrap Carousel.

HTML

<div class="item loading"><div id="map-canvas"></div></div>

CSS

.loading { display: block; position: absolute; }

JS

$(document).ready(function(){
    // render map //
    google.maps.event.addListenerOnce(map, 'idle', function(){
        $('.loading').removeClass('loading');
    });
}

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I had the same issue but the password was good and "Log on as batch job" alone was not sufficient.

Check that the IIS application pool identity account or group has both the "Log on as Batch Job" permission AND that it can "impersonate a client after authentication".

To change these settings perform the following steps on the web front end server:

  • Start>Run type "secpol.msc"
    • Find: Security Settings>Local Policies>User Rights assignment
    • Add user or group to "Log on as Batch Job"
    • Check group membership of service account (in Active Directory) if a particular group is being used for this purpose.
    • Find "impersonate a client after authentication" and add the application pool identity
    • Reboot the server

You should be able to access the site!

Where do I mark a lambda expression async?

To mark a lambda async, simply prepend async before its argument list:

// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
    SQLiteUtils slu = new SQLiteUtils();
    await slu.DeleteGroupAsync(groupName);
}));

Number of occurrences of a character in a string

Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.

string test = "key1=value1&key2=value2&key3=value3";

var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
                     .Cast<Match>()
                     .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

var count = keyValues.Count - 1;

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

Fixing Sublime Text 2 line endings?

to chnage line endings from LF to CRLF:

open Sublime and follow the steps:-

1 press Ctrl+shift+p then install package name line unify endings

then again press Ctrl+shift+p

2 in the blank input box type "Line unify ending "

3 Hit enter twice

Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

Just today I had the (questionable) pleasure to get VB6 code running on Windows / 64 Bit. I did come across this thread, but none of the proposed solutions worked for me. Neither worked adding references using the "Project -> References..." menu.

To get it running, I had to manually modify the VB6 project file (*.vbp). For all the libraries I had load issue with I had to use the following notation to define as reference: Object={Registry Key}#Version#0; LIBRARY.OCX Example: Object={FAEEE763-117E-101B-8933-08002B2F4F5A}#1.1#0; DBLIST32.OCX

I had not to register any of the libraries (using regsvr32), these were all already correctly registered. I guess why my solution works is that if the "object={[...]" notation is used (instead of the "Reference=*\G{[...]" notation) VB Studio is using the Registry Key only and gets rooted to C:\Windows\SysWOW64 while as the other way ends up looking in C:\Windows\System32

By the way, IE11 is installed. Whether or not this matters, only Bill G might know. My guess is that my solution works regardless which IE is installed. You just might have to unregister and register the missing libraries as mentioned in this thread.

Hope that helps anyone who faces similar issues.

Chrome ignores autocomplete="off"

None of the solutions worked except for giving it a fake field to autocomplete. I made a React component to address this issue.

import React from 'react'

// Google Chrome stubbornly refuses to respect the autocomplete="off" HTML attribute so
// we have to give it a "fake" field for it to autocomplete that never gets "used".

const DontBeEvil = () => (
  <div style={{ display: 'none' }}>
    <input type="text" name="username" />
    <input type="password" name="password" />
  </div>
)

export default DontBeEvil

How to avoid soft keyboard pushing up my layout?

windowSoftInputMode will either pan or resize your activity layout. One thing that you can do is to attach an onFocusChanged listener to your EditText and when the user selects/taps the EditText then you hide or move your navigation buttons out of the screen. When the EditText loses focus then you can put the navigation buttons back at the bottom of the activity.

How to create a inner border for a box in html?

IE doesn't support outline-offset so another solution would be to create 2 div tags, one nested into the other one. The inner one would have a border and be slightly smaller than the container.

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  width: 400px;_x000D_
  height: 100px;_x000D_
  background: #000000;_x000D_
  padding: 10px;_x000D_
}_x000D_
.inner {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: #000000;_x000D_
  border: 1px dashed #ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="inner"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I see the current value of my $PATH variable on OS X?

You need to use the command echo $PATH to display the PATH variable or you can just execute set or env to display all of your environment variables.

By typing $PATH you tried to run your PATH variable contents as a command name.

Bash displayed the contents of your path any way. Based on your output the following directories will be searched in the following order:

/usr/local/share/npm/bin
/Library/Frameworks/Python.framework/Versions/2.7/bin
/usr/local/bin
/usr/local/sbin
~/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/local/git/bin

To me this list appears to be complete.

MySQL - How to select data by string length

I used this sentences to filter

SELECT table.field1, table.field2 FROM table WHERE length(field) > 10;

you can change 10 for other number that you want to filter.

React - changing an uncontrolled input

One potential downside with setting the field value to "" (empty string) in the constructor is if the field is an optional field and is left unedited. Unless you do some massaging before posting your form, the field will be persisted to your data storage as an empty string instead of NULL.

This alternative will avoid empty strings:

constructor(props) {
    super(props);
    this.state = {
        name: null
    }
}

... 

<input name="name" type="text" value={this.state.name || ''}/>

How to change text transparency in HTML/CSS?

Just use the rgba tag as your text color. You could use opacity, but that would affect the whole element, not just the text. Say you have a border, it would make that transparent as well.

.text
    {
        font-family: Garamond, serif;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.5);
    }

How to locate the php.ini file (xampp)

This is one of those "you were technically accurate, but you didn't answer my question" but it doesn't mean the above were wrong or misguided - they just didn't run into my issue.

So, I figure I'll give an answer.

As the others mentioned (spot on), I created a file:

<?php
phpinfo(); 
?>

So that worked great. However, it showed "(none)"

So where do you find (none)!?

In my case, on Windows, you just go to where php is installed; I had already had installed it in c:\php I believe it would be the same steps on other platforms.

Then, from a command line, powershell for ex, type: notepad c:\php\php.ini

Tell it yes, you do want to create it, then add whatever changes you needed in the first place. For me, for example:

extension_dir = "c:\php\ext"
extension=mysqli
upload_max_filesize = 25M
post_max_size = 13M
max_execution_time = 300

Then save. Fixed!

By the way - if you do "file new" and then "save as" Notepad will helpfully rename your file to php.ini.txt. Friends let friends NOT AVOID THE CLI.

How to check if a Constraint exists in Sql server?

I use the following query to check for an existing constraint before I create it.

IF (NOT EXISTS(SELECT 1 FROM sysconstraints WHERE OBJECT_NAME(constid) = 'UX_CONSTRAINT_NAME' AND OBJECT_NAME(id) = 'TABLE_NAME')) BEGIN
...
END

This queries for the constraint by name targeting a given table name. Hope this helps.

how to append a css class to an element by javascript?

var element = document.getElementById(element_id);
element.className += " " + newClassName;

Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).

Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.

In prototype, for instance:

// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);

See how much nicer that is?!

JavaScript private methods

Since everybody was posting here his own code, I'm gonna do that too...

I like Crockford because he introduced real object oriented patterns in Javascript. But he also came up with a new misunderstanding, the "that" one.

So why is he using "that = this"? It has nothing to do with private functions at all. It has to do with inner functions!

Because according to Crockford this is buggy code:

Function Foo( ) {
    this.bar = 0; 
    var foobar=function( ) {
        alert(this.bar);
    }
} 

So he suggested doing this:

Function Foo( ) {
    this.bar = 0;
    that = this; 
    var foobar=function( ) {
        alert(that.bar);
    }
}

So as I said, I'm quite sure that Crockford was wrong his explanation about that and this (but his code is certainly correct). Or was he just fooling the Javascript world, to know who is copying his code? I dunno...I'm no browser geek ;D

EDIT

Ah, that's what is all about: What does 'var that = this;' mean in JavaScript?

So Crockie was really wrong with his explanation....but right with his code, so he's still a great guy. :))

how to set start page in webconfig file in asp.net c#

the following code worked fine for me. kindly check other setting in your web config

 <system.webServer>
     <defaultDocument>
            <files>
                <clear />               
                <add value="Login.aspx"/>
            </files>
        </defaultDocument>
    </system.webServer>

Adjust UILabel height depending on the text

My approach to compute the dynamic height of UILabel.

    let width = ... //< width of this label 
    let text = ... //< display content

    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.preferredMaxLayoutWidth = width

    // Font of this label.
    //label.font = UIFont.systemFont(ofSize: 17.0)
    // Compute intrinsicContentSize based on font, and preferredMaxLayoutWidth
    label.invalidateIntrinsicContentSize() 
    // Destination height
    let height = label.intrinsicContentSize.height

Wrap to function:

func computeHeight(text: String, width: CGFloat) -> CGFloat {
    // A dummy label in order to compute dynamic height.
    let label = UILabel()

    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.font = UIFont.systemFont(ofSize: 17.0)

    label.preferredMaxLayoutWidth = width
    label.text = text
    label.invalidateIntrinsicContentSize()

    let height = label.intrinsicContentSize.height
    return height
}

Java: Local variable mi defined in an enclosing scope must be final or effectively final

Yes this is happening because you are accessing mi variable from within your anonymous inner class, what happens deep inside is that another copy of your variable is created and will be use inside the anonymous inner class, so for data consistency the compiler will try restrict you from changing the value of mi so that's why its telling you to set it to final.

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

Just read this post and according to the angular 2 docs:

export CUSTOM_ELEMENTS_SCHEMA
Defines a schema that will allow:

any non-Angular elements with a - in their name,
any properties on elements with a - in their name which is the common rule for custom elements.

So just in case anyone runs into this problem, once you have added CUSTOM_ELEMENTS_SCHEMA to your NgModule, make sure that whatever new custom element you use has a 'dash' in its name eg. or etc.

How to use string.substr() function?

Possible solution with string_view

void do_it_with_string_view( void )
{
    std::string a { "12345" };
    for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
        std::cout << v.substr( 0, 2 ) << " ";
    std::cout << std::endl;
}

Angular 5, HTML, boolean on checkbox is checked

You can use this:

<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">

Here, record is the model for current row and status is boolean value.

Passing properties by reference in C#

You can't ref a property, but if your functions need both get and set access you can pass around an instance of a class with a property defined:

public class Property<T>
{
    public delegate T Get();
    public delegate void Set(T value);
    private Get get;
    private Set set;
    public T Value {
        get {
            return get();
        }
        set {
            set(value);
        }
    }
    public Property(Get get, Set set) {
        this.get = get;
        this.set = set;
    }
}

Example:

class Client
{
    private string workPhone; // this could still be a public property if desired
    public readonly Property<string> WorkPhone; // this could be created outside Client if using a regular public property
    public int AreaCode { get; set; }
    public Client() {
        WorkPhone = new Property<string>(
            delegate () { return workPhone; },
            delegate (string value) { workPhone = value; });
    }
}
class Usage
{
    public void PrependAreaCode(Property<string> phone, int areaCode) {
        phone.Value = areaCode.ToString() + "-" + phone.Value;
    }
    public void PrepareClientInfo(Client client) {
        PrependAreaCode(client.WorkPhone, client.AreaCode);
    }
}

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

This works for me for Django 1.9 . The Python script to execute was in the root of the Django project.

    import django 
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PROJECT_NAME.settings")
    django.setup()
    from APP_NAME.models import *

Set PROJECT_NAME and APP_NAME to yours

How can I install the Beautiful Soup module on the Mac?

On advice from http://for-ref-only.blogspot.de/2012/08/installing-beautifulsoup-for-python-3.html, I used the Windows command prompt with:

C:\Python\Scripts\easy_install c:\Python\BeautifulSoup\beautifulsoup4-4.3.1

where BeautifulSoup\beautifulsoup4-4.3.1 is the downloaded and extracted beautifulsoup4-4.3.1.tar file. It works.

How to store an array into mysql?

If you just store the data in a database as you would if you were manually putting it into an array

"INSERT INTO database_name.database_table (`array`)
    VALUES
    ('One,Two,Three,Four')";

Then when you are pulling from the database, use the explode() function

$sql = mysql_query("SELECT * FROM database_name.database_table");
$numrows = mysql_num_rows($sql);
if($numrows != 0){
    while($rows = mysql_fetch_assoc($sql)){
        $array_from_db = $rows['array'];
    }
}else{
    echo "No rows found!".mysql_error();
}
$array = explode(",",$array_from_db);
foreach($array as $varchar){
    echo $varchar."<br/>";
}

Like so!

How to check if the string is empty?

If you just use

not var1 

it is not possible to difference a variable which is boolean False from an empty string '':

var1 = ''
not var1
> True

var1 = False
not var1
> True

However, if you add a simple condition to your script, the difference is made:

var1  = False
not var1 and var1 != ''
> True

var1 = ''
not var1 and var1 != ''
> False

How can I get the file name from request.FILES?

NOTE if you are using python 3.x:

request.FILES is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type="file") is "myfile" so "myfile" will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile'] you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:

list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
    filename = f.name
    list.append(filename)

of course one can squeeze the whole thing in one line, but this is easy to understand

Run Function After Delay

$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     
    $(".navigation").hide();
    $(".page").children(".panel").fadeIn(1000);
 }

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)

});

For more see here

Javascript form validation with password confirming

Just add onsubmit event handler for your form:

<form  action="insert.php" onsubmit="return myFunction()" method="post">

Remove onclick from button and make it input with type submit

<input type="submit" value="Submit">

And add boolean return statements to your function:

function myFunction() {
    var pass1 = document.getElementById("pass1").value;
    var pass2 = document.getElementById("pass2").value;
    var ok = true;
    if (pass1 != pass2) {
        //alert("Passwords Do not match");
        document.getElementById("pass1").style.borderColor = "#E34234";
        document.getElementById("pass2").style.borderColor = "#E34234";
        return false;
    }
    else {
        alert("Passwords Match!!!");
    }
    return ok;
}

Hot deploy on JBoss - how do I make JBoss "see" the change?

I am using JBoss AS 7.1.1.Final. Adding following code snippet in my web.xml helped me to change jsp files on the fly :

<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>development</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>

Hope this helps.!!

How to create nested directories using Mkdir in Golang?

An utility method like the following can be used to solve this.

import (
  "os"
  "path/filepath"
  "log"
)

func ensureDir(fileName string) {
  dirName := filepath.Dir(fileName)
  if _, serr := os.Stat(dirName); serr != nil {
    merr := os.MkdirAll(dirName, os.ModePerm)
    if merr != nil {
        panic(merr)
    }
  }
}



func main() {
  _, cerr := os.Create("a/b/c/d.txt")
  if cerr != nil {
    log.Fatal("error creating a/b/c", cerr)
  }
  log.Println("created file in a sub-directory.")
}

TypeError: Converting circular structure to JSON in nodejs

Try using this npm package. This helped me decoding the res structure from my node while using passport-azure-ad for integrating login using Microsoft account

https://www.npmjs.com/package/circular-json

You can stringify your circular structure by doing:

const str = CircularJSON.stringify(obj);

then you can convert it onto JSON using JSON parser

JSON.parse(str)

Why does the Visual Studio editor show dots in blank spaces?

~ FOR VISUAL STUDIO 6 ~

use: ctrl+shift+8 to toggle on/off.

(or manualy go to: Edit> Advance > "View Whitespaces")

goodluck!

Works also for Visual Studio 2008, when Tools/Options/Environment/Keyboard/Mapping Scheme: Visual C++ 6 is selected.

CSS ''background-color" attribute not working on checkbox inside <div>

We can provide background color from the css file. Try this one,

<!DOCTYPE html>
<html>
    <head>
        <style>
            input[type="checkbox"] {
                width: 25px;
                height: 25px;
                background: gray;
                -webkit-appearance: none;
                -moz-appearance: none;
                appearance: none;
                border: none;
                outline: none;
                position: relative;
                left: -5px;
                top: -5px;
                cursor: pointer;
            }
            input[type="checkbox"]:checked {
                background: blue;
            }
            .checkbox-container {
                position: absolute;
                display: inline-block;
                margin: 20px;
                width: 25px;
                height: 25px;
                overflow: hidden;
            }
        </style>    
    </head>
    <body>
        <div class="checkbox-container">
            <input type="checkbox" />
        </div>
    </body>
</html>

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

inject bean reference into a Quartz job in Spring?

This is a quite an old post which is still useful. All the solutions that proposes these two had little condition that not suite all:

  • SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); This assumes or requires it to be a spring - web based project
  • AutowiringSpringBeanJobFactory based approach mentioned in previous answer is very helpful, but the answer is specific to those who don't use pure vanilla quartz api but rather Spring's wrapper for the quartz to do the same.

If you want to remain with pure Quartz implementation for scheduling(Quartz with Autowiring capabilities with Spring), I was able to do it as follows:

I was looking to do it quartz way as much as possible and thus little hack proves helpful.

 public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory{

    private AutowireCapableBeanFactory beanFactory;

    public AutowiringSpringBeanJobFactory(final ApplicationContext applicationContext){
        beanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        beanFactory.initializeBean(job, job.getClass().getName());
        return job;
    }
}


@Configuration
public class SchedulerConfig {   
    @Autowired private ApplicationContext applicationContext;

    @Bean
    public AutowiringSpringBeanJobFactory getAutowiringSpringBeanJobFactory(){
        return new AutowiringSpringBeanJobFactory(applicationContext);
    }
}


private void initializeAndStartScheduler(final Properties quartzProperties)
            throws SchedulerException {
        //schedulerFactory.initialize(quartzProperties);
        Scheduler quartzScheduler = schedulerFactory.getScheduler();

        //Below one is the key here. Use the spring autowire capable job factory and inject here
        quartzScheduler.setJobFactory(autowiringSpringBeanJobFactory);
        quartzScheduler.start();
    }

quartzScheduler.setJobFactory(autowiringSpringBeanJobFactory); gives us an autowired job instance. Since AutowiringSpringBeanJobFactory implicitly implements a JobFactory, we now enabled an auto-wireable solution. Hope this helps!

How to compare Boolean?

As object?

equals

public boolean equals(Object obj)

Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

Overrides: equals in class Object

Parameters: obj - the object to compare with.

Returns: true if the Boolean objects represent the same value; false otherwise.

boolean a = true;
boolean b = false;

System.out.println("a.equals(b):" + ((Object)a).equals( ((Object)b) ));

Output: a.equals(b):false

Jquery DatePicker Set default date

Today date:

$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });

15 days from today:

$( ".selector" ).datepicker( "setDate", 15);
// Or on the init
$( ".selector" ).datepicker({ defaultDate: 15 });

jQuery ui docs

Send json post using php

use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

C++11 reverse range-based for-loop

Got this example from cppreference. It works with:

GCC 10.1+ with flag -std=c++20

#include <ranges>
#include <iostream>
 
int main()
{
    static constexpr auto il = {3, 1, 4, 1, 5, 9};
 
    std::ranges::reverse_view rv {il};
    for (int i : rv)
        std::cout << i << ' ';
 
    std::cout << '\n';
 
    for(int i : il | std::views::reverse)
        std::cout << i << ' ';
}

Detecting attribute change of value of an attribute I made

You would have to watch the DOM node changes. There is an API called MutationObserver, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.

One way you could get around this problem is to have the part of the code that modifies the data-select-content-val attribute dispatch an event that you can listen to.

For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.

The code here is

$(function() {  
  // Here you register for the event and do whatever you need to do.
  $(document).on('data-attribute-changed', function() {
    var data = $('#contains-data').data('mydata');
    alert('Data changed to: ' + data);
  });

  $('#button').click(function() {
    $('#contains-data').data('mydata', 'foo');
    // Whenever you change the attribute you will user the .trigger
    // method. The name of the event is arbitrary
    $(document).trigger('data-attribute-changed');
  });

   $('#getbutton').click(function() {
    var data = $('#contains-data').data('mydata');
    alert('Data is: ' + data);
  });
});

Subtracting 2 lists in Python

If you have two lists called 'a' and 'b', you can do: [m - n for m,n in zip(a,b)]

Git on Windows: How do you set up a mergetool?

For IntelliJ IDEA (Community Edition) 3-way git mergetool configuration in Windows environment (~/.gitconfig)

Cygwin

[mergetool "ideamerge"]
     cmd = C:/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe merge `cygpath -wa $LOCAL` `cygpath -wa $REMOTE` `cygpath -wa $BASE` `cygpath -wa $MERGED`
[merge]
     tool = ideamerge

Msys

[mergetool "ideamerge"]
cmd = "/c/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe" merge `~/winpath.sh $LOCAL` `~/winpath.sh $REMOTE` `~/winpath.sh $BASE` `~/winpath.sh $MERGED`
[merge]
 tool = ideamerge

The ~/winpath.sh is to convert paths to Windows on msys and is taken from msys path conversion question on stackoverflow

#! /bin/sh                                                               

function wpath {                                                         
    if [ -z "$1" ]; then                                                 
        echo "$@"                                                        
    else                                                                 
        if [ -f "$1" ]; then                                             
            local dir=$(dirname "$1")                                    
            local fn=$(basename "$1")                                    
            echo "$(cd "$dir"; echo "$(pwd -W)/$fn")" | sed 's|/|\\|g';  
        else                                                             
            if [ -d "$1" ]; then                                         
                echo "$(cd "$1"; pwd -W)" | sed 's|/|\\|g';              
            else                                                         
                echo "$1" | sed 's|^/\(.\)/|\1:\\|g; s|/|\\|g';          
            fi                                                           
        fi                                                               
    fi                                                                   
}                                                                        

wpath "$@" 

Python: avoid new line with print command

Utilize a trailing comma to prevent a new line from being presented:

print "this should be"; print "on the same line"

Should be:

print "this should be", "on the same line"

In addition, you can just attach the variable being passed to the end of the desired string by:

print "Nope, that is not a two. That is a", x

You can also use:

print "Nope, that is not a two. That is a %d" % x #assuming x is always an int

You can access additional documentation regarding string formatting utilizing the % operator (modulo).

How can I reference a dll in the GAC from Visual Studio?

May be it's too late to answer, but i found a very simple way to do this(without a hack).

  1. Put your dll in GAC (for 3.5 Drag Drop inside "C:\Windows\assembly\")
  2. GoTo Projects --> Properties
  3. Click Reference Path (for 3.5 it's "C:\Windows\assembly\")
  4. and Build

Hope it helps

How to find my realm file?

I found most simplest way for iOS/macOS (for swift 3 Xcode 8.3)

override func viewDidLoad() {

   // for swift 2.0 Xcode 7
   print(Realm.Configuration.defaultConfiguration.fileURL!)
}

Then x code will log the correct path, check the screen below.

enter image description here

Now open your Finder and press ? + ? + G (command+shift+G) and paste the path that logs on your Xcode

Listing contents of a bucket with boto3

A more parsimonious way, rather than iterating through via a for loop you could also just print the original object containing all files inside your S3 bucket:

session = Session(aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key)
s3 = session.resource('s3')
bucket = s3.Bucket('bucket_name')

files_in_s3 = bucket.objects.all() 
#you can print this iterable with print(list(files_in_s3))

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

5 Jan 2021: link update thanks to @Sadap's comment.

Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.

For example, you can see that _WIN32 is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).

Anyway, I found the tables quite informative and thought I'd share here.

jQuery table sort

My vote! jquery.sortElements.js and simple jquery
Very simple, very easy, thanks nandhp...

            $('th').live('click', function(){

            var th = $(this), thIndex = th.index(), var table = $(this).parent().parent();

                switch($(this).attr('inverse')){
                case 'false': inverse = true; break;
                case 'true:': inverse = false; break;
                default: inverse = false; break;
                }
            th.attr('inverse',inverse)

            table.find('td').filter(function(){
                return $(this).index() === thIndex;
            }).sortElements(function(a, b){
                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;
            }, function(){
                // parentNode is the element we want to move
                return this.parentNode; 
            });
            inverse = !inverse;     
            });

Dei uma melhorada do código
One cod better! Function for All tables in all Th in all time... Look it!
DEMO

Get local IP address in Node.js

Any IP address of your machine you can find by using the os module - and that's native to Node.js:

var os = require('os');

var networkInterfaces = os.networkInterfaces();

console.log(networkInterfaces);

All you need to do is call os.networkInterfaces() and you'll get an easy manageable list - easier than running ifconfig by leagues.

How to get Git to clone into current directory

it's useful to create a new file by mkdir filename,then running the command of git clone xxxxx,it does work in my computer

Adding a simple spacer to twitter bootstrap

My approach. Tricky, but works well for me

<p>&nbsp;</p>

How to convert a string to a date in sybase

Use the convert function, for example:

select * from data 
where dateVal < convert(datetime, '01/01/2008', 103)

Where the convert style (103) determines the date format to use.

Where does npm install packages?

You can find globally installed modules by the command

npm list -g

It will provide you the location where node.js modules have been installed.

C:\Users\[Username]\AppData\Roaming\npm

If you install node.js modules locally in a folder, you can type the following command to see the location.

npm list

Renaming Columns in an SQL SELECT Statement

you have to rename each column

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

Can you pass parameters to an AngularJS controller on creation?

It looks like the best solution for you is actually a directive. This allows you to still have your controller, but define custom properties for it.

Use this if you need access to variables in the wrapping scope:

angular.module('myModule').directive('user', function ($filter) {
  return {
    link: function (scope, element, attrs) {
      $scope.connection = $resource('api.com/user/' + attrs.userId);
    }
  };
});

<user user-id="{% id %}"></user>

Use this if you don't need access to variables in the wrapping scope:

angular.module('myModule').directive('user', function ($filter) {
  return {
    scope: {
      userId: '@'
    },
    link: function (scope, element, attrs) {
      $scope.connection = $resource('api.com/user/' + scope.userId);
    }
  };
});

<user user-id="{% id %}"></user>

Set the absolute position of a view

In general, you can add a View in a specific position using a FrameLayout as container by specifying the leftMargin and topMargin attributes.

The following example will place a 20x20px ImageView at position (100,200) using a FrameLayout as fullscreen container:

XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:background="#33AAFF"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

Activity / Fragment / Custom view

//...
FrameLayout root = (FrameLayout)findViewById(R.id.root);
ImageView img = new ImageView(this);
img.setBackgroundColor(Color.RED);
//..load something inside the ImageView, we just set the background color

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(20, 20);
params.leftMargin = 100;
params.topMargin  = 200;
root.addView(img, params);
//...

This will do the trick because margins can be used as absolute (X,Y) coordinates without a RelativeLayout:

enter image description here

Can I use VARCHAR as the PRIMARY KEY?

It is ok for sure. With just few hundred of entries, it will be fast.

You can add an unique id as as primary key (int autoincrement) ans set your coupon_code as unique. So if you need to do request in other tables it's better to use int than varchar

Need to remove href values when printing in Chrome

If you use the following CSS

<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css"    />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />

just change it into the following style by adding media="screen"

<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />

I think it will work.

the former answers like

    @media print {
  a[href]:after {
    content: none !important;
  }
}

were not worked well in the chrome browse.

await vs Task.Wait - Deadlock?

Based on what I read from different sources:

An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

To wait for a single task to complete, you can call its Task.Wait method. A call to the Wait method blocks the calling thread until the single class instance has completed execution. The parameterless Wait() method is used to wait unconditionally until a task completes. The task simulates work by calling the Thread.Sleep method to sleep for two seconds.

This article is also a good read.

double free or corruption (!prev) error in c program

I didn't check all the code but my guess is that the error is in the malloc call. You have to replace

 double *ptr = malloc(sizeof(double*) * TIME);

for

 double *ptr = malloc(sizeof(double) * TIME);

since you want to allocate size for a double (not the size of a pointer to a double).

How to pass object from one component to another in Angular 2?

Component 2, the directive component can define a input property (@input annotation in Typescript). And Component 1 can pass that property to the directive component from template.

See this SO answer How to do inter communication between a master and detail component in Angular2?

and how input is being passed to child components. In your case it is directive.

Elegant way to create empty pandas DataFrame with NaN of type float

You could specify the dtype directly when constructing the DataFrame:

>>> df = pd.DataFrame(index=range(0,4),columns=['A'], dtype='float')
>>> df.dtypes
A    float64
dtype: object

Specifying the dtype forces Pandas to try creating the DataFrame with that type, rather than trying to infer it.

MySQL "Or" Condition

Use brackets to group the OR statements.

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

You can also use IN

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo','$Date_ThreeDaysAgo','$Date_FourDaysAgo','$Date_FiveDaysAgo','$Date_SixDaysAgo','$Date_SevenDaysAgo')");

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

Get folder name of the file in Python

you can use pathlib

from pathlib import Path
Path(r"C:\folder1\folder2\filename.xml").parts[-2]

The output of the above was this:

'folder2'

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

How to echo out the values of this array?

The problem here is in your explode statement

//$item['date'] presumably = 20120514.  Do a print of this
$eventDate = trim($item['date']);

//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));

 //$myarray is currently = to '20'

 foreach ($myarray as $value) {
    //Now you are iterating through a string
    echo $value;
 }

Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.

AttributeError: 'module' object has no attribute 'model'

It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -

class Poll(models.Model):
    question = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published')

HTML form submit to PHP script

Assuming you've fixed the syntax errors (you've closed the select box before the name attribute), you're using the same name for the select box as the submit button. Give the select box a different name.

Pythonic way to return list of every nth item in a larger list

List comprehensions are exactly made for that:

smaller_list = [x for x in range(100001) if x % 10 == 0]

You can get more info about them in the python official documentation: http://docs.python.org/tutorial/datastructures.html#list-comprehensions

How to add a footer to the UITableView?

Initially I was just trying the method:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

but after using this along with:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

problem was solved. Sample Program-

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *sampleView = [[UIView alloc] init];
    sampleView.frame = CGRectMake(SCREEN_WIDTH/2, 5, 60, 4);
    sampleView.backgroundColor = [UIColor blackColor];
    return sampleView;
}

and include UITableViewDelegate protocol.

@interface TestViewController : UIViewController <UITableViewDelegate>

Python - Count elements in list

len() 

it will count the element in the list, tuple and string and dictionary, eg.

>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string 
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple 
>>> len(tup)
3

To learn Python you can use byte of python , it is best ebook for python beginners.

How to check if a String is numeric in Java

Regex Matching

Here is another example upgraded "CraigTP" regex matching with more validations.

public static boolean isNumeric(String str)
{
    return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
}
  1. Only one negative sign - allowed and must be in beginning.
  2. After negative sign there must be digit.
  3. Only one decimal sign . allowed.
  4. After decimal sign there must be digit.

Regex Test

1                  --                   **VALID**
1.                 --                   INVALID
1..                --                   INVALID
1.1                --                   **VALID**
1.1.1              --                   INVALID

-1                 --                   **VALID**
--1                --                   INVALID
-1.                --                   INVALID
-1.1               --                   **VALID**
-1.1.1             --                   INVALID

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

The current answer can be simplified to...

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

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

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

Oracle Age calculation from Date of birth and Today

Or how about this?

with some_birthdays as
( 
    select date '1968-06-09' d from dual union all
    select date '1970-06-10' from dual union all
    select date '1972-06-11' from dual union all
    select date '1974-12-11' from dual union all
    select date '1976-09-17' from dual
)
select trunc(sysdate) today
, d birth_date
, floor(months_between(trunc(sysdate),d)/12) age
from some_birthdays;

Split pandas dataframe in two if it has more than 10 rows

You can use the DataFrame head and tail methods as syntactic sugar instead of slicing/loc here. I use a split size of 3; for your example use headSize=10

def split(df, headSize) :
    hd = df.head(headSize)
    tl = df.tail(len(df)-headSize)
    return hd, tl

df = pd.DataFrame({    'A':[2,4,6,8,10,2,4,6,8,10],
                       'B':[10,-10,0,20,-10,10,-10,0,20,-10],
                       'C':[4,12,8,0,0,4,12,8,0,0],
                      'D':[9,10,0,1,3,np.nan,np.nan,np.nan,np.nan,np.nan]})

# Split dataframe into top 3 rows (first) and the rest (second)
first, second = split(df, 3)

Favicon: .ico or .png / correct tags?

See here: Cross Browser favicon

Thats the way to go:

<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->

T-SQL: How to Select Values in Value List that are NOT IN the Table?

For SQL Server 2008

SELECT email,
       CASE
         WHEN EXISTS(SELECT *
                     FROM   Users U
                     WHERE  E.email = U.email) THEN 'Exist'
         ELSE 'Not Exist'
       END AS [Status]
FROM   (VALUES('email1'),
              ('email2'),
              ('email3'),
              ('email4')) E(email)  

For previous versions you can do something similar with a derived table UNION ALL-ing the constants.

/*The SELECT list is the same as previously*/
FROM (
SELECT 'email1' UNION ALL
SELECT 'email2' UNION ALL
SELECT 'email3' UNION ALL
SELECT 'email4'
)  E(email)

Or if you want just the non-existing ones (as implied by the title) rather than the exact resultset given in the question, you can simply do this

SELECT email
FROM   (VALUES('email1'),
              ('email2'),
              ('email3'),
              ('email4')) E(email)  
EXCEPT
SELECT email
FROM Users

Best way to check function arguments?

This checks the type of input arguments upon calling the function:

def func(inp1:int=0,inp2:str="*"):

    for item in func.__annotations__.keys():
        assert isinstance(locals()[item],func.__annotations__[item])

    return (something)

first=7
second="$"
print(func(first,second))

Also check with second=9 (it must give assertion error)

What is the &#xA; character?

&#xA; is the HTML representation in hex of a line feed character. It represents a new line on Unix and Unix-like (for example) operating systems.

You can find a list of such characters at (for example) http://la.remifa.so/unicode/latin1.html

How to view the list of compile errors in IntelliJ?

the "problem view" mentioned in previous answers was helpful, but i saw it didn't catch all the errors in project. After running application, it began populating other classes that had issues but didn't appear at first in that problems view.

How can I change property names when serializing with Json.net?

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

Convert time in HH:MM:SS format to seconds only?

    $time = 00:06:00;
    $timeInSeconds = strtotime($time) - strtotime('TODAY');

Android marshmallow request permission?

Android-M ie, API 23 introduced Runtime Permissions for reducing security flaws in android device, where users can now directly manage app permissions at runtime.so if the user denies a particular permission of your application you have to obtain it by asking the permission dialog that you mentioned in your query.

So check before action ie, check you have permission to access the resource link and if your application doesn't have that particular permission you can request the permission link and handle the the permissions request response like below.

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

               } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

So finally, It's a good practice to go through behavior changes if you are planning to work with new versions to avoid force closes :)

Permissions Best Practices.

You can go through the official sample app here.

Create instance of generic type whose constructor requires a parameter?

It is still possible, with high performance, by doing the following:

    //
    public List<R> GetAllItems<R>() where R : IBaseRO, new() {
        var list = new List<R>();
        using ( var wl = new ReaderLock<T>( this ) ) {
            foreach ( var bo in this.items ) {
                T t = bo.Value.Data as T;
                R r = new R();
                r.Initialize( t );
                list.Add( r );
            }
        }
        return list;
    }

and

    //
///<summary>Base class for read-only objects</summary>
public partial interface IBaseRO  {
    void Initialize( IDTO dto );
    void Initialize( object value );
}

The relevant classes then have to derive from this interface and initialize accordingly. Please note, that in my case, this code is part of a surrounding class, which already has <T> as generic parameter. R, in my case, also is a read-only class. IMO, the public availability of Initialize() functions has no negative effect on the immutability. The user of this class could put another object in, but this would not modify the underlying collection.

Why should we include ttf, eot, woff, svg,... in a font-face

WOFF 2.0, based on the Brotli compression algorithm and other improvements over WOFF 1.0 giving more than 30 % reduction in file size, is supported in Chrome, Opera, and Firefox.

http://en.wikipedia.org/wiki/Web_Open_Font_Format http://en.wikipedia.org/wiki/Brotli

http://sth.name/2014/09/03/Speed-up-webfonts/ has an example on how to use it.

Basically you add a src url to the woff2 file and specify the woff2 format. It is important to have this before the woff-format: the browser will use the first format that it supports.

How to detect input type=file "change" for the same file?

Believe me, it will definitely help you!

// there I have called two `onchange event functions` due to some different scenario processing.

<input type="file" class="selectImagesHandlerDialog" 
    name="selectImagesHandlerDialog" 
    onclick="this.value=null;" accept="image/x-png,image/gif,image/jpeg" multiple 
    onchange="delegateMultipleFilesSelectionAndOpen(event); disposeMultipleFilesSelections(this);" />


// delegating multiple files select and open
var delegateMultipleFilesSelectionAndOpen = function (evt) {

  if (!evt.target.files) return;

  var selectedPhotos = evt.target.files;
  // some continuous source

};


// explicitly removing file input value memory cache
var disposeMultipleFilesSelections = function () {
  this.val = null;
};

Hope this will help many of you guys.

Adding options to a <select> using jQuery?

var select = $('#myselect');
var newOptions = {
                'red' : 'Red',
                'blue' : 'Blue',
                'green' : 'Green',
                'yellow' : 'Yellow'
            };
$('option', select).remove();
$.each(newOptions, function(text, key) {
    var option = new Option(key, text);
    select.append($(option));
});