Programs & Examples On #Iis 6

IIS (Internet Information Services) is a web server application and a set of feature extension modules created by Microsoft as part of Windows. IIS version 6 is shipped with Windows Server 2003 and Windows XP Professional x64 Edition. Both Windows XP and Windows Server 2003 are end of life, so migration to newer releases must be done.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

If you have Exchange 2010:

(In my case, the error message didn't contain " for [email protected]")

This shows how to add a receive connector: http://exchangeserverpro.com/how-to-configure-a-relay-connector-for-exchange-server-2010/

But I also needed to perform a step found here: http://recover-email.blogspot.com.au/2013/12/how-to-solve-exchange-smtp-server-error.html

  • Go to Exchange Management Shell and run the command
  • Get-ReceiveConnector "JiraTest" | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "ms-Exch-SMTP-Accept-Any-Recipient"

While working on this, I ran the following on the affected server's PowerShell console until the error went away:

Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "Test Email" -Body "This is a test"

Login failed for user 'DOMAIN\MACHINENAME$'

I also had this error with a SQL Server authenticated user

I tried some of the fixes, but they did not work.

The solution in my case was to configure its "Server Authentication Mode" to allow SQL Server authentication, under Management Studio: Properties/Security.

How to redirect a URL path in IIS?

Format the redirect URL in the following way:

stuff.mysite.org.uk$S$Q

The $S will say that any path must be applied to the new URL. $Q says that any parameter variables must be passed to the new URL.

In IIS 7.0, you must enable the option Redirect to exact destination. I believe there must be an option like this in IIS 6.0 too.

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

As drewm himself said this is due to the subsequent redirect after the POST to the script has in fact succeeded. (I might have added this as a comment to his answer but you need 50 reputation to comment and I'm new round here - daft rule IMHO)

BUT it also applies if you're trying to redirect to a page, not just a directory - at least it did for me. I was trying to redirect to /thankyou.html. What fixes this is using an absolute URL, i.e. http://example.com/thankyou.html

How to allow download of .json file with ASP.NET

Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).

  • Extension: .json
  • MIME type: application/json

Don't forget to restart IIS after the change.

UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.

What does 'IISReset' do?

It stops and starts the services that IIS consists of.

You can think of it as closing the relevant program and starting it up again.

IIS Request Timeout on long ASP.NET operation

If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.

For example:

// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;

This value can also be configured in your web.config file in the httpRuntime configuration element:

<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300" 
  ... other configuration attributes ...
/>

enter image description here

Please note according to the MSDN documentation:

"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."

If you've already done this but are finding that your session is expiring then increase the ASP.NET HttpSessionState.Timeout value:

For example:

// Increase session timeout to thirty minutes
Session.Timeout = 30;

This value can also be configured in your web.config file in the sessionState configuration element:

<configuration>
  <system.web>
    <sessionState 
      mode="InProc"
      cookieless="true"
      timeout="30" />
  </system.web>
</configuration>

If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.

The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.

Socket transport "ssl" in PHP not enabled

Ran into the same problem on Laravel 4 trying to send e-mail using SSL encryption.

Having WAMPServer 2.2 on Windows 7 64bit I only enabled php_openssl in the php.ini, restarted WAMPServer and worked flawlessly.

Did following:

  • Click WampServer -> PHP -> PHP extensions -> php_openssl
  • Restart WampServer

How to automatically select all text on focus in WPF TextBox?

This seems to work well for me. It's basically a recap of some earlier posts. I just put this into my MainWindow.xaml.cs file in the constructor. I create two handlers, one for keyboard, and one for the mouse, and funnel both events into the same function, HandleGotFocusEvent, which is defined right after the constructor in the same file.

public MainWindow()
{
   InitializeComponent();

   EventManager.RegisterClassHandler(typeof(TextBox), 
      UIElement.GotKeyboardFocusEvent,
      new RoutedEventHandler(HandleGotFocusEvent), true);
   EventManager.RegisterClassHandler(typeof(TextBox),
      UIElement.GotMouseCaptureEvent,
      new RoutedEventHandler(HandleGotFocusEvent), true);   
}
private void HandleGotFocusEvent(object sender, RoutedEventArgs e)
{
   if (sender is TextBox)
      (sender as TextBox).SelectAll();
}

How to get the current time as datetime

You can use Swift4 or Swift 5 bellow like:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let current_date = dateFormatter.string(from: date)
print("current_date-->",current_date)

output like:

2020-03-02

Why should we typedef a struct so often in C?

In 'C' programming language the keyword 'typedef' is used to declare a new name for some object(struct, array, function..enum type). For example, I will use a 'struct-s'. In 'C' we often declare a 'struct' outside of the 'main' function. For example:

struct complex{ int real_part, img_part }COMPLEX;

main(){

 struct KOMPLEKS number; // number type is now a struct type
 number.real_part = 3;
 number.img_part = -1;
 printf("Number: %d.%d i \n",number.real_part, number.img_part);

}

Each time I decide to use a struct type I will need this keyword 'struct 'something' 'name'.'typedef' will simply rename that type and I can use that new name in my program every time I want. So our code will be:

typedef struct complex{int real_part, img_part; }COMPLEX;
//now COMPLEX is the new name for this structure and if I want to use it without
// a keyword like in the first example 'struct complex number'.

main(){

COMPLEX number; // number is now the same type as in the first example
number.real_part = 1;
number.img)part = 5;
printf("%d %d \n", number.real_part, number.img_part);

}

If you have some local object(struct, array, valuable) that will be used in your entire program you can simply give it a name using a 'typedef'.

Is there a way to 'uniq' by column?

or if u want to use uniq:

<mycvs.cvs tr -s ',' ' ' | awk '{print $3" "$2" "$1}' | uniq -c -f2

gives:

1 01:05:47.893000000 2009-11-27 [email protected]
2 00:58:29.793000000 2009-11-27 [email protected]
1

Timestamp Difference In Hours for PostgreSQL

This might sound crazy to a lot of developers who like to take advantage of database functions,

But after exhaustive problems thinking, creating and bugfixing applications for mysql and postgrsql with php comparing date functions, I've come to the conclusion (for myself), that the easiest way, that is the simplest with less SQL headaches is not to take advantage of any of them.

Why? because if you are developing in a middleware language like PHP, PHP has all of these functions, and they are easier to implement in the application ode as comparing integers. PostgreSQL timestamp is NOT == UNIX TIMESTAMP and MySQL's UNIX TIMESTAMP is NOT PostgresQL's or Oracles timestamp.. it gets harder to port if you use database timestamps..

so just use an integer, not a timestamp, as the number of seconds since january 1st 1970 midnight. and never mind database timestamps. , and use gmdate() and store everything as gmt time to avoid timezone issues.

if you need to search, sort or compare the day from other data, or the month or the year or the day of the week, or anything, in your application, and INTEGER datatype for time_day, time_hour, time_seconds.. or whatever you wnat to index to be searched will make for smoother and more portable databases. you can just use one field, in most instances: INTEGER time_created NOT NULL

(more fields in your database row is the only drawback to this solution that i have found, and that doesnt cause as many headaches, or cups of coffee :)

php's date functions are outstanding to compare dates, but in mysql or postgresql, comparing dates ? nah.. use integer sql comparisons

i realize it may SEEM easier to use CURRENT_TIMESTAMP on an insert function. HA! don't be fooled.

You cant do DELETE FROM SESSION_TABLE WHERE time-initialized < '2 days' if time-intitialized is a postgresql timestamp. but you CAN do:

DELETE FROM SESSION_TABLE WHERE time_initialized < '$yesterday'

As long as you set $yesterday in php as the integer of seconds since 1970 that yesterday was.

This is easier housekeeping of session records than comparing timestamps in postgresql select statements.

SELECT age(), SELECT extract(), and asbtime are headaches in an of themselves. this is just my opinion.

you can do addition, substraction, <, >, all with php date objects

_peter_sysko U4EA Networks, Inc.

How to set Python's default version to 3.x on OS X?

Go to terminal type:

alias python=python3.x

This will setup default python as python3.x

How does one check if a table exists in an Android SQLite database?

Important condition is IF NOT EXISTS to check table is already exist or not in database

like...

String query = "CREATE TABLE IF NOT EXISTS " + TABLE_PLAYER_PHOTO + "("
            + KEY_PLAYER_ID + " TEXT,"
            + KEY_PLAYER_IMAGE + " TEXT)";
db.execSQL(query);

What is the difference between Jupyter Notebook and JupyterLab?

This answer shows the python perspective. Jupyter supports various languages besides python.

Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.

I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:

  1. In Jupyterlab, you can create ".py" files, ".ipynb" files, open terminal etc. Jupyter Notebook allows ".ipynb" files while providing you the choice to choose "python 2" or "python 3".
  2. Jupyterlab can open multiple ".ipynb" files inside a single browser tab. Whereas, Jupyter Notebook will create new tab to open new ".ipynb" files every time. Hovering between various tabs of browser is tedious, thus Jupyterlab is more helpful here.

I'd recommend using PIP to install Jupyterlab.

If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:

  1. Go to the file --> Right click --> Open With --> Choose another app --> More Apps --> Look for another apps on this PC --> Click.
  2. This will open a file explorer window. Now go inside your Python installation folder. You should see Scripts folder. Go inside it.
  3. Once you find jupyter-lab.exe, select that and now it will open the .ipynb files by default on your PC.

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

Android: how to handle button click

Option 1 and 2 involves using inner class that will make the code kind of clutter. Option 2 is sort of messy because there will be one listener for every button. If you have small number of button, this is okay. For option 4 I think this will be harder to debug as you will have to go back and fourth the xml and java code. I personally use option 3 when I have to handle multiple button clicks.

Java String import

String is present in package java.lang which is imported by default in all java programs.

How to watch for a route change in AngularJS?

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });

How to find the last day of the month from date?

There is also the built in PHP function cal_days_in_month()?

"This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30

Selecting a row of pandas series/dataframe by integer index

The primary purpose of the DataFrame indexing operator, [] is to select columns.

When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.

So, in the question above: df[2] searches for a column name matching the integer value 2. This column does not exist and a KeyError is raised.


The DataFrame indexing operator completely changes behavior to select rows when slice notation is used

Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.

df[2:3]

This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.

df[6:20:3]

You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.

I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc.

Unbound classpath container in Eclipse

  1. right click on the project folder go to Properties at bottom
  2. go to Java Build path
  3. click on Libraries tab
  4. select Classpath
  5. click Add Add Library button on right
  6. select JRE System Library and click Next and then Finish
  7. click Apply and Close the error should go away in IDE.

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

Please make sure that the column names, data types, and order in the table from where you are selecting records is exactly same as the destination table. Only difference should be that destination table has an identity column as the first column, that is not there in source table.

I was facing similar issue when I was executing "INSERT INTO table_Dest SELECT * FROM table_source_linked_server_excel". The tables had 115 columns.

I had two such tables where I was loading data from Excel (As linked server) into tables in database. In database tables, I had added an identity column called 'id' that was not there in source Excel. For one table the query was running successfully and in another I got the error "An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server". This was puzzling as the scenario was exactly same for both the queries. So I investigated into this and what I found was that in the query where I was getting error with INSERT INTO .. SELECT *:

  1. Some of the column names in source table were modified, though values were correct
  2. There were some extra columns beyond actual data columns that were being selected by SELECT *. I discovered this by using the option of "Script table as > Select to > new query window" on the source Excel table (under linked servers). There was one hidden column just after the last column in Excel, though it did not have any data. I deleted that column in source Excel table and saved it.

After making the above two changes the query for INSERT INTO... SELECT * ran successfully. The identity column in destination table generated identity values for each inserted row as expected.

So, even though the destination table may have an identity column that is not there in source table, the INSERT INTO.. SELECT * will run successfully if the names, data types, and column order in source and destination are exactly the same.

Hope it helps someone.

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

CSS to hide INPUT BUTTON value text

The difference some of you are seeing in solutions that work or not in the different IEs may be due to having compatibility mode on or off. In IE8, text-indent works just fine unless compatibility mode is turned on. If compatibility mode is on, then font-size and line-height do the trick but can mess up Firefox's display.

So we can use a css hack to let firefox ignore our ie rule.. like so...

text-indent:-9999px;
*font-size: 0px; line-height: 0;

Pass Method as Parameter using C#

