Programs & Examples On #Fortress

Fortress Open Source IAM SDK

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

I found the error because i was new to git you must check whether you have entered the correct syntax

i made a mistake and wrote git commit

and got the same error

use git commit -m 'some comment'

and you wont be seeing the page with

What does -Xmn jvm option stands for

From here:

-Xmn : the size of the heap for the young generation

Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".

And a more "official" source from IBM:

-Xmn

Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.

If condition inside of map() React

You're mixing if statement with a ternary expression, that's why you're having a syntax error. It might be easier for you to understand what's going on if you extract mapping function outside of your render method:

renderItem = (id) => {
    // just standard if statement
    if (this.props.schema.collectionName.length < 0) {
        return (
            <Expandable>
                <ObjectDisplay
                    key={id}
                    parentDocumentId={id}
                    schema={schema[this.props.schema.collectionName]}
                    value={this.props.collection.documents[id]}
                />
            </Expandable>
        );
    }
    return (
        <h1>hejsan</h1>
    );
}

Then just call it when mapping:

render() {
    return (
        <div>
            <div className="box">
                { 
                    this.props.collection.ids
                        .filter(
                            id =>
                            // note: this is only passed when in top level of document
                            this.props.collection.documents[id][
                                this.props.schema.foreignKey
                            ] === this.props.parentDocumentId
                        )
                        .map(this.renderItem)
                }
            </div>
        </div>
    )
}

Of course, you could have used the ternary expression as well, it's a matter of preference. What you use, however, affects the readability, so make sure to check different ways and tips to properly do conditional rendering in react and react native.

Switch statement equivalent in Windows batch file

Hariprasad didupe suggested a solution provided by Batchography, but it could be improved a bit. Unlike with other cases getting into default case will set ERRORLEVEL to 1 and, if that is not desired, you should manually set ERRORLEVEL to 0:

goto :switch-case-N-%N% 2>nul || (
    rem Default case
    rem Manually set ERRORLEVEL to 0 
    type nul>nul
    echo Something else
)
...

The readability could be improved for the price of a call overhead:

call:Switch SwitchLabel %N% || (
:SwitchLabel-1
    echo One
    goto:EOF     
:SwitchLabel-2
    echo Two
    goto:EOF
:SwitchLabel-3
    echo Three
    goto:EOF
:SwitchLabel-
    echo Default case
)

:Switch
goto:%1-%2 2>nul || (
    type nul>nul
    goto:%1-
)
exit /b

Few things to note:

  1. As stated before, this has a call overhead;
  2. Default case is required. If no action is needed put rem inside to avoid parenthesis error;
  3. All cases except the default one are executed in the sub-context. If you want to exit parent context (usually script) you may use this;
  4. Default case is executed in a parent context, so it cannot be combined with other cases (as reaching goto:EOF will exit parent context). This could be circumvented by replacing goto:%1- in subroutine with call:%1- for the price of additional call overhead;
  5. Subroutine takes label prefix (sans hyphen) and control variable. Without label prefix switch will look for labels with :- prefix (which are valid) and not passing a control variable will lead to default case.

Check if a time is between two times (time DataType)

Let us consider a table which stores the shift details

enter image description here

Please check the SQL queries to generate table and finding the schedule based on an input(time)

Declaring the Table variable

declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)

Adding values to Table variable

insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'

Creating another table variable with an additional field named "Flag"

declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)

Adding values to temporary table with swapping the start and end time

insert into @Temp select MyShift,case when (StartTime>EndTime) then EndTime else StartTime end,case when (StartTime>EndTime) then StartTime else EndTime end,case when (StartTime>EndTime) then 1 else 0 end from @MyShiftTable

Creating input variable to find the Shift

declare @time time=convert(time,'10:12:40.3530000')

Query to find the shift corresponding to the time supplied

select myShift from @Temp where
(@time between StartTime and EndTime and Flag=0) or (@time not between StartTime and EndTime and Flag=1)

PHP - Copy image to my server direct from URL

Two ways, if you're using PHP5 (or higher)

copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.png');

If not, use file_get_contents

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.png", "w");
fwrite($fp, $content);
fclose($fp);

From this SO post

How can I use a carriage return in a HTML tooltip?

We had a requirement where we needed to test all of these, here is what I wish to share

_x000D_
_x000D_
document.getElementById("tooltip").setAttribute("title", "Tool\x0ATip\x0AOn\x0ANew\x0ALine")
_x000D_
<p title='Tool_x000D_
Tip_x000D_
On_x000D_
New_x000D_
Line'>Tooltip with <pre>_x000D_
  new _x000D_
  line</pre> Works in all browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title="Tool&#13;Tip&#13;On&#13;New&#13;Line">Tooltip with <code>&amp;#13;</code> Not works Firefox browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool&#10;Tip&#10;On&#10;New&#10;Line'>Tooltip with <code>&amp;#10;</code> Works in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool&#x0aTip&#x0aOn&#x0aNew&#x0aLine'>Tooltip with <code>&amp;#xD;</code> May work in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p id='tooltip'>Tooltip with <code>document.getElementById("tooltip").setAttribute("title", "Tool\x0ATip\x0AOn\x0ANew\x0ALine")</code> May work in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
_x000D_
<p title="List:_x000D_
  • List item here_x000D_
  • Another list item here_x000D_
  • Aaaand another list item, lol">Tooltip with <code>• </code>Unordered list tooltip</p>_x000D_
<hr/>_x000D_
_x000D_
_x000D_
<p title='Tool\nTip\nOn\nNew\nLine'>Tooltip with <code>\n</code> May not work in modern browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool\tTip\tOn\tNew\tLine'>Tooltip with <code>\t</code> May not work in modern browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool&#013;Tip&#013;On&#013;New&#013;Line'>Tooltip with <code>&amp;#013;</code> Works in most browsers</p>_x000D_
<hr/>
_x000D_
_x000D_
_x000D_

Fiddle

Get today date in google appScript

The following can be used to get the date:

