Programs & Examples On #Progress

A progress bar or progress window is a component in a (not necessarily graphical) user interface used to convey the progress of a task, such as a download or file transfer. "Progress" is also the name of a development tool and database from Progress Software Corporation. The "progress-4gl", "progress-db" and "openedge" tags are more specific to that environment.

Progress during large file copy (Copy-Item & Write-Progress?)

Not that I'm aware of. I wouldn't recommend using copy-item for this anyway. I don't think it has been designed to be robust like robocopy.exe to support retry which you would want for extremely large file copies over the network.

CSS Progress Circle

I created a fiddle using only CSS.

_x000D_
_x000D_
.wrapper {_x000D_
  width: 100px; /* Set the size of the progress bar */_x000D_
  height: 100px;_x000D_
  position: absolute; /* Enable clipping */_x000D_
  clip: rect(0px, 100px, 100px, 50px); /* Hide half of the progress bar */_x000D_
}_x000D_
/* Set the sizes of the elements that make up the progress bar */_x000D_
.circle {_x000D_
  width: 80px;_x000D_
  height: 80px;_x000D_
  border: 10px solid green;_x000D_
  border-radius: 50px;_x000D_
  position: absolute;_x000D_
  clip: rect(0px, 50px, 100px, 0px);_x000D_
}_x000D_
/* Using the data attributes for the animation selectors. */_x000D_
/* Base settings for all animated elements */_x000D_
div[data-anim~=base] {_x000D_
  -webkit-animation-iteration-count: 1;  /* Only run once */_x000D_
  -webkit-animation-fill-mode: forwards; /* Hold the last keyframe */_x000D_
  -webkit-animation-timing-function:linear; /* Linear animation */_x000D_
}_x000D_
_x000D_
.wrapper[data-anim~=wrapper] {_x000D_
  -webkit-animation-duration: 0.01s; /* Complete keyframes asap */_x000D_
  -webkit-animation-delay: 3s; /* Wait half of the animation */_x000D_
  -webkit-animation-name: close-wrapper; /* Keyframes name */_x000D_
}_x000D_
_x000D_
.circle[data-anim~=left] {_x000D_
  -webkit-animation-duration: 6s; /* Full animation time */_x000D_
  -webkit-animation-name: left-spin;_x000D_
}_x000D_
_x000D_
.circle[data-anim~=right] {_x000D_
  -webkit-animation-duration: 3s; /* Half animation time */_x000D_
  -webkit-animation-name: right-spin;_x000D_
}_x000D_
/* Rotate the right side of the progress bar from 0 to 180 degrees */_x000D_
@-webkit-keyframes right-spin {_x000D_
  from {_x000D_
    -webkit-transform: rotate(0deg);_x000D_
  }_x000D_
  to {_x000D_
    -webkit-transform: rotate(180deg);_x000D_
  }_x000D_
}_x000D_
/* Rotate the left side of the progress bar from 0 to 360 degrees */_x000D_
@-webkit-keyframes left-spin {_x000D_
  from {_x000D_
    -webkit-transform: rotate(0deg);_x000D_
  }_x000D_
  to {_x000D_
    -webkit-transform: rotate(360deg);_x000D_
  }_x000D_
}_x000D_
/* Set the wrapper clip to auto, effectively removing the clip */_x000D_
@-webkit-keyframes close-wrapper {_x000D_
  to {_x000D_
    clip: rect(auto, auto, auto, auto);_x000D_
  }_x000D_
}
_x000D_
<div class="wrapper" data-anim="base wrapper">_x000D_
  <div class="circle" data-anim="base left"></div>_x000D_
  <div class="circle" data-anim="base right"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Also check this fiddle here (CSS only)

_x000D_
_x000D_
@import url(http://fonts.googleapis.com/css?family=Josefin+Sans:100,300,400);_x000D_
    _x000D_
.arc1 {_x000D_
    width: 160px;_x000D_
    height: 160px;_x000D_
    background: #00a0db;_x000D_
    -webkit-transform-origin: -31% 61%;_x000D_
    margin-left: -30px;_x000D_
    margin-top: 20px;_x000D_
    -webkit-transform: translate(-54px,50px);_x000D_
    -moz-transform: translate(-54px,50px);_x000D_
    -o-transform: translate(-54px,50px);_x000D_
}_x000D_
.arc2 {_x000D_
    width: 160px;_x000D_
    height: 160px;_x000D_
    background: #00a0db;_x000D_
    -webkit-transform: skew(45deg,0deg);_x000D_
    -moz-transform: skew(45deg,0deg);_x000D_
    -o-transform: skew(45deg,0deg);_x000D_
    margin-left: -180px;_x000D_
    margin-top: -90px;_x000D_
    position: absolute;_x000D_
    -webkit-transition: all .5s linear;_x000D_
    -moz-transition: all .5s linear;_x000D_
    -o-transition: all .5s linear;_x000D_
}_x000D_
_x000D_
.arc-container:hover .arc2 {_x000D_
    margin-left: -50px;_x000D_
    -webkit-transform: skew(-20deg,0deg);_x000D_
    -moz-transform: skew(-20deg,0deg);_x000D_
    -o-transform: skew(-20deg,0deg);_x000D_
}_x000D_
_x000D_
.arc-wrapper {_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    border-radius:150px;_x000D_
    background: #424242;_x000D_
    overflow:hidden;_x000D_
    left: 50px;_x000D_
    top: 50px;_x000D_
    position: absolute;_x000D_
}_x000D_
.arc-hider {_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    border-radius: 150px;_x000D_
    border: 50px solid #e9e9e9;_x000D_
    position:absolute;_x000D_
    z-index:5;_x000D_
    box-shadow:inset 0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
_x000D_
.arc-inset  {_x000D_
    font-family: "Josefin Sans";_x000D_
    font-weight: 100;_x000D_
    position: absolute;_x000D_
    font-size: 413px;_x000D_
    margin-top: -64px;_x000D_
    z-index: 5;_x000D_
    left: 30px;_x000D_
    line-height: 327px;_x000D_
    height: 280px;_x000D_
    -webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0.2));_x000D_
}_x000D_
.arc-lowerInset {_x000D_
    font-family: "Josefin Sans";_x000D_
    font-weight: 100;_x000D_
    position: absolute;_x000D_
    font-size: 413px;_x000D_
    margin-top: -64px;_x000D_
    z-index: 5;_x000D_
    left: 30px;_x000D_
    line-height: 327px;_x000D_
    height: 280px;_x000D_
    color: white;_x000D_
    -webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,0.2), rgba(0,0,0,1));_x000D_
}_x000D_
.arc-overlay {_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background-image: linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
    background-image: -o-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
    background-image: -moz-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
    background-image: -webkit-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
_x000D_
    padding-left: 32px;_x000D_
    box-sizing: border-box;_x000D_
    -moz-box-sizing: border-box;_x000D_
    line-height: 100px;_x000D_
    font-family: sans-serif;_x000D_
    font-weight: 400;_x000D_
    text-shadow: 0 1px 0 #fff;_x000D_
    font-size: 22px;_x000D_
    border-radius: 100px;_x000D_
    position: absolute;_x000D_
    z-index: 5;_x000D_
    top: 75px;_x000D_
    left: 75px;_x000D_
    box-shadow:0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
.arc-container {_x000D_
    position: relative;_x000D_
    background: #e9e9e9;_x000D_
    height: 250px;_x000D_
    width: 250px;_x000D_
}
_x000D_
<div class="arc-container">_x000D_
    <div class="arc-hider"></div>_x000D_
    <div class="arc-inset">_x000D_
        o_x000D_
    </div>_x000D_
    <div class="arc-lowerInset">_x000D_
        o_x000D_
    </div>_x000D_
    <div class="arc-overlay">_x000D_
        35%_x000D_
    </div>_x000D_
    <div class="arc-wrapper">_x000D_
        <div class="arc2"></div>_x000D_
        <div class="arc1"></div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or this beautiful round progress bar with HTML5, CSS3 and JavaScript.

Text Progress Bar in the Console

Here's a nice example of a progressbar written in Python: http://nadiana.com/animated-terminal-progress-bar-in-python

But if you want to write it yourself. You could use the curses module to make things easier :)

[edit] Perhaps easier is not the word for curses. But if you want to create a full-blown cui than curses takes care of a lot of stuff for you.

[edit] Since the old link is dead I have put up my own version of a Python Progressbar, get it here: https://github.com/WoLpH/python-progressbar

When to use CouchDB over MongoDB and vice versa

I'm sure you can with Mongo (more familiar with it), and pretty sure you can with couch too.

Both are documented oriented (JSON-based) so there would be no "columns" but rather fields in documents -- but they can be fully dynamic.

They both do it you may want to look at other factors on which to use: other features you care about, popularity, etc. Google insights, indeed.com job posts would be ways to look at popularity.

You could just try it i think you should be able to have mongo running in 5 minutes.

Pretty printing XML in Python

As of Python 3.9 (still a release candidate as of 12 Aug 2020), there is a new xml.etree.ElementTree.indent() function for pretty-printing XML trees.

Sample usage:

import xml.etree.ElementTree as ET

element = ET.XML("<html><body>text</body></html>")
ET.indent(element)
print(ET.tostring(element, encoding='unicode'))

The upside is that it does not require any additional libraries. For more information check https://bugs.python.org/issue14465 and https://github.com/python/cpython/pull/15200

Does the Java &= operator apply & or &&?

see 15.22.2 of the JLS. For boolean operands, the & operator is boolean, not bitwise. The only difference between && and & for boolean operands is that for && it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).

So in your case, if b is a primitive, a = a && b, a = a & b, and a &= b all do the same thing.

Make selected block of text uppercase

Creator of the change-case extension here. I've updated the extension to support spanning lines.

To map the upper case command to a keybinding (e.g. CTRL+T+U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:

{
  "key": "ctrl+t ctrl+u",
  "command": "extension.changeCase.upper",
  "when": "editorTextFocus"
}

EDIT:

With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase and editor.action.transformToLowercase. These don't have default keybindings. They also work with multi-line blocks.

The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake_case, kebab-case, etc.

Manifest merger failed : uses-sdk:minSdkVersion 14

<uses-sdk tools:node="replace" />

No longer works.

change uses-sdk to

<uses-sdk tools:overrideLibrary="com.packagename.of.libary.with.conflict" />

and add
xmlns:tools="http://schemas.android.com/tools" in the AndroidManifest.xml file

Chrome Extension: Make it run every page load

From a background script you can listen to the chrome.tabs.onUpdated event and check the property changeInfo.status on the callback. It can be loading or complete. If it is complete, do the action.

Example:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {

    // do your things

  }
})

Because this will probably trigger on every tab completion, you can also check if the tab is active on its homonymous attribute, like this:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete' && tab.active) {

    // do your things

  }
})

How to identify server IP address in PHP

You may have to use $HTTP_SERVER_VARS['server_ADDR'] if you are not getting anything from above answers and if you are using older version of PHP