You need to use a delegate. In this case all your methods take a string parameter and return an int - this is most simply represented by the Func<string, int> delegate1. So your code can become correct with as simple a change as this:

public bool RunTheMethod(Func<string, int> myMethodName)
{
    // ... do stuff
    int i = myMethodName("My String");
    // ... do more stuff
    return true;
}

Delegates have a lot more power than this, admittedly. For example, with C# you can create a delegate from a lambda expression, so you could invoke your method this way:

RunTheMethod(x => x.Length);

That will create an anonymous function like this:

// The <> in the name make it "unspeakable" - you can't refer to this method directly
// in your own code.
private static int <>_HiddenMethod_<>(string x)
{
    return x.Length;
}

and then pass that delegate to the RunTheMethod method.

You can use delegates for event subscriptions, asynchronous execution, callbacks - all kinds of things. It's well worth reading up on them, particularly if you want to use LINQ. I have an article which is mostly about the differences between delegates and events, but you may find it useful anyway.


1 This is just based on the generic Func<T, TResult> delegate type in the framework; you could easily declare your own:

public delegate int MyDelegateType(string value)

and then make the parameter be of type MyDelegateType instead.

Why did my Git repo enter a detached HEAD state?

The other way to get in a git detached head state is to try to commit to a remote branch. Something like:

git fetch
git checkout origin/foo
vi bar
git commit -a -m 'changed bar'

Note that if you do this, any further attempt to checkout origin/foo will drop you back into a detached head state!

The solution is to create your own local foo branch that tracks origin/foo, then optionally push.

This probably has nothing to do with your original problem, but this page is high on the google hits for "git detached head" and this scenario is severely under-documented.

What does an exclamation mark before a cell reference mean?

When entered as the reference of a Named range, it refers to range on the sheet the named range is used on.

For example, create a named range MyName refering to =SUM(!B1:!K1)

Place a formula on Sheet1 =MyName. This will sum Sheet1!B1:K1

Now place the same formula (=MyName) on Sheet2. That formula will sum Sheet2!B1:K1

Note: (as pnuts commented) this and the regular SheetName!B1:K1 format are relative, so reference different cells as the =MyName formula is entered into different cells.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:

  1. Go to the Project Structure, click on Modules, and click on your Module
  2. Choose the "Dependencies" tab
  3. Click the "+" button on the right-hand side and select "Jars or directories..."
  4. Add the directory(ies) you want (note you can multi-select) and click OK
  5. In the dialog that comes up, select "classes" and NOT "jar directory"
  6. Make sure you're using that Module in your run target

Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.

How to get hex color value rather than RGB value?

This one looks a bit nicer:

var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var r   = parseInt(rgb[0], 10);
var g   = parseInt(rgb[1], 10);
var b   = parseInt(rgb[2], 10);
var hex = '#'+ r.toString(16) + g.toString(16) + b.toString(16);

a more succinct one-liner:

var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var hex = '#'+ Number(rgb[0]).toString(16) + Number(rgb[1]).toString(16) + Number(rgb[2]).toString(16);

forcing jQuery to always return hex:

$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle) {
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        }
        if (bg.search("rgb") == -1) {
            return bg;
        } else {
            bg = bg.match(/\d+/g);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[0]) + hex(bg[1]) + hex(bg[2]);
        }
    }
}

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Another possible cause of similar issue could be wrong processorArchitecture in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:

https://bitbucket.org/anthony_tuininga/cx_freeze/pull-request/71/changed-x86-in-windows-manifest-to/diff

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

You can use functions in pyspark.sql.functions: functions like year, month, etc

refer to here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame

from pyspark.sql.functions import *

newdf = elevDF.select(year(elevDF.date).alias('dt_year'), month(elevDF.date).alias('dt_month'), dayofmonth(elevDF.date).alias('dt_day'), dayofyear(elevDF.date).alias('dt_dayofy'), hour(elevDF.date).alias('dt_hour'), minute(elevDF.date).alias('dt_min'), weekofyear(elevDF.date).alias('dt_week_no'), unix_timestamp(elevDF.date).alias('dt_int'))

newdf.show()


+-------+--------+------+---------+-------+------+----------+----------+
|dt_year|dt_month|dt_day|dt_dayofy|dt_hour|dt_min|dt_week_no|    dt_int|
+-------+--------+------+---------+-------+------+----------+----------+
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497603|
|   2015|       9|     6|      249|      0|     1|        36|1441497694|
|   2015|       9|     6|      249|      0|    20|        36|1441498808|
|   2015|       9|     6|      249|      0|    20|        36|1441498811|
|   2015|       9|     6|      249|      0|    20|        36|1441498815|

What is the default text size on Android?

the default text size of the textview

if you not used any of the below

TextAppearance.Small

TextAppearance.Medium

TextAppearance.Large

then the default size is 14sp

String, StringBuffer, and StringBuilder

  • You use String when an immutable structure is appropriate; obtaining a new character sequence from a String may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated).
  • You use StringBuilder when you need to create a mutable character sequence, usually to concatenate several character sequences together.
  • You use StringBuffer in the same circumstances you would use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).

See an example here.

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Got this error because I had the Data Source Name in User DSN instead of System DSN enter image description here

Writelines writes lines without newline, Just fills the file

As we have well established here, writelines does not append the newlines for you. But, what everyone seems to be missing, is that it doesn't have to when used as a direct "counterpart" for readlines() and the initial read persevered the newlines!

When you open a file for reading in binary mode (via 'rb'), then use readlines() to fetch the file contents into memory, split by line, the newlines remain attached to the end of your lines! So, if you then subsequently write them back, you don't likely want writelines to append anything!

So if, you do something like:

with open('test.txt','rb') as f: lines=f.readlines()
with open('test.txt','wb') as f: f.writelines(lines)

You should end up with the same file content you started with.

JSON parsing using Gson for Java

One way would be created a JsonObject and iterating through the parameters. For example

JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);

Then you can extract bean values like:

String fieldValue = jobj.get(fieldName).getAsString();
boolean fieldValue = jobj.get(fieldName).getAsBoolean();
int fieldValue = jobj.get(fieldName).getAsInt();

Hope this helps.

Mail not sending with PHPMailer over SSL using SMTP

I got a similar failure with SMTP whenever my client machine changes network connection (e.g., home vs. office network) and somehow restarting network service (or rebooting the machine) resolves the issue for me. Not sure if this would apply to your case, but just in case.

sudo /etc/init.d/networking restart   # for ubuntu

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

This is a mismatch between assemblies: a DLL referenced from an assembly doesn't have a method signature that's expected.

Clean the solution, rebuild everything, and try again.

Also, be careful if this is a reference to something that's in the GAC; it could be that something somewhere is pointing to an incorrect version. Make sure (through the Properties of each reference) that the correct version is chosen or that Specific Version is set false.

How to show disable HTML select option in by default?

Another SELECT tag solution for those who want to keep first option blank.

_x000D_
_x000D_
<label>Unreal :</label>_x000D_
<select name="unreal">_x000D_
   <option style="display:none"></option>_x000D_
   <option>Money</option>_x000D_
   <option>Country</option>_x000D_
   <option>God</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Git blame -- prior commits?

Building on Will Shepard's answer, his output will include duplicate lines for commits where there was no change, so you can filter those as as follows (using this answer)

LINE=1 FILE=a; for commit in $(git rev-list HEAD $FILE); do git blame -n -L$LINE,+1 $commit -- $FILE; done | sed '$!N; /^\(.*\)\n\1$/!P; D'

Note that I removed the REVS argument and this goes back to the root commit. This is due to Max Nanasy's observation above.

set up device for development (???????????? no permissions)

Enter the following commands:

adb kill-server
sudo ./adb start-server
adb devices

This happens when you are not running adb server as root.

How to include a Font Awesome icon in React's render()

I was experienced this case; I need the react/redux site that should be working perfectly in production.

but there was a 'strict mode'; Shouldn't lunch it with these commands.

yarn global add serve
serve -s build

Should working with only click the build/index.html file. When I used fontawesome with npm font-awesome, it was working in development mode but not working in the 'strict mode'.

Here is my solution:

public/css/font-awesome.min.css
public/fonts/font-awesome.eot 
*** other different types of files(4) ***
*** I copied these files for node_module/font-awesome ***
*** after copied then can delete the font-awesome from package.json ***

in public/index.html

<link rel="stylesheet" href="%PUBLIC_URL%/css/font-awesome.min.css">

After all of above steps, the fontawesome works NICELY!!!

How to convert an array of strings to an array of floats in numpy?

You can use this as well

import numpy as np
x=np.array(['1.1', '2.2', '3.3'])
x=np.asfarray(x,float)

CORS with POSTMAN

Use the browser/chrome postman plugin to check the CORS/SOP like a website. Use desktop application instead to avoid these controls.

Equal sized table cells to fill the entire width of the containing table

Using table-layout: fixed as a property for table and width: calc(100%/3); for td (assuming there are 3 td's). With these two properties set, the table cells will be equal in size.

Refer to the demo.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

If you're recompiling a disassembled APK with APK tool:

Just Set Memory Allocation a little bigger

set switch -Xmx1024mto -Xmx2048m

java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"

you're good to go.. :)

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

I needed to drop a table and re-create with a data from a view. I was creating a table out of a view and this is what I did:

DROP TABLE <table_name>;
CREATE TABLE <table_name> AS SELECT * FROM <view>;

The above worked for me using MySQL MariaDb.

Styling JQuery UI Autocomplete

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

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

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

}

How to check if an element exists in the xml using xpath?

Use:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

When to use <span> instead <p>?

The p tag denotes a paragraph element. It has margins/padding applied to it. A span is an unstyled inline tag. An important difference is that p is a block element when span is inline, meaning that <p>Hi</p><p>There</p> would appear on different lines when <span>Hi</span><span>There</span> winds up side by side.

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

.PopupPanel
{
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: white;
    z-index: 100;
    height: 400px;
    margin-top: -200px;

    width: 600px;
    margin-left: -300px;
}

Trying to include a library, but keep getting 'undefined reference to' messages

If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in

extern "C" void foo();

How to configure static content cache per folder and extension in IIS7?

You can do it on a per file basis. Use the path attribute to include the filename

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <location path="YourFileNameHere.xml">
        <system.webServer>
            <staticContent>
                <clientCache cacheControlMode="DisableCache" />
            </staticContent>
        </system.webServer>
    </location>
</configuration>

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

Bart Kiers, your regex has a couple issues. The best way to do that is this:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

m2e lifecycle-mapping not found

m2e 1.7 introduces a new syntax for lifecycle mapping metadata that doesn't cause this warning anymore:

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
    <execution>

        <!-- This executes the goal in Eclipse on project import.
             Other options like are available, eg ignore.  -->
        <?m2e execute?>

        <phase>generate-sources</phase>
        <goals><goal>add-source</goal></goals>
        <configuration>
            <sources>
                <source>src/bootstrap/java</source>
            </sources>
        </configuration>
    </execution>
</executions>
</plugin>

Opening a SQL Server .bak file (Not restoring!)

There is no standard way to do this. You need to use 3rd party tools such as ApexSQL Restore or SQL Virtual Restore. These tools don’t really read the backup file directly. They get SQL Server to “think” of backup files as if these were live databases.

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

use DBName

select * from TABLE_NAME A

where A.date >= '2018-06-26 21:24' and A.date <= '2018-06-26 21:28';

drag drop files into standard html file input

This is the "DTHML" HTML5 way to do it. Normal form input (which IS read only as Ricardo Tomasi pointed out). Then if a file is dragged in, it is attached to the form. This WILL require modification to the action page to accept the file uploaded this way.

_x000D_
_x000D_
function readfiles(files) {_x000D_
  for (var i = 0; i < files.length; i++) {_x000D_
    document.getElementById('fileDragName').value = files[i].name_x000D_
    document.getElementById('fileDragSize').value = files[i].size_x000D_
    document.getElementById('fileDragType').value = files[i].type_x000D_
    reader = new FileReader();_x000D_
    reader.onload = function(event) {_x000D_
      document.getElementById('fileDragData').value = event.target.result;}_x000D_
    reader.readAsDataURL(files[i]);_x000D_
  }_x000D_
}_x000D_
var holder = document.getElementById('holder');_x000D_
holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
holder.ondragend = function () { this.className = ''; return false; };_x000D_
holder.ondrop = function (e) {_x000D_
  this.className = '';_x000D_
  e.preventDefault();_x000D_
  readfiles(e.dataTransfer.files);_x000D_
}
_x000D_
#holder.hover { border: 10px dashed #0c0 !important; }
_x000D_
<form method="post" action="http://example.com/">_x000D_
  <input type="file"><input id="fileDragName"><input id="fileDragSize"><input id="fileDragType"><input id="fileDragData">_x000D_
  <div id="holder" style="width:200px; height:200px; border: 10px dashed #ccc"></div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