function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1;  if(month.toString().length==1){var month = 
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

How can I output the value of an enum class in C++11

To write simpler,

enum class Color
{
    Red = 1,
    Green = 11,
    Blue = 111
};

int value = static_cast<int>(Color::Blue); // 111

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

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

You can use git config command to write a new rule to .git/config to fetch pull requests from the repository:

$ git config --local --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/origin/pr/*'

And then just:

$ git fetch origin
Fetching origin
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 2), reused 4 (delta 2), pack-reused 0
Unpacking objects: 100% (4/4), done.
From https://github.com/container-images/memcached
 * [new ref]         refs/pull/2/head -> origin/pr/2
 * [new ref]         refs/pull/3/head -> origin/pr/3

How do I pretty-print existing JSON data with Java?

Use gson. https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(my_bean);

output

{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

You can use .on() to capture multiple events and then test for touch on the screen, e.g.:

$('#selector')
.on('touchstart mousedown', function(e){
  e.preventDefault();
  var touch = e.touches[0];
  if(touch){
    // Do some stuff
  }
  else {
    // Do some other stuff
  }
});

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

How to read an http input stream

try this code

String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";

while ((line = br.readLine()) != null) {
    sb.append(line);
}

data = sb.toString();
System.out.println(data);

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

Seeing the underlying SQL in the Spring JdbcTemplate?

Try adding in log4j.xml

<!--  enable query logging -->
<category name="org.springframework.jdbc.core.JdbcTemplate">
    <priority value="DEBUG" />
</category>

<!-- enable query logging for SQL statement parameter value -->
<category name="org.springframework.jdbc.core.StatementCreatorUtils">
    <priority value="TRACE" />
</category>

your logs looks like:

DEBUG JdbcTemplate:682 - Executing prepared SQL query
DEBUG JdbcTemplate:616 - Executing prepared SQL statement [your sql query]
TRACE StatementCreatorUtils:228 - Setting SQL statement parameter value: column index 1, parameter value [param], value class [java.lang.String], SQL type unknown

How can I do a case insensitive string comparison?

This is not the best practice in .NET framework (4 & +) to check equality

String.Compare(x.Username, (string)drUser["Username"], 
                  StringComparison.OrdinalIgnoreCase) == 0

Use the following instead

String.Equals(x.Username, (string)drUser["Username"], 
                   StringComparison.OrdinalIgnoreCase) 

MSDN recommends:

  • Use an overload of the String.Equals method to test whether two strings are equal.
  • Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.

How to cut first n and last n columns?

The first part of your question is easy. As already pointed out, cut accepts omission of either the starting or the ending index of a column range, interpreting this as meaning either “from the start to column n (inclusive)” or “from column n (inclusive) to the end,” respectively:

$ printf 'this:is:a:test' | cut -d: -f-2
this:is
$ printf 'this:is:a:test' | cut -d: -f3-
a:test

It also supports combining ranges. If you want, e.g., the first 3 and the last 2 columns in a row of 7 columns:

$ printf 'foo:bar:baz:qux:quz:quux:quuz' | cut -d: -f-3,6-
foo:bar:baz:quux:quuz

However, the second part of your question can be a bit trickier depending on what kind of input you’re expecting. If by “last n columns” you mean “last n columns (regardless of their indices in the overall row)” (i.e. because you don’t necessarily know how many columns you’re going to find in advance) then sadly this is not possible to accomplish using cut alone. In order to effectively use cut to pull out “the last n columns” in each line, the total number of columns present in each line must be known beforehand, and each line must be consistent in the number of columns it contains.

If you do not know how many “columns” may be present in each line (e.g. because you’re working with input that is not strictly tabular), then you’ll have to use something like awk instead. E.g., to use awk to pull out the last 2 “columns” (awk calls them fields, the number of which can vary per line) from each line of input:

$ printf '/a\n/a/b\n/a/b/c\n/a/b/c/d\n' | awk -F/ '{print $(NF-1) FS $(NF)}'
/a
a/b
b/c
c/d

Get connection string from App.config

First you have to add System.Configuration reference to your project and then use below code to get connection string.

_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Is there a way to have printf() properly print out an array (of floats, say)?

You need to go for a loop:

for (int i = 0; i < sizeof(foo) / sizeof(float); ++i)
   printf("%f", foo[i]);
printf("\n");

Change the Arrow buttons in Slick slider

You can use FontAwesome "content" values and apply as follow by css. These apply "chevron right/left" icons.

.custom-slick .slick-prev:before {
    content: "?";
    font-family: 'FontAwesome';
    font-size: 22px;
}
.custom-slick .slick-next:before {
    content: "?";
    font-family: 'FontAwesome';
    font-size: 22px;
}

How to update ruby on linux (ubuntu)?

On Ubuntu 12.04 (Precise Pangolin), I got this working with the following command:

sudo apt-get install ruby1.9.1
sudo apt-get install ruby1.9.3

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

Destroy or remove a view in Backbone.js

According to current Backbone documentation....

view.remove()

Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

`IF` statement with 3 possible answers each based on 3 different ranges

This is what I did:

Very simply put:

=IF(C7>100,"Profit",IF(C7=100,"Quota Met","Loss"))

The first IF Statement, if true will input Profit, and if false will lead on to the next IF statement and so forth :)

I only have basic formula knowledge but it's working so I will accept I am right!

Get filename in batch for loop

When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.

FOR /R C:\Directory %F in (*.*) do echo %~nF

should echo only the filenames.

PHP 7: Missing VCRUNTIME140.dll

I had same problem when installing Robot Framework 2.9.2 using the Windows installer version on Windows 7.

I could solve it installing the VC14 builds require to have the "Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed" from Microsoft website.

make div's height expand with its content

Thw following should work:

.main #main_content {
    padding: 5px;
    margin: 0px;
    overflow: auto;
    width: 100%; //for some explorer browsers to trigger hasLayout
}

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

How to place the "table" at the middle of the webpage?

The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.

That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!

<style>
  html, body {
    height: 100%;
  }
  #tableContainer-1 {
    height: 100%;
    width: 100%;
    display: table;
  }
  #tableContainer-2 {
    vertical-align: middle;
    display: table-cell;
    height: 100%;
  }
  #myTable {
    margin: 0 auto;
  }
</style>
<div id="tableContainer-1">
  <div id="tableContainer-2">
    <table id="myTable" border>
      <tr><td>Name</td><td>J W BUSH</td></tr>
      <tr><td>Proficiency</td><td>PHP</td></tr>
      <tr><td>Company</td><td>BLAH BLAH</td></tr>
    </table>
  </div>
</div>

HTTP Request in Kotlin

I think using okhttp is the easiest solution. Here you can see an example for POST method, sending a json, and with auth.

val url = "https://example.com/endpoint"

val client = OkHttpClient()

val JSON = MediaType.get("application/json; charset=utf-8")
val body = RequestBody.create(JSON, "{\"data\":\"$data\"}")
val request = Request.Builder()
        .addHeader("Authorization", "Bearer $token")
        .url(url)
        .post(body)
        .build()

val  response = client . newCall (request).execute()

println(response.request())
println(response.body()!!.string())

Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

UPDATE: July 7th, 2019 I'm gonna give two examples using latest Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).

UPDATE: January 25th, 2021 Everything is okay with the most updated versions.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-kotlin -->
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-kotlin</artifactId>
            <version>2.12.1</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

Get Method

fun get() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users?page=2")

    val request = Request.Builder()
            .url(url)
            .get()
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val mapperAll = ObjectMapper()
    val objData = mapperAll.readTree(responseBody)

    objData.get("data").forEachIndexed { index, jsonNode ->
        println("$index $jsonNode")
    }
}

POST Method

fun post() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users")

    //just a string
    var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"

    //or using jackson
    val mapperAll = ObjectMapper()
    val jacksonObj = mapperAll.createObjectNode()
    jacksonObj.put("name", "Rolando")
    jacksonObj.put("job", "Fakeador")
    val jacksonString = jacksonObj.toString()

    val mediaType = "application/json; charset=utf-8".toMediaType()
    val body = jacksonString.toRequestBody(mediaType)

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val objData = mapperAll.readTree(responseBody)

    println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
}

How to select rows in a DataFrame between two values, in Python Pandas?

newdf = df.query('closing_price.mean() <= closing_price <= closing_price.std()')

or

mean = closing_price.mean()
std = closing_price.std()

newdf = df.query('@mean <= closing_price <= @std')

concatenate char array in C

in rare cases when you can't use strncat, strcat or strcpy. And you don't have access to <string.h> so you can't use strlen. Also you maybe don't even know the size of the char arrays and you still want to concatenate because you got only pointers. Well, you can do old school malloc and count characters yourself like..

char *combineStrings(char* inputA, char* inputB) {
    size_t len = 0, lenB = 0;
    while(inputA[len] != '\0') len++;
    while(inputB[lenB] != '\0') lenB++;
    char* output = malloc(len+lenB);
    sprintf((char*)output,"%s%s",inputA,inputB);
    return output;
}

It just needs #include <stdio.h> which you will have most likely included already

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

you can simply use JSON.stringify(options) convert JSON object to string before submit, then warning dismiss and works fine

How does jQuery work when there are multiple elements with the same ID value?

Everybody says "Each id value must be used only once within a document", but what we do to get the elements we need when we have a stupid page that has more than one element with same id. If we use JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this

$("[id=duplicatedId]")

You will get a collection with all elements with id=duplicatedId

Systrace for Windows

There are several tools all built around Xperf. It's rather complex but very powerful -- see the quick start guide. There are other useful resources on the Windows Performance Analysis page

How to add row in JTable?

Use:

DefaultTableModel model = new DefaultTableModel(); 
JTable table = new JTable(model); 

// Create a couple of columns 
model.addColumn("Col1"); 
model.addColumn("Col2"); 

// Append a row 
model.addRow(new Object[]{"v1", "v2"});

How to increase executionTimeout for a long-running query?

You can set executionTimeout in web.config to support the longer execution time.

executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN

<httpRuntime  executionTimeout = "300" />

This make execution timeout to five minutes.

Optional Int32 attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

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. The default is 110 seconds, Reference.

The thread has exited with code 0 (0x0) with no unhandled exception

The framework creates threads to support each window you create, eg, as when you create a Form and .Show() it. When the windows close, the threads are terminated (ie, they exit).

This is normal behavior. However, if the application is creating threads, and there are a lot of thread exit messages corresponding to these threads (one could tell possibly by the thread's names, by giving them distinct names in the app), then perhaps this is indicative of a problem with the app creating threads when it shouldn't, due to a program logic error.

It would be an interesting followup to have the original poster let us know what s/he discovered regarding the problems with the server crashing. I have a feeling it wouldn't have anything to do with this... but it's hard to tell from the information posted.

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json"
        publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="7.0.0.0"/>
  </dependentAssembly>
</assemblyBinding>

Works for me.... just put the version you are using in newVersion i.e(newVersion="7.0.0.0")

How to hide UINavigationBar 1px bottom line

pxpgraphics's answer for Swift 3.0.

import Foundation
import UIKit

extension UINavigationBar {

  func hideBottomHairline() {
    let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
    navigationBarImageView!.isHidden = true
  }

  func showBottomHairline() {
    let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
    navigationBarImageView!.isHidden = false
  }

  private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
    if view is UIImageView && view.bounds.height <= 1.0 {
      return (view as! UIImageView)
    }

    let subviews = (view.subviews as [UIView])
    for subview: UIView in subviews {
      if let imageView: UIImageView = hairlineImageViewInNavigationBar(view: subview) {
        return imageView
      }
    }
    return nil
  }
}

extension UIToolbar {

  func hideHairline() {
    let navigationBarImageView = hairlineImageViewInToolbar(view: self)
    navigationBarImageView!.isHidden = true
  }

  func showHairline() {
    let navigationBarImageView = hairlineImageViewInToolbar(view: self)
    navigationBarImageView!.isHidden = false
  }

  private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? {
    if view is UIImageView && view.bounds.height <= 1.0 {
      return (view as! UIImageView)
    }

    let subviews = (view.subviews as [UIView])
    for subview: UIView in subviews {
      if let imageView: UIImageView = hairlineImageViewInToolbar(view: subview) {
        return imageView
      }
    }
    return nil
  }
}

Formatting Phone Numbers in PHP

this takes 7, 10 and 11 digit, removes additional characters and adds dashes by going right to left through the string. change the dash to a space or dot.

$raw_phone = preg_replace('/\D/', '', $raw_phone);
$temp = str_split($raw_phone);
$phone_number = "";
for ($x=count($temp)-1;$x>=0;$x--) {
    if ($x === count($temp) - 5 || $x === count($temp) - 8 || $x === count($temp) - 11) {
        $phone_number = "-" . $phone_number;
    }
    $phone_number = $temp[$x] . $phone_number;
}
echo $phone_number;

How to set a Fragment tag by code?

This is the best way I have found :

   public class MainActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
          // Let's first dynamically add a fragment into a frame container
          getSupportFragmentManager().beginTransaction(). 
              replace(R.id.flContainer, new DemoFragment(), "SOMETAG").
              commit();
          // Now later we can lookup the fragment by tag
          DemoFragment fragmentDemo = (DemoFragment) 
              getSupportFragmentManager().findFragmentByTag("SOMETAG");
        }
    }
}

Convert dictionary to list collection in C#

Alternatively:

var keys = new List<string>(dicNumber.Keys);

Calling javascript function in iframe

When you access resultFrame through document.all it only pulls it as an HTML element, not a window frame. You get the same issue if you have a frame fire an event using a "this" self-reference.

Replace:

document.all.resultFrame.Reset();

With:

window.frames.resultFrame.Reset();

Or:

document.all.resultFrame.contentWindow.Reset();

Re-order columns of table in Oracle

Look at the package DBMS_Redefinition. It will rebuild the table with the new ordering. It can be done with the table online.

As Phil Brown noted, think carefully before doing this. However there is overhead in scanning the row for columns and moving data on update. Column ordering rules I use (in no particular order):

  • Group related columns together.
  • Not NULL columns before null-able columns.
  • Frequently searched un-indexed columns first.
  • Rarely filled null-able columns last.
  • Static columns first.
  • Updateable varchar columns later.
  • Indexed columns after other searchable columns.

These rules conflict and have not all been tested for performance on the latest release. Most have been tested in practice, but I didn't document the results. Placement options target one of three conflicting goals: easy to understand column placement; fast data retrieval; and minimal data movement on updates.

How do I use arrays in C++?

Arrays on the type level

An array type is denoted as T[n] where T is the element type and n is a positive size, the number of elements in the array. The array type is a product type of the element type and the size. If one or both of those ingredients differ, you get a distinct type:

#include <type_traits>

static_assert(!std::is_same<int[8], float[8]>::value, "distinct element type");
static_assert(!std::is_same<int[8],   int[9]>::value, "distinct size");

Note that the size is part of the type, that is, array types of different size are incompatible types that have absolutely nothing to do with each other. sizeof(T[n]) is equivalent to n * sizeof(T).

Array-to-pointer decay

The only "connection" between T[n] and T[m] is that both types can implicitly be converted to T*, and the result of this conversion is a pointer to the first element of the array. That is, anywhere a T* is required, you can provide a T[n], and the compiler will silently provide that pointer:

                  +---+---+---+---+---+---+---+---+
the_actual_array: |   |   |   |   |   |   |   |   |   int[8]
                  +---+---+---+---+---+---+---+---+
                    ^
                    |
                    |
                    |
                    |  pointer_to_the_first_element   int*

This conversion is known as "array-to-pointer decay", and it is a major source of confusion. The size of the array is lost in this process, since it is no longer part of the type (T*). Pro: Forgetting the size of an array on the type level allows a pointer to point to the first element of an array of any size. Con: Given a pointer to the first (or any other) element of an array, there is no way to detect how large that array is or where exactly the pointer points to relative to the bounds of the array. Pointers are extremely stupid.

Arrays are not pointers

The compiler will silently generate a pointer to the first element of an array whenever it is deemed useful, that is, whenever an operation would fail on an array but succeed on a pointer. This conversion from array to pointer is trivial, since the resulting pointer value is simply the address of the array. Note that the pointer is not stored as part of the array itself (or anywhere else in memory). An array is not a pointer.

static_assert(!std::is_same<int[8], int*>::value, "an array is not a pointer");

One important context in which an array does not decay into a pointer to its first element is when the & operator is applied to it. In that case, the & operator yields a pointer to the entire array, not just a pointer to its first element. Although in that case the values (the addresses) are the same, a pointer to the first element of an array and a pointer to the entire array are completely distinct types:

static_assert(!std::is_same<int*, int(*)[8]>::value, "distinct element type");

The following ASCII art explains this distinction:

      +-----------------------------------+
      | +---+---+---+---+---+---+---+---+ |
+---> | |   |   |   |   |   |   |   |   | | int[8]
|     | +---+---+---+---+---+---+---+---+ |
|     +---^-------------------------------+
|         |
|         |
|         |
|         |  pointer_to_the_first_element   int*
|
|  pointer_to_the_entire_array              int(*)[8]

Note how the pointer to the first element only points to a single integer (depicted as a small box), whereas the pointer to the entire array points to an array of 8 integers (depicted as a large box).

The same situation arises in classes and is maybe more obvious. A pointer to an object and a pointer to its first data member have the same value (the same address), yet they are completely distinct types.

If you are unfamiliar with the C declarator syntax, the parenthesis in the type int(*)[8] are essential:

  • int(*)[8] is a pointer to an array of 8 integers.
  • int*[8] is an array of 8 pointers, each element of type int*.

Accessing elements

C++ provides two syntactic variations to access individual elements of an array. Neither of them is superior to the other, and you should familiarize yourself with both.

Pointer arithmetic

Given a pointer p to the first element of an array, the expression p+i yields a pointer to the i-th element of the array. By dereferencing that pointer afterwards, one can access individual elements:

std::cout << *(x+3) << ", " << *(x+7) << std::endl;

If x denotes an array, then array-to-pointer decay will kick in, because adding an array and an integer is meaningless (there is no plus operation on arrays), but adding a pointer and an integer makes sense:

   +---+---+---+---+---+---+---+---+
x: |   |   |   |   |   |   |   |   |   int[8]
   +---+---+---+---+---+---+---+---+
     ^           ^               ^
     |           |               |
     |           |               |
     |           |               |
x+0  |      x+3  |          x+7  |     int*

(Note that the implicitly generated pointer has no name, so I wrote x+0 in order to identify it.)

If, on the other hand, x denotes a pointer to the first (or any other) element of an array, then array-to-pointer decay is not necessary, because the pointer on which i is going to be added already exists:

   +---+---+---+---+---+---+---+---+
   |   |   |   |   |   |   |   |   |   int[8]
   +---+---+---+---+---+---+---+---+
     ^           ^               ^
     |           |               |
     |           |               |
   +-|-+         |               |
x: | | |    x+3  |          x+7  |     int*
   +---+

Note that in the depicted case, x is a pointer variable (discernible by the small box next to x), but it could just as well be the result of a function returning a pointer (or any other expression of type T*).

Indexing operator

Since the syntax *(x+i) is a bit clumsy, C++ provides the alternative syntax x[i]:

std::cout << x[3] << ", " << x[7] << std::endl;

Due to the fact that addition is commutative, the following code does exactly the same:

std::cout << 3[x] << ", " << 7[x] << std::endl;

The definition of the indexing operator leads to the following interesting equivalence:

&x[i]  ==  &*(x+i)  ==  x+i

However, &x[0] is generally not equivalent to x. The former is a pointer, the latter an array. Only when the context triggers array-to-pointer decay can x and &x[0] be used interchangeably. For example:

T* p = &array[0];  // rewritten as &*(array+0), decay happens due to the addition
T* q = array;      // decay happens due to the assignment

On the first line, the compiler detects an assignment from a pointer to a pointer, which trivially succeeds. On the second line, it detects an assignment from an array to a pointer. Since this is meaningless (but pointer to pointer assignment makes sense), array-to-pointer decay kicks in as usual.

Ranges

An array of type T[n] has n elements, indexed from 0 to n-1; there is no element n. And yet, to support half-open ranges (where the beginning is inclusive and the end is exclusive), C++ allows the computation of a pointer to the (non-existent) n-th element, but it is illegal to dereference that pointer:

   +---+---+---+---+---+---+---+---+....
x: |   |   |   |   |   |   |   |   |   .   int[8]
   +---+---+---+---+---+---+---+---+....
     ^                               ^
     |                               |
     |                               |
     |                               |
x+0  |                          x+8  |     int*

For example, if you want to sort an array, both of the following would work equally well:

std::sort(x + 0, x + n);
std::sort(&x[0], &x[0] + n);

Note that it is illegal to provide &x[n] as the second argument since this is equivalent to &*(x+n), and the sub-expression *(x+n) technically invokes undefined behavior in C++ (but not in C99).

Also note that you could simply provide x as the first argument. That is a little too terse for my taste, and it also makes template argument deduction a bit harder for the compiler, because in that case the first argument is an array but the second argument is a pointer. (Again, array-to-pointer decay kicks in.)

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I am facing Same Problem i do following Setup Now Application Work fine

1-

<compilation debug="true" targetFramework="4.7.1">
      <assemblies>
        <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, 
      PublicKeyToken=cc7b13ffcd2ddd51"/>
      </assemblies>
    </compilation>

2- Add Reference

 **C:\Program Files (x86)\Microsoft Visual
Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\ADL
 Tools\2.4.0000.0\ASALocalRun\netstandard.dll**

3-

Copy Above Path Dll to Application Bin Folder on web server

Getting the ID of the element that fired an event

Though it is mentioned in other posts, I wanted to spell this out:

$(event.target).id is undefined

$(event.target)[0].id gives the id attribute.

event.target.id also gives the id attribute.

this.id gives the id attribute.

and

$(this).id is undefined.

The differences, of course, is between jQuery objects and DOM objects. "id" is a DOM property so you have to be on the DOM element object to use it.

(It tripped me up, so it probably tripped up someone else)

PHP + MySQL transactions examples

One more procedural style example with mysqli_multi_query, assumes $query is filled with semicolon-separated statements.

mysqli_begin_transaction ($link);

for (mysqli_multi_query ($link, $query);
    mysqli_more_results ($link);
    mysqli_next_result ($link) );

! mysqli_errno ($link) ?
    mysqli_commit ($link) : mysqli_rollback ($link);

how to configure hibernate config file for sql server

Don't forget to enable tcp/ip connections in SQL SERVER Configuration tools

How to find an available port?

Using 'ServerSocket' class we can identify whether given port is in use or free. ServerSocket provides a constructor that take an integer (which is port number) as argument and initialise server socket on the port. If ServerSocket throws any IO Exception, then we can assume this port is already in use.

Following snippet is used to get all available ports.

for (int port = 1; port < 65535; port++) {
         try {
                  ServerSocket socket = new ServerSocket(port);
                  socket.close();
                  availablePorts.add(port);
         } catch (IOException e) {

         }
}

Reference link.

Redeploy alternatives to JRebel

By the Spring guys, used for Grails reloading but works with Java too:

https://github.com/SpringSource/spring-loaded

How to add Google Maps Autocomplete search box?

So I've been playing around with this and it seems you need both places and js maps api activated. Then use the following:

HTML:

<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">

JS:

<script>
function initMap() {
  var input = document.getElementById('searchTextField');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    document.getElementById("address").value = JSON.stringify(place.address_components);
  });
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>

Self Join to get employee manager name

Try this one.

SELECT Employee.emp_id, Employee.emp_name,Manager.emp_id as Mgr_Id, Manager.emp_name as Mgr_Name 
FROM tblEmployeeDetails Employee 
LEFT JOIN tblEmployeeDetails Manager ON Employee.emp_mgr_id = Manager.emp_id

C++ Remove new line from multiline string

s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());

modal View controllers - how to display and dismiss

Example in Swift, picturing the foundry's explanation above and the Apple's documentation:

  1. Basing on the Apple's documentation and the foundry's explanation above (correcting some errors), presentViewController version using delegate design pattern:

ViewController.swift

import UIKit

protocol ViewControllerProtocol {
    func dismissViewController1AndPresentViewController2()
}

class ViewController: UIViewController, ViewControllerProtocol {

    @IBAction func goToViewController1BtnPressed(sender: UIButton) {
        let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
        vc1.delegate = self
        vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
        self.presentViewController(vc1, animated: true, completion: nil)
    }

    func dismissViewController1AndPresentViewController2() {
        self.dismissViewControllerAnimated(false, completion: { () -> Void in
            let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
            self.presentViewController(vc2, animated: true, completion: nil)
        })
    }

}

ViewController1.swift

import UIKit

class ViewController1: UIViewController {

    var delegate: protocol<ViewControllerProtocol>!

    @IBAction func goToViewController2(sender: UIButton) {
        self.delegate.dismissViewController1AndPresentViewController2()
    }

}

ViewController2.swift

import UIKit

class ViewController2: UIViewController {

}
  1. Basing on the foundry's explanation above (correcting some errors), pushViewController version using delegate design pattern:

ViewController.swift

import UIKit

protocol ViewControllerProtocol {
    func popViewController1AndPushViewController2()
}

class ViewController: UIViewController, ViewControllerProtocol {

    @IBAction func goToViewController1BtnPressed(sender: UIButton) {
        let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
        vc1.delegate = self
        self.navigationController?.pushViewController(vc1, animated: true)
    }

    func popViewController1AndPushViewController2() {
        self.navigationController?.popViewControllerAnimated(false)
        let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
        self.navigationController?.pushViewController(vc2, animated: true)
    }

}

ViewController1.swift

import UIKit

class ViewController1: UIViewController {

    var delegate: protocol<ViewControllerProtocol>!

    @IBAction func goToViewController2(sender: UIButton) {
        self.delegate.popViewController1AndPushViewController2()
    }

}

ViewController2.swift

import UIKit

class ViewController2: UIViewController {

}

Correct way to detach from a container without stopping it

Type Ctrl+p then Ctrl+q. It will help you to turn interactive mode to daemon mode.

See https://docs.docker.com/v1.7/articles/basics/#running-an-interactive-shell.

# To detach the tty without exiting the shell,
# use the escape sequence Ctrl-p + Ctrl-q
# note: This will continue to exist in a stopped state once exited (see "docker ps -a")

How to execute raw SQL in Flask-SQLAlchemy app

result = db.engine.execute(text("<sql here>"))

executes the <sql here> but doesn't commit it unless you're on autocommit mode. So, inserts and updates wouldn't reflect in the database.

To commit after the changes, do

result = db.engine.execute(text("<sql here>").execution_options(autocommit=True))

Split a string by a delimiter in python

You can use the str.split method: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']

What does the "static" modifier after "import" mean?

the difference between "import static com.showboy.Myclass" and "import com.showboy.Myclass"?

The first should generate a compiler error since the static import only works for importing fields or member types. (assuming MyClass is not an inner class or member from showboy)

I think you meant

import static com.showboy.MyClass.*;

which makes all static fields and members from MyClass available in the actual compilation unit without having to qualify them... as explained above

What is the list of supported languages/locales on Android?

Following jrub post on May 4 '2015, I'm adding updated locale list. Executed on a Nexus 6P with Android 7.0 Nougat and English US locale.

af_ [Afrikaans]
af_NA [Afrikaans (Namibia)]
af_ZA [Afrikaans (South Africa)]
agq_ [Aghem]
agq_CM [Aghem (Cameroon)]
ak_ [Akan]
ak_GH [Akan (Ghana)]
am_ [Amharic]
am_ET [Amharic (Ethiopia)]
ar_ [Arabic]
ar_001 [Arabic (World)]
ar_AE [Arabic (United Arab Emirates)]
ar_BH [Arabic (Bahrain)]
ar_DJ [Arabic (Djibouti)]
ar_DZ [Arabic (Algeria)]
ar_EG [Arabic (Egypt)]
ar_EH [Arabic (Western Sahara)]
ar_ER [Arabic (Eritrea)]
ar_IL [Arabic (Israel)]
ar_IQ [Arabic (Iraq)]
ar_JO [Arabic (Jordan)]
ar_KM [Arabic (Comoros)]
ar_KW [Arabic (Kuwait)]
ar_LB [Arabic (Lebanon)]
ar_LY [Arabic (Libya)]
ar_MA [Arabic (Morocco)]
ar_MR [Arabic (Mauritania)]
ar_OM [Arabic (Oman)]
ar_PS [Arabic (Palestine)]
ar_QA [Arabic (Qatar)]
ar_SA [Arabic (Saudi Arabia)]
ar_SD [Arabic (Sudan)]
ar_SO [Arabic (Somalia)]
ar_SS [Arabic (South Sudan)]
ar_SY [Arabic (Syria)]
ar_TD [Arabic (Chad)]
ar_TN [Arabic (Tunisia)]
ar_YE [Arabic (Yemen)]
as_ [Assamese]
as_IN [Assamese (India)]
asa_ [Asu]
asa_TZ [Asu (Tanzania)]
az_ [Azerbaijani (Cyrillic)]
az_ [Azerbaijani (Latin)]
az_ [Azerbaijani]
az_AZ [Azerbaijani (Cyrillic,Azerbaijan)]
az_AZ [Azerbaijani (Latin,Azerbaijan)]
bas_ [Basaa]
bas_CM [Basaa (Cameroon)]
be_ [Belarusian]
be_BY [Belarusian (Belarus)]
bem_ [Bemba]
bem_ZM [Bemba (Zambia)]
bez_ [Bena]
bez_TZ [Bena (Tanzania)]
bg_ [Bulgarian]
bg_BG [Bulgarian (Bulgaria)]
bm_ [Bambara]
bm_ML [Bambara (Mali)]
bn_ [Bengali]
bn_BD [Bengali (Bangladesh)]
bn_IN [Bengali (India)]
bo_ [Tibetan]
bo_CN [Tibetan (China)]
bo_IN [Tibetan (India)]
br_ [Breton]
br_FR [Breton (France)]
brx_ [Bodo]
brx_IN [Bodo (India)]
bs_ [Bosnian (Cyrillic)]
bs_ [Bosnian (Latin)]
bs_ [Bosnian]
bs_BA [Bosnian (Cyrillic,Bosnia & Herzegovina)]
bs_BA [Bosnian (Latin,Bosnia & Herzegovina)]
ca_ [Catalan]
ca_AD [Catalan (Andorra)]
ca_ES [Catalan (Spain)]
ca_FR [Catalan (France)]
ca_IT [Catalan (Italy)]
ce_ [Chechen]
ce_RU [Chechen (Russia)]
cgg_ [Chiga]
cgg_UG [Chiga (Uganda)]
chr_ [Cherokee]
chr_US [Cherokee (United States)]
cs_ [Czech]
cs_CZ [Czech (Czech Republic)]
cy_ [Welsh]
cy_GB [Welsh (United Kingdom)]
da_ [Danish]
da_DK [Danish (Denmark)]
da_GL [Danish (Greenland)]
dav_ [Taita]
dav_KE [Taita (Kenya)]
de_ [German]
de_AT [German (Austria)]
de_BE [German (Belgium)]
de_CH [German (Switzerland)]
de_DE [German (Germany)]
de_LI [German (Liechtenstein)]
de_LU [German (Luxembourg)]
dje_ [Zarma]
dje_NE [Zarma (Niger)]
dsb_ [Lower Sorbian]
dsb_DE [Lower Sorbian (Germany)]
dua_ [Duala]
dua_CM [Duala (Cameroon)]
dyo_ [Jola-Fonyi]
dyo_SN [Jola-Fonyi (Senegal)]
dz_ [Dzongkha]
dz_BT [Dzongkha (Bhutan)]
ebu_ [Embu]
ebu_KE [Embu (Kenya)]
ee_ [Ewe]
ee_GH [Ewe (Ghana)]
ee_TG [Ewe (Togo)]
el_ [Greek]
el_CY [Greek (Cyprus)]
el_GR [Greek (Greece)]
en_ [English]
en_001 [English (World)]
en_150 [English (Europe)]
en_AG [English (Antigua & Barbuda)]
en_AI [English (Anguilla)]
en_AS [English (American Samoa)]
en_AT [English (Austria)]
en_AU [English (Australia)]
en_BB [English (Barbados)]
en_BE [English (Belgium)]
en_BI [English (Burundi)]
en_BM [English (Bermuda)]
en_BS [English (Bahamas)]
en_BW [English (Botswana)]
en_BZ [English (Belize)]
en_CA [English (Canada)]
en_CC [English (Cocos (Keeling) Islands)]
en_CH [English (Switzerland)]
en_CK [English (Cook Islands)]
en_CM [English (Cameroon)]
en_CX [English (Christmas Island)]
en_CY [English (Cyprus)]
en_DE [English (Germany)]
en_DG [English (Diego Garcia)]
en_DK [English (Denmark)]
en_DM [English (Dominica)]
en_ER [English (Eritrea)]
en_FI [English (Finland)]
en_FJ [English (Fiji)]
en_FK [English (Falkland Islands (Islas Malvinas))]
en_FM [English (Micronesia)]
en_GB [English (United Kingdom)]
en_GD [English (Grenada)]
en_GG [English (Guernsey)]
en_GH [English (Ghana)]
en_GI [English (Gibraltar)]
en_GM [English (Gambia)]
en_GU [English (Guam)]
en_GY [English (Guyana)]
en_HK [English (Hong Kong)]
en_IE [English (Ireland)]
en_IL [English (Israel)]
en_IM [English (Isle of Man)]
en_IN [English (India)]
en_IO [English (British Indian Ocean Territory)]
en_JE [English (Jersey)]
en_JM [English (Jamaica)]
en_KE [English (Kenya)]
en_KI [English (Kiribati)]
en_KN [English (St. Kitts & Nevis)]
en_KY [English (Cayman Islands)]
en_LC [English (St. Lucia)]
en_LR [English (Liberia)]
en_LS [English (Lesotho)]
en_MG [English (Madagascar)]
en_MH [English (Marshall Islands)]
en_MO [English (Macau)]
en_MP [English (Northern Mariana Islands)]
en_MS [English (Montserrat)]
en_MT [English (Malta)]
en_MU [English (Mauritius)]
en_MW [English (Malawi)]
en_MY [English (Malaysia)]
en_NA [English (Namibia)]
en_NF [English (Norfolk Island)]
en_NG [English (Nigeria)]
en_NL [English (Netherlands)]
en_NR [English (Nauru)]
en_NU [English (Niue)]
en_NZ [English (New Zealand)]
en_PG [English (Papua New Guinea)]
en_PH [English (Philippines)]
en_PK [English (Pakistan)]
en_PN [English (Pitcairn Islands)]
en_PR [English (Puerto Rico)]
en_PW [English (Palau)]
en_RW [English (Rwanda)]
en_SB [English (Solomon Islands)]
en_SC [English (Seychelles)]
en_SD [English (Sudan)]
en_SE [English (Sweden)]
en_SG [English (Singapore)]
en_SH [English (St. Helena)]
en_SI [English (Slovenia)]
en_SL [English (Sierra Leone)]
en_SS [English (South Sudan)]
en_SX [English (Sint Maarten)]
en_SZ [English (Swaziland)]
en_TC [English (Turks & Caicos Islands)]
en_TK [English (Tokelau)]
en_TO [English (Tonga)]
en_TT [English (Trinidad & Tobago)]
en_TV [English (Tuvalu)]
en_TZ [English (Tanzania)]
en_UG [English (Uganda)]
en_UM [English (U.S. Outlying Islands)]
en_US [English (United States)]
en_US [English (United States,Computer)]
en_VC [English (St. Vincent & Grenadines)]
en_VG [English (British Virgin Islands)]
en_VI [English (U.S. Virgin Islands)]
en_VU [English (Vanuatu)]
en_WS [English (Samoa)]
en_ZA [English (South Africa)]
en_ZM [English (Zambia)]
en_ZW [English (Zimbabwe)]
eo_ [Esperanto]
es_ [Spanish]
es_419 [Spanish (Latin America)]
es_AR [Spanish (Argentina)]
es_BO [Spanish (Bolivia)]
es_CL [Spanish (Chile)]
es_CO [Spanish (Colombia)]
es_CR [Spanish (Costa Rica)]
es_CU [Spanish (Cuba)]
es_DO [Spanish (Dominican Republic)]
es_EA [Spanish (Ceuta & Melilla)]
es_EC [Spanish (Ecuador)]
es_ES [Spanish (Spain)]
es_GQ [Spanish (Equatorial Guinea)]
es_GT [Spanish (Guatemala)]
es_HN [Spanish (Honduras)]
es_IC [Spanish (Canary Islands)]
es_MX [Spanish (Mexico)]
es_NI [Spanish (Nicaragua)]
es_PA [Spanish (Panama)]
es_PE [Spanish (Peru)]
es_PH [Spanish (Philippines)]
es_PR [Spanish (Puerto Rico)]
es_PY [Spanish (Paraguay)]
es_SV [Spanish (El Salvador)]
es_US [Spanish (United States)]
es_UY [Spanish (Uruguay)]
es_VE [Spanish (Venezuela)]
et_ [Estonian]
et_EE [Estonian (Estonia)]
eu_ [Basque]
eu_ES [Basque (Spain)]
ewo_ [Ewondo]
ewo_CM [Ewondo (Cameroon)]
fa_ [Persian]
fa_AF [Persian (Afghanistan)]
fa_IR [Persian (Iran)]
ff_ [Fulah]
ff_CM [Fulah (Cameroon)]
ff_GN [Fulah (Guinea)]
ff_MR [Fulah (Mauritania)]
ff_SN [Fulah (Senegal)]
fi_ [Finnish]
fi_FI [Finnish (Finland)]
fil_ [Filipino]
fil_PH [Filipino (Philippines)]
fo_ [Faroese]
fo_DK [Faroese (Denmark)]
fo_FO [Faroese (Faroe Islands)]
fr_ [French]
fr_BE [French (Belgium)]
fr_BF [French (Burkina Faso)]
fr_BI [French (Burundi)]
fr_BJ [French (Benin)]
fr_BL [French (St. Barthélemy)]
fr_CA [French (Canada)]
fr_CD [French (Congo (DRC))]
fr_CF [French (Central African Republic)]
fr_CG [French (Congo (Republic))]
fr_CH [French (Switzerland)]
fr_CI [French (Côte d’Ivoire)]
fr_CM [French (Cameroon)]
fr_DJ [French (Djibouti)]
fr_DZ [French (Algeria)]
fr_FR [French (France)]
fr_GA [French (Gabon)]
fr_GF [French (French Guiana)]
fr_GN [French (Guinea)]
fr_GP [French (Guadeloupe)]
fr_GQ [French (Equatorial Guinea)]
fr_HT [French (Haiti)]
fr_KM [French (Comoros)]
fr_LU [French (Luxembourg)]
fr_MA [French (Morocco)]
fr_MC [French (Monaco)]
fr_MF [French (St. Martin)]
fr_MG [French (Madagascar)]
fr_ML [French (Mali)]
fr_MQ [French (Martinique)]
fr_MR [French (Mauritania)]
fr_MU [French (Mauritius)]
fr_NC [French (New Caledonia)]
fr_NE [French (Niger)]
fr_PF [French (French Polynesia)]
fr_PM [French (St. Pierre & Miquelon)]
fr_RE [French (Réunion)]
fr_RW [French (Rwanda)]
fr_SC [French (Seychelles)]
fr_SN [French (Senegal)]
fr_SY [French (Syria)]
fr_TD [French (Chad)]
fr_TG [French (Togo)]
fr_TN [French (Tunisia)]
fr_VU [French (Vanuatu)]
fr_WF [French (Wallis & Futuna)]
fr_YT [French (Mayotte)]
fur_ [Friulian]
fur_IT [Friulian (Italy)]
fy_ [Western Frisian]
fy_NL [Western Frisian (Netherlands)]
ga_ [Irish]
ga_IE [Irish (Ireland)]
gd_ [Scottish Gaelic]
gd_GB [Scottish Gaelic (United Kingdom)]
gl_ [Galician]
gl_ES [Galician (Spain)]
gsw_ [Swiss German]
gsw_CH [Swiss German (Switzerland)]
gsw_FR [Swiss German (France)]
gsw_LI [Swiss German (Liechtenstein)]
gu_ [Gujarati]
gu_IN [Gujarati (India)]
guz_ [Gusii]
guz_KE [Gusii (Kenya)]
gv_ [Manx]
gv_IM [Manx (Isle of Man)]
ha_ [Hausa]
ha_GH [Hausa (Ghana)]
ha_NE [Hausa (Niger)]
ha_NG [Hausa (Nigeria)]
haw_ [Hawaiian]
haw_US [Hawaiian (United States)]
hi_ [Hindi]
hi_IN [Hindi (India)]
hr_ [Croatian]
hr_BA [Croatian (Bosnia & Herzegovina)]
hr_HR [Croatian (Croatia)]
hsb_ [Upper Sorbian]
hsb_DE [Upper Sorbian (Germany)]
hu_ [Hungarian]
hu_HU [Hungarian (Hungary)]
hy_ [Armenian]
hy_AM [Armenian (Armenia)]
ig_ [Igbo]
ig_NG [Igbo (Nigeria)]
ii_ [Sichuan Yi]
ii_CN [Sichuan Yi (China)]
in_ [Indonesian]
in_ID [Indonesian (Indonesia)]
is_ [Icelandic]
is_IS [Icelandic (Iceland)]
it_ [Italian]
it_CH [Italian (Switzerland)]
it_IT [Italian (Italy)]
it_SM [Italian (San Marino)]
iw_ [Hebrew]
iw_IL [Hebrew (Israel)]
ja_ [Japanese]
ja_JP [Japanese (Japan)]
jgo_ [Ngomba]
jgo_CM [Ngomba (Cameroon)]
ji_ [Yiddish]
ji_001 [Yiddish (World)]
jmc_ [Machame]
jmc_TZ [Machame (Tanzania)]
ka_ [Georgian]
ka_GE [Georgian (Georgia)]
kab_ [Kabyle]
kab_DZ [Kabyle (Algeria)]
kam_ [Kamba]
kam_KE [Kamba (Kenya)]
kde_ [Makonde]
kde_TZ [Makonde (Tanzania)]
kea_ [Kabuverdianu]
kea_CV [Kabuverdianu (Cape Verde)]
khq_ [Koyra Chiini]
khq_ML [Koyra Chiini (Mali)]
ki_ [Kikuyu]
ki_KE [Kikuyu (Kenya)]
kk_ [Kazakh]
kk_KZ [Kazakh (Kazakhstan)]
kkj_ [Kako]
kkj_CM [Kako (Cameroon)]
kl_ [Kalaallisut]
kl_GL [Kalaallisut (Greenland)]
kln_ [Kalenjin]
kln_KE [Kalenjin (Kenya)]
km_ [Khmer]
km_KH [Khmer (Cambodia)]
kn_ [Kannada]
kn_IN [Kannada (India)]
ko_ [Korean]
ko_KP [Korean (North Korea)]
ko_KR [Korean (South Korea)]
kok_ [Konkani]
kok_IN [Konkani (India)]
ks_ [Kashmiri]
ks_IN [Kashmiri (India)]
ksb_ [Shambala]
ksb_TZ [Shambala (Tanzania)]
ksf_ [Bafia]
ksf_CM [Bafia (Cameroon)]
ksh_ [Colognian]
ksh_DE [Colognian (Germany)]
kw_ [Cornish]
kw_GB [Cornish (United Kingdom)]
ky_ [Kyrgyz]
ky_KG [Kyrgyz (Kyrgyzstan)]
lag_ [Langi]
lag_TZ [Langi (Tanzania)]
lb_ [Luxembourgish]
lb_LU [Luxembourgish (Luxembourg)]
lg_ [Ganda]
lg_UG [Ganda (Uganda)]
lkt_ [Lakota]
lkt_US [Lakota (United States)]
ln_ [Lingala]
ln_AO [Lingala (Angola)]
ln_CD [Lingala (Congo (DRC))]
ln_CF [Lingala (Central African Republic)]
ln_CG [Lingala (Congo (Republic))]
lo_ [Lao]
lo_LA [Lao (Laos)]
lrc_ [Northern Luri]
lrc_IQ [Northern Luri (Iraq)]
lrc_IR [Northern Luri (Iran)]
lt_ [Lithuanian]
lt_LT [Lithuanian (Lithuania)]
lu_ [Luba-Katanga]
lu_CD [Luba-Katanga (Congo (DRC))]
luo_ [Luo]
luo_KE [Luo (Kenya)]
luy_ [Luyia]
luy_KE [Luyia (Kenya)]
lv_ [Latvian]
lv_LV [Latvian (Latvia)]
mas_ [Masai]
mas_KE [Masai (Kenya)]
mas_TZ [Masai (Tanzania)]
mer_ [Meru]
mer_KE [Meru (Kenya)]
mfe_ [Morisyen]
mfe_MU [Morisyen (Mauritius)]
mg_ [Malagasy]
mg_MG [Malagasy (Madagascar)]
mgh_ [Makhuwa-Meetto]
mgh_MZ [Makhuwa-Meetto (Mozambique)]
mgo_ [Meta']
mgo_CM [Meta' (Cameroon)]
mk_ [Macedonian]
mk_MK [Macedonian (Macedonia (FYROM))]
ml_ [Malayalam]
ml_IN [Malayalam (India)]
mn_ [Mongolian]
mn_MN [Mongolian (Mongolia)]
mr_ [Marathi]
mr_IN [Marathi (India)]
ms_ [Malay]
ms_BN [Malay (Brunei)]
ms_MY [Malay (Malaysia)]
ms_SG [Malay (Singapore)]
mt_ [Maltese]
mt_MT [Maltese (Malta)]
mua_ [Mundang]
mua_CM [Mundang (Cameroon)]
my_ [Burmese]
my_MM [Burmese (Myanmar (Burma))]
mzn_ [Mazanderani]
mzn_IR [Mazanderani (Iran)]
naq_ [Nama]
naq_NA [Nama (Namibia)]
nb_ [Norwegian Bokmål]
nb_NO [Norwegian Bokmål (Norway)]
nb_SJ [Norwegian Bokmål (Svalbard & Jan Mayen)]
nd_ [North Ndebele]
nd_ZW [North Ndebele (Zimbabwe)]
ne_ [Nepali]
ne_IN [Nepali (India)]
ne_NP [Nepali (Nepal)]
nl_ [Dutch]
nl_AW [Dutch (Aruba)]
nl_BE [Dutch (Belgium)]
nl_BQ [Dutch (Caribbean Netherlands)]
nl_CW [Dutch (Curaçao)]
nl_NL [Dutch (Netherlands)]
nl_SR [Dutch (Suriname)]
nl_SX [Dutch (Sint Maarten)]
nmg_ [Kwasio]
nmg_CM [Kwasio (Cameroon)]
nn_ [Norwegian Nynorsk]
nn_NO [Norwegian Nynorsk (Norway)]
nnh_ [Ngiemboon]
nnh_CM [Ngiemboon (Cameroon)]
nus_ [Nuer]
nus_SS [Nuer (South Sudan)]
nyn_ [Nyankole]
nyn_UG [Nyankole (Uganda)]
om_ [Oromo]
om_ET [Oromo (Ethiopia)]
om_KE [Oromo (Kenya)]
or_ [Oriya]
or_IN [Oriya (India)]
os_ [Ossetic]
os_GE [Ossetic (Georgia)]
os_RU [Ossetic (Russia)]
pa_ [Punjabi (Arabic)]
pa_ [Punjabi (Gurmukhi)]
pa_ [Punjabi]
pa_IN [Punjabi (Gurmukhi,India)]
pa_PK [Punjabi (Arabic,Pakistan)]
pl_ [Polish]
pl_PL [Polish (Poland)]
ps_ [Pashto]
ps_AF [Pashto (Afghanistan)]
pt_ [Portuguese]
pt_AO [Portuguese (Angola)]
pt_BR [Portuguese (Brazil)]
pt_CV [Portuguese (Cape Verde)]
pt_GW [Portuguese (Guinea-Bissau)]
pt_MO [Portuguese (Macau)]
pt_MZ [Portuguese (Mozambique)]
pt_PT [Portuguese (Portugal)]
pt_ST [Portuguese (São Tomé & Príncipe)]
pt_TL [Portuguese (Timor-Leste)]
qu_ [Quechua]
qu_BO [Quechua (Bolivia)]
qu_EC [Quechua (Ecuador)]
qu_PE [Quechua (Peru)]
rm_ [Romansh]
rm_CH [Romansh (Switzerland)]
rn_ [Rundi]
rn_BI [Rundi (Burundi)]
ro_ [Romanian]
ro_MD [Romanian (Moldova)]
ro_RO [Romanian (Romania)]
rof_ [Rombo]
rof_TZ [Rombo (Tanzania)]
ru_ [Russian]
ru_BY [Russian (Belarus)]
ru_KG [Russian (Kyrgyzstan)]
ru_KZ [Russian (Kazakhstan)]
ru_MD [Russian (Moldova)]
ru_RU [Russian (Russia)]
ru_UA [Russian (Ukraine)]
rw_ [Kinyarwanda]
rw_RW [Kinyarwanda (Rwanda)]
rwk_ [Rwa]
rwk_TZ [Rwa (Tanzania)]
sah_ [Sakha]
sah_RU [Sakha (Russia)]
saq_ [Samburu]
saq_KE [Samburu (Kenya)]
sbp_ [Sangu]
sbp_TZ [Sangu (Tanzania)]
se_ [Northern Sami]
se_FI [Northern Sami (Finland)]
se_NO [Northern Sami (Norway)]
se_SE [Northern Sami (Sweden)]
seh_ [Sena]
seh_MZ [Sena (Mozambique)]
ses_ [Koyraboro Senni]
ses_ML [Koyraboro Senni (Mali)]
sg_ [Sango]
sg_CF [Sango (Central African Republic)]
shi_ [Tachelhit (Latin)]
shi_ [Tachelhit (Tifinagh)]
shi_ [Tachelhit]
shi_MA [Tachelhit (Latin,Morocco)]
shi_MA [Tachelhit (Tifinagh,Morocco)]
si_ [Sinhala]
si_LK [Sinhala (Sri Lanka)]
sk_ [Slovak]
sk_SK [Slovak (Slovakia)]
sl_ [Slovenian]
sl_SI [Slovenian (Slovenia)]
smn_ [Inari Sami]
smn_FI [Inari Sami (Finland)]
sn_ [Shona]
sn_ZW [Shona (Zimbabwe)]
so_ [Somali]
so_DJ [Somali (Djibouti)]
so_ET [Somali (Ethiopia)]
so_KE [Somali (Kenya)]
so_SO [Somali (Somalia)]
sq_ [Albanian]
sq_AL [Albanian (Albania)]
sq_MK [Albanian (Macedonia (FYROM))]
sq_XK [Albanian (Kosovo)]
sr_ [Serbian (Cyrillic)]
sr_ [Serbian (Latin)]
sr_ [Serbian]
sr_BA [Serbian (Cyrillic,Bosnia & Herzegovina)]
sr_BA [Serbian (Latin,Bosnia & Herzegovina)]
sr_ME [Serbian (Cyrillic,Montenegro)]
sr_ME [Serbian (Latin,Montenegro)]
sr_RS [Serbian (Cyrillic,Serbia)]
sr_RS [Serbian (Latin,Serbia)]
sr_XK [Serbian (Cyrillic,Kosovo)]
sr_XK [Serbian (Latin,Kosovo)]
sv_ [Swedish]
sv_AX [Swedish (Åland Islands)]
sv_FI [Swedish (Finland)]
sv_SE [Swedish (Sweden)]
sw_ [Swahili]
sw_CD [Swahili (Congo (DRC))]
sw_KE [Swahili (Kenya)]
sw_TZ [Swahili (Tanzania)]
sw_UG [Swahili (Uganda)]
ta_ [Tamil]
ta_IN [Tamil (India)]
ta_LK [Tamil (Sri Lanka)]
ta_MY [Tamil (Malaysia)]
ta_SG [Tamil (Singapore)]
te_ [Telugu]
te_IN [Telugu (India)]
teo_ [Teso]
teo_KE [Teso (Kenya)]
teo_UG [Teso (Uganda)]
th_ [Thai]
th_TH [Thai (Thailand)]
ti_ [Tigrinya]
ti_ER [Tigrinya (Eritrea)]
ti_ET [Tigrinya (Ethiopia)]
to_ [Tongan]
to_TO [Tongan (Tonga)]
tr_ [Turkish]
tr_CY [Turkish (Cyprus)]
tr_TR [Turkish (Turkey)]
twq_ [Tasawaq]
twq_NE [Tasawaq (Niger)]
tzm_ [Central Atlas Tamazight]
tzm_MA [Central Atlas Tamazight (Morocco)]
ug_ [Uyghur]
ug_CN [Uyghur (China)]
uk_ [Ukrainian]
uk_UA [Ukrainian (Ukraine)]
ur_ [Urdu]
ur_IN [Urdu (India)]
ur_PK [Urdu (Pakistan)]
uz_ [Uzbek (Arabic)]
uz_ [Uzbek (Cyrillic)]
uz_ [Uzbek (Latin)]
uz_ [Uzbek]
uz_AF [Uzbek (Arabic,Afghanistan)]
uz_UZ [Uzbek (Cyrillic,Uzbekistan)]
uz_UZ [Uzbek (Latin,Uzbekistan)]
vai_ [Vai (Latin)]
vai_ [Vai (Vai)]
vai_ [Vai]
vai_LR [Vai (Latin,Liberia)]
vai_LR [Vai (Vai,Liberia)]
vi_ [Vietnamese]
vi_VN [Vietnamese (Vietnam)]
vun_ [Vunjo]
vun_TZ [Vunjo (Tanzania)]
wae_ [Walser]
wae_CH [Walser (Switzerland)]
xog_ [Soga]
xog_UG [Soga (Uganda)]
yav_ [Yangben]
yav_CM [Yangben (Cameroon)]
yo_ [Yoruba]
yo_BJ [Yoruba (Benin)]
yo_NG [Yoruba (Nigeria)]
zgh_ [Standard Moroccan Tamazight]
zgh_MA [Standard Moroccan Tamazight (Morocco)]
zh_ [Chinese (Simplified Han)]
zh_ [Chinese (Traditional Han)]
zh_ [Chinese]
zh_CN [Chinese (Simplified Han,China)]
zh_HK [Chinese (Simplified Han,Hong Kong)]
zh_HK [Chinese (Traditional Han,Hong Kong)]
zh_MO [Chinese (Simplified Han,Macau)]
zh_MO [Chinese (Traditional Han,Macau)]
zh_SG [Chinese (Simplified Han,Singapore)]
zh_TW [Chinese (Traditional Han,Taiwan)]
zu_ [Zulu]
zu_ZA [Zulu (South Africa)]

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

Parse v. TryParse

For the record, I am testing two codes: That simply try to convert from a string to a number and if it fail then assign number to zero.

        if (!Int32.TryParse(txt,out tmpint)) {
            tmpint = 0;
        }

and:

        try {
            tmpint = Convert.ToInt32(txt);
        } catch (Exception) {
            tmpint = 0;
        }

For c#, the best option is to use tryparse because try&Catch alternative thrown the exception

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

That it is painful slow and undesirable, however, the code does not stop unless Debug's exception are settled for stop with it.

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

How to escape a JSON string to have it in a URL?

I'll offer an oddball alternative. Sometimes it's easier to use different encoding, especially if you're dealing with a variety of systems that don't all handle the details of URL encoding the same way. This isn't the most mainstream approach but can come in handy in certain situations.

Rather than URL-encoding the data, you can base64-encode it. The benefit of this is the encoded data is very generic, consisting only of alpha characters and sometimes trailing ='s. Example:

JSON array-of-strings:

["option", "Fred's dog", "Bill & Trudy", "param=3"]

That data, URL-encoded as the data param:

"data=%5B%27option%27%2C+%22Fred%27s+dog%22%2C+%27Bill+%26+Trudy%27%2C+%27param%3D3%27%5D"

Same, base64-encoded:

"data=WyJvcHRpb24iLCAiRnJlZCdzIGRvZyIsICJCaWxsICYgVHJ1ZHkiLCAicGFyYW09MyJd"

The base64 approach can be a bit shorter, but more importantly it's simpler. I often have problems moving URL-encoded data between cURL, web browsers and other clients, usually due to quotes, embedded % signs and so on. Base64 is very neutral because it doesn't use special characters.

What's the difference between select_related and prefetch_related in Django ORM?

Gone through the already posted answers. Just thought it would be better if I add an answer with actual example.

Let' say you have 3 Django models which are related.

class M1(models.Model):
    name = models.CharField(max_length=10)

class M2(models.Model):
    name = models.CharField(max_length=10)
    select_relation = models.ForeignKey(M1, on_delete=models.CASCADE)
    prefetch_relation = models.ManyToManyField(to='M3')

class M3(models.Model):
    name = models.CharField(max_length=10)

Here you can query M2 model and its relative M1 objects using select_relation field and M3 objects using prefetch_relation field.

However as we've mentioned M1's relation from M2 is a ForeignKey, it just returns only 1 record for any M2 object. Same thing applies for OneToOneField as well.

But M3's relation from M2 is a ManyToManyField which might return any number of M1 objects.

Consider a case where you have 2 M2 objects m21, m22 who have same 5 associated M3 objects with IDs 1,2,3,4,5. When you fetch associated M3 objects for each of those M2 objects, if you use select related, this is how it's going to work.

Steps:

  1. Find m21 object.
  2. Query all the M3 objects related to m21 object whose IDs are 1,2,3,4,5.
  3. Repeat same thing for m22 object and all other M2 objects.

As we have same 1,2,3,4,5 IDs for both m21, m22 objects, if we use select_related option, it's going to query the DB twice for the same IDs which were already fetched.

Instead if you use prefetch_related, when you try to get M2 objects, it will make a note of all the IDs that your objects returned (Note: only the IDs) while querying M2 table and as last step, Django is going to make a query to M3 table with the set of all IDs that your M2 objects have returned. and join them to M2 objects using Python instead of database.

This way you're querying all the M3 objects only once which improves performance.

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

ImportError: No module named 'bottle' - PyCharm

In some cases no "No module ..." can appear even on local files. In such cases you just need to mark appropriate directories as "source directories":

Mark as source lib directory

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

This solved my problem when I had to deal with HTML page with embedded JavaScript

WebElement empSalary =  driver.findElement(By.xpath(PayComponentAmount));
Actions mouse2 = new Actions(driver);
mouse2.clickAndHold(empSalary).sendKeys(Keys.chord(Keys.CONTROL, "a"), "1234").build().perform();

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].onchange()", empSalary);

How do I simulate placeholder functionality on input date field?

You can do something like this:

<input onfocus="(this.type='date')" class="js-form-control" placeholder="Enter Date">

excel formula to subtract number of days from a date

Assuming the original date is in cell A1:

=DATE(YEAR(A1), MONTH(A1), DAY(A1)-180)

How can I get a specific field of a csv file?

import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
   text = row[1]

Following the comments to the SO question here, a best, more robust code would be:

import csv
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    for row in mycsv:
        text = row[1]
        ............

Update: If what the OP actually wants is the last string in the last row of the csv file, there are several aproaches that not necesarily needs csv. For example,

fulltxt = open(mifilepath, 'rb').read()
laststring = fulltxt.split(',')[-1]

This is not good for very big files because you load the complete text in memory but could be ok for small files. Note that laststring could include a newline character so strip it before use.

And finally if what the OP wants is the second string in line n (for n=2):

Update 2: This is now the same code than the one in the answer from J.F.Sebastian. (The credit is for him):

import csv
line_number = 2     
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    text = mycsv[line_number][1]
    ............

How to use paths in tsconfig.json?

if typescript + webpack 2 + at-loader is being used, there is an additional step (@mleko's solution was only partially working for me):

// tsconfig.json
{
  "compilerOptions": {
    ...
    "rootDir": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}    

// webpack.config.js
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');

resolve: {
    plugins: [
        new TsConfigPathsPlugin(/* { tsconfig, compiler } */)
    ]
}