How to get the current directory of the cmdlet being executed

The easiest method seems to be to use the following predefined variable:

 $PSScriptRoot

about_Automatic_Variables and about_Scripts both state:

In PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in PowerShell 3.0, it is valid in all scripts.

I use it like this:

 $MyFileName = "data.txt"
 $filebase = Join-Path $PSScriptRoot $MyFileName

jQuery Show-Hide DIV based on Checkbox Value

You might consider using the :checked selector, provided by jQuery. Something like this:

$('.pChk').click(function() {
    if( $('.pChk:checked').length > 0 ) {
        $("#ProjectListButton").show();
    } else {
        $("#ProjectListButton").hide();
    }
}); 

How to show progress dialog in Android?

ProgressDialog is deprecated since API 26

still you can use this:

public void button_click(View view)
{
    final ProgressDialog progressDialog = ProgressDialog.show(Login.this,"Please Wait","Processing...",true);
}

Differences between SP initiated SSO and IDP initiated SSO

In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.

Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html

When to use throws in a Java method declaration?

The code that you looked at is not ideal. You should either:

  1. Catch the exception and handle it; in which case the throws is unnecesary.

  2. Remove the try/catch; in which case the Exception will be handled by a calling method.

  3. Catch the exception, possibly perform some action and then rethrow the exception (not just the message)

How and where are Annotations used in Java?

There are mutiple applications for Java's annotations. First of all, they may used by the compiler (or compiler extensions). Consider for example the Override annotation:

class Foo {

    @Override public boolean equals(Object other) {
        return ...;
    }
}

This one is actually built into the Java JDK. The compiler will signal an error, if some method is tagged with it, which does not override a method inherited from a base class. This annotation may be helpful in order to avoid the common mistake, where you actually intend to override a method, but fail to do so, because the signature given in your method does not match the signature of the method being overridden:

class Foo {

    @Override public boolean equals(Foo other) {  // Compiler signals an error for this one
        return ...;
    }
}

As of JDK7, annotations are allowed on any type. This feature can now be used for compiler annotations such as NotNull, like in:

public void processSomething(@NotNull String text) {
    ...
}

which allows the compiler to warn you about improper/unchecked uses of variables and null values.

Another more advanced application for annotations involves reflection and annotation processing at run-time. This is (I think) what you had in mind when you speak of annotations as "replacement for XML based configuration". This is the kind of annotation processing used, for example, by various frameworks and JCP standards (persistence, dependency injection, you name it) in order to provide the necessary meta-data and configuration information.

How can I use a DLL file from Python?

ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.

I would encourage you to check out Boost Python. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) C++ compiler from Microsoft.

Executing multiple commands from a Windows cmd script

I have just been doing the exact same(ish) task of creating a batch script to run maven test scripts. The problem is that calling maven scrips with mvn clean install ... is itself a script and so needs to be done with call mvn clean install.

Code that will work

rem run a maven clean install
cd C:\rbe-ui-test-suite 
call mvn clean install
rem now run through all the test scripts
call mvn clean install -Prun-integration-tests -Dpattern=tc-login
call mvn clean install -Prun-integration-tests -Dpattern=login-1

Note rather the use of call. This will allow the use of consecutive maven scripts in the batch file.

How to configure Docker port mapping to use Nginx as an upstream proxy?

Just found an article from Anand Mani Sankar wich shows a simple way of using nginx upstream proxy with docker composer.

Basically one must configure the instance linking and ports at the docker-compose file and update upstream at nginx.conf accordingly.

Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

Function pointer to member function

While this is based on the sterling answers elsewhere on this page, I had a use case which wasn't completely solved by them; for a vector of pointers to functions do the following:

#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>

class A{
public:
  typedef vector<int> (A::*AFunc)(int I1,int I2);
  vector<AFunc> FuncList;
  inline int Subtract(int I1,int I2){return I1-I2;};
  inline int Add(int I1,int I2){return I1+I2;};
  ...
  void Populate();
  void ExecuteAll();
};

void A::Populate(){
    FuncList.push_back(&A::Subtract);
    FuncList.push_back(&A::Add);
    ...
}

void A::ExecuteAll(){
  int In1=1,In2=2,Out=0;
  for(size_t FuncId=0;FuncId<FuncList.size();FuncId++){
    Out=(this->*FuncList[FuncId])(In1,In2);
    printf("Function %ld output %d\n",FuncId,Out);
  }
}

int main(){
  A Demo;
  Demo.Populate();
  Demo.ExecuteAll();
  return 0;
}

Something like this is useful if you are writing a command interpreter with indexed functions that need to be married up with parameter syntax and help tips etc. Possibly also useful in menus.

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

Array to Hash Ruby

a = ["item 1", "item 2", "item 3", "item 4"]
h = Hash[*a] # => { "item 1" => "item 2", "item 3" => "item 4" }

That's it. The * is called the splat operator.

One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."

So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Lukasz Niemier (also in the comments) offers this method for large data sets:

h = Hash[a.each_slice(2).to_a]

iTunes Connect: How to choose a good SKU?

Spending some time coming up with an SKU naming strategy can help you. You’ll be able to make it easy for team members to read and understand what each SKU represents. Use a value that is meaningful to your organization.

Ultimately, your SKU is a way to record important product information, so the more straightforward it is, the better for everyone.

Sticking to alphanumeric SKUs and substituting “-” or “_” for space is always the safest and best bet.

E.g. Your app name: Social Point, Submit year: 2020 = Your SKU is: Social_Point_2020

How To have Dynamic SQL in MySQL Stored Procedure

After 5.0.13, in stored procedures, you can use dynamic SQL:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

How to convert list data into json in java

public static List<Product> getCartList() {

    JSONObject responseDetailsJson = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
        JSONObject formDetailsJson = new JSONObject();
        formDetailsJson.put("id", "1");
        formDetailsJson.put("name", "name1");
       jsonArray.add(formDetailsJson);
    }
    responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format

    return cartList;

}

you can get the data in the following form

{
    "forms": [
        { "id": "1", "name": "name1" },
        { "id": "2", "name": "name2" } 
    ]
}

Reference an Element in a List of Tuples

Rather than:

first_element = myList[i[0]]

You probably want:

first_element = myList[i][0]

How to match all occurrences of a regex

You can use string.scan(your_regex).flatten. If your regex contains groups, it will return in a single plain array.

string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"
your_regex = /(\d+)[m-t]/
string.scan(your_regex).flatten
=> ["54", "1", "3"]

Regex can be a named group as well.

string = 'group_photo.jpg'
regex = /\A(?<name>.*)\.(?<ext>.*)\z/
string.scan(regex).flatten

You can also use gsub, it's just one more way if you want MatchData.

str.gsub(/\d/).map{ Regexp.last_match }

How Many Seconds Between Two Dates?

Just subtract:

var a = new Date();
alert("Wait a few seconds, then click OK");

var b = new Date();
var difference = (b - a) / 1000;

alert("You waited: " + difference + " seconds");

Illegal Character when trying to compile java code

Even I was facing this issue as am using notepad++ to code. It is very convenient to type the code in notepad++. However after compiling I get an error " error: illegal character: '\u00bb'". Solution : Start writing the code in older version of notepad(which will be there by default in your PC) and save it. Later the modifications can be done using notepad++. It works!!!

onclick event pass <li> id or value

I prefer to use the HTML5 data API, check this documentation:

A example

_x000D_
_x000D_
$('#some-list li').click(function() {_x000D_
  var textLoaded = 'Loading element with id='_x000D_
         + $(this).data('id');_x000D_
   $('#loading-content').text(textLoaded);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul id='some-list'>_x000D_
  <li data-id='1'>One </li>_x000D_
  <li data-id='2'>Two </li>_x000D_
  <!-- ... more li -->_x000D_
  <li data-id='n'>Other</li>_x000D_
</ul>_x000D_
_x000D_
<h1 id='loading-content'></h1>
_x000D_
_x000D_
_x000D_

string.split - by multiple character delimiter

More fast way using directly a no-string array but a string:

string[] StringSplit(string StringToSplit, string Delimitator)
{
    return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}

StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/

How to set session timeout in web.config

The value you are setting in the timeout attribute is the one of the correct ways to set the session timeout value.

The timeout attribute specifies the number of minutes a session can be idle before it is abandoned. The default value for this attribute is 20.

By assigning a value of 1 to this attribute, you've set the session to be abandoned in 1 minute after its idle.

To test this, create a simple aspx page, and write this code in the Page_Load event,

Response.Write(Session.SessionID);

Open a browser and go to this page. A session id will be printed. Wait for a minute to pass, then hit refresh. The session id will change.

Now, if my guess is correct, you want to make your users log out as soon as the session times out. For doing this, you can rig up a login page which will verify the user credentials, and create a session variable like this -

Session["UserId"] = 1;

Now, you will have to perform a check on every page for this variable like this -

if(Session["UserId"] == null)
    Response.Redirect("login.aspx");

This is a bare-bones example of how this will work.

But, for making your production quality secure apps, use Roles & Membership classes provided by ASP.NET. They provide Forms-based authentication which is much more reliabletha the normal Session-based authentication you are trying to use.

How to define two angular apps / modules in one page?

Manual bootstrapping both the modules will work. Look at this

  <!-- IN HTML -->
  <div id="dvFirst">
    <div ng-controller="FirstController">
      <p>1: {{ desc }}</p>
    </div>
  </div>

  <div id="dvSecond">
    <div ng-controller="SecondController ">
      <p>2: {{ desc }}</p>
    </div>
  </div>



// IN SCRIPT       
var dvFirst = document.getElementById('dvFirst');
var dvSecond = document.getElementById('dvSecond');

angular.element(document).ready(function() {
   angular.bootstrap(dvFirst, ['firstApp']);
   angular.bootstrap(dvSecond, ['secondApp']);
});

Here is the link to the Plunker http://plnkr.co/edit/1SdZ4QpPfuHtdBjTKJIu?p=preview

NOTE: In html, there is no ng-app. id has been used instead.

What is "android:allowBackup"?

It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"), it is possible to modify/read the content of an app even on a non-rooted device.

Solution - use android:allowBackup="false" in the manifest file.

You can read this post to have more information: Hacking Android Apps Using Backup Techniques

How to $watch multiple variable change in angular

$scope.$watch('age + name', function () {
  //called when name or age changed
});

Adding and removing style attribute from div with jquery

To completely remove the style attribute of the voltaic_holder span, do this:

$("#voltaic_holder").removeAttr("style");

To add an attribute, do this:

$("#voltaic_holder").attr("attribute you want to add", "value you want to assign to attribute");

To remove only the top style, do this:

$("#voltaic_holder").css("top", "");

How to install libusb in Ubuntu

Usually to use the library you need to install the dev version.

Try

sudo apt-get install libusb-1.0-0-dev

How to ignore whitespace in a regular expression subject string?

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

Equivalent of explode() to work with strings in MySQL

You can use stored procedure in this way..

DELIMITER |

CREATE PROCEDURE explode( pDelim VARCHAR(32), pStr TEXT)                                
BEGIN                                
  DROP TABLE IF EXISTS temp_explode;                                
  CREATE TEMPORARY TABLE temp_explode (id INT AUTO_INCREMENT PRIMARY KEY NOT NULL, word VARCHAR(40));                                
  SET @sql := CONCAT('INSERT INTO temp_explode (word) VALUES (', REPLACE(QUOTE(pStr), pDelim, '\'), (\''), ')');                                
  PREPARE myStmt FROM @sql;                                
  EXECUTE myStmt;                                
END |   

DELIMITER ;
  • example call:

     SET @str  = "The quick brown fox jumped over the lazy dog"; 
     SET @delim = " "; 
    
    CALL explode(@delim,@str);
    SELECT id,word FROM temp_explode;
    

Chrome:The website uses HSTS. Network errors...this page will probably work later

One very quick way around this is, when you're viewing the "Your connection is not private" screen:

type badidea

type thisisunsafe (credit to The Java Guy for finding the new passphrase)

That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.

This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.

Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.

Edit: as of 30 Jan 2018 this passphrase appears to no longer work.

If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:

How to create a self-signed certificate with openssl?

Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.

Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea passphrase no longer works.

Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).

The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).