It is even more boss if you can make the whole window a drop zone, see How do I detect a HTML5 drag event entering and leaving the window, like Gmail does?

What is the purpose of a self executing function in javascript?

Simplistic. So very normal looking, its almost comforting:

var userName = "Sean";

console.log(name());

function name() {
  return userName;
}

However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations?

Wait... what?

I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'.

So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it.

One problem: it has a function in it called 'name' same as my function.

This is what's called collision. We've got two functions declared in the same scope with the same name. We want to avoid this.

So we need to scope our code somehow.

The only way to scope code in javascript is to wrap it in a function:

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.

We have a function in a function... which is weird to look at, but totally legal.

Only one problem. Our code doesn't work. Our userName variable is never echoed into the console!

We can solve this issue by adding a call to our function after our existing code block...

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

main();

Or before!

main();

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim.

We need MORE scoping. And some way to automatically execute our main() function.

Now we come to auto-execution functions (or self-executing, self-running, whatever).

((){})();

The syntax is awkward as sin. However, it works.

When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.

So lets look at our code again, with some self-executing syntax:

(function main() {
  var userName = "Sean";

    console.log(name());

    function name() {
      return userName;
    }
  }
)();

So, in most tutorials you read, you will now be bombard with the term 'anonymous self-executing' or something similar.

After many years of professional development, I strongly urge you to name every function you write for debugging purposes.

When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!

Hugely long-winded and I hope it helps!

Django DateField default options

date = models.DateTimeField(default=datetime.now, blank=True)

Routing with Multiple Parameters using ASP.NET MVC

Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.

A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Summary:

First you enable attribute routing

 public class RouteConfig 
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapMvcAttributeRoutes();
     } 
 }

Then you can use attributes to define parameters and optionally data types

public class BooksController : Controller
{
    // eg: /books
    // eg: /books/1430210079
    [Route("books/{isbn?}")]
    public ActionResult View(string isbn)

UTF-8 encoding problem in Spring MVC

Convert the JSON string to UTF-8 on your own.

@RequestMapping(value = "/example.json", method = RequestMethod.GET)
@ResponseBody
public byte[] example() throws Exception {

    return "{ 'text': 'äöüß' } ".getBytes("UTF-8");
}

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

  • The @@identity function returns the last identity created in the same session.
  • The scope_identity() function returns the last identity created in the same session and the same scope.
  • The ident_current(name) returns the last identity created for a specific table or view in any session.
  • The identity() function is not used to get an identity, it's used to create an identity in a select...into query.

The session is the database connection. The scope is the current query or the current stored procedure.

A situation where the scope_identity() and the @@identity functions differ, is if you have a trigger on the table. If you have a query that inserts a record, causing the trigger to insert another record somewhere, the scope_identity() function will return the identity created by the query, while the @@identity function will return the identity created by the trigger.

So, normally you would use the scope_identity() function.

Difference between "process.stdout.write" and "console.log" in node.js?

Another important difference in this context would with process.stdout.clearLine() and process.stdout.cursorTo(0).

This would be useful if you want to show percentage of download or processing in the only one line. If you use clearLine(), cursorTo() with console.log() it doesn't work because it also append \n to the text. Just try out this example:

var waitInterval = 500;
var totalTime = 5000;
var currentInterval = 0;

function showPercentage(percentage){
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    console.log(`Processing ${percentage}%...` ); //replace this line with process.stdout.write(`Processing ${percentage}%...`);
}

var interval = setInterval(function(){
 currentInterval += waitInterval;
 showPercentage((currentInterval/totalTime) * 100);
}, waitInterval);

setTimeout(function(){
 clearInterval(interval); 
}, totalTime);

How to get selected option using Selenium WebDriver with Java

Completing the answer:

String selectedOption = new Select(driver.findElement(By.xpath("Type the xpath of the drop-down element"))).getFirstSelectedOption().getText();

Assert.assertEquals("Please select any option...", selectedOption);

Google Chrome Printing Page Breaks

Have that issue. So long time pass... Without side-fields of page it's break normal, but when fields appears, page and "page break space" will scale. So, with a normal field, within a document, it was shown incorrect. I fix it with set

    width:100%

and use

div.page
  {
    page-break-before: always;
    page-break-inside: avoid;
  }

Use it on first line.

TensorFlow not found using pip

The correct way to install it would be as mentioned here

$ pip install --upgrade TF_BINARY_URL   # Python 2.7
$ pip3 install --upgrade TF_BINARY_URL  # Python 3.N

Find the correct TF_BINARY_URL for your hardware from the tensor flow official homepage

Is it possible to decrypt MD5 hashes?

Yes, exactly what you're asking for is possible. It is not possible to 'decrypt' an MD5 password without help, but it is possible to re-encrypt an MD5 password into another algorithm, just not all in one go.

What you do is arrange for your users to be able to logon to your new system using the old MD5 password. At the point that they login they have given your login program an unhashed version of the password that you prove matches the MD5 hash that you have. You can then convert this unhashed password to your new hashing algorithm.

Obviously, this is an extended process because you have to wait for your users to tell you what the passwords are, but it does work.

(NB: seven years later, oh well hopefully someone will find it useful)

.NET 4.0 has a new GAC, why?

Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.

In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.

To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.

Source

Why?

It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.

See the following information in MSDN about the GAC changes in 4.0.

For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.

As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.

Can't specify the 'async' modifier on the 'Main' method of a console app

When the C# 5 CTP was introduced, you certainly could mark Main with async... although it was generally not a good idea to do so. I believe this was changed by the release of VS 2013 to become an error.

Unless you've started any other foreground threads, your program will exit when Main completes, even if it's started some background work.

What are you really trying to do? Note that your GetList() method really doesn't need to be async at the moment - it's adding an extra layer for no real reason. It's logically equivalent to (but more complicated than):

public Task<List<TvChannel>> GetList()
{
    return new GetPrograms().DownloadTvChannels();
}

char initial value in Java

As you will see in linked discussion there is no need for initializing char with special character as it's done for us and is represented by '\u0000' character code.

So if we want simply to check if specified char was initialized just write:

if(charVariable != '\u0000'){
 actionsOnInitializedCharacter();
}

Link to question: what's the default value of char?

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

The issue for me was the type I was using was in objective-c in a swift project and I had forgotten to import the type's objective-c header file in the bridging header file

How to check string length with JavaScript

Leaving a reply (and an answer to the question title), For the future googlers...

You can use .length to get the length of a string.

var x = 'Mozilla'; var empty = '';

console.log('Mozilla is ' + x.length + ' code units long');

/*"Mozilla is 7 code units long" */

console.log('The empty string has a length of ' + empty.length);

/*"The empty string has a length of 0" */

If you intend to get the length of a textarea say id="txtarea" then you can use the following code.

txtarea = document.getElementById('txtarea');
console.log(txtarea.value.length);

You should be able to get away with using this with BMP Unicode symbols. If you want to support "non BMP Symbols" like (), then its an edge case, and you need to find some work around.

HTML Upload MAX_FILE_SIZE does not appear to work

PHP.net explanation about MAX_FILE_SIZE hidden field.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.

http://php.net/manual/en/features.file-upload.post-method.php

Ways to eliminate switch in code

Switch is not a good way to go as it breaks the Open Close Principal. This is how I do it.

public class Animal
{
       public abstract void Speak();
}


public class Dog : Animal
{
   public virtual void Speak()
   {
       Console.WriteLine("Hao Hao");
   }
}

public class Cat : Animal
{
   public virtual void Speak()
   {
       Console.WriteLine("Meauuuu");
   }
}

And here is how to use it (taking your code):

foreach (var animal in zoo) 
{
    echo animal.speak();
}

Basically what we are doing is delegating the responsibility to the child class instead of having the parent decide what to do with children.

You might also want to read up on "Liskov Substitution Principle".

Changing date format in R

Using one line to convert the dates to preferred format:

nzd$date <- format(as.Date(nzd$date, format="%d/%m/%Y"),"%Y/%m/%d")

How to Lazy Load div background images

I've found this on the plugin's official site:

<div class="lazy" data-original="img/bmw_m1_hood.jpg" style="background-image: url('img/grey.gif'); width: 765px; height: 574px;"></div>

$("div.lazy").lazyload({
      effect : "fadeIn"
});

Source: http://www.appelsiini.net/projects/lazyload/enabled_background.html

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

Docker - Ubuntu - bash: ping: command not found

Every time you get this kind of error

bash: <command>: command not found
  • On a host with that command already working with this solution:

    dpkg -S $(which <command>)
    
  • Don't have a host with that package installed? Try this:

    apt-file search /bin/<command>
    

How to check if ping responded or not in a batch file

Here's something I found:

:pingtheserver
ping %input% | find "Reply" > nul
if not errorlevel 1 (
    echo server is online, up and running.
) else (
    echo host has been taken down wait 3 seconds to refresh
    ping 1.1.1.1 -n 1 -w 3000 >NUL
    goto :pingtheserver
) 

Note that ping 1.1.1.1 -n -w 1000 >NUL will wait 1 second but only works when connected to a network

How can I check out a GitHub pull request with git?

If you're following the "github fork" workflow, where you create a fork and add the remote upstream repo:

14:47 $ git remote -v
origin  [email protected]:<yourname>/<repo_name>.git (fetch)
origin  [email protected]:<yourname>/<repo_name>.git (push)
upstream        [email protected]:<repo_owrer>/<repo_name>.git (fetch)
upstream        [email protected]:<repo_owner>/<repo_name>.git (push)

to pull into your current branch your command would look like:

git pull upstream pull/<pull_request_number>/head

to pull into a new branch the code would look like:

git fetch upstream pull/<pull_request_number>/head:newbranch

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

i had this problem when running the magento indexer in osx. and yes its related to php problem when connecting to mysql through pdo

in mac osx xampp, to fix this you have create symbolic link to directory /var/mysql, here is how

cd /var/mysql && sudo ln -s /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

if the directory /var/mysql doesnt exist, we must create it with

sudo mkdir /var/mysql

Problems with Android Fragment back stack

First of all thanks @Arvis for an eye opening explanation.

I prefer different solution to the accepted answer here for this problem. I don't like messing with overriding back behavior any more than absolutely necessary and when I've tried adding and removing fragments on my own without default back stack poping when back button is pressed I found my self in fragment hell :) If you .add f2 over f1 when you remove it f1 won't call any of callback methods like onResume, onStart etc. and that can be very unfortunate.

Anyhow this is how I do it:

Currently on display is only fragment f1.

f1 -> f2

Fragment2 f2 = new Fragment2();
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,f2).addToBackStack(null).commit();

nothing out of the ordinary here. Than in fragment f2 this code takes you to fragment f3.

f2 -> f3

Fragment3 f3 = new Fragment3();
getActivity().getSupportFragmentManager().popBackStack();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content, f3).addToBackStack(null).commit();

I'm not sure by reading docs if this should work, this poping transaction method is said to be asynchronous, and maybe a better way would be to call popBackStackImmediate(). But as far I can tell on my devices it's working flawlessly.

The said alternative would be:

final FragmentActivity activity = getActivity();
activity.getSupportFragmentManager().popBackStackImmediate();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.main_content, f3).addToBackStack(null).commit();

Here there will actually be brief going back to f1 beofre moving on to f3, so a slight glitch there.

This is actually all you have to do, no need to override back stack behavior...

is there a require for json in node.js

As of node v0.5.x yes you can require your JSON just as you would require a js file.

var someObject = require('./somefile.json')

In ES6:

import someObject from ('./somefile.json')

Should try...catch go inside or outside a loop?

All right, after Jeffrey L Whitledge said that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:

public class Main {

    private static final int NUM_TESTS = 100;
    private static int ITERATIONS = 1000000;
    // time counters
    private static long inTime = 0L;
    private static long aroundTime = 0L;