Advanced path resolution in TypeScript 2.0

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

I think this diagram from Microsoft explains all. In order to tell IE how to render the content, !DOCTYPE has to work with X-UA-Compatible meta tag. !DOCTYPE by itself has no affect on changing IE Document Mode.

enter image description here

http://ie.microsoft.com/testdrive/ieblog/2010/Mar/02_HowIE8DeterminesDocumentMode_3.png

Why doesn't CSS ellipsis work in table cell?

Just offering an alternative as I had this problem and none of the other answers here had the desired effect I wanted. So instead I used a list. Now semantically the information I was outputting could have been regarded as both tabular data but also listed data.

So in the end what I did was:

<ul>
    <li class="group">
        <span class="title">...</span>
        <span class="description">...</span>
        <span class="mp3-player">...</span>
        <span class="download">...</span>
        <span class="shortlist">...</span>
    </li>
    <!-- looped <li> -->
</ul>

So basically ul is table, li is tr, and span is td.

Then in CSS I set the span elements to be display:block; and float:left; (I prefer that combination to inline-block as it'll work in older versions of IE, to clear the float effect see: http://css-tricks.com/snippets/css/clear-fix/) and to also have the ellipses:

span {
    display: block;
    float: left;
    width: 100%;

    // truncate when long
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

Then all you do is set the max-widths of your spans and that'll give the list an appearance of a table.

How do I format a date in Jinja2?

You can use it like this in template without any filters

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}

Does Java support default parameter values?

No, but the simplest way to implement this is:

public myParameterizedFunction(String param1, int param2, Boolean param3) {

    param3 = param3 == null ? false : param3;
}

public myParameterizedFunction(String param1, int param2) {

    this(param1, param2, false);
}

or instead of the ternary operator, you can use if:

public myParameterizedFunction(String param1, int param2, Boolean param3) {

    if (param3 == null) {
        param3 = false;
    }
}

public myParameterizedFunction(String param1, int param2) {

    this(param1, param2, false);
}

Find the last element of an array while using a foreach loop in PHP

If I understand you, then all you need is to reverse the array and get the last element by a pop command:

   $rev_array = array_reverse($array);

   echo array_pop($rev_array);

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Unclosed Character Literal error

String y = "hello";

would work (note the double quotes).

char y = 'h'; this will work for chars (note the single quotes)

but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.

check if jquery has been loaded, then load it if false

Maybe something like this:

<script>
if(!window.jQuery)
{
   var script = document.createElement('script');
   script.type = "text/javascript";
   script.src = "path/to/jQuery";
   document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

How to avoid warning when introducing NAs by coercion

In general suppressing warnings is not the best solution as you may want to be warned when some unexpected input will be provided.
Solution below is wrapper for maintaining just NA during data type conversion. Doesn't require any package.

as.num = function(x, na.strings = "NA") {
    stopifnot(is.character(x))
    na = x %in% na.strings
    x[na] = 0
    x = as.numeric(x)
    x[na] = NA_real_
    x
}
as.num(c("1", "2", "X"), na.strings="X")
#[1]  1  2 NA

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

You should think about updating the object interchangeably and then simply store the object with the updated fields. Something like done below

function update(_id) {
    return new Promise((resolve, reject) => {

        ObjModel.findOne({_id}).exec((err, obj) => {

            if(err) return reject(err)

            obj = updateObject(obj, { 
                some_key: {
                    param2 : "val2_new",
                    param3 : "val3_new"
                }
            })

            obj.save((err, obj) => {
                if(err) return reject(err)
                resolve(obj)
            })
        })
    })
}


function updateObject(obj, data) {

    let keys = Object.keys(data)

    keys.forEach(key => {

        if(!obj[key]) obj[key] = data[key]

        if(typeof data[key] == 'object') 
            obj[key] = updateObject(obj[key], data[key])
        else
            obj[key] = data[key]
    })

    return obj
}

Google maps API V3 - multiple markers on exact same spot

Adding to Matthew Fox's sneaky genius answer, I have added a small random offset to each lat and lng when setting the marker object. For example:

new LatLng(getLat()+getMarkerOffset(), getLng()+getMarkerOffset()),

private static double getMarkerOffset(){
    //add tiny random offset to keep markers from dropping on top of themselves
    double offset =Math.random()/4000;
    boolean isEven = ((int)(offset *400000)) %2 ==0;
    if (isEven) return  offset;
    else        return -offset;
}

How to get the entire document HTML as a string?

I am using outerHTML for elements (the main <html> container), and XMLSerializer for anything else including <!DOCTYPE>, random comments outside the <html> container, or whatever else might be there. It seems that whitespace isn't preserved outside the <html> element, so I'm adding newlines by default with sep="\n".

_x000D_
_x000D_
function get_document_html(sep="\n") {_x000D_
    let html = "";_x000D_
    let xml = new XMLSerializer();_x000D_
    for (let n of document.childNodes) {_x000D_
        if (n.nodeType == Node.ELEMENT_NODE)_x000D_
            html += n.outerHTML + sep;_x000D_
        else_x000D_
            html += xml.serializeToString(n) + sep;_x000D_
    }_x000D_
    return html;_x000D_
}_x000D_
_x000D_
console.log(get_document_html().slice(0, 200));
_x000D_
_x000D_
_x000D_

How can I wrap text in a label using WPF?

To wrap text in the label control, change the the template of label as follows:

<Style x:Key="ErrorBoxStyle" TargetType="{x:Type Label}">
    <Setter Property="BorderBrush" Value="#FFF08A73"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Foreground" Value="Red"/>
    <Setter Property="Background" Value="#FFFFE3DF"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Padding" Value="5"/>
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Top"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Label}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" CornerRadius="5" HorizontalAlignment="Stretch">
                     
                    <TextBlock TextWrapping="Wrap" Text="{TemplateBinding Content}"/>
                </Border>
                    
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Launching Google Maps Directions via an intent on Android

A nice kotlin solution, using the latest cross-platform answer mentioned by lakshman sai...

No unnecessary Uri.toString and the Uri.parse though, this answer clean and minimal:

 val intentUri = Uri.Builder().apply {
      scheme("https")
      authority("www.google.com")
      appendPath("maps")
      appendPath("dir")
      appendPath("")
      appendQueryParameter("api", "1")
      appendQueryParameter("destination", "${yourLocation.latitude},${yourLocation.longitude}")
 }.build()
 startActivity(Intent(Intent.ACTION_VIEW).apply {
      data = intentUri
 })

How to Clone Objects

Painlessly: Using NClone library

Person a = new Person() { head = "big", feet = "small" };
Person b = Clone.ObjectGraph(a); 

Why can't Python parse this JSON data?

Here you go with modified data.json file:

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": [{
        "id": "valore"
    }],
    "om_points": "value",
    "parameters": [{
        "id": "valore"
    }]
}