The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:

Wikipedia: List of Internet Top Level Domains: Special Use Domains

These top-level domains seem to be exempt from the new https-only restrictions:

  • .local
  • .localhost
  • .test
  • (any custom/non-standard top-level domain)

See the answer and link from codinghands to the original question for more information:

answer from codinghands

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

If username/password contains any special characters then inside the camel configuration use RAW for Configuring the values like

  • RAW(se+re?t&23) where se+re?t&23 is actual password

  • RAW({abc.ftp.password}) where {abc.ftp.password} values comes from a spring property file.

By using RAW, solved my issue.

http://camel.apache.org/how-do-i-configure-endpoints.html

How to replicate background-attachment fixed on iOS

It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.

Check this comment by @PaulIrish:

Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.

you can see workarounds to this in this posts:

Fixed background image with ios7

Fixed body background scrolls with the page on iOS7

How can I find an element by CSS class with XPath?

XPath has a contains-token function, specifically designed for this situation:

//div[contains-token(@class, 'Test')]

It's only supported in the latest version of XPath (3.1) so you'll need an up-to-date implementation.

React.js: Identifying different inputs with one onChange handler

The key of your state should be the same as the name of your input field. Then you can do this in the handleEvent method;

this.setState({
        [event.target.name]: event.target.value
});

How can I label points in this scatterplot?

Your call to text() doesn't output anything because you inverted your x and your y:

plot(abs_losses, percent_losses, 
     main= "Absolute Losses vs. Relative Losses(in%)",
     xlab= "Losses (absolute, in miles of millions)",
     ylab= "Losses relative (in % of January´2007 value)",
     col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)

text(abs_losses, percent_losses, labels=namebank, cex= 0.7)

Now if you want to move your labels down, left, up or right you can add argument pos= with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:

 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)

enter image description here

You can of course gives a vector of value to pos if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):

 pos_vector <- rep(3, length(namebank))
 pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)

enter image description here

How to convert vector to array

We can do this using data() method. C++11 provides this method.

Code Snippet

#include<bits/stdc++.h>
using namespace std;


int main()
{
  ios::sync_with_stdio(false);

  vector<int>v = {7, 8, 9, 10, 11};
  int *arr = v.data();

  for(int i=0; i<v.size(); i++)
  {
    cout<<arr[i]<<" ";
  }

  return 0;
}

Specifying onClick event type with Typescript and React.Konva

React.MouseEvent works for me:

private onClick = (e: React.MouseEvent<HTMLInputElement>) => {
  let button = e.target as HTMLInputElement;
}

how to modify an existing check constraint?

No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)

$(window).height() vs $(document).height

$(document).height:if your device height was bigger. Your page has Not any scroll;

$(document).height: assume you have not scroll and return this height;

$(window).height: return your page height on your device.

JPanel setBackground(Color.BLACK) does nothing

If your panel is 'not opaque' (transparent) you wont see your background color.

DataTables fixed headers misaligned with columns in wide tables

Instead using sScrollX,sScrollY use separate div style

.scrollStyle
 {
  height:200px;overflow-x:auto;overflow-y:scroll;
 }

Add below after datatable call in script

 jQuery('.dataTable').wrap('<div class="scrollStyle" />');

Its working perfectly after many tries.

When do you use Git rebase instead of Git merge?

While merging is definitely the easiest and most common way to integrate changes, it's not the only one: Rebase is an alternative means of integration.

Understanding Merge a Little Better

When Git performs a merge, it looks for three commits:

  • (1) Common ancestor commit. If you follow the history of two branches in a project, they always have at least one commit in common: at this point in time, both branches had the same content and then evolved differently.
  • (2) + (3) Endpoints of each branch. The goal of an integration is to combine the current states of two branches. Therefore, their respective latest revisions are of special interest. Combining these three commits will result in the integration we're aiming for.

Fast-Forward or Merge Commit

In very simple cases, one of the two branches doesn't have any new commits since the branching happened - its latest commit is still the common ancestor.

Enter image description here

In this case, performing the integration is dead simple: Git can just add all the commits of the other branch on top of the common ancestor commit. In Git, this simplest form of integration is called a "fast-forward" merge. Both branches then share the exact same history.

Enter image description here

In a lot of cases, however, both branches moved forward individually.

Enter image description here

To make an integration, Git will have to create a new commit that contains the differences between them - the merge commit.

Enter image description here

Human Commits & Merge Commits

Normally, a commit is carefully created by a human being. It's a meaningful unit that wraps only related changes and annotates them with a comment.

A merge commit is a bit different: instead of being created by a developer, it gets created automatically by Git. And instead of wrapping a set of related changes, its purpose is to connect two branches, just like a knot. If you want to understand a merge operation later, you need to take a look at the history of both branches and the corresponding commit graph.

Integrating with Rebase

Some people prefer to go without such automatic merge commits. Instead, they want the project's history to look as if it had evolved in a single, straight line. No indication remains that it had been split into multiple branches at some point.

Enter image description here

Let's walk through a rebase operation step by step. The scenario is the same as in the previous examples: we want to integrate the changes from branch-B into branch-A, but now by using rebase.

Enter image description here

We will do this in three steps

  1. git rebase branch-A // Synchronises the history with branch-A
  2. git checkout branch-A // Change the current branch to branch-A
  3. git merge branch-B // Merge/take the changes from branch-B to branch-A

First, Git will "undo" all commits on branch-A that happened after the lines began to branch out (after the common ancestor commit). However, of course, it won't discard them: instead you can think of those commits as being "saved away temporarily".

Enter image description here

Next, it applies the commits from branch-B that we want to integrate. At this point, both branches look exactly the same.

Enter image description here

In the final step, the new commits on branch-A are now reapplied - but on a new position, on top of the integrated commits from branch-B (they are re-based).

The result looks like development had happened in a straight line. Instead of a merge commit that contains all the combined changes, the original commit structure was preserved.

Enter image description here

Finally, you get a clean branch branch-A with no unwanted and auto generated commits.

Note: Taken from the awesome post by git-tower. The disadvantages of rebase is also a good read in the same post.

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

Select distinct using linq

You should override Equals and GetHashCode meaningfully, in this case to compare the ID:

public class LinqTest
{
    public int id { get; set; }
    public string value { get; set; }

    public override bool Equals(object obj)
    {
        LinqTest obj2 = obj as LinqTest;
        if (obj2 == null) return false;
        return id == obj2.id;
    }

    public override int GetHashCode()
    {
        return id;
    }
}

Now you can use Distinct:

List<LinqTest> uniqueIDs = myList.Distinct().ToList();

CSS vertical alignment of inline/inline-block elements

Simply floating both elements left achieves the same result.

div {
background:yellow;
vertical-align:middle;
margin:10px;
}

a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}

span {
background:red;
display:inline-block;
float:left;
}

Finding the max/min value in an array of primitives using Java

Pass the array to a method that sorts it with Arrays.sort() so it only sorts the array the method is using then sets min to array[0] and max to array[array.length-1].

How to automate drag & drop functionality using Selenium WebDriver Java

There is a page documenting Advanced User Interactions; which has a lot of great examples on how to generate a sequence of actions, you can find it here

// Configure the action
Actions builder = new Actions(driver);

builder.keyDown(Keys.CONTROL)
   .click(someElement)
   .click(someOtherElement)
   .keyUp(Keys.CONTROL);

// Then get the action:
Action selectMultiple = builder.build();

// And execute it:
selectMultiple.perform();   

or

Actions builder = new Actions(driver);

Action dragAndDrop = builder.clickAndHold(someElement)
   .moveToElement(otherElement)
   .release(otherElement)
   .build();

dragAndDrop.perform();

Is there a vr (vertical rule) in html?

you can do in 2 way :

  1. create style as you already gave in div but change border-left to border-right
  2. take a image and make its width 1-2 px

Searching multiple files for multiple words

If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

  1. Find What = text1*.*text2
  2. Filters : .
  3. Search mode = Regular Expression
  4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(
  id__in=UserZone.objects.filter(zone=zone1).values('user'))

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

How do I store an array in localStorage?

The JSON approach works, on ie 7 you need json2.js, with it it works perfectly and despite the one comment saying otherwise there is localStorage on it. it really seems like the best solution with the least hassle. Of course one could write scripts to do essentially the same thing as json2 does but there is little point in that.

at least with the following version string there is localStorage, but as said you need to include json2.js because that isn't included by the browser itself: 4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; BRI/2; NP06; .NET4.0C; .NET4.0E; Zune 4.7) (I would have made this a comment on the reply, but can't).

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to sanity check a date in Java

looks like SimpleDateFormat is not checking the pattern strictly even after setLenient(false); method is applied on it, so i have used below method to validate if the date inputted is valid date or not as per supplied pattern.

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public boolean isValidFormat(String dateString, String pattern) {
    boolean valid = true;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
    try {
        formatter.parse(dateString);
    } catch (DateTimeParseException e) {
        valid = false;
    }
    return valid;
}

Update just one gem with bundler

If you want to update a single gem to a specific version:

  1. change the version of the gem in the Gemfile
  2. bundle update
> ruby -v
ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin19]
> gem -v
3.0.3
> bundle -v
Bundler version 2.1.4

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

IntelliJ - show where errors are