    public static void main(String[] args) {
        for (int i = 0; i < NUM_TESTS; i++) {
            test();
            ITERATIONS += 1; // so the tests don't always return the same number
        }
        System.out.println("Inside loop: " + (inTime/1000000.0) + " ms.");
        System.out.println("Around loop: " + (aroundTime/1000000.0) + " ms.");
    }
    public static void test() {
        aroundTime += testAround();
        inTime += testIn();
    }
    public static long testIn() {
        long start = System.nanoTime();
        Integer i = tryInLoop();
        long ret = System.nanoTime() - start;
        System.out.println(i); // don't optimize it away
        return ret;
    }
    public static long testAround() {
        long start = System.nanoTime();
        Integer i = tryAroundLoop();
        long ret = System.nanoTime() - start;
        System.out.println(i); // don't optimize it away
        return ret;
    }
    public static Integer tryInLoop() {
        int count = 0;
        for (int i = 0; i < ITERATIONS; i++) {
            try {
                count = Integer.parseInt(Integer.toString(count)) + 1;
            } catch (NumberFormatException ex) {
                return null;
            }
        }
        return count;
    }
    public static Integer tryAroundLoop() {
        int count = 0;
        try {
            for (int i = 0; i < ITERATIONS; i++) {
                count = Integer.parseInt(Integer.toString(count)) + 1;
            }
            return count;
        } catch (NumberFormatException ex) {
            return null;
        }
    }
}

I checked the resulting bytecode using javap to make sure that nothing got inlined.

The results showed that, assuming insignificant JIT optimizations, Jeffrey is correct; there is absolutely no performance difference on Java 6, Sun client VM (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.

Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or Ray Hayes's way.

How to add browse file button to Windows Form using C#

OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}

In this code you can put your address in a text box.

Find all files with name containing string

grep -R "somestring" | cut -d ":" -f 1

$('body').on('click', '.anything', function(){})

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

Getting A File's Mime Type In Java

It is better to use two layer validation for files upload.

First you can check for the mimeType and validate it.

Second you should look to convert the first 4 bytes of your file to hexadecimal and then compare it with the magic numbers. Then it will be a really secure way to check for file validations.

Which browser has the best support for HTML 5 currently?

i think right now is Firefox 3.6.2, but when internet explorer 9 launched, it will support HTML5

how to use a like with a join in sql?

Using conditional criteria in a join is definitely different than the Where clause. The cardinality between the tables can create differences between Joins and Where clauses.

For example, using a Like condition in an Outer Join will keep all records in the first table listed in the join. Using the same condition in the Where clause will implicitly change the join to an Inner join. The record has to generally be present in both tables to accomplish the conditional comparison in the Where clause.

I generally use the style given in one of the prior answers.

tbl_A as ta
    LEFT OUTER JOIN tbl_B AS tb
            ON ta.[Desc] LIKE '%' + tb.[Desc] + '%'

This way I can control the join type.

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

Expanding on @Renaud idea, cors now provides a very easy way of doing this:

From cors official documentation found here:

" origin: Configures the Access-Control-Allow-Origin CORS header. Possible values: Boolean - set origin to true to reflect the request origin, as defined by req.header('Origin'), or set it to false to disable CORS. "

Hence we simply do the following:

const app = express();
const corsConfig = {
    credentials: true,
    origin: true,
};
app.use(cors(corsConfig));

Lastly I think it is worth mentioning that there are use cases where we would want to allow cross origin requests from anyone; for example, when building a public REST API.

NOTE: I would have liked to leave this as a comment on his answer, but unfortunately I don't have the reputation points.

get list of pandas dataframe columns based on data type

If after 6 years you still have the issue, this should solve it :)

cols = [c for c in df.columns if df[c].dtype in ['object', 'datetime64[ns]']]

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:

$('input[type=file]').change(function () {
    console.log(this.files[0].mozFullPath);
});

http://jsfiddle.net/SCK5A/

So don't waste your time.

edit: If you need the file's path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.

scp or sftp copy multiple files with single command

Problem: Copying multiple directories from remote server to local machine using a single SCP command and retaining each directory as it is in the remote server.

Solution: SCP can do this easily. This solves the annoying problem of entering password multiple times when using SCP with multiple folders. Consequently, this also saves a lot of time!

e.g.

# copies folders t1, t2, t3 from `test` to your local working directory
# note that there shouldn't be any space in between the folder names;
# we also escape the braces.
# please note the dot at the end of the SCP command

~$ cd ~/working/directory
~$ scp -r [email protected]:/work/datasets/images/test/\{t1,t2,t3\}  .

PS: Motivated by this great answer: scp or sftp copy multiple files with single command


Based on the comments, this also works fine in Git Bash on Windows

PHP PDO returning single row

how about using limit 0,1 for mysql optimisation

and about your code:

$DBH = new PDO( "connection string goes here" );

$STH - $DBH -> prepare( "select figure from table1" );

$STH -> execute();

$result = $STH ->fetch(PDO::FETCH_ASSOC)

echo $result["figure"];

$DBH = null;

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

How do I make a request using HTTP basic authentication with PHP curl?

For those who don't want to use curl:

//url
$url = 'some_url'; 

//Credentials
$client_id  = "";
$client_pass= ""; 

//HTTP options
$opts = array('http' =>
    array(
        'method'    => 'POST',
        'header'    => array ('Content-type: application/json', 'Authorization: Basic '.base64_encode("$client_id:$client_pass")),
        'content' => "some_content"
    )
);

//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);

$result = json_decode($json, true);
if(json_last_error() != JSON_ERROR_NONE){
    return null;
}

print_r($result);

Hide div by default and show it on click with bootstrap

I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse class to show/hide divs and Bootstrap's "Collapse Event".

What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div> based on, lets say, menu buttons on a navbar. Below is a simple solution to this. The anchor tags (<a>) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-

All that the JavaScript does is makes all the other <div> hide using

$(".main-container.collapse").not($(this)).collapse('hide');

when the loaded <div> is displayed by checking the Collapse event shown.bs.collapse. Here's the Bootstrap documentation on Collapse Event.

Note: main-container is just a custom class.

Here it goes-