You can call or print data on console by using below lines:

import json
from pprint import pprint
with open('data.json') as data_file:
    data_item = json.load(data_file)
pprint(data_item)

Expected output for print(data_item['parameters'][0]['id']):

{'maps': [{'id': 'blabla', 'iscategorical': '0'},
          {'id': 'blabla', 'iscategorical': '0'}],
 'masks': [{'id': 'valore'}],
 'om_points': 'value',
 'parameters': [{'id': 'valore'}]}

Expected output for print(data_item['parameters'][0]['id']):

valore

How to echo (or print) to the js console with php

https://github.com/bkdotcom/PHPDebugConsole

Support for all the javascript console methods:
assert, clear, count, error, group, groupCollapsed, groupEnd, info, log, table, trace, time, timeEnd, warn
plus a few more:
alert, groupSummary, groupUncollapse, timeGet

$debug = new \bdk\Debug(array(
    'collect' => true,
    'output' => true,
    'outputAs' => 'script',
));

$debug->log('hello world');
$debug->info('all of the javascript console methods are supported');
\bdk\Debug::_log('can use static methods');
$debug->trace();
$list = array(
    array('userId'=>1, 'name'=>'Bob', 'sex'=>'M', 'naughty'=>false),
    array('userId'=>10, 'naughty'=>true, 'name'=>'Sally', 'extracol' => 'yes', 'sex'=>'F'),
    array('userId'=>2, 'name'=>'Fred', 'sex'=>'M', 'naughty'=>false),
);
$debug->table('people', $list);