In my case, I unknowingly unchecked 'Error Stripe Mark' option (Idea 2018.2: Settings > Editor > Color Scheme > General and expand `Error and Warnings' & click 'Error').

Fix is to check 'Error Stripe Mark' option of 'Error' (as highlighted in the below image). Now you will see the error marks in scrollbar area.

enter image description here

Package doesn't exist error in intelliJ

I had the same problem and it was fixed for me by changing the "Maven home directory" in Settings from "Bundled" to my locally installed maven. Perhaps this triggered some kind of refresh somewhere since I had not changed this setting for months without any issue.

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

Saving images in Python at a very high quality

In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:

Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:

import seaborn as sb

image = sb.heatmap(matrix)   # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png")   # This saves it

This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.

Another way I like is this. I set the size of the next image as follows:

plt.subplots(figsize=(15,15))

And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

How to import XML file into MySQL database table using XML_LOAD(); function

Since ID is auto increment, you can also specify ID=NULL as,

LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

In order to not have the Cannot recover key exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.


Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy. Setting that to unlimited with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty() or via the java.security file. The java.security file could also be appended to by adding -Djava.security.properties=my_security.properties to the command to start the program as detailed here.


Since JDK 8u161 unlimited cryptography is enabled by default.

beyond top level package error in relative import

None of these solutions worked for me in 3.6, with a folder structure like:

package1/
    subpackage1/
        module1.py
package2/
    subpackage2/
        module2.py

My goal was to import from module1 into module2. What finally worked for me was, oddly enough:

import sys
sys.path.append(".")

Note the single dot as opposed to the two-dot solutions mentioned so far.


Edit: The following helped clarify this for me:

import os
print (os.getcwd())

In my case, the working directory was (unexpectedly) the root of the project.

Checking the form field values before submitting that page

use return before calling the function, while you click the submit button, two events(form posting as you used submit button and function call for onclick) will happen, to prevent form posting you have to return false, you have did it, also you have to specify the return i.e, to expect a value from the function,

this is a code:

input type="submit" name="continue" value="submit" onClick="**return** checkform();"

How to communicate between Docker containers via "hostname"

EDIT : It is not bleeding edge anymore : http://blog.docker.com/2016/02/docker-1-10/

Original Answer
I battled with it the whole night. If you're not afraid of bleeding edge, the latest version of Docker engine and Docker compose both implement libnetwork.

With the right config file (that need to be put in version 2), you will create services that will all see each other. And, bonus, you can scale them with docker-compose as well (you can scale any service you want that doesn't bind port on the host)

Here is an example file

version: "2"
services:
  router:
    build: services/router/
    ports:
      - "8080:8080"
  auth:
    build: services/auth/
  todo:
    build: services/todo/
  data:
    build: services/data/

And the reference for this new version of compose file: https://github.com/docker/compose/blob/1.6.0-rc1/docs/networking.md

$(document).ready shorthand

What about this?

(function($) { 
   $(function() {
     // more code using $ as alias to jQuery
     // will be fired when document is ready
   });
})(jQuery);

ERROR: Sonar server 'http://localhost:9000' can not be reached

For others who ran into this issue in a project that is not using a sonar-runners.property file, you may find (as I did) that you need to tweak your pom.xml file, adding a sonar.host.url property.

For example, I needed to add the following line under the 'properties' element:

<sonar.host.url>https://sonar.my-internal-company-domain.net</sonar.host.url>

Where the url points to our internal sonar deployment.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

In Addition to Ben's Answer, You can try Below Queries as per your need

USE {database-name};  
GO  
-- Truncate the log by changing the database recovery model to SIMPLE.  
ALTER DATABASE {database-name}
SET RECOVERY SIMPLE;  
GO  
-- Shrink the truncated log file to 1 MB.  
DBCC SHRINKFILE ({database-file-name}, 1);  
GO  
-- Reset the database recovery model.  
ALTER DATABASE {database-name}
SET RECOVERY FULL;  
GO 

Update Credit @cema-sp

To find database file names use below query

select * from sys.database_files;

Drop all data in a pandas dataframe

My favorite:

df = df.iloc[0:0]

But be aware df.index.max() will be nan. To add items I use:

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data

jquery change class name

I think you're looking for this:

$('#td_id').removeClass('change_me').addClass('new_class');

How to replace a whole line with sed?

sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file

Understanding the Linux oom-killer's logs

Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.

Short answer to your question: Yes there are other stuff included than whats in the list.

What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.

From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.

Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.

Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.

Add ... if string is too long PHP

$string = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";

if(strlen($string) >= 50)
{
    echo substr($string, 50); //prints everything after 50th character
    echo substr($string, 0, 50); //prints everything before 50th character
}

FlutterError: Unable to load asset

inside pubspec.yaml, DON'T USE TAB!

flutter:
<space><space>assets:
<space><space><space><space>assets/

example:

flutter:
  assets:
    assets/

Capture key press (or keydown) event on DIV element

Here example on plain JS:

_x000D_
_x000D_
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
  console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
  outline: none;_x000D_
}
_x000D_
<div _x000D_
  id="myDiv"_x000D_
  tabindex="0"_x000D_
>_x000D_
  Press me and start typing_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get ID of the last updated row in MySQL?

No need for so long Mysql code. In PHP, query should look something like this:

$updateQuery = mysql_query("UPDATE table_name SET row='value' WHERE id='$id'") or die ('Error');
$lastUpdatedId = mysql_insert_id();

Passing parameters to addTarget:action:forControlEvents

I subclassed UIButton in CustomButton and I add a property where I store my data. So I call method: (CustomButton*) sender and in the method I only read my data sender.myproperty.

Example CustomButton:

@interface CustomButton : UIButton
@property(nonatomic, retain) NSString *textShare;
@end

Method action:

+ (void) share: (CustomButton*) sender
{
    NSString *text = sender.textShare;
    //your work…
}

Assign action

    CustomButton *btn = [[CustomButton alloc] initWithFrame: CGRectMake(margin, margin, 60, 60)];
    // other setup…

    btnWa.textShare = @"my text";
    [btn addTarget: self action: @selector(shareWhatsapp:)  forControlEvents: UIControlEventTouchUpInside];

Splitting a string at every n-th character

Java does not provide very full-featured splitting utilities, so the Guava libraries do:

Iterable<String> pieces = Splitter.fixedLength(3).split(string);

Check out the Javadoc for Splitter; it's very powerful.

How do I dynamically change the content in an iframe using jquery?

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

How to set a cookie to expire in 1 hour in Javascript?

Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

How do I get the App version and build number using Swift?

Swift 4

func getAppVersion() -> String {
    return "\(Bundle.main.infoDictionary!["CFBundleShortVersionString"] ?? "")"
}

Bundle.main.infoDictionary!["CFBundleShortVersionString"]

Swift old syntax

let appVer: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

I know that PHPMailer library can handle that kind of SMTP transactions.

Also, a fake sendmail with sendmail-SSL library should do the job.

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

What's the difference between jquery.js and jquery.min.js?

Jquery.min.js is nothing else but compressed version of jquery.js. You can use it the same way as jquery.js, but it's smaller, so in production you should use minified version and when you're debugging you can use normal jquery.js version. If you want to compress your own javascript file you can these compressors:

Or just read topis on StackOverflow about js compression :) :

Creating a simple configuration file and parser in C++

In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline(). While by default it will read up to the next '\n' (which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like = in your example.

For simplicity, the following presumes that the = are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.

const char config[] = "url=http://example.com\n"
                      "file=main.exe\n"
                      "true=0";

std::istringstream is_file(config);

std::string line;
while( std::getline(is_file, line) )
{
  std::istringstream is_line(line);
  std::string key;
  if( std::getline(is_line, key, '=') )
  {
    std::string value;
    if( std::getline(is_line, value) ) 
      store_line(key, value);
  }
}

(Adding error handling is left as an exercise to the reader.)

PHP: Possible to automatically get all POSTed data?

You can use $_REQUEST as well as $_POST to reach everything such as Post, Get and Cookie data.

Argument of type 'X' is not assignable to parameter of type 'X'

This problem basically comes when your compiler gets failed to understand the difference between cast operator of the type string to Number.

you can use the Number object and pass your value to get the appropriate results for it by using Number(<<<<...Variable_Name......>>>>)

Grep only the first match and stop

My grep-a-like program ack has a -1 option that stops at the first match found anywhere. It supports the -m 1 that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I'm not C++ developer so I will not provide code. But I can provide simple hsv2rgb algorithm (rgb2hsv here) which I currently discover - I update wiki with description: HSV and HLS. Main improvement is that I carefully observe r,g,b as hue functions and introduce simpler shape function to describe them (without loosing accuracy). The Algorithm - on input we have: h (0-255), s (0-255), v(0-255)

r = 255*f(5),   g = 255*f(3),   b = 255*f(1)

We use function f described as follows

f(n) = v/255 - (v/255)*(s/255)*max(min(k,4-k,1),0)

where (mod can return fraction part; k is floating point number)

k = (n+h*360/(255*60)) mod 6;

Here are snippets/PoV in SO in JS: HSV and HSL

Check with jquery if div has overflowing elements

This is the jQuery solution that worked for me. offsetWidth etc. didn't work.

function is_overflowing(element, extra_width) {
    return element.position().left + element.width() + extra_width > element.parent().width();
}

If this doesn't work, ensure that elements' parent has the desired width (personally, I had to use parent().parent()). position is relative to the parent. I've also included extra_width because my elements ("tags") contain images which take small time to load, but during the function call they have zero width, spoiling the calculation. To get around that, I use the following calling code:

var extra_width = 0;
$(".tag:visible").each(function() {
    if (!$(this).find("img:visible").width()) {
        // tag image might not be visible at this point,
        // so we add its future width to the overflow calculation
        // the goal is to hide tags that do not fit one line
        extra_width += 28;
    }
    if (is_overflowing($(this), extra_width)) {
        $(this).hide();
    }
});

Hope this helps.

How do I parse JSON in Android?

  1. Writing JSON Parser Class

    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {}
    
        public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
  2. Parsing JSON Data
    Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.

    2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.

    // url to make request
    private static String url = "http://api.9android.net/contacts";
    
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    
    // contacts JSONArray
    JSONArray contacts = null;
    

    2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    
        try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);
    
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);
    
            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);
    
            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);
    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

How to get element value in jQuery

<ul id="unOrderedList">
<li value="2">Whatever</li>
.
.



 $('#unOrderedList li').click(function(){
      var value = $(this).attr('value');
     alert(value); 
  });

Your looking for the attribute "value" inside the "li" tag

How to render a DateTime in a specific format in ASP.NET MVC 3?

If all your DateTime types are rendered the same way you can use a custom DateTime display template.

In your Views folder create a folder named "DisplayTemplates" either under your controller specific views folder, or under "Shared" folder (these work similar to partials).

Inside create a file named DateTime.cshtml that takes DateTime as the @model and code how you want to render your date:

@model System.DateTime
@Model.ToLongDateString()

Now you can just use this in your views and it should work:

@Html.DisplayFor(mod => mod.MyDateTime)

As long as you follow the convention of adding it to the "DisplayTemplates" folder and naming the file to match the type your are displaying, MVC will automatically use that to display your values. This also works for editing scenarios using "EditorTemplates".

Here's some more information on templates.

pass array to method Java

You do this:

private void PassArray() {
    String[] arrayw = new String[4]; //populate array
    PrintA(arrayw);
}

private void PrintA(String[] a) {
    //do whatever with array here
}

Just pass it as any other variable.
In Java, arrays are passed by reference.

Change the Textbox height?

All you have to do is enable the multiline in the properties window, put the size you want in that same window and then in your .cs after the InitializeComponent put txtexample.Multiline = false; and so the multiline is not enabled but the size of the txt is as you put it.

InitializeComponent();
txtEmail.Multiline = false;
txtPassword.Multiline = false;

enter image description here

enter image description here

enter image description here

Equivalent of jQuery .hide() to set visibility: hidden

An even simpler way to do this is to use jQuery's toggleClass() method

CSS

.newClass{visibility: hidden}

HTML

<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>

JS

$(document).ready(function(){
    $(".trigger").click(function(){
        $(".hidden_element").toggleClass("newClass");
    });
});

Classes cannot be accessed from outside package

Note that the default when you make a class is not public as far as packages are considered. Make sure that you actually write public class [MyClass] { when defining your class. I've made this mistake more times than I care to admit.

select2 changing items dynamically

In my project I use following code:

$('#attribute').select2();
$('#attribute').bind('change', function(){
    var $options = $();
    for (var i in data) {
        $options = $options.add(
            $('<option>').attr('value', data[i].id).html(data[i].text)
        );
    }
    $('#value').html($options).trigger('change');
});

Try to comment out the select2 part. The rest of the code will still work.

Problems with a PHP shell script: "Could not open input file"

I know its stupid but in my case i was outside of my project folder i didn't have spark file.

Android custom Row Item for ListView

create resource layout file list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
<TextView
        android:id="@+id/header_text"
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:text="Header"
        />
<TextView
        android:id="@+id/item_text"
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:text="dynamic text"
        />
</LinearLayout>

and initialise adaptor like this

adapter = new ArrayAdapter<String>(this, R.layout.list_item,R.id.item_text,data_array);

How to do logging in React Native?

You can use remote js debugly option from your device or you can simply use react-native log-android and react-native log-ios for ios.

Detect WebBrowser complete page loading

The following should work.

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    //Check if page is fully loaded or not
    if (this.webBrowser1.ReadyState != WebBrowserReadyState.Complete)
        return;
    else
        //Action to be taken on page loading completion
}

Creating multiple log files of different content with log4j

Demo link: https://github.com/RazvanSebastian/spring_multiple_log_files_demo.git

My solution is based on XML configuration using spring-boot-starter-log4j. The example is a basic example using spring-boot-starter and the two Loggers writes into different log files.

How to test if a file is a directory in a batch script?

One issue with using %%~si\NUL method is that there is the chance that it guesses wrong. Its possible to have a filename shorten to the wrong file. I don't think %%~si resolves the 8.3 filename, but guesses it, but using string manipulation to shorten the filepath. I believe if you have similar file paths it may not work.

An alternative method:

dir /AD %F% 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir)

:IsFile
  echo %F% is a file
  goto done

:IsDir
  echo %F% is a directory
  goto done

:done

You can replace (goto IsFile)||(goto IsDir) with other batch commands:
(echo Is a File)||(echo is a Directory)

Why would you use Expression<Func<T>> rather than Func<T>?

There is a more philosophical explanation about it from Krzysztof Cwalina's book(Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries);

Rico Mariani

Edit for non-image version:

Most times you're going to want Func or Action if all that needs to happen is to run some code. You need Expression when the code needs to be analyzed, serialized, or optimized before it is run. Expression is for thinking about code, Func/Action is for running it.

Insert variable into Header Location PHP

You can add it like this

header('Location: http://linkhere.com/'.$url_endpoint);

Specify an SSH key for git push for a given domain

An alternative approach to the one offered above by Mark Longair is to use an alias that will run any git command, on any remote, with an alternative SSH key. The idea is basically to switch your SSH identity when running the git commands.

Advantages relative to the host alias approach in the other answer:

  • Will work with any git commands or aliases, even if you can't specify the remote explicitly.
  • Easier to work with many repositories because you only need to set it up once per client machine, not once per repository on each client machine.

I use a few small scripts and a git alias admin. That way I can do, for example:

git admin push 

To push to the default remote using the alternative ("admin") SSH key. Again, you could use any command (not just push) with this alias. You could even do git admin clone ... to clone a repository that you would only have access to using your "admin" key.

Step 1: Create the alternative SSH keys, optionally set a passphrase in case you're doing this on someone else's machine.

Step 2: Create a script called “ssh-as.sh” that runs stuff that uses SSH, but uses a given SSH key rather than the default:

#!/bin/bash
exec ssh ${SSH_KEYFILE+-i "$SSH_KEYFILE"} "$@"

Step 3: Create a script called “git-as.sh” that runs git commands using the given SSH key.

#!/bin/bash
SSH_KEYFILE=$1 GIT_SSH=${BASH_SOURCE%/*}/ssh-as.sh exec git "${@:2}"

Step 4: Add an alias (using something appropriate for “PATH_TO_SCRIPTS_DIR” below):

# Run git commands as the SSH identity provided by the keyfile ~/.ssh/admin
git config --global alias.admin \!"PATH_TO_SCRIPTS_DIR/git-as.sh ~/.ssh/admin"

More details at: http://noamlewis.wordpress.com/2013/01/24/git-admin-an-alias-for-running-git-commands-as-a-privileged-ssh-identity/

Is there a difference between /\s/g and /\s+/g?

+ means "one or more characters" and without the plus it means "one character." In your case both result in the same output.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Use this function which suits every situation.

CREATE FUNCTION dbo.fnNumPadLeft (@input INT, @pad tinyint)
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @NumStr VARCHAR(250)

    SET @NumStr = LTRIM(@input)

    IF(@pad > LEN(@NumStr))
        SET @NumStr = REPLICATE('0', @Pad - LEN(@NumStr)) + @NumStr;

    RETURN @NumStr;
END

Sample output

SELECT [dbo].[fnNumPadLeft] (2016,10) -- returns 0000002016
SELECT [dbo].[fnNumPadLeft] (2016,5) -- returns 02016
SELECT [dbo].[fnNumPadLeft] (2016,2) -- returns 2016
SELECT [dbo].[fnNumPadLeft] (2016,0) -- returns 2016 

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

SignalR Console app example

The Self-Host now uses Owin. Checkout http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host to setup the server. It's compatible with the client code above.

AngularJS - Passing data between pages

If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

Dealing with float precision in Javascript

> var x = 0.1
> var y = 0.2
> var cf = 10
> x * y
0.020000000000000004
> (x * cf) * (y * cf) / (cf * cf)
0.02

Quick solution:

var _cf = (function() {
  function _shift(x) {
    var parts = x.toString().split('.');
    return (parts.length < 2) ? 1 : Math.pow(10, parts[1].length);
  }
  return function() { 
    return Array.prototype.reduce.call(arguments, function (prev, next) { return prev === undefined || next === undefined ? undefined : Math.max(prev, _shift (next)); }, -Infinity);
  };
})();

Math.a = function () {
  var f = _cf.apply(null, arguments); if(f === undefined) return undefined;
  function cb(x, y, i, o) { return x + f * y; }
  return Array.prototype.reduce.call(arguments, cb, 0) / f;
};

Math.s = function (l,r) { var f = _cf(l,r); return (l * f - r * f) / f; };

Math.m = function () {
  var f = _cf.apply(null, arguments);
  function cb(x, y, i, o) { return (x*f) * (y*f) / (f * f); }
  return Array.prototype.reduce.call(arguments, cb, 1);
};

Math.d = function (l,r) { var f = _cf(l,r); return (l * f) / (r * f); };

> Math.m(0.1, 0.2)
0.02

You can check the full explanation here.

Converting Varchar Value to Integer/Decimal Value in SQL Server

Table structure...very basic:

create table tabla(ID int, Stuff varchar (50));

insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');

Query:

SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla

Or, try this:

SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla

Working on SQLServer 2008

How can I print variable and string on same line in Python?

use String formatting

print("If there was a birth every 7 seconds, there would be: {} births".format(births))
 # Will replace "{}" with births

if you doing a toy project use:

print('If there was a birth every 7 seconds, there would be:' births'births) 

or

print('If there was a birth every 7 seconds, there would be: %d births' %(births))
# Will replace %d with births

The definitive guide to form-based website authentication

When hashing, don't use fast hash algorithms such as MD5 (many hardware implementations exist). Use something like SHA-512. For passwords, slower hashes are better.

The faster you can create hashes, the faster any brute force checker can work. Slower hashes will therefore slow down brute forcing. A slow hash algorithm will make brute forcing impractical for longer passwords (8 digits +)

Pattern matching using a wildcard

If you really do want to use wildcards to identify specific variables, then you can use a combination of ls() and grep() as follows:

l = ls()
vars.with.result <- l[grep("result", l)]

How to run a single test with Mocha?

Consolidate all your tests in one test.js file & your package json add scripts as:

  "scripts": {
  "api:test": "node_modules/.bin/mocha --timeout 10000 --recursive api_test/"
},

Type command on your test directory:

npm run api:test

Unzip a file with php

Just use this:

  $master = $_GET["master"];
  system('unzip' $master.'.zip'); 

in your code $master is passed as a string, system will be looking for a file called $master.zip

  $master = $_GET["master"];
  system('unzip $master.zip'); `enter code here`

How to disable all div content

Another way, in jQuery, would be to get the inner height, inner width and positioning of the containing DIV, and simply overlay another DIV, transparent, over the top the same size. This will work on all elements inside that container, instead of only the inputs.

Remember though, with JS disabled, you'll still be able to use the DIVs inputs/content. The same goes with the above answers too.

Java - Convert int to Byte Array of 4 Bytes?

public static  byte[] my_int_to_bb_le(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_le(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

public static  byte[] my_int_to_bb_be(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_be(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}

Best data type to store money values in MySQL

Storing money as BIGINT multiplied by 100 or more with the reason to use less storage space makes no sense in all "normal" situations.

Notification Icon with the new Firebase Cloud Messaging system

There is also one ugly but working way. Decompile FirebaseMessagingService.class and modify it's behavior. Then just put the class to the right package in yout app and dex use it instead of the class in the messaging lib itself. It is quite easy and working.

There is method:

private void zzo(Intent intent) {
    Bundle bundle = intent.getExtras();
    bundle.remove("android.support.content.wakelockid");
    if (zza.zzac(bundle)) {  // true if msg is notification sent from FirebaseConsole
        if (!zza.zzdc((Context)this)) { // true if app is on foreground
            zza.zzer((Context)this).zzas(bundle); // create notification
            return;
        }
        // parse notification data to allow use it in onMessageReceived whe app is on foreground
        if (FirebaseMessagingService.zzav(bundle)) {
            zzb.zzo((Context)this, intent);
        }
    }
    this.onMessageReceived(new RemoteMessage(bundle));
}

This code is from version 9.4.0, method will have different names in different version because of obfuscation.

Can't use WAMP , port 80 is used by IIS 7.5

goto services and stop the "World Wide Web Publishing Service" after restart the wamp server. after that start the "World Wide Web Publishing Service"

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How to add a browser tab icon (favicon) for a website?

I have created an online Favicon Generator with which you can create favicons from Font Awesome Icons. You can preview the created favicon live in the browser.

enter image description here

If you want additional features please feel free to submit an issue or a pull request here :).

jQuery UI 1.10: dialog and zIndex option

To sandwich an my element between the modal screen and a dialog, I need to lift my element above the modal-screen, and then lift the dialog above my element.

I had a small success by doing the following after creating the dialog on element $dlg.

$dlg.closest('.ui-dialog').css('zIndex',adjustment);

Since each dialog has a different starting z-index (they incrementally get larger) I make adjustment a string with a boost value, like this:

const adjustment = "+=99";

However, jQuery just keeps increasing the zIndex value on the modal screen, so by the second dialog, the sandwich no longer worked. I gave up on ui-dialog "modal", made it "false", and just created my own modal. It imitates jQueryUI exactly. Here it is:

CoverAll = {};
CoverAll.modalDiv = null;

CoverAll.modalCloak = function(zIndex) {
  var div = CoverAll.modalDiv;
  if(!CoverAll.modalDiv) {
    div = CoverAll.modalDiv = document.createElement('div');
    div.style.background = '#aaaaaa';
    div.style.opacity    = '0.3';
    div.style.position   = 'fixed';
    div.style.top        = '0';
    div.style.left       = '0';
    div.style.width      = '100%';
    div.style.height     = '100%';
  }
  if(!div.parentElement) {
    document.body.appendChild(div);
  }
  if(zIndex == null)
    zIndex = 100;
  div.style.zIndex  = zIndex;
  return div;
}

CoverAll.modalUncloak = function() {
  var div = CoverAll.modalDiv;
  if(div && div.parentElement) {
    document.body.removeChild(div);
  }
  return div;
}

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

You should be able to set the className property of the element. You could do a += to append it.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

No output to console from a WPF application?

I use Console.WriteLine() for use in the Output window...

Add UIPickerView & a Button in Action sheet - How?

Since iOS 8, you can't, it doesn't work because Apple changed internal implementation of UIActionSheet. Please refer to Apple Documentation:

Subclassing Notes

UIActionSheet is not designed to be subclassed, nor should you add views to its hierarchy. If you need to present a sheet with more customization than provided by the UIActionSheet API, you can create your own and present it modally with presentViewController:animated:completion:.

Multiple REPLACE function in Oracle

The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE statements, and I don't think there is a better way.

If you are going to make heavy use of this, you could consider writing your own function:

CREATE TYPE t_text IS TABLE OF VARCHAR2(256);

CREATE FUNCTION multiple_replace(
  in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
  RETURN VARCHAR2
AS
  v_result VARCHAR2(32767);
BEGIN
  IF( in_old.COUNT <> in_new.COUNT ) THEN
    RETURN in_text;
  END IF;
  v_result := in_text;
  FOR i IN 1 .. in_old.COUNT LOOP
    v_result := REPLACE( v_result, in_old(i), in_new(i) );
  END LOOP;
  RETURN v_result;
END;

and then use it like this:

SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
                         NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
                         NEW t_text( 'text', 'tokens', 'replace' )
                       )
FROM dual

This is text with some tokens to replace

If all of your tokens have the same format ('#VAL' || i || '#'), you could omit parameter in_old and use your loop-counter instead.

PHP-FPM doesn't write to error log

In my case php-fpm outputs 500 error without any logging because of missing php-mysql module. I moved joomla installation to another server and forgot about it. So apt-get install php-mysql and service restart solved it.

I started with trying to fix broken logging without success. Finally with strace i found fail message after db-related system calls. Though my case is not directly related to op's question, I hope it could be useful.

How to find serial number of Android device?

As Dave Webb mentions, the Android Developer Blog has an article that covers this.

I spoke with someone at Google to get some additional clarification on a few items. Here's what I discovered that's NOT mentioned in the aforementioned blog post:

  • ANDROID_ID is the preferred solution. ANDROID_ID is perfectly reliable on versions of Android <=2.1 or >=2.3. Only 2.2 has the problems mentioned in the post.
  • Several devices by several manufacturers are affected by the ANDROID_ID bug in 2.2.
  • As far as I've been able to determine, all affected devices have the same ANDROID_ID, which is 9774d56d682e549c. Which is also the same device id reported by the emulator, btw.
  • Google believes that OEMs have patched the issue for many or most of their devices, but I was able to verify that as of the beginning of April 2011, at least, it's still quite easy to find devices that have the broken ANDROID_ID.

Based on Google's recommendations, I implemented a class that will generate a unique UUID for each device, using ANDROID_ID as the seed where appropriate, falling back on TelephonyManager.getDeviceId() as necessary, and if that fails, resorting to a randomly generated unique UUID that is persisted across app restarts (but not app re-installations).

import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class DeviceUuidFactory {

    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";
    protected static volatile UUID uuid;

    public DeviceUuidFactory(Context context) {
        if (uuid == null) {
            synchronized (DeviceUuidFactory.class) {
                if (uuid == null) {
                    final SharedPreferences prefs = context
                            .getSharedPreferences(PREFS_FILE, 0);
                    final String id = prefs.getString(PREFS_DEVICE_ID, null);
                    if (id != null) {
                        // Use the ids previously computed and stored in the
                        // prefs file
                        uuid = UUID.fromString(id);
                    } else {
                        final String androidId = Secure.getString(
                            context.getContentResolver(), Secure.ANDROID_ID);
                        // Use the Android ID unless it's broken, in which case
                        // fallback on deviceId,
                        // unless it's not available, then fallback on a random
                        // number which we store to a prefs file
                        try {
                            if (!"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId
                                        .getBytes("utf8"));
                            } else {
                                final String deviceId = ((TelephonyManager) 
                                        context.getSystemService(
                                            Context.TELEPHONY_SERVICE))
                                            .getDeviceId();
                                uuid = deviceId != null ? UUID
                                        .nameUUIDFromBytes(deviceId
                                                .getBytes("utf8")) : UUID
                                        .randomUUID();
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                        // Write the value out to the prefs file
                        prefs.edit()
                                .putString(PREFS_DEVICE_ID, uuid.toString())
                                .commit();
                    }
                }
            }
        }
    }

    /**
     * Returns a unique UUID for the current android device. As with all UUIDs,
     * this unique ID is "very highly likely" to be unique across all Android
     * devices. Much more so than ANDROID_ID is.
     * 
     * The UUID is generated by using ANDROID_ID as the base key if appropriate,
     * falling back on TelephonyManager.getDeviceID() if ANDROID_ID is known to
     * be incorrect, and finally falling back on a random UUID that's persisted
     * to SharedPreferences if getDeviceID() does not return a usable value.
     * 
     * In some rare circumstances, this ID may change. In particular, if the
     * device is factory reset a new device ID may be generated. In addition, if
     * a user upgrades their phone from certain buggy implementations of Android
     * 2.2 to a newer, non-buggy version of Android, the device ID may change.
     * Or, if a user uninstalls your app on a device that has neither a proper
     * Android ID nor a Device ID, this ID may change on reinstallation.
     * 
     * Note that if the code falls back on using TelephonyManager.getDeviceId(),
     * the resulting ID will NOT change after a factory reset. Something to be
     * aware of.
     * 
     * Works around a bug in Android 2.2 for many devices when using ANDROID_ID
     * directly.
     * 
     * @see http://code.google.com/p/android/issues/detail?id=10603
     * 
     * @return a UUID that may be used to uniquely identify your device for most
     *         purposes.
     */
    public UUID getDeviceUuid() {
        return uuid;
    }
}

Nested ng-repeat

Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:

<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>

How to set input type date's default value to today?

this works for me:

document.getElementById('datePicker').valueAsDate = new Date();

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

JQuery addclass to selected div, remove class if another div is selected

It's all about the selector. You can change your code to be something like this:

<div class="formbuilder">
    <div class="active">Heading</div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>

Then use this javascript:

$(document).ready(function () {
    $('.formbuilder div').on('click', function () {
        $('.formbuilder div').removeClass('active');
        $(this).addClass('active');
    });
});

The example in a working jsfiddle

See this api about the selector I used: http://api.jquery.com/descendant-selector/

How to track down access violation "at address 00000000"

The accepted answer does not tell the entire story.

Yes, whenever you see zeros, a NULL pointer is involved. That is because NULL is by definition zero. So calling zero NULL may not be saying much.

What is interesting about the message you get is the fact that NULL is mentioned twice. In fact, the message you report looks a little bit like the messages Windows-brand operating systems show the user.

The message says the address NULL tried to read NULL. So what does that mean? Specifically, how does an address read itself?

We typically think of the instructions at an address reading and writing from memory at certain addresses. Knowing that allows us to parse the error message. The message is trying to articulate that the instruction at address NULL tried to read NULL.

Of course, there is no instruction at address NULL, that is why we think of NULL as special in our code. But every instruction can be thought of as commencing with the attempt to read itself. If the CPUs EIP register is at address NULL, then the CPU will attempt to read the opcode for an instruction from address 0x00000000 (NULL). This attempt to read NULL will fail, and generate the message you have received.

In the debugger, notice that EIP equals 0x00000000 when you receive this message. This confirms the description I have given you.

The question then becomes, "why does my program attempt to execute the NULL address." There are three possibilities which spring to mind:

  • You have attempt to make a function call via a function pointer which you have declared, assigned to NULL, never initialized otherwise, and are dereferencing.
  • Similarly, you may be calling an "abstract" C++ method which has a NULL entry in the object's vtable. These are created in your code with the syntax virtual function_name()=0.
  • In your code, a stack buffer has been overflowed while writing zeros. The zeros have been written beyond the end of the stack buffer, over the preserved return address. When the function later executes its ret instruction, the value 0x00000000 (NULL) is loaded from the overwritten memory spot. This type of error, stack overflow, is the eponym of our forum.

Since you mention that you are calling a third-party library, I will point out that it may be a situation of the library expecting you to provide a non-NULL function pointer as input to some API. These are sometimes known as "call back" functions.

You will have to use the debugger to narrow down the cause of your problem further, but the above possiblities should help you solve the riddle.

How to add New Column with Value to the Existing DataTable?

Add the column and update all rows in the DataTable, for example:

DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
    DataRow row = tbl.NewRow();
    row["ID"] = i;
    row["Name"] = i + ". row";
    tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
    row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;

Force IE compatibility mode off using tags

The meta tag solution wasn't working for us but setting it in the response header did:

header('X-UA-Compatible: IE=edge,chrome=1');

Difference between try-catch and throw in java

All these keywords try, catch and throw are related to the exception handling concept in java. An exception is an event that occurs during the execution of programs. Exception disrupts the normal flow of an application. Exception handling is a mechanism used to handle the exception so that the normal flow of application can be maintained. Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.

For more detail visit Java tutorial for beginners.

JDK was not found on the computer for NetBeans 6.5

I was facing the same problem, not it works fine.

  1. just open cmd

  2. cd to the directory where your netbeans setup file is located.

  3. in cmd, write the name of the entire setup file and write --javahome "address of jdk"

  4. hit enter, it will surely solve your problem

for example, if the setup file is: netbeans8.02.exe

and path of JDK is C:/program files/java/jdk9.01

then run the command,

netbeans8.02.exe --javahome "C:/program files/java/jdk9.01"

and hit enter! :-)

char initial value in Java

Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.

If you want the char equivalent of 0, it's just Unicode 0, which can be written as

char c = '\0';

That's also the default value for an instance (or static) variable of type char.

Total memory used by Python process?

Even easier to use than /proc/self/status: /proc/self/statm. It's just a space delimited list of several statistics. I haven't been able to tell if both files are always present.

/proc/[pid]/statm

Provides information about memory usage, measured in pages. The columns are:

  • size (1) total program size (same as VmSize in /proc/[pid]/status)
  • resident (2) resident set size (same as VmRSS in /proc/[pid]/status)
  • shared (3) number of resident shared pages (i.e., backed by a file) (same as RssFile+RssShmem in /proc/[pid]/status)
  • text (4) text (code)
  • lib (5) library (unused since Linux 2.6; always 0)
  • data (6) data + stack
  • dt (7) dirty pages (unused since Linux 2.6; always 0)

Here's a simple example:

from pathlib import Path
from resource import getpagesize

PAGESIZE = getpagesize()
PATH = Path('/proc/self/statm')


def get_resident_set_size() -> int:
    """Return the current resident set size in bytes."""
    # statm columns are: size resident shared text lib data dt
    statm = PATH.read_text()
    fields = statm.split()
    return int(fields[1]) * PAGESIZE


data = []
start_memory = get_resident_set_size()
for _ in range(10):
    data.append('X' * 100000)
    print(get_resident_set_size() - start_memory)

That produces a list that looks something like this:

0
0
368640
368640
368640
638976
638976
909312
909312
909312

You can see that it jumps by about 300,000 bytes after roughly 3 allocations of 100,000 bytes.

.mp4 file not playing in chrome

I was actually running into some strange errors with mp4's a while ago. What fixed it for me was re-encoding the video using known supported codecs (H.264 & MP3).

I actually used the VLC player to do so and it worked fine afterward. I converted using the mentioned codecs H.264/MP3. That solved it for me.

Maybe the problem is not in the format but in the JavaScript implementation of the play/ pause methods. May I suggest visiting the following link where Google developer explains it in a good way?

Additionally, you could choose to use the newer webp format, which Chrome supports out of the box, but be careful with other browsers. Check the support for it before implementation. Here's a link that describes the mentioned format.

On that note: I've created a small script that easily converts all standard formats to webp. You can easily configure it to fit your needs. Here's the Github repo of the same projects.

Jquery Chosen plugin - dynamically populate list by Ajax

var object = $("#lstValue_chosen").find('.chosen-choices').find('input[type="text"]')[0];
var _KeyCode = event.which || event.keyCode;
if (_KeyCode != 37 && _KeyCode != 38 && _KeyCode != 39 && _KeyCode != 40) { 

    if (object.value != "") {
        var SelectedObjvalue = object.value;
        if (SelectedObjvalue.length > 0) {
            var obj = { value: SelectedObjvalue };
            var SelectedListValue = $('#lstValue').val();
            var Uniqueid = $('#uniqueid').val();

            $.ajax({
                url: '/Admin/GetUserListBox?SelectedValue=' + SelectedListValue + '&Uniqueid=' + Uniqueid,
                data: { value: SelectedObjvalue },
                type: 'GET',
                async: false,
                success: function (response) {
                    if (response.length > 0) {
                        $('#lstValue').html('');
                        var options = '';                            
                        $.each(response, function (i, obj) {
                            options += '<option value="' + obj.Value + '">' + obj.Text + '</option>';
                        });
                        $('#lstValue').append(options);
                        $('#lstValue').val(SelectedListValue);
                        $('#lstValue').trigger("chosen:updated");
                        object.value = SelectedObjvalue;
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    //jAlert("Error. Please, check the data.", " Deactivate User");
                    alert(error.StatusText);
                }
            });
        }
    }
}

How to keep two folders automatically synchronized?

You can use inotifywait (with the modify,create,delete,move flags enabled) and rsync.

while inotifywait -r -e modify,create,delete,move /directory; do
    rsync -avz /directory /target
done

If you don't have inotifywait on your system, run sudo apt-get install inotify-tools

How to use onBlur event on Angular2?

/*for reich text editor */
  public options: Object = {
    charCounterCount: true,
    height: 300,
    inlineMode: false,
    toolbarFixed: false,
    fontFamilySelection: true,
    fontSizeSelection: true,
    paragraphFormatSelection: true,

    events: {
      'froalaEditor.blur': (e, editor) => { this.handleContentChange(editor.html.get()); }}

phpmailer error "Could not instantiate mail function"

You need to make sure that your from address is a valid email account setup on that server.

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

Replace Div with another Div

HTML

<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>

JavaScript

jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));

How to iterate for loop in reverse order in swift?

Xcode 6 beta 4 added two functions to iterate on ranges with a step other than one: stride(from: to: by:), which is used with exclusive ranges and stride(from: through: by:), which is used with inclusive ranges.

To iterate on a range in reverse order, they can be used as below:

for index in stride(from: 5, to: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2

for index in stride(from: 5, through: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2, 1

Note that neither of those is a Range member function. They are global functions that return either a StrideTo or a StrideThrough struct, which are defined differently from the Range struct.

A previous version of this answer used the by() member function of the Range struct, which was removed in beta 4. If you want to see how that worked, check the edit history.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

stdcall and cdecl

Those things are Compiler- and Platform-specific. Neither the C nor the C++ standard say anything about calling conventions except for extern "C" in C++.

how does a caller know if it should free up the stack ?

The caller knows the calling convention of the function and handles the call accordingly.

At the call site, does the caller know if the function being called is a cdecl or a stdcall function ?

Yes.

How does it work ?

It is part of the function declaration.

How does the caller know if it should free up the stack or not ?

The caller knows the calling conventions and can act accordingly.

Or is it the linkers responsibility ?

No, the calling convention is part of a function's declaration so the compiler knows everything it needs to know.

If a function which is declared as stdcall calls a function(which has a calling convention as cdecl), or the other way round, would this be inappropriate ?

No. Why should it?

In general, can we say that which call will be faster - cdecl or stdcall ?

I don't know. Test it.

Get textarea text with javascript or Jquery

Get textarea text with JavaScript:

<!DOCTYPE html>
<body>
<form id="form1">
    <div>
        <textarea id="area1" rows="5">Yes</textarea>
        <input type="button" value="get txt" onclick="go()" />
        <br />
        <p id="as">Now what</p>
    </div>
</form>
</body>

function go() {
    var c1 = document.getElementById('area1').value;
    var d1 = document.getElementById('as');
    d1.innerHTML = c1;
}

http://jsfiddle.net/PUpeJ/3/

Converting an integer to binary in C

You can convert decimal to bin, hexa to decimal, hexa to bin, vice-versa etc by following this example. CONVERTING DECIMAL TO BIN

int convert_to_bin(int number){
    int binary = 0, counter = 0;
    while(number > 0){
        int remainder = number % 2;
        number /= 2;
        binary += pow(10, counter) * remainder;
        counter++;
    }   
}

Then you can print binary equivalent like this:

printf("08%d", convert_to_bin(13)); //shows leading zeros

If file exists then delete the file

IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in  Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat

Detect if PHP session exists

If you are on php 5.4+, it is cleaner to use session_status():

if (session_status() == PHP_SESSION_ACTIVE) {
  echo 'Session is active';
}
  • PHP_SESSION_DISABLED if sessions are disabled.
  • PHP_SESSION_NONE if sessions are enabled, but none exists.
  • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

How do I iterate and modify Java Sets?

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.

Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
    temp.add(i+1);
s.clear();
s.addAll(temp);

What does enctype='multipart/form-data' mean?

When you make a POST request, you have to encode the data that forms the body of the request in some way.

HTML forms provide three methods of encoding.

  • application/x-www-form-urlencoded (the default)
  • multipart/form-data
  • text/plain

Work was being done on adding application/json, but that has been abandoned.

(Other encodings are possible with HTTP requests generated using other means than an HTML form submission. JSON is a common format for use with web services and some still use SOAP.)

The specifics of the formats don't matter to most developers. The important points are:

  • Never use text/plain.

When you are writing client-side code:

  • use multipart/form-data when your form includes any <input type="file"> elements
  • otherwise you can use multipart/form-data or application/x-www-form-urlencoded but application/x-www-form-urlencoded will be more efficient

When you are writing server-side code:

  • Use a prewritten form handling library

Most (such as Perl's CGI->param or the one exposed by PHP's $_POST superglobal) will take care of the differences for you. Don't bother trying to parse the raw input received by the server.

Sometimes you will find a library that can't handle both formats. Node.js's most popular library for handling form data is body-parser which cannot handle multipart requests (but has documentation which recommends some alternatives which can).


If you are writing (or debugging) a library for parsing or generating the raw data, then you need to start worrying about the format. You might also want to know about it for interest's sake.

application/x-www-form-urlencoded is more or less the same as a query string on the end of the URL.

multipart/form-data is significantly more complicated but it allows entire files to be included in the data. An example of the result can be found in the HTML 4 specification.

text/plain is introduced by HTML 5 and is useful only for debugging — from the spec: They are not reliably interpretable by computer — and I'd argue that the others combined with tools (like the Network Panel in the developer tools of most browsers) are better for that).

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

Blocking device rotation on mobile web pages

_x000D_
_x000D_
#rotate-device {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    position: fixed;_x000D_
    z-index: 9999;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    background-color: #000;_x000D_
    background-image: url(/path to img/rotate.png);_x000D_
    background-size: 100px 100px;_x000D_
    background-position: center;_x000D_
    background-repeat: no-repeat;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
@media only screen and (max-device-width: 667px) and (min-device-width: 320px) and (orientation: landscape){_x000D_
 #rotate-device {_x000D_
  display: block;_x000D_
 }_x000D_
}
_x000D_
<div id="rotate-device"></div>
_x000D_
_x000D_
_x000D_

Enter key in textarea

Simply add this tad to your textarea.

onkeydown="if(event.keyCode == 13) return false;"

Multiple variables in a 'with' statement?

I think you want to do this instead:

from __future__ import with_statement

with open("out.txt","wt") as file_out:
    with open("in.txt") as file_in:
        for line in file_in:
            file_out.write(line)

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Here, the pi member of the original and copied X object will both point to the same int.


Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.


The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

Filtering collections in C#

Here is a code block / example of some list filtering using three different methods that I put together to show Lambdas and LINQ based list filtering.

#region List Filtering

static void Main(string[] args)
{
    ListFiltering();
    Console.ReadLine();
}

private static void ListFiltering()
{
    var PersonList = new List<Person>();

    PersonList.Add(new Person() { Age = 23, Name = "Jon", Gender = "M" }); //Non-Constructor Object Property Initialization
    PersonList.Add(new Person() { Age = 24, Name = "Jack", Gender = "M" });
    PersonList.Add(new Person() { Age = 29, Name = "Billy", Gender = "M" });

    PersonList.Add(new Person() { Age = 33, Name = "Bob", Gender = "M" });
    PersonList.Add(new Person() { Age = 45, Name = "Frank", Gender = "M" });

    PersonList.Add(new Person() { Age = 24, Name = "Anna", Gender = "F" });
    PersonList.Add(new Person() { Age = 29, Name = "Sue", Gender = "F" });
    PersonList.Add(new Person() { Age = 35, Name = "Sally", Gender = "F" });
    PersonList.Add(new Person() { Age = 36, Name = "Jane", Gender = "F" });
    PersonList.Add(new Person() { Age = 42, Name = "Jill", Gender = "F" });

    //Logic: Show me all males that are less than 30 years old.

    Console.WriteLine("");
    //Iterative Method
    Console.WriteLine("List Filter Normal Way:");
    foreach (var p in PersonList)
        if (p.Gender == "M" && p.Age < 30)
            Console.WriteLine(p.Name + " is " + p.Age);

    Console.WriteLine("");
    //Lambda Filter Method
    Console.WriteLine("List Filter Lambda Way");
    foreach (var p in PersonList.Where(p => (p.Gender == "M" && p.Age < 30))) //.Where is an extension method
        Console.WriteLine(p.Name + " is " + p.Age);

    Console.WriteLine("");
    //LINQ Query Method
    Console.WriteLine("List Filter LINQ Way:");
    foreach (var v in from p in PersonList
                      where p.Gender == "M" && p.Age < 30
                      select new { p.Name, p.Age })
        Console.WriteLine(v.Name + " is " + v.Age);
}

private class Person
{
    public Person() { }
    public int Age { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
}

#endregion

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

I faced the same issue in my scenario as follow:

I created textbook table first with

create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );

Then chapter table:

create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40), constraint pk_chapter primary key(txtbk_isbn,chapter_title), constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));

Then topic table:

create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));

Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:

create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20), primary key (txtbk_isbn, chapter_title, topic_id), foreign key (txtbk_isbn) references textbook(txtbk_isbn), foreign key (chapter_title) references chapter(chapter_title), foreign key (topic_id) references topic (topic_id));

The solution was to refer to composite foreign key as below:

create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20), primary key (txtbk_isbn, chapter_title, topic_id), foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title), foreign key (topic_id) references topic (topic_id));

Thanks to APC post in which he mentioned in his post a statement that:

Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED

How to pass multiple parameters from ajax to mvc controller?

You can do it by not initializing url and writing it at hardcode like this

//var url = '@Url.Action("ActionName", "Controller");

$.post("/Controller/ActionName?para1=" + data + "&para2=" + data2, function (result) {
        $("#" + data).html(result);
        ............. Your code
    });

While your controller side code must be like this below:

public ActionResult ActionName(string para1, string para2)
{
   Your Code .......
}

this was simple way. now we can do pass multiple data by json also like this:

var val1= $('#btn1').val();  
var val2= $('#btn2').val(); 
$.ajax({
                    type: "GET",
                    url: '@Url.Action("Actionre", "Contr")',
                    contentType: "application/json; charset=utf-8",
                    data: { 'para1': val1, 'para2': val2 },
                    dataType: "json",
                    success: function (cities) {
                        ur code.....
                    }
                });

While your controller side code will be same:

public ActionResult ActionName(string para1, string para2)
{
   Your Code .......
}

How to get share counts using graph API

The facebook like button does two things that the API does not do. This might create confusion when you compare the two.

  1. If the URL you use in your like button has a redirect the button will actually show the count of the redirect URL versus the count of the URL you are using.

  2. If the page has a og:url property the like button will show the likes of that url instead of the url in the browser.

Hope this helps someone

How to "select distinct" across multiple data frame columns in pandas?

I've tried different solutions. First was:

a_df=np.unique(df[['col1','col2']], axis=0)

and it works well for not object data Another way to do this and to avoid error (for object columns type) is to apply drop_duplicates()

a_df=df.drop_duplicates(['col1','col2'])[['col1','col2']]

You can also use SQL to do this, but it worked very slow in my case:

from pandasql import sqldf
q="""SELECT DISTINCT col1, col2 FROM df;"""
pysqldf = lambda q: sqldf(q, globals())
a_df = pysqldf(q)

How to return temporary table from stored procedure

Take a look at this code,

CREATE PROCEDURE Test

AS
    DECLARE @tab table (no int, name varchar(30))

    insert @tab  select eno,ename from emp  

    select * from @tab
RETURN

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

This is working code

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            { 
                    DropDownList1.DataTextField = "user_name";
                    DropDownList1.DataValueField = "user_id";
                    DropDownList1.DataSource = getData();// get the data into the list you can set it
                    DropDownList1.DataBind();

    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));
            }
        }

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

PHP Fatal error: Uncaught exception 'Exception'

For

throw new Exception('test exception');

I got 500 (but didn't see anything in the browser), until I put

php_flag display_errors on

in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only

How to use the DropDownList's SelectedIndexChanged event

You should add AutoPostBack="true" to DropDownList1

                <asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
                    DataSourceID="Sql_fur_model_manu"    
                    DataTextField="manufacturer" DataValueField="manufacturer" 
                    onselectedindexchanged="ddmanu_SelectedIndexChanged">
                </asp:DropDownList>

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

You can try like below with sqljdbc4-2.0.jar:

 public void getConnection() throws ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String url = "jdbc:sqlserver://<SERVER_IP>:<PORT_NO>;databaseName=" + DATABASE_NAME;
        Connection conn = DriverManager.getConnection(url, USERNAME, PASSWORD);
        System.out.println("DB Connection started");
        Statement sta = conn.createStatement();
        String Sql = "select * from TABLE_NAME";
        ResultSet rs = sta.executeQuery(Sql);
        while (rs.next()) {
            System.out.println(rs.getString("COLUMN_NAME"));
        }
    }

How to select data where a field has a min value in MySQL?

this will give you result that has the minimum price on all records.

SELECT *
FROM pieces
WHERE price =  ( SELECT MIN(price) FROM pieces )

PHP - get base64 img string decode and save as jpg (resulting empty image )

Decode and save image as PNG

header('content-type: image/png');

           ob_start();

        $ret = fopen($fullurl, 'r', true, $context);
        $contents = stream_get_contents($ret);
        $base64 = 'data:image/PNG;base64,' . base64_encode($contents);
        echo "<img src=$base64 />" ;


        ob_end_flush();

How to keep indent for second line in ordered lists via CSS?

I believe this will do what you are looking for.

.cssClass li {
    list-style-type: disc;
    list-style-position: inside;
    text-indent: -1em;
    padding-left: 1em;
}

JSFiddle: https://jsfiddle.net/dzbos70f/

enter image description here

Check whether a path is valid

I haven't had any problems with the code below. (Relative paths must start with '/' or '\').

private bool IsValidPath(string path, bool allowRelativePaths = false)
{
    bool isValid = true;

    try
    {
        string fullPath = Path.GetFullPath(path);

        if (allowRelativePaths)
        {
            isValid = Path.IsPathRooted(path);
        }
        else
        {
            string root = Path.GetPathRoot(path);
            isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
        }
    }
    catch(Exception ex)
    {
        isValid = false;
    }

    return isValid;
}

For example these would return false:

IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("./abc", true);
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", true);

And these would return true:

IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", true);
IsValidPath(@"\abc", true);

How to use a decimal range() step value?

The range() built-in function returns a sequence of integer values, I'm afraid, so you can't use it to do a decimal step.

I'd say just use a while loop:

i = 0.0
while i <= 1.0:
    print i
    i += 0.1

If you're curious, Python is converting your 0.1 to 0, which is why it's telling you the argument can't be zero.

Update query with PDO and MySQL

This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.

Here's the difference:

  • INSERT creates a new row. I'm guessing that you really want to create a new row.
  • UPDATE changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.

So this will probably do what you want:

$sql = "INSERT INTO `access_users`   
  (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
  VALUES (:firstname, :surname, :email, :telephone);
  ";

Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.

MySQL also supports an alternative syntax for INSERT:

$sql = "INSERT INTO `access_users`   
  SET `contact_first_name` = :firstname,
    `contact_surname` = :surname,
    `contact_email` = :email,
    `telephone` = :telephone
  ";

This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.

How to build a query string for a URL in C#?

Here's a fluent/lambda-ish way as an extension method (combining concepts in previous posts) that supports multiple values for the same key. My personal preference is extensions over wrappers for discover-ability by other team members for stuff like this. Note that there's controversy around encoding methods, plenty of posts about it on Stack Overflow (one such post) and MSDN bloggers (like this one).

public static string ToQueryString(this NameValueCollection source)
{
    return String.Join("&", source.AllKeys
        .SelectMany(key => source.GetValues(key)
            .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))))
        .ToArray());
}

edit: with null support, though you'll probably need to adapt it for your particular situation

public static string ToQueryString(this NameValueCollection source, bool removeEmptyEntries)
{
    return source != null ? String.Join("&", source.AllKeys
        .Where(key => !removeEmptyEntries || source.GetValues(key)
            .Where(value => !String.IsNullOrEmpty(value))
            .Any())
        .SelectMany(key => source.GetValues(key)
            .Where(value => !removeEmptyEntries || !String.IsNullOrEmpty(value))
            .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), value != null ? HttpUtility.UrlEncode(value) : string.Empty)))
        .ToArray())
        : string.Empty;
}

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

Sounds like an error you would get when your forms authentication ticket has expired. What is the timeout period for your ticket? Is it set to sliding or absolute expiration?

I believe the default for the timeout is 20 minutes with sliding expiration so if a user gets authenticated and at some point doesn't hit your site for 20 minutes their ticket would be expired. If it is set to absolute expiration it will expire X number of minutes after it was issued where X is your timeout setting.

You can set the timeout and expiration policy (e.g. sliding, absolute) in your web/machine.config under /configuration/system.web/authentication/forms

Compute mean and standard deviation by group for multiple variables in a data.frame

There is a helpful function in the psych package.

You should try the following implementation:

psych::describeBy(data$dependentvariable, group = data$groupingvariable)

How to have multiple colors in a Windows batch file?

Yes, it is possible with cmdcolor:

echo \033[32mhi \033[92mworld

hi will be dark green, and world - light green.