_x000D_
_x000D_
$(".main-container.collapse").on('shown.bs.collapse', function () {    _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
       $(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
    This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
    This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android global variable

You could use application preferences. They are accessible from any activity or piece of code as long as you pass on the Context object, and they are private to the application that uses them, so you don't need to worry about exposing application specific values, unless you deal with routed devices. Even so, you could use hashing or encryption schemes to save the values. Also, these preferences are stored from an application run to the next. Here is some code examples that you can look at.

Xcode 6.1 Missing required architecture X86_64 in file

Setting the build active architectures only to No fixed this problem for me. enter image description here

Regular expression to limit number of characters to 10

pattern: /[\w\W]{1,10}/g

I used this expression for my case, it includes all the characters available in the text.

jQuery multiple conditions within if statement

Try

if (!(i == 'InvKey' || i == 'PostDate')) {

or

if (i != 'InvKey' || i != 'PostDate') {

that says if i does not equals InvKey OR PostDate

var.replace is not a function

My guess is that the code that's calling your trim function is not actually passing a string to it.

To fix this, you can make str a string, like this: str.toString().replace(...)
...as alper pointed out below.

Styling input buttons for iPad and iPhone

I had the same issue today using primefaces (primeng) and angular 7. Add the following to your style.css

p-button {
   -webkit-appearance: none !important;
}

i am also using a bit of bootstrap which has a reboot.css, that overrides it with (thats why i had to add !important)

button {
  -webkit-appearance: button;

}

how to convert current date to YYYY-MM-DD format with angular 2

Example as per doc

@Component({
  selector: 'date-pipe',
  template: `<div>
    <p>Today is {{today | date}}</p>
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>
    <p>The time is {{today | date:'jmZ'}}</p>
  </div>`
})
export class DatePipeComponent {
  today: number = Date.now();
}

Template

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mmss' }}        // output is '43:11'
{{dateObj  | date: 'dd/MM/yyyy'}} // 15/06/2015

To Use in your component.

@Injectable()
import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need. 
  }
}

In your app.module.ts

providers: [DatePipe,...] 

all you have to do is use this service now.

How to percent-encode URL parameters in Python?

If you're using django, you can use urlquote:

>>> from django.utils.http import urlquote
>>> urlquote(u"Müller")
u'M%C3%BCller'

Note that changes to Python since this answer was published mean that this is now a legacy wrapper. From the Django 2.1 source code for django.utils.http:

A legacy compatibility wrapper to Python's urllib.parse.quote() function.
(was used for unicode handling on Python 2)

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

You can't. Your only option is to divide this into multiple tables and put the form tag outside of it. You could end up nesting your tables, but this is not recommended:

<table>
  <tr><td><form>
    <table><tr><td>id</td><td>name</td>...</tr></table>
  </form></td></tr>
</table>

I would remove the tables entirely and replace it with styled html elements like divs and spans.

How to return a value from a Form in C#?

I normally create a static method on form/dialog, that I can call. This returns the success (OK-button) or failure, along with the values that needs to be filled in.

 public class ResultFromFrmMain {
     public DialogResult Result { get; set; }
     public string Field1 { get; set; }


 }

And on the form:

public static ResultFromFrmMain Execute() {
     using (var f = new frmMain()) {
          var result = new ResultFromFrmMain();
          result.Result = f.ShowDialog();
          if (result.Result == DialogResult.OK) {
             // fill other values
          }
          return result;
     }
}

To call your form;

public void MyEventToCallForm() {
   var result = frmMain.Execute();
   if (result.Result == DialogResult.OK) {
       myTextBox.Text = result.Field1; // or something like that
   }
}

iPhone SDK on Windows (alternative solutions)

No, you must have an Intel Mac of some sort. I went to Best Buy and got a 24" iMac with 4G RAM for $1499 using their 18 month no interest promotion. I pay a minimum payment of something like $16 a month. As long as I pay the entire thing off within 18 months - no interest. That was the only way I was getting into iPhone development.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I encountered the same problem , my resolution was to rename the the folder name under the workspace folder. i.e. com.ibm.collaboration.realtime.alertmanager.embedded was renamed to com.ibm.collaboration.realtime.alertmanager.2embeddedxx and rebuilt my project.

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

How to set value to variable using 'execute' in t-sql?

The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised

You'll have to use a temp table/table variable outside of the dynamic SQL:

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)

INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')  

select * FROM @siteId

Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY

"Javac" doesn't work correctly on Windows 10

If you have set all PATH variables correctly after installation, just restart it.

I had the same problem, I had also installed new Windows7 OS then I upgraded it to Win 10. Then i started setup necessary tools like IntelliJ, Java jdk,jre, eclipse so on. In cmd, java -version worked but javac compiler got unrecognized. I checked and all good, the files in the folders, path are correct and so on.

I restarted and checked it again in cmd ,it worked.

How do I get hour and minutes from NSDate?

With iOS 8, Apple introduced a helper method to retrieve the hour, minute, second and nanosecond from an NSDate object.

Objective-C

NSDate *date = [NSDate currentDate];
NSInteger hour = 0;
NSInteger minute = 0;
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
[currentCalendar getHour:&hour minute:&minute second:NULL nanosecond:NULL fromDate:date];
NSLog(@"the hour is %ld and minute is %ld", (long)hour, (long)minute);

Swift

let date = NSDate()
var hour = 0
var minute = 0
let calendar = NSCalendar.currentCalendar()
if #available(iOS 8.0, *) {
    calendar.getHour(&hour, minute: &minute, second: nil, nanosecond: nil, fromDate: date)
    print("the hour is \(hour) and minute is \(minute)")
}

How to enable C# 6.0 feature in Visual Studio 2013?

A lot of the answers here were written prior to Roslyn (the open-source .NET C# and VB compilers) moving to .NET 4.6. So they won't help you if your project targets, say, 4.5.2 as mine did (inherited and can't be changed).

But you can grab a previous version of Roslyn from https://www.nuget.org/packages/Microsoft.Net.Compilers and install that instead of the latest version. I used 1.3.2. (I tried 2.0.1 - which appears to be the last version that runs on .NET 4.5 - but I couldn't get it to compile*.) Run this from the Package Manager console in VS 2013:

PM> Install-Package Microsoft.Net.Compilers -Version 1.3.2

Then restart Visual Studio. I had a couple of problems initially; you need to set the C# version back to default (C#6.0 doesn't appear in the version list but seems to have been made the default), then clean, save, restart VS and recompile.

Interestingly, I didn't have any IntelliSense errors due to the C#6.0 features used in the code (which were the reason for wanting C#6.0 in the first place).

* version 2.0.1 threw error The "Microsoft.CodeAnalysis.BuildTasks.Csc task could not be loaded from the assembly Microsoft.Build.Tasks.CodeAnalysis.dll. Could not load file or assembly 'Microsoft.Build.Utilities.Core, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

UPDATE One thing I've noticed since posting this answer is that if you change any code during debug ("Edit and Continue"), you'll like find that your C#6.0 code will suddenly show as errors in what seems to revert to a pre-C#6.0 environment. This requires a restart of your debug session. VERY annoying especially for web applications.

Wait some seconds without blocking UI execution

I use:

private void WaitNSeconds(int segundos)
{
    if (segundos < 1) return;
    DateTime _desired = DateTime.Now.AddSeconds(segundos);
    while (DateTime.Now < _desired) {
         System.Windows.Forms.Application.DoEvents();
    }
}

Check if option is selected with jQuery, if not select a default

lencioni's answer is what I'd recommend. You can change the selector for the option ('#mySelect option:last') to select the option with a specific value using "#mySelect option[value='yourDefaultValue']". More on selectors.

If you're working extensively with select lists on the client check out this plugin: http://www.texotela.co.uk/code/jquery/select/. Take a look the source if you want to see some more examples of working with select lists.

Move column by name to front of table in pandas

The most simplist thing you can try is:

df=df[[ 'Mid',   'Upper',   'Lower', 'Net'  , 'Zsore']]

int array to string

I've left this here for posterity but don't recommend its use as it's not terribly readable. This is especially true now that I've come back to see if after a period of some time and have wondered what I was thinking when I wrote it (I was probably thinking 'crap, must get this written before someone else posts an answer'.)

string s = string.Concat(arr.Cast<object>().ToArray());

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

I had the same problem. Adding include path does work for all except std::string.

I noticed in the mingw-Toolchain many system header files *.tcc

I added filetype *.tcc as "C++ Header File" in Preferences > C/C++/ File Types. Now std::string can be resolved from the internal index and Code Analyzer. Perhaps this is added to Eclipse CDT by default in feature.

I hope this helps to someone...

PS: I'm using Eclipse Mars, mingw gcc 4.8.1, Own Makefile, no Eclipse Makefilebuilder.

How do I remove blank pages coming between two chapters in Appendix?

If you specify the option 'openany' in the \documentclass declaration each chapter in the book (I'm guessing you're using the book class as chapters open on the next page in reports and articles don't have chapters) will open on a new page, not necessarily the next odd-numbered page.

Of course, that's not quite what you want. I think you want to set openany for chapters in the appendix. 'fraid I don't know how to do that, I suspect that you need to roll up your sleeves and wrestle with TeX itself

JavaScript Loading Screen while page loads

If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with

$(document).ajaxStop(function(){
    alert("All AJAX requests completed");
});

https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.

INSERT ... ON DUPLICATE KEY (do nothing)

HOW TO IMPLEMENT 'insert if not exist'?

1. REPLACE INTO

pros:

  1. simple.

cons:

  1. too slow.

  2. auto-increment key will CHANGE(increase by 1) if there is entry matches unique key or primary key, because it deletes the old entry then insert new one.

2. INSERT IGNORE

pros:

  1. simple.

cons:

  1. auto-increment key will not change if there is entry matches unique key or primary key but auto-increment index will increase by 1

  2. some other errors/warnings will be ignored such as data conversion error.

3. INSERT ... ON DUPLICATE KEY UPDATE

pros:

  1. you can easily implement 'save or update' function with this

cons:

  1. looks relatively complex if you just want to insert not update.

  2. auto-increment key will not change if there is entry matches unique key or primary key but auto-increment index will increase by 1

4. Any way to stop auto-increment key increasing if there is entry matches unique key or primary key?

As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode config after version 5.1" if you are using innodb as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.

Singletons vs. Application Context in Android?

I very much recommend singletons. If you have a singleton that needs a context, have:

MySingleton.getInstance(Context c) {
    //
    // ... needing to create ...
    sInstance = new MySingleton(c.getApplicationContext());
}

I prefer singletons over Application because it helps keep an app much more organized and modular -- instead of having one place where all of your global state across the app needs to be maintained, each separate piece can take care of itself. Also the fact that singletons lazily initialize (at request) instead of leading you down the path of doing all initialization up-front in Application.onCreate() is good.

There is nothing intrinsically wrong with using singletons. Just use them correctly, when it makes sense. The Android framework actually has a lot of them, for it to maintain per-process caches of loaded resources and other such things.

Also for simple applications multithreading doesn't become an issue with singletons, because by design all standard callbacks to the app are dispatched on the main thread of the process so you won't have multi-threading happening unless you introduce it explicitly through threads or implicitly by publishing a content provider or service IBinder to other processes.

Just be thoughtful about what you are doing. :)

How to change text color of simple list item

If you want to keep all the style but change few details, you can use the default style defined on the Android and change what you want

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:textColor="@android:color/background_light"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall" />

Then set the adapter using:

setListAdapter(new ArrayAdapter<String>(getApplicationContext(),
            R.layout.list_item_custom, mStringList));

Source: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/layout/simple_list_item_activated_1.xml

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How do I make curl ignore the proxy?

Add your proxy preferences into .curlrc

proxy = 1.2.3.4
noproxy = .dev,localhost,127.0.0.1

This make all dev domains and local machine request ignore the proxy.

How do I repair an InnoDB table?

See this article: http://www.unilogica.com/mysql-innodb-recovery/ (It's in portuguese)

Are explained how to use innodb_force_recovery and innodb_file_per_table. I discovered this after need to recovery a crashed database with a single ibdata1.

Using innodb_file_per_table, all tables in InnoDB will create a separated table file, like MyISAM.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

Text file with 0D 0D 0A line breaks

Netscape ANSI encoded files use 0D 0D 0A for their line breaks.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

Bookmarking this URL should give you a full-screen compose window, without any distractions:

https://mail.google.com/mail/?view=cm&fs=1&tf=1

Additionally, if you want to be future-proof (see for instance how other URLs in this question stopped working) you can bookmark a link to:

mailto:

It will open your default email client and you probably already have Gmail configured for that purpose.

How to center absolute div horizontally using CSS?

Centering div with position: absolute and width: unknown:

HTML:

<div class="center">
  <span></span>

  <div>
    content...
  </div>

</div>

CSS:

.center{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: grid;
  grid-template-columns: auto auto;
  overflow: auto;
}

Getting Java version at runtime

Here is the answer from @mvanle, converted to Scala: scala> val Array(javaVerPrefix, javaVerMajor, javaVerMinor, _, _) = System.getProperty("java.runtime.version").split("\\.|_|-b") javaVerPrefix: String = 1 javaVerMajor: String = 8 javaVerMinor: String = 0

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

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

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

Should I return EXIT_SUCCESS or 0 from main()?

This is a never ending story that reflect the limits (an myth) of "interoperability and portability over all".

What the program should return to indicate "success" should be defined by who is receiving the value (the Operating system, or the process that invoked the program) not by a language specification.

But programmers likes to write code in "portable way" and hence they invent their own model for the concept of "operating system" defining symbolic values to return.

Now, in a many-to-many scenario (where many languages serve to write programs to many system) the correspondence between the language convention for "success" and the operating system one (that no one can grant to be always the same) should be handled by the specific implementation of a library for a specific target platform.

But - unfortunatly - these concept where not that clear at the time the C language was deployed (mainly to write the UNIX kernel), and Gigagrams of books where written by saying "return 0 means success", since that was true on the OS at that time having a C compiler.

From then on, no clear standardization was ever made on how such a correspondence should be handled. C and C++ has their own definition of "return values" but no-one grant a proper OS translation (or better: no compiler documentation say anything about it). 0 means success if true for UNIX - LINUX and -for independent reasons- for Windows as well, and this cover 90% of the existing "consumer computers", that - in the most of the cases - disregard the return value (so we can discuss for decades, bu no-one will ever notice!)

Inside this scenario, before taking a decision, ask these questions: - Am I interested to communicate something to my caller about my existing? (If I just always return 0 ... there is no clue behind the all thing) - Is my caller having conventions about this communication ? (Note that a single value is not a convention: that doesn't allow any information representation)

If both of this answer are no, probably the good solution is don't write the main return statement at all. (And let the compiler to decide, in respect to the target is working to).

If no convention are in place 0=success meet the most of the situations (and using symbols may be problematic, if they introduce a convention).

If conventions are in place, ensure to use symbolic constants that are coherent with them (and ensure convention coherence, not value coherence, between platforms).

Android: ScrollView force to bottom

This works instantly. Without delay.

// wait for the scroll view to be laid out
scrollView.post(new Runnable() {
  public void run() {
    // then wait for the child of the scroll view (normally a LinearLayout) to be laid out
    scrollView.getChildAt(0).post(new Runnable() {
      public void run() {
        // finally scroll without animation
        scrollView.scrollTo(0, scrollView.getBottom());
      }
    }
  }
}

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").

Java LinkedHashMap get first or last entry

For first element use entrySet().iterator().next() and stop iterating after 1 iteration. For last one the easiest way is to preserve the key in a variable whenever you do a map.put.

What's the difference between deadlock and livelock?

All the content and examples here are from

Operating Systems: Internals and Design Principles
William Stallings
8º Edition

Deadlock: A situation in which two or more processes are unable to proceed because each is waiting for one the others to do something.

For example, consider two processes, P1 and P2, and two resources, R1 and R2. Suppose that each process needs access to both resources to perform part of its function. Then it is possible to have the following situation: the OS assigns R1 to P2, and R2 to P1. Each process is waiting for one of the two resources. Neither will release the resource that it already owns until it has acquired the other resource and performed the function requiring both resources. The two processes are deadlocked

Livelock: A situation in which two or more processes continuously change their states in response to changes in the other process(es) without doing any useful work:

Starvation: A situation in which a runnable process is overlooked indefinitely by the scheduler; although it is able to proceed, it is never chosen.

Suppose that three processes (P1, P2, P3) each require periodic access to resource R. Consider the situation in which P1 is in possession of the resource, and both P2 and P3 are delayed, waiting for that resource. When P1 exits its critical section, either P2 or P3 should be allowed access to R. Assume that the OS grants access to P3 and that P1 again requires access before P3 completes its critical section. If the OS grants access to P1 after P3 has finished, and subsequently alternately grants access to P1 and P3, then P2 may indefinitely be denied access to the resource, even though there is no deadlock situation.

APPENDIX A - TOPICS IN CONCURRENCY

Deadlock Example

If both processes set their flags to true before either has executed the while statement, then each will think that the other has entered its critical section, causing deadlock.

/* PROCESS 0 */
flag[0] = true;            // <- get lock 0
while (flag[1])            // <- is lock 1 free?
    /* do nothing */;      // <- no? so I wait 1 second, for example
                           // and test again.
                           // on more sophisticated setups we can ask
                           // to be woken when lock 1 is freed
/* critical section*/;     // <- do what we need (this will never happen)
flag[0] = false;           // <- releasing our lock

 /* PROCESS 1 */
flag[1] = true;
while (flag[0])
    /* do nothing */;
/* critical section*/;
flag[1] = false;

Livelock Example

/* PROCESS 0 */
flag[0] = true;          // <- get lock 0
while (flag[1]){         
    flag[0] = false;     // <- instead of sleeping, we do useless work
                         //    needed by the lock mechanism
    /*delay */;          // <- wait for a second
    flag[0] = true;      // <- and restart useless work again.
}
/*critical section*/;    // <- do what we need (this will never happen)
flag[0] = false; 

/* PROCESS 1 */
flag[1] = true;
while (flag[0]) {
    flag[1] = false;
    /*delay */;
    flag[1] = true;
}
/* critical section*/;
flag[1] = false;

[...] consider the following sequence of events:

  • P0 sets flag[0] to true.
  • P1 sets flag[1] to true.
  • P0 checks flag[1].
  • P1 checks flag[0].
  • P0 sets flag[0] to false.
  • P1 sets flag[1] to false.
  • P0 sets flag[0] to true.
  • P1 sets flag[1] to true.

This sequence could be extended indefinitely, and neither process could enter its critical section. Strictly speaking, this is not deadlock, because any alteration in the relative speed of the two processes will break this cycle and allow one to enter the critical section. This condition is referred to as livelock. Recall that deadlock occurs when a set of processes wishes to enter their critical sections but no process can succeed. With livelock, there are possible sequences of executions that succeed, but it is also possible to describe one or more execution sequences in which no process ever enters its critical section.

Not content from the book anymore.

And what about spinlocks?

Spinlock is a technique to avoid the cost of the OS lock mechanism. Typically you would do:

try
{
   lock = beginLock();
   doSomething();
}
finally
{
   endLock();
}

A problem start to appear when beginLock() costs much more than doSomething(). In very exagerated terms, imagine what happens when the beginLock costs 1 second, but doSomething cost just 1 millisecond.

In this case if you waited 1 millisecond, you would avoid being hindered for 1 second.

Why the beginLock would cost so much? If the lock is free is does not cost a lot (see https://stackoverflow.com/a/49712993/5397116), but if the lock is not free the OS will "freeze" your thread, setup a mechanism to wake you when the lock is freed, and then wake you again in the future.

All of this is much more expensive than some loops checking the lock. That is why sometimes is better to do a "spinlock".

For example:

void beginSpinLock(lock)
{
   if(lock) loopFor(1 milliseconds);
   else 
   {
     lock = true;
     return;
   }

   if(lock) loopFor(2 milliseconds);
   else 
   {
     lock = true;
     return;
   }

   // important is that the part above never 
   // cause the thread to sleep.
   // It is "burning" the time slice of this thread.
   // Hopefully for good.

   // some implementations fallback to OS lock mechanism
   // after a few tries
   if(lock) return beginLock(lock);
   else 
   {
     lock = true;
     return;
   }
}

If your implementation is not careful, you can fall on livelock, spending all CPU on the lock mechanism.

Also see:

https://preshing.com/20120226/roll-your-own-lightweight-mutex/
Is my spin lock implementation correct and optimal?

Summary:

Deadlock: situation where nobody progress, doing nothing (sleeping, waiting etc..). CPU usage will be low;

Livelock: situation where nobody progress, but CPU is spent on the lock mechanism and not on your calculation;

Starvation: situation where one procress never gets the chance to run; by pure bad luck or by some of its property (low priority, for example);

Spinlock: technique of avoiding the cost waiting the lock to be freed.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.

WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");

The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.

Using floats with sprintf() in embedded C

%g can do this:

#include <stdio.h>
int main() {
  float w = 234.567;
  char x[__SIZEOF_FLOAT__];
  sprintf(x, "%g", w);
  puts(x);
}

XPath test if node value is number

I've been dealing with 01 - which is a numeric.

string(number($v)) != string($v) makes the segregation

Is there a way to crack the password on an Excel VBA Project?

Colin Pickard has an excellent answer, but there is one 'watch out' with this. There are instances (I haven't figured out the cause yet) where the total length of the "CMG=........GC=...." entry in the file is different from one excel file to the next. In some cases, this entry will be 137 bytes, and in others it will be 143 bytes. The 137 byte length is the odd one, and if this happens when you create your file with the '1234' password, just create another file, and it should jump to the 143 byte length.

If you try to paste the wrong number of bytes into the file, you will lose your VBA project when you try to open the file with Excel.

EDIT

This is not valid for Excel 2007/2010 files. The standard .xlsx file format is actually a .zip file containing numerous sub-folders with the formatting, layout, content, etc, stored as xml data. For an unprotected Excel 2007 file, you can just change the .xlsx extension to .zip, then open the zip file and look through all the xml data. It's very straightforward.

However, when you password protect an Excel 2007 file, the entire .zip (.xlsx) file is actually encrypted using RSA encryption. It is no longer possible to change the extension to .zip and browse the file contents.

Best PHP IDE for Mac? (Preferably free!)

Here's the lowdown on Mac IDE's for PHP

NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.

Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.

Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.

Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.

Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.

PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.

Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.

I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.

Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC

hibernate could not get next sequence value

You need to set your @GeneratedId column with strategy GenerationType.IDENTITY instead of GenerationType.AUTO

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "JUD_ID")
private Long _judId;

How to pass text in a textbox to JavaScript function?

You could either access the element’s value by its name:

document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"

So:

<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />

Or you assign an ID to the element that then identifies it and you can access it with getElementById:

<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />

Go doing a GET request and building the Querystring

Using NewRequest just to create an URL is an overkill. Use the net/url package:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    base, err := url.Parse("http://www.example.com")
    if err != nil {
        return
    }

    // Path params
    base.Path += "this will get automatically encoded"

    // Query params
    params := url.Values{}
    params.Add("q", "this will get encoded as well")
    base.RawQuery = params.Encode() 

    fmt.Printf("Encoded URL is %q\n", base.String())
}

Playground: https://play.golang.org/p/YCTvdluws-r

Why can't I display a pound (£) symbol in HTML?

1st: the pound symbol is a "special" char in utf8 encoding (try saving £$ in a iso-8859-1 (or iso-8859-15) file and you will get ä when encoding using header)

2nd: change your encoding to utf8 form the file. there are plenty of methods to do it. notepad and notepad++ are great sugestions.

3rd: use ob_start(); (in php) BEFORE YOU MAKE ANY OUTPUT if you are getting weird encoding errors, like missing the encoding sometimes. and YES, this solves it! this kind of errors occurs when a page is encoded in windows-1252(ANSI),ASCII,iso-8859-1(5) and then you have all the others in utf8. this is a terrible error and can cause weird things like session_start(); not working.

4th: other php solutions:

utf8_encode('£');
htmlentities('£');
echo '&amp;pound;';

5th: javascript solutions:

document.getElementById('id_goes_here').innerText.replace('£','&amp;pound;');
document.getElementById('id_goes_here').innerText.replace('£',"\u00A3");
$(this).html().replace('£','&amp;pound;'); //jquery
$(this).html().replace('£',"\u00A3"); //jquery
String.fromCharCode('163');

you MUST send £, so it will repair the broken encoded code point. please, avoid these solutions! use php! these solutions only show how to 'fix' the error, and the last one only to create the well-encoded char.

How to make FileFilter in java?

Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.

The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:

public boolean accept(File file) {
    if (file.isDirectory()) {
      return true;
    } else {
      String path = file.getAbsolutePath().toLowerCase();
      for (int i = 0, n = extensions.length; i < n; i++) {
        String extension = extensions[i];
        if ((path.endsWith(extension) && (path.charAt(path.length() 
                  - extension.length() - 1)) == '.')) {
          return true;
        }
      }
    }
    return false;
}

Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.

javascript - pass selected value from popup window to parent window input box

use: opener.document.<id of document>.innerHTML = xmlhttp.responseText;

How do I specify the platform for MSBuild?

In MSBuild or Teamcity use command line

MSBuild yourproject.sln /property:Configuration=Release /property:Platform=x64

or use shorter form:

MSBuild yourproject.sln /p:Configuration=Release /p:Platform=x64

However you need to set up platform in your project anyway, see the answer by Julien Hoarau.

Alter column, add default constraint

I use the stored procedure below to update the defaults on a column.

It automatically removes any prior defaults on the column, before adding the new default.

Examples of usage:

-- Update default to be a date.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','getdate()';
-- Update default to be a number.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
-- Update default to be a string. Note extra quotes, as this is not a function.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';

Stored procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Sample function calls:
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','ColumnName','getdate()';
--exec [dbol].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
create PROCEDURE [dbo].[ColumnDefaultUpdate]
    (
        -- Table name, including schema, e.g. '[dbo].[TableName]'
        @TABLE_NAME VARCHAR(100), 
        -- Column name, e.g. 'ColumnName'.
        @COLUMN_NAME VARCHAR(100),
        -- New default, e.g. '''MyDefault''' or 'getdate()'
        -- Note that if you want to set it to a string constant, the contents
        -- must be surrounded by extra quotes, e.g. '''MyConstant''' not 'MyConstant'
        @NEW_DEFAULT VARCHAR(100)
    )
AS 
BEGIN       
    -- Trim angle brackets so things work even if they are included.
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, '[', '')
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, ']', '')

    print 'Table name: ' + @TABLE_NAME;
    print 'Column name: ' + @COLUMN_NAME;
    DECLARE @ObjectName NVARCHAR(100)
    SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
    WHERE [object_id] = OBJECT_ID(@TABLE_NAME) AND [name] = @COLUMN_NAME;

    IF @ObjectName <> '' 
    begin
        print 'Removed default: ' + @ObjectName;
        --print('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
        EXEC('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
    end

    EXEC('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    --print('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    print 'Added default of: ' + @NEW_DEFAULT;
END

Errors this stored procedure eliminates

If you attempt to add a default to a column when one already exists, you will get the following error (something you will never see if using this stored proc):

-- Using the stored procedure eliminates this error:
Msg 1781, Level 16, State 1, Line 1
Column already has a DEFAULT bound to it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

Zookeeper connection error

Check the zookeeper logs (/var/log/zookeeper). It looks like a connection is established, which should mean there is a record of it.

I had the same situation and it was because a process opened connections and failed to close them. This eventually exceeded the per-host connection limit and my logs were overflowing with

2016-08-03 15:21:13,201 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@188] - Too many connections from /172.31.38.64 - max is 50

Assuming zookeeper is on the usual port, you could do a check for that with:

lsof -i -P | grep 2181

Declaring multiple variables in JavaScript

I think it's a matter of personal preference. I prefer to do it in the following way:

   var /* Variables */
            me = this, that = scope,
            temp, tempUri, tempUrl,
            videoId = getQueryString()["id"],
            host = location.protocol + '//' + location.host,
            baseUrl = "localhost",
            str = "Visit W3Schools",
            n = str.search(/w3schools/i),
            x = 5,
            y = 6,
            z = x + y
   /* End Variables */;

How to remove unused imports in Intellij IDEA on commit?

If you are using IntelliJ IDEA or Android Studio:

Android optimize imports

Go to Settings > Editor > General >Auto Import and check the Optimize imports on the fly checkbox.

Unable to load DLL 'SQLite.Interop.dll'

I had this problem because Visual C++ 2010 redistributable no installed in my PC.if you have not already installed Visual c++ 2010 redistributable Download and install this(check x86 or 64 dll).

Vertical align text in block element

According to the CSS Flexible Box Layout Module, you can declare the a element as a flex container (see figure) and use align-items to vertically align text along the cross axis (which is perpendicular to the main axis).

enter image description here

All you need to do is:

display: flex;
align-items: center;

See this fiddle.

Using reCAPTCHA on localhost

As per Google recaptcha documentation

localhost domains are no longer supported by default. If you wish to continue supporting them for development you can add them to the list of supported domains for your site key. Go to the admin console to update your list of supported domains. We advise to use a separate key for development and production and to not allow localhost on your production site key

How to modify WooCommerce cart, checkout pages (main theme portion)

I've found this works well as a conditional within page.php that includes the WooCommerce cart and checkout screens.

!is_page(array('cart', 'checkout'))

Drawing a line/path on Google Maps

public class MainActivity extends FragmentActivity  {


  List<Overlay> mapOverlays;
  GeoPoint point1, point2;
  LocationManager locManager;
  Drawable drawable;
  Document document;
  GMapV2GetRouteDirection v2GetRouteDirection;
  LatLng fromPosition;
  LatLng toPosition;
  GoogleMap mGoogleMap;
  MarkerOptions markerOptions;
  Location location ;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        v2GetRouteDirection = new GMapV2GetRouteDirection();
      SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
        mGoogleMap = supportMapFragment.getMap();

        // Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
        mGoogleMap.getUiSettings().setCompassEnabled(true);
        mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
        mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
        mGoogleMap.setTrafficEnabled(true);
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
        markerOptions = new MarkerOptions();
        fromPosition = new LatLng(11.663837, 78.147297);
        toPosition = new LatLng(11.723512, 78.466287);
        GetRouteTask getRoute = new GetRouteTask();
        getRoute.execute();
  }
  /**
   *
   * @author VIJAYAKUMAR M
   * This class Get Route on the map
   *
   */
  private class GetRouteTask extends AsyncTask<String, Void, String> {

        private ProgressDialog Dialog;
        String response = "";
        @Override
        protected void onPreExecute() {
              Dialog = new ProgressDialog(MainActivity.this);
              Dialog.setMessage("Loading route...");
              Dialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {
              //Get All Route values
                         document = v2GetRouteDirection.getDocument(fromPosition, toPosition,          GMapV2GetRouteDirection.MODE_DRIVING);
                    response = "Success";
              return response;

        }

        @Override
        protected void onPostExecute(String result) {
              mGoogleMap.clear();
              if(response.equalsIgnoreCase("Success")){
              ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
              PolylineOptions rectLine = new PolylineOptions().width(10).color(
                          Color.RED);

              for (int i = 0; i < directionPoint.size(); i++) {
                    rectLine.add(directionPoint.get(i));
              }
              // Adding route on the map
              mGoogleMap.addPolyline(rectLine);
              markerOptions.position(toPosition);
              markerOptions.draggable(true);
              mGoogleMap.addMarker(markerOptions);

              }

              Dialog.dismiss();
        }
  }
  @Override
  protected void onStop() {
        super.onStop();
        finish();
    }
 }

Route Helper class

 public class GMapV2GetRouteDirection {
  public final static String MODE_DRIVING = "driving";
  public final static String MODE_WALKING = "walking";

  public GMapV2GetRouteDirection() { }

  public Document getDocument(LatLng start, LatLng end, String mode) {
    String url = "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin=" + start.latitude + "," + start.longitude 
            + "&destination=" + end.latitude + "," + end.longitude
            + "&sensor=false&units=metric&mode=driving";

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        return doc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
  }

  public String getDurationText (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DurationText", node2.getTextContent());
    return node2.getTextContent();
 }

 public int getDurationValue (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DurationValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
  }

  public String getDistanceText (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DistanceText", node2.getTextContent());
    return node2.getTextContent();
  }

  public int getDistanceValue (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DistanceValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
  }

  public String getStartAddress (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("start_address");
    Node node1 = nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
  }

  public String getEndAddress (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("end_address");
    Node node1 = nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
  }

  public String getCopyRights (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("copyrights");
    Node node1 = nl1.item(0);
    Log.i("CopyRights", node1.getTextContent());
    return node1.getTextContent();
  }

   public ArrayList<LatLng> getDirection (Document doc) {
    NodeList nl1, nl2, nl3;
    ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
    nl1 = doc.getElementsByTagName("step");
    if (nl1.getLength() > 0) {
        for (int i = 0; i < nl1.getLength(); i++) {
            Node node1 = nl1.item(i);
            nl2 = node1.getChildNodes();

            Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
            nl3 = locationNode.getChildNodes();
            Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
            double lat = Double.parseDouble(latNode.getTextContent());
            Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            double lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));

            locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "points"));
            ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
            for(int j = 0 ; j < arr.size() ; j++) {
                listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
            }

            locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "lat"));
            lat = Double.parseDouble(latNode.getTextContent());
            lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));
        }
    }

    return listGeopoints;
 }

 private int getNodeIndex(NodeList nl, String nodename) {
    for(int i = 0 ; i < nl.getLength() ; i++) {
        if(nl.item(i).getNodeName().equals(nodename))
            return i;
    }
    return -1;
 }

 private ArrayList<LatLng> decodePoly(String encoded) {
    ArrayList<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;
    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
        poly.add(position);
    }
    return poly;
  }
 }

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Your initial statement in the marked solution isn't entirely true. While your new solution may accomplish your original goal, it is still possible to circumvent the original error while preserving your AuthorizationHandler logic--provided you have basic authentication scheme handlers in place, even if they are functionally skeletons.