this will output the appropriate <script> tag upon script shutdown

alternatively, you can output as html, chromeLogger, FirePHP, file, plaintext, websockets, etc

upcomming release includes a psr-3 (logger) implementation

How to remove from a map while iterating it?

The C++20 draft contains the convenience function std::erase_if.

So you can use that function to do it as a one-liner.

std::map<K, V> map_obj;
//calls needs_removing for each element and erases it, if true was reuturned
std::erase_if(map_obj,needs_removing);
//if you need to pass only part of the key/value pair
std::erase_if(map_obj,[](auto& kv){return needs_removing(kv.first);});

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

No problems with my terminal. The above answers helped me looking in the right directions but it didn't work for me until I added 'ignore':

fix_encoding = lambda s: s.decode('utf8', 'ignore')

As indicated in the comment below, this may lead to undesired results. OTOH it also may just do the trick well enough to get things working and you don't care about losing some characters.

How to disable a link using only CSS?

Apply below class on html.

.avoid-clicks {
  pointer-events: none;
}

How to format string to money

//Extra currency symbol and currency formatting: "€3,311.50":
String result = (Decimal.Parse("000000331150") / 100).ToString("C");

//No currency symbol and no currency formatting: "3311.50"
String result = (Decimal.Parse("000000331150") / 100).ToString("f2");

adding to window.onload event?

There are basically two ways

  1. store the previous value of window.onload so your code can call a previous handler if present before or after your code executes

  2. using the addEventListener approach (that of course Microsoft doesn't like and requires you to use another different name).

The second method will give you a bit more safety if another script wants to use window.onload and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.

Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.

ImportError: no module named win32api

This is resolve my case as found on Where to find the win32api module for Python?

pip install pypiwin32

What is a predicate in c#?

In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.

I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.

System.Net.WebException: The remote name could not be resolved:

It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult is generic, however you can determine the exact issue catching HttpRequestException and then inspecting InnerException: if it's a WebException then you can check the WebException.Status property, for example WebExceptionStatus.NameResolutionFailure should indicate a DNS resolution problem.


It may happen, there isn't much you can do.

What I'd suggest to always wrap that (network related) code in a loop with a try/catch block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:

private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;

public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
    using (var client = new HttpClient()) {
        for (int i=1; i <= NumberOfRetries; ++i) {
            try {
                return await client.GetAsync(url); 
            }
            catch (Exception e) when (i < NumberOfRetries) {
                await Task.Delay(DelayOnRetry);
            }
        }
    }
}

Table scroll with HTML and CSS

This work for me

Demo: jsfiddle

$(function() 
{
    Fixed_Header();
});

function Fixed_Header()
{
    $('.User_Table thead').css({'position': 'absolute'});
    $('.User_Table tbody tr:eq("2") td').each(function(index,e){
        $('.User_Table thead tr th:eq("'+index+'")').css({'width' : $(this).outerWidth() +"px" });
    });
    var Header_Height = $('.User_Table thead').outerHeight();
    $('.User_Table thead').css({'margin-top' : "-"+Header_Height+"px"});
    $('.User_Table').css({'margin-top' : Header_Height+"px"});
}

How do I modify a MySQL column to allow NULL?

My solution:

ALTER TABLE table_name CHANGE column_name column_name type DEFAULT NULL

For example:

ALTER TABLE SCHEDULE CHANGE date date DATETIME DEFAULT NULL;

Node.js Error: Cannot find module express

Have you tried

npm install

If you're specifically looking for just express

npm install --save express

Difference between ApiController and Controller in ASP.NET MVC

Quick n Short Answer

If you want to return a view, you should be in "Controller".

Normal Controller - ASP.NET MVC: you deal with normal "Controller" if you are in ASP.net Web Application. You can create Controller-Actions and you can return Views().

ApiController Controller: you create ApiControllers when you are developing ASP.net REST APIs. you can't return Views (though you can return Json/Data for HTML as string). These apis are considered as backend and their functions are called to return data not the view

Please dont forgt to mark this as answer, take care

More Details here

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Adding java.util.list will resolve your problem because List interface which you are trying to use is part of java.util.list package.

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

ctypes - Beginner

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

Generate a unique id

This question seems to be answered, however for completeness, I would add another approach.

You can use a unique ID number generator which is based on Twitter's Snowflake id generator. C# implementation can be found here.

var id64Generator = new Id64Generator();

// ...

public string generateID(string sourceUrl)
{
    return string.Format("{0}_{1}", sourceUrl, id64Generator.GenerateId());
}

Note that one of very nice features of that approach is possibility to have multiple generators on independent nodes (probably something useful for a search engine) generating real time, globally unique identifiers.

// node 0
var id64Generator = new Id64Generator(0);

// node 1
var id64Generator = new Id64Generator(1);

// ... node 10
var id64Generator = new Id64Generator(10);

Joining 2 SQL SELECT result sets into one

Use a FULL OUTER JOIN:

select 
   a.col_a,
   a.col_b,
   b.col_c
from
   (select col_a,col_bfrom tab1) a
join 
   (select col_a,col_cfrom tab2) b 
on a.col_a= b.col_a

What is the simplest way to swap each pair of adjoining chars in a string with Python?

Like so:

>>> s = "2143658709"
>>> ''.join([s[i+1] + s[i] for i in range(0, len(s), 2)])
'1234567890'

>>> s = "badcfe"
>>> ''.join([s[i+1] + s[i] for i in range(0, len(s), 2)])
'abcdef'

Update Tkinter Label from variable

The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True block preceding the line root.mainloop().


GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.

from tkinter import *

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

t = Entry(root, textvariable = var)
t.pack()

root.mainloop() # the window is now displayed

I like the following reference: tkinter 8.5 reference: a GUI for Python


Here is a working example of what you were trying to do:

from tkinter import *
from time import sleep

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

for i in range(6):
    sleep(1) # Need this to slow the changes down
    var.set('goodbye' if i%2 else 'hello')
    root.update_idletasks()

root.update Enter event loop until all pending events have been processed by Tcl.

Java: Casting Object to Array type

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0];

Edit Crystal report file without Crystal Report software

My dad moved his office after 30 year and they need to update the address in the header of their Crystal Reports 7 (1997!) based billing system.

After buying old copies of Access 97 and Visual Studio 2003 Pro, I found out that both programs were too new - they could open the RPT files, but they saved them with an updated version that would not open in the billing system.

I ended up being able to make the changes using this life-saver program...

http://www.softwareforces.com/Products/rpt-inspector-professional-suite-for-crystal-reports

It was available with a 10 day free trial, and I only needed about 10 minutes to make my changes. That said, I would have happily paid whatever they asked for it. :)

Some hints:

  1. When I opened my RPT files, I got an error saving the database could not be found. I ignored this error and everything worked fine.
  2. Because my RPT files were Crystal Reports version 7, I had to go into Options->Misc and tell the program to save in the old format...

enter image description here

Are there any naming convention guidelines for REST APIs?

I think you should avoid camel caps. The norm is to use lower case letters. I would also avoid underscores and use dashes instead

So your URL should look like this (ignoring the design issues as you requested :-))

api.service.com/hello-world/user-id/x

state machines tutorials

State machines can be very complex for a complex problem. They are also subject to unexpected bugs. They can turn into a nightmare if someone runs into a bug or needs to change the logic in the future. They are also difficult to follow and debug without the state diagram. Structured programming is much better (for example you would probably not use a state machine at mainline level). You can use structured programming even in interrupt context (which is where state machines are usually used). See this article "Macros to simulate multi-tasking/blocking code at interrupt level" found at codeproject.com.

Can I use complex HTML with Twitter Bootstrap's Tooltip?

Just as normal, using data-original-title:

Html:

<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>

Javascript:

$("[rel=tooltip]").tooltip({html:true});

The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.

Writing List of Strings to Excel CSV File in Python

The csv.writer writerow method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).

csvwriter.writerow(row)

Write the row parameter to the writer’s file object, formatted according to the current dialect.

Do either:

import csv
RESULTS = [
    ['apple','cherry','orange','pineapple','strawberry']
]
with open('output.csv','wb') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writerows(RESULTS)