Speaking broadly, Authentication Handlers and schemes are meant to establish + validate identity, which makes them required for Authorization Handlers/policies to function--as they run on the supposition that an identity has already been established.

ASP.NET Dev Haok summarizes this best best here: "Authentication today isn't aware of authorization at all, it only cares about producing a ClaimsPrincipal per scheme. Authorization has to be aware of authentication somewhat, so AuthenticationSchemes in the policy is a mechanism for you to associate the policy with schemes used to build the effective claims principal for authorization (or it just uses the default httpContext.User for the request, which does rely on DefaultAuthenticateScheme)." https://github.com/aspnet/Security/issues/1469

In my case, the solution I'm working on provided its own implicit concept of identity, so we had no need for authentication schemes/handlers--just header tokens for authorization. So until our identity concepts changes, our header token authorization handlers that enforce the policies can be tied to 1-to-1 scheme skeletons.

Tags on endpoints:

[Authorize(AuthenticationSchemes = "AuthenticatedUserSchemeName", Policy = "AuthorizedUserPolicyName")]

Startup.cs:

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = "AuthenticatedUserSchemeName";
        }).AddScheme<ValidTokenAuthenticationSchemeOptions, ValidTokenAuthenticationHandler>("AuthenticatedUserSchemeName", _ => { });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("AuthorizedUserPolicyName", policy =>
            {
                //policy.RequireClaim(ClaimTypes.Sid,"authToken");
                policy.AddAuthenticationSchemes("AuthenticatedUserSchemeName");
                policy.AddRequirements(new ValidTokenAuthorizationRequirement());
            });
            services.AddSingleton<IAuthorizationHandler, ValidTokenAuthorizationHandler>();