or:

import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','wb') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writerow(RESULT)

Measuring function execution time in R

Another possible way of doing this would be to use Sys.time():

start.time <- Sys.time()
...Relevent codes...
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

Not the most elegant way to do it, compared to the answere above , but definitely a way to do it.

Best way to iterate through a Perl array

The best way to decide questions like this to benchmark them:

use strict;
use warnings;
use Benchmark qw(:all);

our @input_array = (0..1000);

my $a = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    foreach my $element (@array) {
       die unless $index == $element;
       $index++;
    }
};

my $b = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (defined(my $element = shift @array)) {
       die unless $index == $element;
       $index++;
    }
};

my $c = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (scalar(@array) !=0) {
       my $element = shift(@array);
       die unless $index == $element;
       $index++;
    }
};

my $d = sub {
    my @array = @{[ @input_array ]};
    foreach my $index (0.. $#array) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $e = sub {
    my @array = @{[ @input_array ]};
    for (my $index = 0; $index <= $#array; $index++) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $f = sub {
    my @array = @{[ @input_array ]};
    while (my ($index, $element) = each @array) {
       die unless $index == $element;
    }
};

my $count;
timethese($count, {
   '1' => $a,
   '2' => $b,
   '3' => $c,
   '4' => $d,
   '5' => $e,
   '6' => $f,
});

And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi

I get:

Benchmark: running 1, 2, 3, 4, 5, 6 for at least 3 CPU seconds...
         1:  3 wallclock secs ( 3.16 usr +  0.00 sys =  3.16 CPU) @ 12560.13/s (n=39690)
         2:  3 wallclock secs ( 3.18 usr +  0.00 sys =  3.18 CPU) @ 7828.30/s (n=24894)
         3:  3 wallclock secs ( 3.23 usr +  0.00 sys =  3.23 CPU) @ 6763.47/s (n=21846)
         4:  4 wallclock secs ( 3.15 usr +  0.00 sys =  3.15 CPU) @ 9596.83/s (n=30230)
         5:  4 wallclock secs ( 3.20 usr +  0.00 sys =  3.20 CPU) @ 6826.88/s (n=21846)
         6:  3 wallclock secs ( 3.12 usr +  0.00 sys =  3.12 CPU) @ 5653.53/s (n=17639)

So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.

@ikegami also points out that there are quite a few differences in these implimentations other than speed.

What is the best way to filter a Java Collection?

Wait for Java 8:

List<Person> olderThan30 = 
  //Create a Stream from the personList
  personList.stream().
  //filter the element to select only those with age >= 30
  filter(p -> p.age >= 30).
  //put those filtered elements into a new List.
  collect(Collectors.toList());

How to apply Hovering on html area tag?

What I did was to create a canvas element that I then position in front of the image map. Then, whenever an area is moused-over, I call a func that gets the coord string for that shape and the shape-type. If it's a poly I use the coords to draw an outline on the canvas. If it's a rect I draw a rect outline. You could easily add code to deal with circles.

You could also set the opacity of the canvas to less than 100% before filling the poly/rect/circle. You could also change the reliance on a global for the canvas's context - this would mean you could deal with more than 1 image-map on the same page.

<!DOCTYPE html>
<html>
<head>
<script>

// stores the device context of the canvas we use to draw the outlines
// initialized in myInit, used in myHover and myLeave
var hdc;

// shorthand func
function byId(e){return document.getElementById(e);}

// takes a string that contains coords eg - "227,307,261,309, 339,354, 328,371, 240,331"
// draws a line from each co-ord pair to the next - assumes starting point needs to be repeated as ending point.
function drawPoly(coOrdStr)
{
    var mCoords = coOrdStr.split(',');
    var i, n;
    n = mCoords.length;

    hdc.beginPath();
    hdc.moveTo(mCoords[0], mCoords[1]);
    for (i=2; i<n; i+=2)
    {
        hdc.lineTo(mCoords[i], mCoords[i+1]);
    }
    hdc.lineTo(mCoords[0], mCoords[1]);
    hdc.stroke();
}

function drawRect(coOrdStr)
{
    var mCoords = coOrdStr.split(',');
    var top, left, bot, right;
    left = mCoords[0];
    top = mCoords[1];
    right = mCoords[2];
    bot = mCoords[3];
    hdc.strokeRect(left,top,right-left,bot-top); 
}

function myHover(element)
{
    var hoveredElement = element;
    var coordStr = element.getAttribute('coords');
    var areaType = element.getAttribute('shape');

    switch (areaType)
    {
        case 'polygon':
        case 'poly':
            drawPoly(coordStr);
            break;

        case 'rect':
            drawRect(coordStr);
    }
}

function myLeave()
{
    var canvas = byId('myCanvas');
    hdc.clearRect(0, 0, canvas.width, canvas.height);
}

function myInit()
{
    // get the target image
    var img = byId('img-imgmap201293016112');

    var x,y, w,h;

    // get it's position and width+height
    x = img.offsetLeft;
    y = img.offsetTop;
    w = img.clientWidth;
    h = img.clientHeight;

    // move the canvas, so it's contained by the same parent as the image
    var imgParent = img.parentNode;
    var can = byId('myCanvas');
    imgParent.appendChild(can);

    // place the canvas in front of the image
    can.style.zIndex = 1;

    // position it over the image
    can.style.left = x+'px';
    can.style.top = y+'px';

    // make same size as the image
    can.setAttribute('width', w+'px');
    can.setAttribute('height', h+'px');

    // get it's context
    hdc = can.getContext('2d');

    // set the 'default' values for the colour/width of fill/stroke operations
    hdc.fillStyle = 'red';
    hdc.strokeStyle = 'red';
    hdc.lineWidth = 2;
}
</script>

<style>
body
{
    background-color: gray;
}
canvas
{
    pointer-events: none;       /* make the canvas transparent to the mouse - needed since canvas is position infront of image */
    position: absolute;
}
</style>

<title></title>
</head>
<body onload='myInit()'>
    <canvas id='myCanvas'></canvas>     <!-- gets re-positioned in myInit(); -->
<center>
<img src='http://dailyaeen.com.pk/epaper/wp-content/uploads/2012/09/27+Sep+2012-1.jpg?1349003469874' usemap='#imgmap_css_container_imgmap201293016112' class='imgmap_css_container' title='imgmap201293016112' alt='imgmap201293016112' id='img-imgmap201293016112' />
<map id='imgmap201293016112' name='imgmap_css_container_imgmap201293016112'>
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="2,0,604,-3,611,-3,611,166,346,165,345,130,-2,130,-2,124,1,128,1,126" href="" alt="imgmap201293016112-0" title="imgmap201293016112-0" class="imgmap201293016112-area" id="imgmap201293016112-area-0" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,131,341,213" href="" alt="imgmap201293016112-1" title="imgmap201293016112-1" class="imgmap201293016112-area" id="imgmap201293016112-area-1" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,166,614,241" href="" alt="imgmap201293016112-2" title="imgmap201293016112-2" class="imgmap201293016112-area" id="imgmap201293016112-area-2" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,242,344,239,345,496,574,495,575,435,917,433" href="" alt="imgmap201293016112-3" title="imgmap201293016112-3" class="imgmap201293016112-area" id="imgmap201293016112-area-3" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,416,341,494" href="" alt="imgmap201293016112-4" title="imgmap201293016112-4" class="imgmap201293016112-area" id="imgmap201293016112-area-4" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,215,341,410" href="" alt="imgmap201293016112-5" title="imgmap201293016112-5" class="imgmap201293016112-area" id="imgmap201293016112-area-5" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="916,533,916,436,578,436,576,495,806,496,807,535" href="" alt="imgmap201293016112-6" title="imgmap201293016112-6" class="imgmap201293016112-area" id="imgmap201293016112-area-6" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="805,536,918,614" href="" alt="imgmap201293016112-7" title="imgmap201293016112-7" class="imgmap201293016112-area" id="imgmap201293016112-area-7" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,494,803,616" href="" alt="imgmap201293016112-8" title="imgmap201293016112-8" class="imgmap201293016112-area" id="imgmap201293016112-area-8" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,497,223,616" href="" alt="imgmap201293016112-9" title="imgmap201293016112-9" class="imgmap201293016112-area" id="imgmap201293016112-area-9" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,494,456,614" href="" alt="imgmap201293016112-10" title="imgmap201293016112-10" class="imgmap201293016112-area" id="imgmap201293016112-area-10" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,935,572,1082" href="" alt="imgmap201293016112-11" title="imgmap201293016112-11" class="imgmap201293016112-area" id="imgmap201293016112-area-11" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,617,457,760" href="" alt="imgmap201293016112-12" title="imgmap201293016112-12" class="imgmap201293016112-area" id="imgmap201293016112-area-12" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,760,577,847" href="" alt="imgmap201293016112-13" title="imgmap201293016112-13" class="imgmap201293016112-area" id="imgmap201293016112-area-13" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,759,344,906" href="" alt="imgmap201293016112-14" title="imgmap201293016112-14" class="imgmap201293016112-area" id="imgmap201293016112-area-14" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,850,571,935" href="" alt="imgmap201293016112-15" title="imgmap201293016112-15" class="imgmap201293016112-area" id="imgmap201293016112-area-15" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="578,761,915,865" href="" alt="imgmap201293016112-16" title="imgmap201293016112-16" class="imgmap201293016112-area" id="imgmap201293016112-area-16" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1017,226,1085" href="" alt="imgmap201293016112-17" title="imgmap201293016112-17" class="imgmap201293016112-area" id="imgmap201293016112-area-17" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,908,342,1017" href="" alt="imgmap201293016112-18" title="imgmap201293016112-18" class="imgmap201293016112-area" id="imgmap201293016112-area-18" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="229,1010,342,1084" href="" alt="imgmap201293016112-19" title="imgmap201293016112-19" class="imgmap201293016112-area" id="imgmap201293016112-area-19" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1086,340,1206" href="" alt="imgmap201293016112-20" title="imgmap201293016112-20" class="imgmap201293016112-area" id="imgmap201293016112-area-20" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1209,224,1290" href="" alt="imgmap201293016112-21" title="imgmap201293016112-21" class="imgmap201293016112-area" id="imgmap201293016112-area-21" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1290,225,1432" href="" alt="imgmap201293016112-22" title="imgmap201293016112-22" class="imgmap201293016112-area" id="imgmap201293016112-area-22" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1432,340,1517" href="" alt="imgmap201293016112-23" title="imgmap201293016112-23" class="imgmap201293016112-area" id="imgmap201293016112-area-23" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,1432,686,1517" href="" alt="imgmap201293016112-24" title="imgmap201293016112-24" class="imgmap201293016112-area" id="imgmap201293016112-area-24" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,1266,686,1429" href="" alt="imgmap201293016112-25" title="imgmap201293016112-25" class="imgmap201293016112-area" id="imgmap201293016112-area-25" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1365,455,1430" href="" alt="imgmap201293016112-26" title="imgmap201293016112-26" class="imgmap201293016112-area" id="imgmap201293016112-area-26" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="231,1291,457,1360" href="" alt="imgmap201293016112-27" title="imgmap201293016112-27" class="imgmap201293016112-area" id="imgmap201293016112-area-27" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1210,342,1289" href="" alt="imgmap201293016112-28" title="imgmap201293016112-28" class="imgmap201293016112-area" id="imgmap201293016112-area-28" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="692,928,916,1016" href="" alt="imgmap201293016112-29" title="imgmap201293016112-29" class="imgmap201293016112-area" id="imgmap201293016112-area-29" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="460,616,916,759" href="" alt="imgmap201293016112-30" title="imgmap201293016112-30" class="imgmap201293016112-area" id="imgmap201293016112-area-30" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1316,917,1518" href="" alt="imgmap201293016112-31" title="imgmap201293016112-31" class="imgmap201293016112-area" id="imgmap201293016112-area-31" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="344,1150,572,1219" href="" alt="imgmap201293016112-32" title="imgmap201293016112-32" class="imgmap201293016112-area" id="imgmap201293016112-area-32" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1015,916,1171" href="" alt="imgmap201293016112-33" title="imgmap201293016112-33" class="imgmap201293016112-area" id="imgmap201293016112-area-33" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,955,686,1032" href="" alt="imgmap201293016112-34" title="imgmap201293016112-34" class="imgmap201293016112-area" id="imgmap201293016112-area-34" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,1036,687,1101" href="" alt="imgmap201293016112-35" title="imgmap201293016112-35" class="imgmap201293016112-area" id="imgmap201293016112-area-35" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="576,1104,689,1172" href="" alt="imgmap201293016112-36" title="imgmap201293016112-36" class="imgmap201293016112-area" id="imgmap201293016112-area-36" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="691,1232,918,1313" href="" alt="imgmap201293016112-37" title="imgmap201293016112-37" class="imgmap201293016112-area" id="imgmap201293016112-area-37" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="341,1085,573,1151" href="" alt="imgmap201293016112-38" title="imgmap201293016112-38" class="imgmap201293016112-area" id="imgmap201293016112-area-38" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,868,917,925,688,927,688,955,576,955,574,867,572,864" href="" alt="imgmap201293016112-39" title="imgmap201293016112-39" class="imgmap201293016112-area" id="imgmap201293016112-area-39" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="919,1173,917,1231,688,1231,688,1266,574,1267,576,1175,576,1175" href="" alt="imgmap201293016112-40" title="imgmap201293016112-40" class="imgmap201293016112-area" id="imgmap201293016112-area-40" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="572,1222,572,1265,459,1265,458,1289,339,1290,344,1225" href="" alt="imgmap201293016112-41" title="imgmap201293016112-41" class="imgmap201293016112-area" id="imgmap201293016112-area-41" />
</map>
</center>

</body>
</html>

Python: avoid new line with print command

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

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

Should be:

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

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

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

You can also use:

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

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

Calling virtual functions inside constructors

The C++ FAQ Lite Covers this pretty well:

Essentially, during the call to the base classes constructor, the object is not yet of the derived type and thus the base type's implementation of the virtual function is called and not the derived type's.

How to construct a WebSocket URI relative to the page URI?

In typescript:

export class WebsocketUtils {

    public static websocketUrlByPath(path) {
        return this.websocketProtocolByLocation() +
            window.location.hostname +
            this.websocketPortWithColonByLocation() +
            window.location.pathname +
            path;
    }

    private static websocketProtocolByLocation() {
        return window.location.protocol === "https:" ? "wss://" : "ws://";
    }

    private static websocketPortWithColonByLocation() {
        const defaultPort = window.location.protocol === "https:" ? "443" : "80";
        if (window.location.port !== defaultPort) {
            return ":" + window.location.port;
        } else {
            return "";
        }
    }
}

Usage:

alert(WebsocketUtils.websocketUrlByPath("/websocket"));

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

no operator "<<" matches these operands

It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare function.

Example

     while ((wrong < MAX_WRONG) && (soFar.compare(THE_WORD) != 0)) 

Remove CSS from a Div using JQuery

Before adding a class you should check if it already had class with .hasClass() method

For your specific question. You should be putting your stuff in Cascading Stylesheet. It's best practice to separate design and functionality.

so the proposed solution of adding and removing class names is best practice.

however when you are manipulating elements you don't control of how they are rendered. removeAttr('style') is BEST way to remove all inline styles.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

hi it worked for me from the recommended link from Fredy Andersen

sudo install_name_tool -change libmysqlclient.16.dylib /usr/local/mysql /lib/libmysqlclient.16.dylib /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle

just had to change to my version of mysql, in the command, thanks

.NET unique object identifier

How about this method:

Set a field in the first object to a new value. If the same field in the second object has the same value, it's probably the same instance. Otherwise, exit as different.

Now set the field in the first object to a different new value. If the same field in the second object has changed to the different value, it's definitely the same instance.

Don't forget to set field in the first object back to it's original value on exit.

Problems?

Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

Each compiler has its own libexec/ directory. Normally libexec directory contains small helper programs called by other programs. In this case, gcc is looking for its own 'cc1' compiler. Your machine may contains different versions of gcc, and each version should have its own 'cc1'. Normally these compilers are located on:


/usr/local/libexec/gcc/<architecture>/<compiler>/<compiler_version>/cc1

Similar path for g++. Above error means, that the current gcc version used is not able to find its own 'cc1' compiler. This normally points to a PATH issue.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

I use .kts Gradle files (Kotlin Gradle DSL) and the kotlin-kapt plugin but I still get a script compilation error when I use Ivanov Maksim's answer.

Unresolved reference: kapt

For me this was the only thing which worked:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = mapOf("room.schemaLocation" to "$projectDir/schemas")
            }
        }
    }
}

How to compile a static library in Linux?

See Creating a shared and static library with the gnu compiler [gcc]

gcc -c -o out.o out.c

-c means to create an intermediary object file, rather than an executable.

ar rcs libout.a out.o

This creates the static library. r means to insert with replacement, c means to create a new archive, and s means to write an index. As always, see the man page for more info.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

I wonder if this question has been answered well: how css margins work and why is it that margin-top:-5; is not the same as margin-bottom:5;?

Margin is distance from the surroundings of the element. margin-top says "... distance from surroundings as we measure from top 'side' of the element's 'box' and margin-bottom being the distance from the bottom 'side' of the 'box'". Then margin-top:5; is concerned with the top 'side' perimeter,-5 in that case; anything approaching from top 'side' can overlap top 'side' of element by 5, and margin-bottom:5; means distance between element bottom 'side' and surrounding is 5.

Basically that but affected by float'ed elements and the like: http://www.w3.org/TR/CSS2/box.html#margin-properties.

http://coding.smashingmagazine.com/2009/07/27/the-definitive-guide-to-using-negative-margins/

I stand to be corrected.

Execute Stored Procedure from a Function

I have figured out a solution to this problem. We can build a Function or View with "rendered" sql in a stored procedure that can then be executed as normal.

1.Create another sproc

CREATE PROCEDURE [dbo].[usp_FunctionBuilder]
DECLARE @outerSql VARCHAR(MAX)
DECLARE @innerSql VARCHAR(MAX)

2.Build the dynamic sql that you want to execute in your function (Example: you could use a loop and union, you could read in another sproc, use if statements and parameters for conditional sql, etc.)

SET @innerSql = 'your sql'

3.Wrap the @innerSql in a create function statement and define any external parameters that you have used in the @innerSql so they can be passed into the generated function.

SET @outerSql = 'CREATE FUNCTION [dbo].[fn_GeneratedFunction] ( @Param varchar(10))
RETURNS TABLE
AS
RETURN
' + @innerSql;


EXEC(@outerSql)

This is just pseudocode but the solution solves many problems such as linked server limitations, parameters, dynamic sql in function, dynamic server/database/table name, loops, etc.

You will need to tweak it to your needs, (Example: changing the return in the function)

VB.NET Switch Statement GoTo Case

you should declare label first use this :

    Select Case parameter 
        Case "userID"
                    ' does something here.
            Case "packageID"
                    ' does something here.
            Case "mvrType" 
                    If otherFactor Then 
                            ' does something here. 
                    Else 
                            GoTo else
                    End If 

            Case Else 
else :
                    ' does some processing... 
                    Exit Select 
    End Select

Oracle: SQL query that returns rows with only numeric values

You can use the REGEXP_LIKE function as:

SELECT X 
FROM myTable 
WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

Sample run:

SQL> SELECT X FROM SO;

X
--------------------
12c
123
abc
a12

SQL> SELECT X  FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

X
--------------------
123

SQL> 

How to close the command line window after running a batch file?

It should close automatically, if it doesn't it means that it is stuck on the first command.

In your example it should close either automatically (without the exit) or explicitly with the exit. I think the issue is with the first command you are running not returning properly.

As a work around you can try using

start "" tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B

How to set the background image of a html 5 canvas to .png image

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image

When does System.gc() do something?

while system.gc works,it will stop the world:all respones are stopped so garbage collector can scan every object to check if it is needed deleted. if the application is a web project, all request are stopped until gc finishes,and this will cause your web project can not work in a monent.

How to take MySQL database backup using MySQL Workbench?

In workbench 6.0 Connect to any of the database. You will see two tabs.

1.Management 2. Schemas

By default Schemas tab is selected. Select Management tab then select Data Export . You will get list of all databases. select the desired database and and the file name and ther options you wish and start export. You are done with backup.

What does -save-dev mean in npm install grunt --save-dev

For me the first answer appears a bit confusing, so to make it short and clean:

npm install <package_name> saves any specified packages into dependencies by default. Additionally, you can control where and how they get saved with some additional flags:

npm install <package_name> --no-save Prevents saving to dependencies.

npm install <package_name> ---save-dev updates the devDependencies in your package. These are only used for local testing and development.

You can read more at in the dcu

How to schedule a periodic task in Java?

These two classes can work together to schedule a periodic task:

Scheduled Task

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

Run Scheduled Task

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

Enable PHP Apache2

You have two ways to enable it.

First, you can set the absolute path of the php module file in your httpd.conf file like this:

LoadModule php5_module /path/to/mods-available/libphp5.so

Second, you can link the module file to the mods-enabled directory:

ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so

Set database timeout in Entity Framework

You can use DbContext.Database.CommandTimeout = 180; // seconds

It's pretty simple and no cast required.

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

Running npm command within Visual Studio Code

As an alternative to some of the answers suggested above, if you have powershell installed, you can invoke that directly as your terminal. That is edit the corresponding setting.json value as follows:

"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"

I find this works well as the environment is correctly configured.

Hibernate Error executing DDL via JDBC Statement

spring.jpa.hibernate.ddl-auto = update

change update to create, and run it

after run safely again change create to update so again all tables will not create and you can use your previous data

Creating a simple XML file using python

For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates

For a Jinja example, see my answer to a similar question.

Here is an example of generating your xml with string templates.

import string
from xml.sax.saxutils import escape

inner_template = string.Template('    <field${id} name="${name}">${value}</field${id}>')

outer_template = string.Template("""<root>
 <doc>
${document_list}
 </doc>
</root>
 """)

data = [
    (1, 'foo', 'The value for the foo document'),
    (2, 'bar', 'The <value> for the <bar> document'),
]

inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result

Output:

<root>
 <doc>
    <field1 name="foo">The value for the foo document</field1>
    <field2 name="bar">The &lt;value&gt; for the &lt;bar&gt; document</field2>
 </doc>
</root>

The downer of the template approach is that you won't get escaping of < and > for free. I danced around that problem by pulling in a util from xml.sax

How to convert object array to string array in Java

In Java 8:

String[] strings = Arrays.stream(objects).toArray(String[]::new);

To convert an array of other types:

String[] strings = Arrays.stream(obj).map(Object::toString).
                   toArray(String[]::new);

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

JavaScript displaying a float to 2 decimal places

number.parseFloat(2) works but it returns a string.

If you'd like to preserve it as a number type you can use:

Math.round(number * 100) / 100

Using a cursor with dynamic SQL in a stored procedure

this code can be useful for you.

example of cursor use in sql server

DECLARE sampleCursor CURSOR FOR 
      SELECT K.Id FROM TableA K WHERE ....;
OPEN sampleCursor
FETCH NEXT FROM sampleCursor INTO @Id
WHILE @@FETCH_STATUS <> -1
BEGIN

UPDATE TableB
   SET 
      ...

Import .bak file to a database in SQL server

Although it is much easier to restore database using SSMS as stated in many answers. You can also restore Database using .bak with SQL server query, for example

RESTORE DATABASE AdventureWorks2012 FROM DISK = 'D:\AdventureWorks2012.BAK'
GO

In above Query you need to keep in mind about .mdf/.ldf file location. You might get error

System.Data.SqlClient.SqlError: Directory lookup for the file "C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\AdventureWorks.MDF" failed with the operating system error 3(The system cannot find the path specified.). (Microsoft.SqlServer.SmoExtended)

So you need to run Query as below

RESTORE FILELISTONLY 
FROM DISK = 'D:\AdventureWorks2012.BAK'

Once you will run above Query you will get location of mdf/ldf use it Restore database using query

USE MASTER
GO
RESTORE DATABASE DBASE 
FROM DISK = 'D:\AdventureWorks2012.BAK'
WITH 
MOVE 'DBASE' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE.MDF',
MOVE 'DBASE_LOG' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE_1.LDF', 
NOUNLOAD,  REPLACE,  NOUNLOAD,  STATS = 5
GO

Source:Restore database from .bak file in SQL server (With & without scripts)

Notepad++ add to every line

Notepad++ Add Word To Start Of Every Line

Follow this instruction to write anything at the start of every line with Notepad++

Open Notepad++,

Press Cntrl+H open the Find/Replace Dialog.

Now type ^ in the Find what textbox (Type ^ without any spaces)

Type anything(like in our example I am writing "John ") in the Replace with textbox (Write text one/more space for adding one/more space after your text in every line)

Select the Regular Expression option

Place your cursor in the first line of your file to ensure all lines are affected

Click Replace All button

enter image description here

enter image description here

Notepad++ Add Text To End Of Every Line

Follow this instruction to write anything at the end of every line with Notepad++

Open Notepad++,

Press Cntrl+H open the Find/Replace Dialog.

Now type $ in the Find what textbox (Type $ without any spaces)

Type anything(like in our example I am writing " John") in the Replace with textbox (Write one/more space text for adding one/more space before your text in every line)

Select the Regular Expression option

Place your cursor in the first line of your file to ensure all lines are affected

Click Replace All button

enter image description here

enter image description here

For all Notepadd++ Tutorials: VISIT:)

Java image resize, maintain aspect ratio

try this

float rateX =  (float)jpDisplayImagen.getWidth()/(float)img.getWidth();
float rateY = (float)jpDisplayImagen.getHeight()/(float)img.getHeight();
if (rateX>rateY){
    int W=(int)(img.getWidth()*rateY);
    int H=(int)(img.getHeight()*rateY);
    jpDisplayImagen.getGraphics().drawImage(img, 0, 0,W,H, null);
}
else{
    int W=(int)(img.getWidth()*rateX);
    int H=(int)(img.getHeight()*rateX);
    jpDisplayImagen.getGraphics().drawImage(img, 0, 0,W,H, null);
}

What's a Good Javascript Time Picker?

I wasn't happy with any of the suggested time pickers, so I created my own with inspiration from Perifer's and the HTML5 spec:

http://github.com/gregersrygg/jquery.timeInput

You can either use the new html5 attributes for time input (step, min, max), or use an options object:

<input type="time" name="myTime" class="time-mm-hh" min="9:00" max="18:00" step="1800" />
<input type="time" name="myTime2" class="time-mm-hh" />

<script type="text/javascript">
    $("input[name='myTime']").timeInput(); // use default or html5 attributes
    $("input[name='myTime2']").timeInput({min: "6:00", max: "15:00", step: 900}); // 15 min intervals from 6:00 am to 3:00 pm
</script>

Validates input like this:

  • Insert ":" if missing
  • Not valid time? Replace with blank
  • Not a valid time according to step? Round up/down to closest step

The HTML5 spec doesn't allow am/pm or localized time syntax, so it only allowes the format hh:mm. Seconds is allowed according to spec, but I have not implemented it yet.

It's very "alpha", so there might be some bugs. Feel free to send me patches/pull requests. Have manually tested in IE 6&8, FF, Chrome and Opera (Latest stable on Linux for the latter ones).

Convert from List into IEnumerable format

IEnumerable<Book> _Book_IE;
List<Book> _Book_List;

If it's the generic variant:

_Book_IE = _Book_List;

If you want to convert to the non-generic one:

IEnumerable ie = (IEnumerable)_Book_List;

AddRange to a Collection

Or you can just make an ICollection extension like this:

 public static ICollection<T> AddRange<T>(this ICollection<T> @this, IEnumerable<T> items)
    {
        foreach(var item in items)
        {
            @this.Add(item);
        }

        return @this;
    }

Using it would be just like using it on a list:

collectionA.AddRange(IEnumerable<object> items);

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

you need to sign the assembly with a key. Go in the project properties under the tab signing: enter image description here

Check number of arguments passed to a Bash script

If you're only interested in bailing if a particular argument is missing, Parameter Substitution is great:

#!/bin/bash
# usage-message.sh

: ${1?"Usage: $0 ARGUMENT"}
#  Script exits here if command-line parameter absent,
#+ with following error message.
#    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT

java.lang.Exception: No runnable methods exception in running JUnits

in my case i just disabled //@RunWith(SpringRunner.class)

and there is no exception

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

The import org.apache.commons cannot be resolved in eclipse juno

The mentioned package/classes are not present in the compiletime classpath. Basically, Java has no idea what you're talking about when you say to import this and that. It can't find them in the classpath.

It's part of Apache Commons FileUpload. Just download the JAR and drop it in /WEB-INF/lib folder of the webapp project and this error should disappear. Don't forget to do the same for Apache Commons IO, that's where FileUpload depends on, otherwise you will get the same problem during runtime.


Unrelated to the concrete problem, I see that you're using Tomcat 7, which is a Servlet 3.0 compatible container. Do you know that you can just use the new request.getPart() method to obtain the uploaded file without the need for the whole Commons FileUpload stuff? Just add @MultipartConfig annotation to the servlet class so that you can use it. See also How to upload files to server using JSP/Servlet?

CSS image overlay with color and transparency

something like this? http://codepen.io/Nunotmp/pen/wKjvB

You can add an empty div and use absolute positioning.

Responsive iframe using Bootstrap

So, youtube gives out the iframe tag as follows:

<iframe width="560" height="315" src="https://www.youtube.com/embed/2EIeUlvHAiM" frameborder="0" allowfullscreen></iframe>

In my case, i just changed it to width="100%" and left the rest as is. It's not the most elegant solution (after all, in different devices you'll get weird ratios) But the video itself does not get deformed, just the frame.

How to generate XML file dynamically using PHP?

An easily broken way to do this is :

<?php
// Send the headers
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";

echo '<xml>';

// echo some dynamically generated content here
/*
<track>
    <path>song_path</path>
    <title>track_number - track_title</title>
</track>
*/

echo '</xml>';

?>

save it as .php

C#: what is the easiest way to subtract time?

Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)

what is the use of xsi:schemaLocation?

An xmlns is a unique identifier within the document - it doesn't have to be a URI to the schema:

XML namespaces provide a simple method for qualifying element and attribute names used in Extensible Markup Language documents by associating them with namespaces identified by URI references.

xsi:schemaLocation is supposed to give a hint as to the actual schema location:

can be used in a document to provide hints as to the physical location of schema documents which may be used for assessment.

Why does Git say my master branch is "already up to date" even though it is not?

Any changes you commit, like deleting all your project files, will still be in place after a pull. All a pull does is merge the latest changes from somewhere else into your own branch, and if your branch has deleted everything, then at best you'll get merge conflicts when upstream changes affect files you've deleted. So, in short, yes everything is up to date.

If you describe what outcome you'd like to have instead of "all files deleted", maybe someone can suggest an appropriate course of action.

Update:

GET THE MOST RECENT OF THE CODE ON MY SYSTEM

What you don't seem to understand is that you already have the most recent code, which is yours. If what you really want is to see the most recent of someone else's work that's on the master branch, just do:

git fetch upstream
git checkout upstream/master

Note that this won't leave you in a position to immediately (re)start your own work. If you need to know how to undo something you've done or otherwise revert changes you or someone else have made, then please provide details. Also, consider reading up on what version control is for, since you seem to misunderstand its basic purpose.

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

The best option since office 2007 is using Open XML SDK for it. We used Word.Interop but it halt sometimes, and it is not recommend for Microsoft, to use it as a server side document formatting, so Open XML SDK lets you creates word documents on DOCX and Open XML formats very easily. It lets you going well with scability, confidence ( the files, if it is corrupted can be rebuild ), and another very fine characteristics.

How do you add Boost libraries in CMakeLists.txt?

I agree with the answers 1 and 2. However, I prefer to specify each library separately. This makes the depencencies clearer in big projects. Yet, there is the danger of mistyping the (case-sensitive) variable names. In that case there is no direct cmake error but some undefined references linker issues later on, which may take some time to resolve. Therefore I use the following cmake function:

function(VerifyVarDefined)
  foreach(lib ${ARGV}) 
    if(DEFINED ${lib})
    else(DEFINED ${lib})
      message(SEND_ERROR "Variable ${lib} is not defined")
    endif(DEFINED ${lib})
  endforeach()
endfunction(VerifyVarDefined)

For the example mentioned above, this looks like:

VerifyVarDefined(Boost_PROGRAM_OPTIONS_LIBRARY Boost_REGEX_LIBRARY)
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )

If I had written "BOOST_PROGRAM_OPTIONS_LIBRARY" there would have been an error triggered by cmake and not much later triggered by the linker.

Get index of selected option with jQuery

You can use the .prop(propertyName) function to get a property from the first element in the jQuery object.

var savedIndex = $(selectElement).prop('selectedIndex');

This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:

$(selectElement).prop('selectedIndex', savedIndex);

Where to find Java JDK Source Code?