Both the empty authentication handler and authorization handler are called (similar in setup to OP's respective posts) but the authorization handler still enforces our authorization policies.

How to make one Observable sequence wait for another to complete before emitting?

well, I know this is pretty old but I think that what you might need is:

var one = someObservable.take(1);

var two = someOtherObservable.pipe(
  concatMap((twoRes) => one.pipe(mapTo(twoRes))),
  take(1)
).subscribe((twoRes) => {
   // one is completed and we get two's subscription.
})

Docker is installed but Docker Compose is not ? why?

The above solutions didn't work for me. But I found this that worked:

sudo apt-get update -y && sudo apt-get install -y python3-pip python3-dev
sudo apt-get remove docker docker-engine docker.io
curl -fsSL get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo pip3 install docker-compose
#sudo docker-compose -f docker-compose-profess.yml pull ofw
sudo usermod -a -G docker $USER
sudo reboot

Count number of 1's in binary representation

I've got a solution that counts the bits in O(Number of 1's) time:

bitcount(n):
    count = 0
    while n > 0:
        count = count + 1
        n = n & (n-1)
    return count

In worst case (when the number is 2^n - 1, all 1's in binary) it will check every bit.

Edit: Just found a very nice constant-time, constant memory algorithm for bitcount. Here it is, written in C:

int BitCount(unsigned int u)
{
     unsigned int uCount;

     uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
     return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}

You can find proof of its correctness here.

Given a URL to a text file, what is the simplest way to read the contents of the text file?

There's really no need to read line-by-line. You can get the whole thing like this:

import urllib
txt = urllib.urlopen(target_url).read()

How to set the JSTL variable value in javascript?

Just don't. Don't write code with code. Write a JSON object or a var somewhere but for the love of a sensible HTTP divide, don't write JavaScript functions or methods hardcoded with vars/properties provided by JSTL. Generating JSON is cool. It ends there or your UI dev hates you.

Imagine if you had to dig into JavaScript to find something that was setting parameters in the middle of a class that originated on the client-side. It's awful. Pass data back and forth. Handle the data. But don't try to generate actual code.

Remove NaN from pandas series

>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0    1
1    2
2    3
3    4
5    5

update or even better approach as @DSM suggested in comments, using pandas.Series.dropna():

>>> s.dropna()
0    1
1    2
2    3
3    4
5    5

Cropping an UIImage

I use the method below.

  -(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect
  {
    CGSize cropSize = rect.size;
    CGFloat widthScale =  
    image.size.width/self.imageViewOriginal.bounds.size.width;
    CGFloat heightScale = 
    image.size.height/self.imageViewOriginal.bounds.size.height;
    cropSize = CGSizeMake(rect.size.width*widthScale,  
    rect.size.height*heightScale);
    CGPoint  pointCrop = CGPointMake(rect.origin.x*widthScale, 
    rect.origin.y*heightScale);
    rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, 
    cropSize.height);
    CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);
    UIImage *croppedImage = [UIImage imageWithCGImage:subImage];
    CGImageRelease(subImage);
    return croppedImage;

}

Exit single-user mode

Today I faced the same issue where my database was changed from Multi User to Single User mode and this was eventually stopping me to publish database.

In order to fix this issue, I had to close all Visual Studio instances and run the below command in Sql Server query window -

USE [Your_Database_Name]; ALTER DATABASE [Your_Database_Name] SET MULTI_USER GO

This command has changed the DB from Single user to Multi User and afterwards, I was successfully able to publish.

Triggering change detection manually in Angular

I was able to update it with markForCheck()

Import ChangeDetectorRef

import { ChangeDetectorRef } from '@angular/core';

Inject and instantiate it

constructor(private ref: ChangeDetectorRef) { 
}

Finally mark change detection to take place

this.ref.markForCheck();

Here's an example where markForCheck() works and detectChanges() don't.

https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview

EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.

(Press STOP/RUN to run it again)

How do I get textual contents from BLOB in Oracle SQL

First of all, you may want to store text in CLOB/NCLOB columns instead of BLOB, which is designed for binary data (your query would work with a CLOB, by the way).

The following query will let you see the first 32767 characters (at most) of the text inside the blob, provided all the character sets are compatible (original CS of the text stored in the BLOB, CS of the database used for VARCHAR2) :

select utl_raw.cast_to_varchar2(dbms_lob.substr(BLOB_FIELD)) from TABLE_WITH_BLOB where ID = '<row id>';

Sending a file over TCP sockets in Python

You can send some flag to stop while loop in server

for example

Server side:

import socket
s = socket.socket()
s.bind(("localhost", 5000))
s.listen(1)
c,a = s.accept()
filetodown = open("img.png", "wb")
while True:
   print("Receiving....")
   data = c.recv(1024)
   if data == b"DONE":
           print("Done Receiving.")
           break
   filetodown.write(data)
filetodown.close()
c.send("Thank you for connecting.")
c.shutdown(2)
c.close()
s.close()
#Done :)

Client side:

import socket
s = socket.socket()
s.connect(("localhost", 5000))
filetosend = open("img.png", "rb")
data = filetosend.read(1024)
while data:
    print("Sending...")
    s.send(data)
    data = filetosend.read(1024)
filetosend.close()
s.send(b"DONE")
print("Done Sending.")
print(s.recv(1024))
s.shutdown(2)
s.close()
#Done :)

Github Windows 'Failed to sync this branch'

This error comes because of a merge conflict in files. I faced it after I had updated my Maven Project's pom.xml but didn't commit it. Using

git status
error: Your local changes to the following files would be overwritten by merge:
<my project>/pom.xml
Please, commit your changes or stash them before you can merge.
Aborting

as the above post suggested helped finding any conflicting changes and you can decide to discard or commit.

What port is used by Java RMI connection?

With reference to other answers above, here is my view -

there are ports involved on both client and server side.

  • for server/remote side, if you export the object without providing a port , remote object would use a random port to listen.

  • a client, when looks up the remote object, it would always use a random port on its side and will connect to the remote object port as listed above.

How to style the <option> with only CSS?

EDIT 2015 May

Disclaimer: I've taken the snippet from the answer linked below:

Important Update!

In addition to WebKit, as of Firefox 35 we'll be able to use the appearance property:

Using -moz-appearance with the none value on a combobox now remove the dropdown button

So now in order to hide the default styling, it's as easy as adding the following rules on our select element:

select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

For IE 11 support, you can use [::-ms-expand][15].

select::-ms-expand { /* for IE 11 */
    display: none;
}

Old Answer

Unfortunately what you ask is not possible by using pure CSS. However, here is something similar that you can choose as a work around. Check the live code below.