Sadly, as of this writing, DESPITE their own documentation readme, there is no src.zip in the JDK 7 or 8 install directories when you download the Windows version.

Note: perhaps this happens because many of us don't actually run the install .exe, but instead extract it. Many of us don't run the Java install (the full blown windows install) for security reasons....we just want the JDK put someplace out of the way where potential viruses cannot find it.

But their policy regarding the windows .exe (whatever it truly is) is indeed nuts, HOWEVER, the src.zip DOES exist in the linux install (a .tar.gz). There are multiple ways of extracting a .tar and a .gz, and I prefer the free "7Zip" utility.

  1. download the Linux 64 bit .tar.gz
  2. use 7zip to uncompress the .tar.gz to a .tar
  3. use 7zip to extract the .tar to the installation directory
  4. src.zip will be waiting for you in that installation directory.
  5. pull it out and place it where you like.

Oracle, this is really beyond stupid.

how to place last div into right top corner of parent div? (css)

Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.

enter image description here

HTML sample:

<body>
    <ul class="nav-tabs">
        <li><a  id="btn-tab-business" class="btn-tab nav-tab-selected"  onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
        <li><a  id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
        <li><a  id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
    </ul>
</body>

CSS sample:

.nav-tabs{
  position: relative;
  padding-bottom: 50px;
}
.nav-tabs li {
  display: inline-block;  
  position: absolute;
  list-style: none;
}
.nav-tabs li:first-child{
  top: 0px;
  left: 0px;
}
.nav-tabs li:last-child{
  top: 0px;
  right: 0px;
}
.nav-tabs li:nth-child(2){
  top: 0px;
  left: 50%;
  transform: translate(-50%, 0%);
}

SQL update trigger only when column is modified

fyi The code I ended up with:

IF UPDATE (QtyToRepair)
    begin
        INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew)
        SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S
        INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber 
        WHERE I.QtyToRepair <> D.QtyToRepair
end

Performance of Arrays vs. Lists

I think the performance will be quite similar. The overhead that is involved when using a List vs an Array is, IMHO when you add items to the list, and when the list has to increase the size of the array that it's using internally, when the capacity of the array is reached.

Suppose you have a List with a Capacity of 10, then the List will increase it's capacity once you want to add the 11th element. You can decrease the performance impact by initializing the Capacity of the list to the number of items it will hold.

But, in order to figure out if iterating over a List is as fast as iterating over an array, why don't you benchmark it ?

int numberOfElements = 6000000;

List<int> theList = new List<int> (numberOfElements);
int[] theArray = new int[numberOfElements];

for( int i = 0; i < numberOfElements; i++ )
{
    theList.Add (i);
    theArray[i] = i;
}

Stopwatch chrono = new Stopwatch ();

chrono.Start ();

int j;

 for( int i = 0; i < numberOfElements; i++ )
 {
     j = theList[i];
 }

 chrono.Stop ();
 Console.WriteLine (String.Format("iterating the List took {0} msec", chrono.ElapsedMilliseconds));

 chrono.Reset();

 chrono.Start();

 for( int i = 0; i < numberOfElements; i++ )
 {
     j = theArray[i];
 }

 chrono.Stop ();
 Console.WriteLine (String.Format("iterating the array took {0} msec", chrono.ElapsedMilliseconds));

 Console.ReadLine();

On my system; iterating over the array took 33msec; iterating over the list took 66msec.

To be honest, I didn't expect that the variation would be that much. So, I've put my iteration in a loop: now, I execute both iteration 1000 times. The results are:

iterating the List took 67146 msec iterating the array took 40821 msec

Now, the variation is not that large anymore, but still ...

Therefore, I've started up .NET Reflector, and the getter of the indexer of the List class, looks like this:

public T get_Item(int index)
{
    if (index >= this._size)
    {
        ThrowHelper.ThrowArgumentOutOfRangeException();
    }
    return this._items[index];
}

As you can see, when you use the indexer of the List, the List performs a check whether you're not going out of the bounds of the internal array. This additional check comes with a cost.

Clear the entire history stack and start a new activity on Android

With Android's Newer Version >= API 16 use finishAffinity()

approach is suitable for >= API 16.

Intent mIntent = new Intent(mContext,MainActivity.class);
finishAffinity();
startActivity(mIntent);
  • Its is same as starting new Activity, and clear all stack.
  • OR Restart to MainActivity/FirstActivity.

What's the purpose of the LEA instruction?

The LEA (Load Effective Address) instruction is a way of obtaining the address which arises from any of the Intel processor's memory addressing modes.

That is to say, if we have a data move like this:

MOV EAX, <MEM-OPERAND>

it moves the contents of the designated memory location into the target register.

If we replace the MOV by LEA, then the address of the memory location is calculated in exactly the same way by the <MEM-OPERAND> addressing expression. But instead of the contents of the memory location, we get the location itself into the destination.

LEA is not a specific arithmetic instruction; it is a way of intercepting the effective address arising from any one of the processor's memory addressing modes.

For instance, we can use LEA on just a simple direct address. No arithmetic is involved at all:

MOV EAX, GLOBALVAR   ; fetch the value of GLOBALVAR into EAX
LEA EAX, GLOBALVAR   ; fetch the address of GLOBALVAR into EAX.

This is valid; we can test it at the Linux prompt:

$ as
LEA 0, %eax
$ objdump -d a.out

a.out:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <.text>:
   0:   8d 04 25 00 00 00 00    lea    0x0,%eax

Here, there is no addition of a scaled value, and no offset. Zero is moved into EAX. We could do that using MOV with an immediate operand also.

This is the reason why people who think that the brackets in LEA are superfluous are severely mistaken; the brackets are not LEA syntax but are part of the addressing mode.

LEA is real at the hardware level. The generated instruction encodes the actual addressing mode and the processor carries it out to the point of calculating the address. Then it moves that address to the destination instead of generating a memory reference. (Since the address calculation of an addressing mode in any other instruction has no effect on CPU flags, LEA has no effect on CPU flags.)

Contrast with loading the value from address zero:

$ as
movl 0, %eax
$ objdump -d a.out | grep mov
   0:   8b 04 25 00 00 00 00    mov    0x0,%eax

It's a very similar encoding, see? Just the 8d of LEA has changed to 8b.

Of course, this LEA encoding is longer than moving an immediate zero into EAX:

$ as
movl $0, %eax
$ objdump -d a.out | grep mov
   0:   b8 00 00 00 00          mov    $0x0,%eax

There is no reason for LEA to exclude this possibility though just because there is a shorter alternative; it's just combining in an orthogonal way with the available addressing modes.

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

Sql query to insert datetime in SQL Server

Management studio creates scripts like:

insert table1 (foodate) values(CAST(N'2012-06-18 10:34:09.000' AS DateTime))

How to calculate modulus of large numbers?

What you're looking for is modular exponentiation, specifically modular binary exponentiation. This wikipedia link has pseudocode.

How to update column with null value

On insert we can use

$arrEntity=$entity->toArray();        
    foreach ($arrEntity as $key => $value) {    
        if (trim($entity->$key) == '' && !is_null($entity->$key) && !is_bool($entity->$key)){
        unset($entity->$key);
        }
    }

On update we can use

$fields=array();
foreach ($fields as $key => $value) {
        if (trim($value) == '' && !is_null($value) && !is_bool($value)){
            $fields[$key] = null;
        }
    }

How to adjust the size of y axis labels only in R?

ucfagls is right, providing you use the plot() command. If not, please give us more detail.

In any case, you can control every axis seperately by using the axis() command and the xaxt/yaxt options in plot(). Using the data of ucfagls, this becomes :

plot(Y ~ X, data=foo,yaxt="n")
axis(2,cex.axis=2)

the option yaxt="n" is necessary to avoid that the plot command plots the y-axis without changing. For the x-axis, this works exactly the same :

plot(Y ~ X, data=foo,xaxt="n")
axis(1,cex.axis=2)

See also the help files ?par and ?axis


Edit : as it is for a barplot, look at the options cex.axis and cex.names :

tN <- table(sample(letters[1:5],100,replace=T,p=c(0.2,0.1,0.3,0.2,0.2)))

op <- par(mfrow=c(1,2))
barplot(tN, col=rainbow(5),cex.axis=0.5) # for the Y-axis
barplot(tN, col=rainbow(5),cex.names=0.5) # for the X-axis
par(op)

alt text

How do I hide anchor text without hiding the anchor?

Another option is to hide based on bootstraps "sr-only" class. If you wrap the text in a span with the class "sr-only" then the text will not be displayed, but screen readers will still have access to it. So you would have:

<li><a href="somehwere"><span class="sr-only">Link text</span></a></li>

If you are not using bootstrap, still keep the above, but also add the below css to define the "sr-only" class:

.sr-only {position: absolute;  width: 1px;  height: 1px;  padding: 0;  margin: -1px;  overflow: hidden;  clip: rect(0 0 0 0);  border: 0; }

How to check a channel is closed or not without reading it?

I know this answer is so late, I have wrote this solution, Hacking Go run-time, It's not safety, It may crashes:

import (
    "unsafe"
    "reflect"
)


func isChanClosed(ch interface{}) bool {
    if reflect.TypeOf(ch).Kind() != reflect.Chan {
        panic("only channels!")
    }
    
    // get interface value pointer, from cgo_export 
    // typedef struct { void *t; void *v; } GoInterface;
    // then get channel real pointer
    cptr := *(*uintptr)(unsafe.Pointer(
        unsafe.Pointer(uintptr(unsafe.Pointer(&ch)) + unsafe.Sizeof(uint(0))),
    ))
    
    // this function will return true if chan.closed > 0
    // see hchan on https://github.com/golang/go/blob/master/src/runtime/chan.go 
    // type hchan struct {
    // qcount   uint           // total data in the queue
    // dataqsiz uint           // size of the circular queue
    // buf      unsafe.Pointer // points to an array of dataqsiz elements
    // elemsize uint16
    // closed   uint32
    // **
    
    cptr += unsafe.Sizeof(uint(0))*2
    cptr += unsafe.Sizeof(unsafe.Pointer(uintptr(0)))
    cptr += unsafe.Sizeof(uint16(0))
    return *(*uint32)(unsafe.Pointer(cptr)) > 0
}

Single huge .css file vs. multiple smaller specific .css files?

Maybe take a look at compass, which is an open source CSS authoring framework. It's based on Sass so it supports cool things like variables, nesting, mixins and imports. Especially imports are useful if you want to keep seperate smaller CSS files but have them combined into 1 automatically (avoiding multiple slow HTTP calls). Compass adds to this a big set of pre-defined mixins that are easy for handling cross-browser stuff. It's written in Ruby but it can easily be used with any system....

Linq style "For Each"

The Array and List<T> classes already have ForEach methods, though only this specific implementation. (Note that the former is static, by the way).

Not sure it really offers a great advantage over a foreach statement, but you could write an extension method to do the job for all IEnumerable<T> objects.

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach (var item in source)
        action(item);
}

This would allow the exact code you posted in your question to work just as you want.

How can you detect the version of a browser?

This is a Update on Fzs2 & kennebec For New Edge Chromium

_x000D_
_x000D_
function get_browser() {
    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; 
    if(/trident/i.test(M[1])){
        tem=/\brv[ :]+(\d+)/g.exec(ua) || []; 
        return {name:'IE',version:(tem[1]||'')};
        }   
    if(M[1]==='Chrome'){
        tem=ua.match(/\bEdg\/(\d+)/)
        if(tem!=null)   {return {name:'Edge(Chromium)', version:tem[1]};}
        tem=ua.match(/\bOPR\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
        }   
    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
    return {
      name: M[0],
      version: M[1]
    };
 }

var browser=get_browser(); // browser.name = 'Edge(Chromium)'
                           // browser.version = '86'

console.log(browser);
_x000D_
_x000D_
_x000D_

How to do URL decoding in Java?

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;

public class URLDecoding { 

    String decoded = "";

    public String decodeMethod(String url) throws UnsupportedEncodingException
    {
        decoded = java.net.URLDecoder.decode(url, "UTF-8"); 
        return  decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
    }

    public String getPathMethod(String url) throws URISyntaxException 
    {
        decoded = new java.net.URI(url).getPath();  
        return  decoded; 
    }

    public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException 
    {
        System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type")); 
        System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest")); 

    } 

}

You can select your method wisely :)

Increasing Google Chrome's max-connections-per-server limit to more than 6

There doesn't appear to be an external way to hack the behaviour of the executables.

You could modify the Chrome(ium) executables as this information is obviously compiled in. That approach brings a lot of problems with support and automatic upgrades so you probably want to avoid doing that. You also need to understand how to make the changes to the binaries which is not something most people can pick up in a few days.

If you compile your own browser you are creating a support issue for yourself as you are stuck with a specific revision. If you want to get new features and bug fixes you will have to recompile. All of this involves tracking Chrome development for bugs and build breakages - not something that a web developer should have to do.

I'd follow @BenSwayne's advice for now, but it might be worth thinking about doing some of the work outside of the client (the web browser) and putting it in a background process running on the same or different machines. This process can handle many more connections and you are just responsible for getting the data back from it. Since it is local(ish) you'll get results back quickly even with minimal connections.

Rendering a template variable as HTML

You can render a template in your code like so:

from django.template import Context, Template
t = Template('This is your <span>{{ message }}</span>.')

c = Context({'message': 'Your message'})
html = t.render(c)

See the Django docs for further information.

How to add a reference programmatically

Ommit

There are two ways to add references via VBA to your projects

1) Using GUID

2) Directly referencing the dll.

Let me cover both.

But first these are 3 things you need to take care of

a) Macros should be enabled

b) In Security settings, ensure that "Trust Access To Visual Basic Project" is checked

enter image description here

c) You have manually set a reference to `Microsoft Visual Basic for Applications Extensibility" object

enter image description here

Way 1 (Using GUID)

I usually avoid this way as I have to search for the GUID in the registry... which I hate LOL. More on GUID here.

Topic: Add a VBA Reference Library via code

Link: http://www.vbaexpress.com/kb/getarticle.php?kb_id=267

'Credits: Ken Puls
Sub AddReference()
     'Macro purpose:  To add a reference to the project using the GUID for the
     'reference library

    Dim strGUID As String, theRef As Variant, i As Long

     'Update the GUID you need below.
    strGUID = "{00020905-0000-0000-C000-000000000046}"

     'Set to continue in case of error
    On Error Resume Next

     'Remove any missing references
    For i = ThisWorkbook.VBProject.References.Count To 1 Step -1
        Set theRef = ThisWorkbook.VBProject.References.Item(i)
        If theRef.isbroken = True Then
            ThisWorkbook.VBProject.References.Remove theRef
        End If
    Next i

     'Clear any errors so that error trapping for GUID additions can be evaluated
    Err.Clear

     'Add the reference
    ThisWorkbook.VBProject.References.AddFromGuid _
    GUID:=strGUID, Major:=1, Minor:=0

     'If an error was encountered, inform the user
    Select Case Err.Number
    Case Is = 32813
         'Reference already in use.  No action necessary
    Case Is = vbNullString
         'Reference added without issue
    Case Else
         'An unknown error was encountered, so alert the user
        MsgBox "A problem was encountered trying to" & vbNewLine _
        & "add or remove a reference in this file" & vbNewLine & "Please check the " _
        & "references in your VBA project!", vbCritical + vbOKOnly, "Error!"
    End Select
    On Error GoTo 0
End Sub

Way 2 (Directly referencing the dll)

This code adds a reference to Microsoft VBScript Regular Expressions 5.5

Option Explicit

Sub AddReference()
    Dim VBAEditor As VBIDE.VBE
    Dim vbProj As VBIDE.VBProject
    Dim chkRef As VBIDE.Reference
    Dim BoolExists As Boolean

    Set VBAEditor = Application.VBE
    Set vbProj = ActiveWorkbook.VBProject

    '~~> Check if "Microsoft VBScript Regular Expressions 5.5" is already added
    For Each chkRef In vbProj.References
        If chkRef.Name = "VBScript_RegExp_55" Then
            BoolExists = True
            GoTo CleanUp
        End If
    Next

    vbProj.References.AddFromFile "C:\WINDOWS\system32\vbscript.dll\3"

CleanUp:
    If BoolExists = True Then
        MsgBox "Reference already exists"
    Else
        MsgBox "Reference Added Successfully"
    End If

    Set vbProj = Nothing
    Set VBAEditor = Nothing
End Sub

Note: I have not added Error Handling. It is recommended that in your actual code, do use it :)

EDIT Beaten by mischab1 :)