_x000D_
_x000D_
div { _x000D_
  margin: 10px;_x000D_
  padding: 10px; _x000D_
  border: 2px solid purple; _x000D_
  width: 200px;_x000D_
  -webkit-border-radius: 5px;_x000D_
  -moz-border-radius: 5px;_x000D_
  border-radius: 5px;_x000D_
}_x000D_
div > ul { display: none; }_x000D_
div:hover > ul {display: block; background: #f9f9f9; border-top: 1px solid purple;}_x000D_
div:hover > ul > li { padding: 5px; border-bottom: 1px solid #4f4f4f;}_x000D_
div:hover > ul > li:hover { background: white;}_x000D_
div:hover > ul > li:hover > a { color: red; }
_x000D_
<div>_x000D_
  Select_x000D_
  <ul>_x000D_
    <li><a href="#">Item 1</a></li>_x000D_
    <li><a href="#">Item 2</a></li>_x000D_
    <li><a href="#">Item 3</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

EDIT

Here is the question that you asked some time ago. How to style a <select> dropdown with CSS only without JavaScript? As it tells there, only in Chrome and to some extent in Firefox you can achieve what you want. Otherwise, unfortunately, there is no cross browser pure CSS solution for styling a select.

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

Remove all elements contained in another array

ECMAScript 6 sets can permit faster computing of the elements of one array that aren't in the other:

_x000D_
_x000D_
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = new Set(['b', 'c', 'g']);

const difference = myArray.filter( x => !toRemove.has(x) );

console.log(difference); // ["a", "d", "e", "f"]
_x000D_
_x000D_
_x000D_

Since the lookup complexity for the V8 engine browsers use these days is O(1), the time complexity of the whole algorithm is O(n).

How To Launch Git Bash from DOS Command Line?

https://stackoverflow.com/a/33368029/15789

I have posted an answer here.

Open a Windows command window, and execute this script. If there is a change in your working directory, it will open a bash terminal in your working directory, and display the current git status. It keeps the bash window open, by calling exec bash.

If you have multiple projects you may create copies of this script with different project folder, and call it from a main batch script.

(How) can I count the items in an enum?

For C++, there are various type-safe enum techniques available, and some of those (such as the proposed-but-never-submitted Boost.Enum) include support for getting the size of a enum.

The simplest approach, which works in C as well as C++, is to adopt a convention of declaring a ...MAX value for each of your enum types:

enum Folders { FA, FB, FC, Folders_MAX = FC };
ContainerClass *m_containers[Folders_MAX + 1];
....
m_containers[FA] = ...; // etc.

Edit: Regarding { FA, FB, FC, Folders_MAX = FC} versus {FA, FB, FC, Folders_MAX]: I prefer setting the ...MAX value to the last legal value of the enum for a few reasons:

  1. The constant's name is technically more accurate (since Folders_MAX gives the maximum possible enum value).
  2. Personally, I feel like Folders_MAX = FC stands out from other entries out a bit more (making it a bit harder to accidentally add enum values without updating the max value, a problem Martin York referenced).
  3. GCC includes helpful warnings like "enumeration value not included in switch" for code such as the following. Letting Folders_MAX == FC + 1 breaks those warnings, since you end up with a bunch of ...MAX enumeration values that should never be included in switch.
switch (folder) 
{
  case FA: ...;
  case FB: ...;
  // Oops, forgot FC!
}

INFO: No Spring WebApplicationInitializer types detected on classpath

For eclipse users: solution is simple just change the nature of project Spring Tools->add spring project nature

done.

How do you implement a good profanity filter?

I concluded, in order to create a good profanity filter we need 3 main components, or at least it is what I am going to do. These they are:

  1. The filter: a background service that verify against a blacklist, dictionary or something like that.
  2. Not allow anonymous account
  3. Report abuse

A bonus, it will be to reward somehow those who contribute with accurate abuse reporters and punish the offender, e.g. suspend their accounts.

How to pass a parameter to routerLink that is somewhere inside the URL?

There are multiple ways of achieving this.

  • Through [routerLink] directive
  • The navigate(Array) method of the Router class
  • The navigateByUrl(string) method which takes a string and returns a promise

The routerLink attribute requires you to import the routingModule into the feature module in case you lazy loaded the feature module or just import the app-routing-module if it is not automatically added to the AppModule imports array.

  • RouterLink
<a [routerLink]="['/user', user.id]">John Doe</a>
<a routerLink="urlString">John Doe</a> // urlString is computed in your component
  • Navigate
// Inject Router into your component
// Inject ActivatedRoute into your component. This will allow the route to be done related to the current url
this._router.navigate(['user',user.id], {relativeTo: this._activatedRoute})
  • NavigateByUrl
this._router.navigateByUrl(urlString).then((bool) => {}).catch()

Loop through checkboxes and count each one checked or unchecked

Using Selectors

You can get all checked checkboxes like this:

var boxes = $(":checkbox:checked");

And all non-checked like this:

var nboxes = $(":checkbox:not(:checked)");

You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array() request to know whether or not any particular box should be checked at a later date.

Serialize

jQuery also has a serialize method that will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:

single=Single2&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2

This will enable you to keep the information for which elements were checked as well.

Command line .cmd/.bat script, how to get directory of running script

Raymond Chen has a few ideas:

https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573

Quoted here in full because MSDN archives tend to be somewhat unreliable:

The easy way is to use the %CD% pseudo-variable. It expands to the current working directory.

set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory

(Of course, directory save/restore could more easily have been done with pushd/popd, but that's not the point here.)

The %CD% trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.

set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args

(I like to use %_% as my scratch environment variable.)

Type SET /? to see the other pseudo-variables provided by the command processor.

Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):

http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741

This covers the use of %~dp0:

If you want to know where the batch file lives: %~dp0

%0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.

CSS Font Border?

Stroke font-character with a Less mixin

Here's a LESS mixin to generate the stroke: http://codepen.io/anon/pen/BNYGBy?editors=110

/// Stroke font-character
/// @param  {Integer} $stroke - Stroke width
/// @param  {Color}   $color  - Stroke color
/// @return {List}            - text-shadow list
.stroke(@stroke, @color) {
  @maxi: @stroke + 1;
  .i-loop (@i) when (@i > 0) {
    @maxj: @stroke + 1;
    .j-loop (@j) when (@j > 0) {
      text-shadow+: (@i - 1)*(1px)  (@j - 1)*(1px) 0 @color;
      text-shadow+: (@i - 1)*(1px)  (@j - 1)*(-1px) 0 @color;
      text-shadow+: (@i - 1)*(-1px)  (@j - 1)*(-1px) 0 @color;
      text-shadow+: (@i - 1)*(-1px)  (@j - 1)*(1px) 0 @color;
      .j-loop(@j - 1);
    }
    .j-loop (0) {}
    .j-loop(@maxj);
    .i-loop(@i - 1);
  }
  .i-loop (0) {}
  .i-loop(@maxi);
  text-shadow+: 0 0 0 @color;
}

(it's based on pixelass answer that instead uses SCSS)

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

React Native Error: ENOSPC: System limit for number of file watchers reached

I solved this issue by using sudo ie

sudo yarn start

or

sudo npm start

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2019 (Express Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQL2019\Express_ENU and click OK

How can I use jQuery to move a div across the screen

In jQuery 1.2 and newer you no longer have to position the element absolutely; you can use normal relative positioning and use += or -= to add to or subtract from properties, e.g.

$("#startAnimation").click(function(){
    $(".toBeAnimated").animate({ 
        marginLeft: "+=250px",
    }, 1000 );
});

And to echo the guy who answered first's advice: Javascript is not performant. Don't overuse animations, or expect things than run nice and fast on your high performance PC on Chrome to look good on a bog-standard PC running IE. Test it, and make sure it degrades well!

Change the color of a bullet in a html list?

<ul>
<li style="color:#ddd;"><span style="color:#000;">List Item</span></li>
</ul>

Timeout a command in bash without unnecessary delay

A very simplistic way:

# command & sleep 5; pkill -9 -x -f "command"

with pkill (option -f) you can kill your specific command with arguments or specify -n to avoid kill old process.

Is it possible to run a .NET 4.5 app on XP?

Sadly, no, you can't run 4.5 programs on XP.

And the relevant post from that Connect page:

Posted by Microsoft on 23/03/2012 at 10:39
Thanks for the report. This behavior is by design in .NET Framework 4.5 Beta. The minimum supported operating systems are Windows 7, Windows Server 2008 SP2 and Windows Server 2008 R2 SP1. Windows XP is not a supported operating system for the Beta release.

Scheduled run of stored procedure on SQL server

You could use SQL Server Service Broker to create custom made mechanism.

Idea (simplified):

  1. Write a stored procedure/trigger that begins a conversation (BEGIN DIALOG) as loopback (FROM my_service TO my_service) - get conversation handler

    DECLARE @dialog UNIQUEIDENTIFIER;
    
    BEGIN DIALOG CONVERSATION @dialog
            FROM SERVICE   [name] 
            TO SERVICE      'name' 
            ...;
    
  2. Start the conversation timer

    DECLARE @time INT;
    BEGIN CONVERSATION TIMER (@dialog)  TIMEOUT = @time;
    
  3. After specified number of seconds a message will be sent to a service. It will be enqueued with associated queue.

    CREATE QUEUE queue_name WITH STATUS = ON, RETENTION = OFF
                 , ACTIVATION (STATUS = ON, PROCEDURE_NAME = <procedure_name>
                 , MAX_QUEUE_READERS = 20, EXECUTE AS N'dbo')
                  , POISON_MESSAGE_HANDLING (STATUS = ON) 
    
  4. Procedure will execute specific code and reanable timer to fire again.


You can find fully-baked solution(T-SQL) written by Michal Golos called Task Scheduler

Key points from blog:

Pros:

  • Supported on each version (from Express to Enterprise). SQL Server Agent Job is not available for SQL Server Express
  • Scoped to database level. You could easiliy move database with associated tasks (especially when you have to move around 100 jobs from one enviromnent to another)
  • Lower privileges needed to see/manipulate tasks(database level)

Proposed distinction:

SQL Server Agent (maintenance):

  • backups
  • index/statistics rebuilds
  • replication

Task Scheduler (business processes):

  • removing old data
  • preaggregations/cyclic recalculations
  • denormalization

How to set it up:

  • get source code from section: "Do pobrania" - To download (enabling broker/setting up schema tsks/configuration table + triggers + stored procedure)/setting up broker things)
  • set up configuration table [tsks].[tsksx_task_scheduler] to add new tasks (columns names are self-descriptive, sample task included)

Warning: Blog is written in Polish but associated source code is in English and it is easy to follow.

Warning 2: Before you use it, please make sure you have tested it on non-production environment.

How to open the Google Play Store directly from my Android application?

Go on Android Developer official link as tutorial step by step see and got the code for your application package from play store if exists or play store apps not exists then open application from web browser.

Android Developer official link

https://developer.android.com/distribute/tools/promote/linking.html

Linking to a Application Page

From a web site: https://play.google.com/store/apps/details?id=<package_name>

From an Android app: market://details?id=<package_name>

Linking to a Product List

From a web site: https://play.google.com/store/search?q=pub:<publisher_name>

From an Android app: market://search?q=pub:<publisher_name>

Linking to a Search Result

From a web site: https://play.google.com/store/search?q=<search_query>&c=apps

From an Android app: market://search?q=<seach_query>&c=apps

How to set corner radius of imageView?

import UIKit

class BorderImage: UIImageView {

    override func awakeFromNib() {
        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 10.0
        layer.masksToBounds = true
    }
}

Based on @DCDC's answer

Split a large dataframe into a list of data frames based on common value in column

From version 0.8.0, dplyr offers a handy function called group_split():

# On sample data from @Aus_10

df %>%
  group_split(g)

[[1]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     2.04      0.627 A    
 2     0.530    -0.703 A    
 3    -0.475     0.541 A    
 4     1.20     -0.565 A    
 5    -0.380    -0.126 A    
 6     1.25     -1.69  A    
 7    -0.153    -1.02  A    
 8     1.52     -0.520 A    
 9     0.905    -0.976 A    
10     0.517    -0.535 A    
# … with 15 more rows

[[2]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     1.61      0.858 B    
 2     1.05     -1.25  B    
 3    -0.440    -0.506 B    
 4    -1.17      1.81  B    
 5     1.47     -1.60  B    
 6    -0.682    -0.726 B    
 7    -2.21      0.282 B    
 8    -0.499     0.591 B    
 9     0.711    -1.21  B    
10     0.705     0.960 B    
# … with 15 more rows

To not include the grouping column:

df %>%
 group_split(g, keep = FALSE)

How to control the width of select tag?

You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.

You need to use max-width instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.

find path of current folder - cmd

Use This Code

@echo off
:: Get the current directory

for /f "tokens=* delims=/" %%A in ('cd') do set CURRENT_DIR=%%A

echo CURRENT_DIR%%A 

(echo this To confirm this code works fine)