Programs & Examples On #Py2exe

Py2exe is a python extension that converts Python Scripts to Windows Executables.

How to call python script on excel vba?

To those who are stuck wondering why a window flashes and goes away without doing anything the python script is meant to do after calling the shell command from VBA: In my program

Sub runpython()

Dim Ret_Val
args = """F:\my folder\helloworld.py"""
Ret_Val = Shell("C:\Users\username\AppData\Local\Programs\Python\Python36\python.exe " & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
   MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub

In the line args = """F:\my folder\helloworld.py""", I had to use triple quotes for this to work. If I use just regular quotes like: args = "F:\my folder\helloworld.py" the program would not work. The reason for this is that there is a space in the path (my folder). If there is a space in the path, in VBA, you need to use triple quotes.

py2exe - generate single executable file

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.

Process to convert simple Python script into Windows executable

You can create executable from python script using NSIS (Nullsoft scriptable install system). Follow the below steps to convert your python files to executable.

  • Download and install NSIS in your system.

  • Compress the folder in the .zip file that you want to export into the executable.

  • Start NSIS and select Installer based on ZIP file. Find and provide a path to your compressed file.

  • Provide your Installer Name and Default Folder path and click on Generate to generate your exe file.

  • Once its done you can click on Test to test executable or Close to complete the process.

  • The executable generated can be installed on the system and can be distributed to use this application without even worrying about installing the required python and its packages.

For a video tutorial follow: How to Convert any Python File to .EXE

How can I convert a .py to .exe for Python?

Python 3.6 is supported by PyInstaller.

Open a cmd window in your Python folder (open a command window and use cd or while holding shift, right click it on Windows Explorer and choose 'Open command window here'). Then just enter

pip install pyinstaller

And that's it.

The simplest way to use it is by entering on your command prompt

pyinstaller file_name.py

For more details on how to use it, take a look at this question.

How to send password securely over HTTP?

HTTPS is so powerful because it uses asymmetric cryptography. This type of cryptography not only allows you to create an encrypted tunnel but you can verify that you are talking to the right person, and not a hacker.

Here is Java source code which uses the asymmetric cipher RSA (used by PGP) to communicate: http://www.hushmail.com/services/downloads/

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

Monitor network activity in Android Phones

For Android Phones(Without Root):- you can use this application tPacketCapture this will capture the network trafic for your device when you enable the capture. See this url for more details about network sniffing without rooting your device.

Once you have the file which is in .pcap format you can use this file and analyze the traffic using any traffic analyzer like Wireshark.

Also see this post for further ideas on Capturing mobile phone traffic on wireshark

What is JSONP, and why was it created?

JSONP works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is tht JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.

For Further Reading Visit: https://blogs.sap.com/2013/07/15/secret-behind-jsonp/

client side snippet of code

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <title>AvLabz - CORS : The Secrets Behind JSONP </title>
     <meta charset="UTF-8" />
    </head>
    <body>
      <input type="text" id="username" placeholder="Enter Your Name"/>
      <button type="submit" onclick="sendRequest()"> Send Request to Server </button>
    <script>
    "use strict";
    //Construct the script tag at Runtime
    function requestServerCall(url) {
      var head = document.head;
      var script = document.createElement("script");

      script.setAttribute("src", url);
      head.appendChild(script);
      head.removeChild(script);
    }

    //Predefined callback function    
    function jsonpCallback(data) {
      alert(data.message); // Response data from the server
    }

    //Reference to the input field
    var username = document.getElementById("username");

    //Send Request to Server
    function sendRequest() {
      // Edit with your Web Service URL
      requestServerCall("http://localhost/PHP_Series/CORS/myService.php?callback=jsonpCallback&message="+username.value+"");
    }    

  </script>
   </body>
   </html>

Server side piece of PHP code

<?php
    header("Content-Type: application/javascript");
    $callback = $_GET["callback"];
    $message = $_GET["message"]." you got a response from server yipeee!!!";
    $jsonResponse = "{\"message\":\"" . $message . "\"}";
    echo $callback . "(" . $jsonResponse . ")";
?>

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

In Asp Net Core, to quickly get it working for development; in Startup.cs, Configure method add

app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

How to display hexadecimal numbers in C?

i use it like this:

printf("my number is 0x%02X\n",number);
// output: my number is 0x4A

Just change number "2" to any number of chars You want to print ;)

Do while loop in SQL Server 2008

If you are not very offended by the GOTO keyword, it can be used to simulate a DO / WHILE in T-SQL. Consider the following rather nonsensical example written in pseudocode:

SET I=1
DO
 PRINT I
 SET I=I+1
WHILE I<=10

Here is the equivalent T-SQL code using goto:

DECLARE @I INT=1;
START:                -- DO
  PRINT @I;
  SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10

Notice the one to one mapping between the GOTO enabled solution and the original DO / WHILE pseudocode. A similar implementation using a WHILE loop would look like:

DECLARE @I INT=1;
WHILE (1=1)              -- DO
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF NOT (@I<=10) BREAK; -- WHILE @I<=10
 END

Now, you could of course rewrite this particular example as a simple WHILE loop, since this is not such a good candidate for a DO / WHILE construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO / WHILE are rare.


REPEAT / UNTIL, anyone (does NOT work in T-SQL)?

SET I=1
REPEAT
  PRINT I
  SET I=I+1
UNTIL I>10

... and the GOTO based solution in T-SQL:

DECLARE @I INT=1;
START:                    -- REPEAT
  PRINT @I;
  SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10

Through creative use of GOTO and logic inversion via the NOT keyword, there is a very close relationship between the original pseudocode and the GOTO based solution. A similar solution using a WHILE loop looks like:

DECLARE @I INT=1;
WHILE (1=1)       -- REPEAT
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF @I>10 BREAK; -- UNTIL @I>10
 END

An argument can be made that for the case of the REPEAT / UNTIL, the WHILE based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.

If it wasn't for all of the disdain around the use of GOTO, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.

Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO.

Maximum number of records in a MySQL database table

I suggest, never delete data. Don't say if the tables is longer than 1000 truncate the end of the table. There needs to be real business logic in your plan like how long has this user been inactive. For example, if it is longer than 1 year then put them in a different table. You would have this happen weekly or monthly in a maintenance script in the middle of a slow time.

When you run into to many rows in your table then you should start sharding the tables or partitioning and put old data in old tables by year such as users_2011_jan, users_2011_feb or use numbers for the month. Then change your programming to work with this model. Maybe make a new table with less information to summarize the data in less columns and then only refer to the bigger partitioned tables when you need more information such as when the user is viewing their profile. All of this should be considered very carefully so in the future it isn't too expensive to re-factor. You could also put only the users which comes to your site all the time in one table and the users that never come in an archived set of tables.

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.

The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.

Here is a good article about fluid vs. flex.

Moving x-axis to the top of a plot in matplotlib

tick_params is very useful for setting tick properties. Labels can be moved to the top with:

    ax.tick_params(labelbottom=False,labeltop=True)

Check table exist or not before create it in Oracle

As Rene also commented, it's quite uncommon to check first and then create the table. If you want to have a running code according to your method, this will be:

declare
nCount NUMBER;
v_sql LONG;

begin
SELECT count(*) into nCount FROM dba_tables where table_name = 'EMPLOYEE';
IF(nCount <= 0)
THEN
v_sql:='
create table EMPLOYEE
(
ID NUMBER(3),
NAME VARCHAR2(30) NOT NULL
)';
execute immediate v_sql;

END IF;
end;

But I'd rather go catch on the Exception, saves you some unnecessary lines of code:

declare
v_sql LONG;
begin

v_sql:='create table EMPLOYEE
  (
  ID NUMBER(3),
  NAME VARCHAR2(30) NOT NULL
  )';
execute immediate v_sql;

EXCEPTION
    WHEN OTHERS THEN
      IF SQLCODE = -955 THEN
        NULL; -- suppresses ORA-00955 exception
      ELSE
         RAISE;
      END IF;
END; 
/

What's the difference between size_t and int in C++?

It's because size_t can be anything other than an int (maybe a struct). The idea is that it decouples it's job from the underlying type.

MySQL "WITH" clause

Oracle does support WITH.

It would look like this.

WITH emps as (SELECT * FROM Employees)
SELECT * FROM emps WHERE ID < 20
UNION ALL
SELECT * FROM emps where Sex = 'F'

@ysth WITH is hard to google because it's a common word typically excluded from searches.

You'd want to look at the SELECT docs to see how subquery factoring works.

I know this doesn't answer the OP but I'm cleaning up any confusion ysth may have started.

How to stop the Timer in android?

I had a similar problem: every time I push a particular button, I create a new Timer.

my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}

Exiting from that activity I deleted the timer:

if(my_timer!=null){
my_timer.cancel();
my_timer = null;
}

But it was not enough because the cancel() method only canceled the latest Timer. The older ones were ignored an didn't stop running. The purge() method was not useful for me. I solved the problem just checking the Timer instantiation:

if(my_timer == null){
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
}

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.

@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {

    @ApiObjectField(description = "The code which is to be verified.")
    @NotBlank(message = "mandatory")
    private final String code;

    @ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
    private final String maskedMobileNumber;

    public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
        this.code = code;
        this.maskedMobileNumber = maskedMobileNumber;
    }

    public String getcode() {
        return code;
    }

    public String getMaskedMobileNumber() {
        return maskedMobileNumber;
    }
}

The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been

public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
    this.code = code;
    this.maskedMobileNumber = maskedMobileNumber;
}

How to set up Android emulator proxy settings

For some leanback (TV) emulators you can use cmd:

adb shell settings put global http_proxy 10.0.2.2:8888

  • 8888 - is a port of proxy on a local machine (host), so on a local machine the http proxy will be 127.0.0.1:8888

To remove proxy (run sequentially in cmd line):

adb shell settings delete global http_proxy

adb shell settings put global global_http_proxy_host ""

adb shell settings put global global_http_proxy_port ""

Regular expression that doesn't contain certain string

In general it's a pain to write a regular expression not containing a particular string. We had to do this for models of computation - you take an NFA, which is easy enough to define, and then reduce it to a regular expression. The expression for things not containing "cat" was about 80 characters long.

Edit: I just finished and yes, it's:

aa([^a] | a[^a])aa

Here is a very brief tutorial. I found some great ones before, but I can't see them anymore.

Simple logical operators in Bash

A very portable version (even to legacy bourne shell):

if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then    do-something
fi

This has the additional quality of running only one subprocess at most (which is the process [), whatever the shell flavor.

Replace = with -eq if variables contain numeric values, e.g.

  • 3 -eq 03 is true, but
  • 3 = 03 is false. (string comparison)

Set disable attribute based on a condition for Html.TextBoxFor

I like Darin method. But quick way to solve this,

Html.TextBox("Expiry", null, new { style = "width: 70px;", maxlength = "10", id = "expire-date", disabled = "disabled" }).ToString().Replace("disabled=\"disabled\"", (1 == 2 ? "" : "disabled=\"disabled\""))

how to toggle (hide/show) a table onClick of <a> tag in java script

Try

<script>
  function toggleTable()
    {

    var status = document.getElementById("loginTable").style.display;

    if (status == 'block') {
      document.getElementById("loginTable").style.display="none";
    } else {
      document.getElementById("loginTable").style.display="block";
    }
  }
</script>

How can an html element fill out 100% of the remaining screen height, using css only?

The accepted solution will not actually work. You will notice that the content div will be equal to the height of its parent, body. So setting the body height to 100% will set it equal to the height of the browser window. Let's say the browser window was 768px in height, by setting the content div height to 100%, the div's height will in turn be 768px. Thus, you will end up with the header div being 150px and the content div being 768px. In the end you will have content 150px below the bottom of the page. For another solution, check out this link.

How to change border color of textarea on :focus

so simple :

 outline-color : blue !important;

the whole CSS for my react-boostrap button is:

.custom-btn {
    font-size:1.9em;
    background: #2f5bff;
    border: 2px solid #78e4ff;
    border-radius: 3px;
    padding: 50px 70px;
    outline-color : blue !important;
    text-transform: uppercase;
    user-select: auto;
    -moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2);
    -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
}

Python calling method in class

Could someone explain to me, how to call the move method with the variable RIGHT

>>> myMissile = MissileDevice(myBattery)  # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)

If you have programmed in any other language with classes, besides python, this sort of thing

class Foo:
    bar = "baz"

is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; and variables defined in its scope are attached to the class, not the instances returned by the class. to refer to bar, above, you can just call it Foo.bar; you can also access class attributes through instances of the class, like Foo().bar.


Im utterly baffled about what 'self' refers too,

>>> class Foo:
...     def quux(self):
...         print self
...         print self.bar
...     bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>

When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. All this does is arrange for the instance to be passed as the first argument.

Add leading zeroes to number in Java?

Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);
}

how to move elasticsearch data from one server to another

We can use elasticdump or multielasticdump to take the backup and restore it, We can move data from one server/cluster to another server/cluster.

Please find a detailed answer which I have provided here.

Adding whitespace in Java

If you have an Instance of the EditText available at the point in your code where you want add whitespace, then this code below will work. There may be some things to consider, for example the code below may trigger any TextWatcher you have set to this EditText, idk for sure, just saying, but this will work when trying to append blank space like this: " ", hasn't worked.

messageInputBox.dispatchKeyEvent(new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_SPACE, 0, 0, 0, 0,
                        KeyEvent.KEYCODE_ENDCALL));

How to select data from 30 days?

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

Dropdown using javascript onchange

easy

<script>
jQuery.noConflict()(document).ready(function() {
    $('#hide').css('display','none');
    $('#plano').change(function(){

        if(document.getElementById('plano').value == 1){
            $('#hide').show('slow');    

        }else 
            if(document.getElementById('plano').value == 0){

             $('#hide').hide('slow'); 
        }else
            if(document.getElementById('plano').value == 0){
             $('#hide').css('display','none');  

            }

    });
    $('#plano').change();
});
</script>

this example shows and hides the div if selected in combobox some specific value

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Get file path of image on Android

To get the path of all images in android I am using following code

public void allImages() 
{
    ContentResolver cr = getContentResolver();
    Cursor cursor;
    Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Images.Media._ID + " != 0";

    cursor = cr.query(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA));
                Log.i("Image path ", fullpath + "");


            } while (cursor.moveToNext());
        }
        cursor.close();
    }

}

Are duplicate keys allowed in the definition of binary search trees?

In the book "Introduction to algorithms", third edition, by Cormen, Leiserson, Rivest and Stein, a binary search tree (BST) is explicitly defined as allowing duplicates. This can be seen in figure 12.1 and the following (page 287):

"The keys in a binary search tree are always stored in such a way as to satisfy the binary-search-tree property: Let x be a node in a binary search tree. If y is a node in the left subtree of x, then y:key <= x:key. If y is a node in the right subtree of x, then y:key >= x:key."

In addition, a red-black tree is then defined on page 308 as:

"A red-black tree is a binary search tree with one extra bit of storage per node: its color"

Therefore, red-black trees defined in this book support duplicates.

What does the line "#!/bin/sh" mean in a UNIX shell script?

#!/bin/sh or #!/bin/bash has to be first line of the script because if you don't use it on the first line then the system will treat all the commands in that script as different commands. If the first line is #!/bin/sh then it will consider all commands as a one script and it will show the that this file is running in ps command and not the commands inside the file.

./echo.sh

ps -ef |grep echo
trainee   3036  2717  0 16:24 pts/0    00:00:00 /bin/sh ./echo.sh
root      3042  2912  0 16:24 pts/1    00:00:00 grep --color=auto echo

Angular 6: How to set response type as text while making http call

Use like below:

  yourFunc(input: any):Observable<string> {
var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json'  });

}

How can I set the default timezone in node.js?

I know this thread is very old, but i think this would help anyone that landed here from google like me.

In GAE Flex (NodeJs), you could set the enviroment variable TZ (the one that manages all date timezones in the app) in the app.yaml file, i leave you here an example:

app.yaml

# [START env]
env_variables:
  # Timezone
  TZ: America/Argentina/Buenos_Aires

Perform curl request in javascript?

You can use JavaScripts Fetch API (available in your browser) to make network requests.

If using node, you will need to install the node-fetch package.

const url = "https://api.wit.ai/message?v=20140826&q=";

const options = {
  headers: {
    Authorization: "Bearer 6Q************"
  }
};

fetch(url, options)
  .then( res => res.json() )
  .then( data => console.log(data) );

In Bootstrap 3,How to change the distance between rows in vertical?

There's a simply way of doing it. You define for all the rows, except the first one, the following class with properties:

.not-first-row
{
   position: relative;
   top: -20px;
}

Then you apply the class to all non-first rows and adjust the negative top value to fit your desired row space. It's easy and works way better. :) Hope it helped.

Easy way to export multiple data.frame to multiple Excel worksheets

I do this all the time, all I do is

WriteXLS::WriteXLS(
    all.dataframes,
    ExcelFileName = xl.filename,
    AdjWidth = T,
    AutoFilter = T,
    FreezeRow = 1,
    FreezeCol = 2,
    BoldHeaderRow = T,
    verbose = F,
    na = '0'
  )

and all those data frames come from here

all.dataframes <- vector()
for (obj.iter in all.objects) {
  obj.name <- obj.iter
  obj.iter <- get(obj.iter)
  if (class(obj.iter) == 'data.frame') {
      all.dataframes <- c(all.dataframes, obj.name)
}

obviously sapply routine would be better here

Is it a bad practice to use break in a for loop?

No, break is the correct solution.

Adding a boolean variable makes the code harder to read and adds a potential source of errors.

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

Don't use Integrated Security. Use User Id=yourUser; pwd=yourPwd;

This solves the problem.

Java logical operator short-circuiting

Java provides two interesting Boolean operators not found in most other computer languages. These secondary versions of AND and OR are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is.

Similarly, the AND operator results in false when A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone. This is very useful when the right-hand operand depends on the left one being true or false in order to function properly.

For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it:

if ( denom != 0 && num / denom >10)

Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception from dividing by zero. If this line of code were written using the single & version of AND, both sides would have to be evaluated, causing a run-time exception when denom is zero.

It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement:

 if ( c==1 & e++ < 100 ) d = 100;

Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.

Please initialize the log4j system properly warning

Alright, so I got it working by changing this

log4j.rootLogger=DebugAppender

to this

log4j.rootLogger=DEBUG, DebugAppender

Apparently you have to specify the logging level to the rootLogger first? I apologize if I wasted anyone's time.

Also, I decided to answer my own question because this wasn't a classpath issue.

Unix command to check the filesize

ls -l --block-size=M 

will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB. If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.

Or

ls -lah 

-h When used with the -l option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to three or less using base 2 for sizes.

man ls

http://unixhelp.ed.ac.uk/CGI/man-cgi?ls

Prevent RequireJS from Caching Required Scripts

Do not use urlArgs for this!

Require script loads respect http caching headers. (Scripts are loaded with a dynamically inserted <script>, which means the request looks just like any old asset getting loaded.)

Serve your javascript assets with the proper HTTP headers to disable caching during development.

Using require's urlArgs means any breakpoints you set will not be preserved across refreshes; you end up needing to put debugger statements everywhere in your code. Bad. I use urlArgs for cache-busting assets during production upgrades with the git sha; then I can set my assets to be cached forever and be guaranteed to never have stale assets.

In development, I mock all ajax requests with a complex mockjax configuration, then I can serve my app in javascript-only mode with a 10 line python http server with all caching turned off. This has scaled up for me to a quite large "enterprisey" application with hundreds of restful webservice endpoints. We even have a contracted designer who can work with our real production codebase without giving him access to our backend code.

Swift alert view with OK and Cancel: which button tapped?

You may want to consider using SCLAlertView, alternative for UIAlertView or UIAlertController.

UIAlertController only works on iOS 8.x or above, SCLAlertView is a good option to support older version.

github to see the details

example:

let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
    print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")

How to format x-axis time scale values in Chart.js v2

I had a different use case, I want different formats based how long between start and end time of data in graph. I found this to be simplest approach

    xAxes = {
        type: "time",
        time: {
            displayFormats: {
                hour: "hA"
            }
        },
        display: true,
        ticks: {
            reverse: true
        },
        gridLines: {display: false}
    }
    // if more than two days between start and end of data,  set format to show date,  not hrs
    if ((parseInt(Cookies.get("epoch_max")) - parseInt(Cookies.get("epoch_min"))) > (1000*60*60*24*2)) {
        xAxes.time.displayFormats.hour = "MMM D";
    }

FileNotFoundException while getting the InputStream object from HttpURLConnection

Please change

con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();

To

con = (HttpURLConnection) new URL("http://YOUR_IP:8080/myapp/service/generate").openConnection();

How do I enable the column selection mode in Eclipse?

To activate the cursor and select the columns you want to select use:

Windows: Alt+Shift+A

Mac: command + option + A

Linux-based OS: Alt+Shift+A

To deactivate, press the keys again.

This information was taken from DJ's Java Blog.

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

gpg decryption fails with no secret key error

You can also be interested at the top answer in here: https://askubuntu.com/questions/1080204/gpg-problem-with-the-agent-permission-denied

basically the solution that worked for me too is:

gpg --decrypt --pinentry-mode=loopback <file>

R - Markdown avoiding package loading messages

```{r results='hide', message=FALSE, warning=FALSE}
library(RJSONIO)
library(AnotherPackage)
```

see Chunk Options in the Knitr docs

Where to get this Java.exe file for a SQL Developer installation

I encountered the following message repeatedly when trying to start SQL Developer from my installation of Oracle Database 11g Enterprise: Enter the full pathname for java.exe.

No matter how many times I browsed to the correct path, I kept being presented with the exact same dialog box. This was in Windows 7, and the solution was to right-click on the SQL Developer icon and select "Run as administrator". I then used this path: C:\app\shellperson\product\11.1.0\db_1\jdk\jre\bin\java.exe

UILabel - Wordwrap text

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

PKIX path building failed in Java application

I ran into similar issues whose cause and solution turned out both to be rather simple:

Main Cause: Did not import the proper cert using keytool

NOTE: Only import root CA (or your own self-signed) certificates

NOTE: don't import an intermediate, non certificate chain root cert

Solution Example for imap.gmail.com

  1. Determine the root CA cert:

    openssl s_client -showcerts -connect imap.gmail.com:993
    

    in this case we find the root CA is Equifax Secure Certificate Authority

  2. Download root CA cert.
  3. Verify downloaded cert has proper SHA-1 and/or MD5 fingerprints by comparing with info found here
  4. Import cert for javax.net.ssl.trustStore:

    keytool -import -alias gmail_imap -file Equifax_Secure_Certificate_Authority.pem
    
  5. Run your java code

How can I change an element's class with JavaScript?

Wow, surprised there are so many overkill answers here...

<div class="firstClass" onclick="this.className='secondClass'">

target="_blank" vs. target="_new"

target="_blank" opens a new tab in most browsers.

How can I remove or replace SVG content?

I am using the SVG using D3.js and i had the same issue.

I used this code for removing the previous svg but the linear gradient inside SVG were not coming in IE

$("#container_div_id").html("");

then I wrote the below code to resolve the issue

$('container_div_id g').remove();
$('#container_div_id path').remove();

here i am removing the previous g and path inside the SVG, replacing with the new one.

Keeping my linear gradient inside SVG tags in the static content and then I called the above code, This works in IE

What is the difference between a definition and a declaration?

To understand the difference between declaration and definition we need to see the assembly code:

uint8_t   ui8 = 5;  |   movb    $0x5,-0x45(%rbp)
int         i = 5;  |   movl    $0x5,-0x3c(%rbp)
uint32_t ui32 = 5;  |   movl    $0x5,-0x38(%rbp)
uint64_t ui64 = 5;  |   movq    $0x5,-0x10(%rbp)
double   doub = 5;  |   movsd   0x328(%rip),%xmm0        # 0x400a20
                        movsd   %xmm0,-0x8(%rbp)

and this is only definition:

ui8 = 5;   |   movb    $0x5,-0x45(%rbp)
i = 5;     |   movl    $0x5,-0x3c(%rbp)
ui32 = 5;  |   movl    $0x5,-0x38(%rbp)
ui64 = 5;  |   movq    $0x5,-0x10(%rbp)
doub = 5;  |   movsd   0x328(%rip),%xmm0        # 0x400a20
               movsd   %xmm0,-0x8(%rbp)

As you can see nothing change.

Declaration is different from definition because it gives information used only by the compiler. For example uint8_t tell the compiler to use asm function movb.

See that:

uint def;                  |  no instructions
printf("some stuff...");   |  [...] callq   0x400450 <printf@plt>
def=5;                     |  movb    $0x5,-0x45(%rbp)

Declaration haven't an equivalent instruction because it is no something to be executed.

Furthermore declaration tells the compiler the scope of the variable.

We can say that declaration is an information used by the compiler to establish the correct use of the variable and for how long some memory belongs to certain variable.

What's the difference between @Component, @Repository & @Service annotations in Spring?

There is no difference between @Component, @Service, @Controller, @Repository. @Component is the Generic annotation to represent the component of our MVC. But there will be several components as part of our MVC application like service layer components, persistence layer components and presentation layer components. So to differentiate them Spring people have given the other three annotations also.

  • To represent persistence layer components: @Repository
  • To represent service layer components: @Service
  • To represent presentation layer components: @Controller
  • or else you can use @Component for all of them.

What does set -e mean in a bash script?

I found this post while trying to figure out what the exit status was for a script that was aborted due to a set -e. The answer didn't appear obvious to me; hence this answer. Basically, set -e aborts the execution of a command (e.g. a shell script) and returns the exit status code of the command that failed (i.e. the inner script, not the outer script).

For example, suppose I have the shell script outer-test.sh:

#!/bin/sh
set -e
./inner-test.sh
exit 62;

The code for inner-test.sh is:

#!/bin/sh
exit 26;

When I run outer-script.sh from the command line, my outer script terminates with the exit code of the inner script:

$ ./outer-test.sh
$ echo $?
26

Validate that a string is a positive integer

If you are using HTML5 forms, you can use attribute min="0" for form element <input type="number" />. This is supported by all major browsers. It does not involve Javascript for such simple tasks, but is integrated in new html standard. It is documented on https://www.w3schools.com/tags/att_input_min.asp

HashMap: One Key, multiple Values

It sounds like you're looking for a multimap. Guava has various Multimap implementations, usually created via the Multimaps class.

I would suggest that using that implementation is likely to be simpler than rolling your own, working out what the API should look like, carefully checking for an existing list when adding a value etc. If your situation has a particular aversion to third party libraries it may be worth doing that, but otherwise Guava is a fabulous library which will probably help you with other code too :)

How to quit android application programmatically

getActivity().finish();
System.exit(0);

this is the best way to exit your app.!!!

The best solution for me.

Marquee text in Android

To get this to work, I had to use ALL three of the things (ellipsize, selected, and singleLine) mentioned already:

TextView tv = (TextView)findViewById(R.id.someTextView);
tv.setSelected(true);
tv.setEllipsize(TruncateAt.MARQUEE);
tv.setSingleLine(true):

Open directory dialog

Ookii folder dialog can be found at Nuget.

PM> Install-Package Ookii.Dialogs.Wpf

And, example code is as below.

var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
if (dialog.ShowDialog(this).GetValueOrDefault())
{
    textBoxFolderPath.Text = dialog.SelectedPath;
}

More information on how to use it: https://github.com/augustoproiete/ookii-dialogs-wpf

Is this very likely to create a memory leak in Tomcat?

The message is actually pretty clear: something creates a ThreadLocal with value of type org.apache.axis.MessageContext - this is a great hint. It most likely means that Apache Axis framework forgot/failed to cleanup after itself. The same problem occurred for instance in Logback. You shouldn't bother much, but reporting a bug to Axis team might be a good idea.

Tomcat reports this error because the ThreadLocals are created per HTTP worker threads. Your application is undeployed but HTTP threads remain - and these ThreadLocals as well. This may lead to memory leaks (org.apache.axis.MessageContext can't be unloaded) and some issues when these threads are reused in the future.

For details see: http://wiki.apache.org/tomcat/MemoryLeakProtection

How to use WinForms progress bar?

There is Task exists, It is unnesscery using BackgroundWorker, Task is more simple. for example:

ProgressDialog.cs:

   public partial class ProgressDialog : Form
    {
        public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }

        public ProgressDialog()
        {
            InitializeComponent();
        }

        public void RunAsync(Action action)
        {
            Task.Run(action);
        }
    }

Done! Then you can reuse ProgressDialog anywhere:

var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;

progressDialog.RunAsync(() =>
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000)
        this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
            this.progressDialog.Progressbar.Value += 1;
        }));
    }
});

progressDialog.ShowDialog();

Error in launching AVD with AMD processor

For those who are using Android Studio based on Jetbrains:

  1. Goto Tools > Android > SDK Manager

  2. Under Extras --> select the checkbox Intel x86 Emulator Accelorator

For those who are unable to use Nexus AVD can also try using Generic AVD.

  1. Goto Tools > Android > AVD Manager

Then create a new Genreic AVD with something like QVGA and use for your app. This AVD does not use hardware acceleration.

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

A different case in which I encountered this was when I was using echo to pipe the JSON into my python script and carelessly wrapped the JSON string in double quotes:

echo "{"thumbnailWidth": 640}" | myscript.py

Note that the JSON string itself has quotes and I should have done:

echo '{"thumbnailWidth": 640}' | myscript.py

As it was, this is what the python script received: {thumbnailWidth: 640}; the double quotes were effectively stripped.

Convert String To date in PHP

Try this:

$new_date=date('d-m-Y', strtotime($date));

getting the difference between date in days in java

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
  dateFormat.format(startDate)+" and "+
  dateFormat.format(endDate)+" is "+
  diffDays+" days.");

This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:

start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
    start.add(Calendar.DAY_OF_MONTH, 1);
    diffDays++;
}
while (start.after(end)) {
    start.add(Calendar.DAY_OF_MONTH, -1);
    diffDays--;
}

Why use multiple columns as primary keys (composite primary key)

The W3Schools example isn't saying when you should use compound primary keys, and is only giving example syntax using the same example table as for other keys.

Their choice of example is perhaps misleading you by combining a meaningless key (P_Id) and a natural key (LastName). This odd choice of primary key says that the following rows are valid according to the schema and are necessary to uniquely identify a student. Intuitively this doesn't make sense.

1234     Jobs
1234     Gates

Further Reading: The great primary-key debate or just Google meaningless primary keys or even peruse this SO question

FWIW - My 2 cents is to avoid multi-column primary keys and use a single generated id field (surrogate key) as the primary key and add additional (unique) constraints where necessary.

Check if value is zero or not null in python

The simpler way:

h = ''
i = None
j = 0
k = 1
print h or i or j or k

Will print 1

print k or j or i or h

Will print 1

How do I disable a Button in Flutter?

This is the easiest way in my opinion:

RaisedButton(
  child: Text("PRESS BUTTON"),
  onPressed: booleanCondition
    ? () => myTapCallback()
    : null
)

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

How to run a JAR file

Before run the jar check Main-Class: classname is available or not in MANIFEST.MF file. MANIFEST.MF is present in jar.

java -jar filename.jar

What is the difference between static_cast<> and C style casting?

See A comparison of the C++ casting operators.

However, using the same syntax for a variety of different casting operations can make the intent of the programmer unclear.

Furthermore, it can be difficult to find a specific type of cast in a large codebase.

the generality of the C-style cast can be overkill for situations where all that is needed is a simple conversion. The ability to select between several different casting operators of differing degrees of power can prevent programmers from inadvertently casting to an incorrect type.

Git: See my last commit

As determined via comments, it appears that the OP is looking for

$ git log --name-status HEAD^..HEAD

This is also very close to the output you'd get from svn status or svn log -v, which many people coming from subversion to git are familiar with.

--name-status is the key here; as noted by other folks in this question, you can use git log -1, git show, and git diff to get the same sort of output. Personally, I tend to use git show <rev> when looking at individual revisions.

Remove all stylings (border, glow) from textarea

if no luck with above try to it a class or even id something like textarea.foo and then your style. or try to !important

How do I print a double value without scientific notation using Java?

use String.format ("%.0f", number)

%.0f for zero decimal

String numSring = String.format ("%.0f", firstNumber);
System.out.println(numString);

Django Cookies, how can I set them?

Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.

Here is an example with a Django view ...

def homepage(request):

    request.session.setdefault('how_many_visits', 0)
    request.session['how_many_visits'] += 1

    print(request.session['how_many_visits'])

    return render(request, 'home.html', {})

If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.

How to declare a variable in a template in Angular

update 3

Issue 2451 is fixed in Angular 4.0.0

See also

update 2

This isn't supported.

There are template variables but it's not supported to assign arbitrary values. They can only be used to refer to the elements they are applied to, exported names of directives or components and scope variables for structural directives like ngFor,

See also https://github.com/angular/angular/issues/2451

Update 1

@Directive({
  selector: '[var]',
  exportAs: 'var'
})
class VarDirective {
  @Input() var:any;
}

and initialize it like

<div #aVariable="var" var="abc"></div>

or

<div #aVariable="var" [var]="'abc'"></div>

and use the variable like

<div>{{aVariable.var}}</div>

(not tested)

  • #aVariable creates a reference to the VarDirective (exportAs: 'var')
  • var="abc" instantiates the VarDirective and passes the string value "abc" to it's value input.
  • aVariable.var reads the value assigned to the var directives var input.

C#: Dynamic runtime cast

Alternatively:

public static T Cast<T>(this dynamic obj) where T:class
{
   return obj as T;
}

Javascript - remove an array item by value

var id_tag = [1,2,3,78,5,6,7,8,47,34,90]; 
var delete_where_id_tag = 90
    id_tag =id_tag.filter((x)=> x!=delete_where_id_tag); 

SQL: How To Select Earliest Row

SELECT company
   , workflow
   , MIN(date)
FROM workflowTable
GROUP BY company
       , workflow

Clearing Magento Log Data

Try:

TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;

You can also refer to following tutorial:
http://www.crucialwebhost.com/kb/article/log-cache-maintenance-script/

Thanks

Get Absolute URL from Relative path (refactored method)

check the following code to retrieve absolute Url :

Page.Request.Url.AbsoluteUri

I hope to be useful.

How to change the background color of a UIButton while it's highlighted?

UIButton extension with Swift 3+ syntax:

extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControlState) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.setBackgroundImage(colorImage, for: forState)
    }}

Use it like:

YourButton.setBackgroundColor(color: UIColor.white, forState: .highlighted)

Original Answer: https://stackoverflow.com/a/30604658/3659227

Meaning of = delete after function declaration

New C++0x standard. Please see section 8.4.3 in the N3242 working draft

System.Collections.Generic.List does not contain a definition for 'Select'

I had this issue , When calling Generic.List like:

mylist.Select( selectFunc )

Where selectFunc is defined as Expression<Func<T, List<string>>>. Simply changed "mylist" to be a IQuerable instead of List then it allowed me to use .Select.

Border around each cell in a range

I have a set of 15 subroutines I add to every Coded Excel Workbook I create and this is one of them. The following routine clears the area and creates a border.

Sample Call:

Call BoxIt(Range("A1:z25"))

Subroutine:

Sub BoxIt(aRng As Range)
On Error Resume Next

    With aRng

        'Clear existing
        .Borders.LineStyle = xlNone

        'Apply new borders
        .BorderAround xlContinuous, xlThick, 0
        With .Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
        With .Borders(xlInsideHorizontal)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
    End With

End Sub

Radio Buttons "Checked" Attribute Not Working

You're using non-standard xhtml code (values should be framed with double quotes, not single quotes)

Try this:

<form>
  <label>Do you want to accept American Express?</label>
  Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />  
  No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>

Callback to a Fragment from a DialogFragment

I solved this in an elegant way with RxAndroid. Receive an observer in the constructor of the DialogFragment and suscribe to observable and push the value when the callback being called. Then, in your Fragment create an inner class of the Observer, create an instance and pass it in the constructor of the DialogFragment. I used WeakReference in the observer to avoid memory leaks. Here is the code:

BaseDialogFragment.java

import java.lang.ref.WeakReference;

import io.reactivex.Observer;

public class BaseDialogFragment<O> extends DialogFragment {

    protected WeakReference<Observer<O>> observerRef;

    protected BaseDialogFragment(Observer<O> observer) {
        this.observerRef = new WeakReference<>(observer);
   }

    protected Observer<O> getObserver() {
    return observerRef.get();
    }
}

DatePickerFragment.java

public class DatePickerFragment extends BaseDialogFragment<Integer>
    implements DatePickerDialog.OnDateSetListener {


public DatePickerFragment(Observer<Integer> observer) {
    super(observer);
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
}

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        if (getObserver() != null) {
            Observable.just(month).subscribe(getObserver());
        }
    }
}

MyFragment.java

//Show the dialog fragment when the button is clicked
@OnClick(R.id.btn_date)
void onDateClick() {
    DialogFragment newFragment = new DatePickerFragment(new OnDateSelectedObserver());
    newFragment.show(getFragmentManager(), "datePicker");
}
 //Observer inner class
 private class OnDateSelectedObserver implements Observer<Integer> {

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(Integer integer) {
       //Here you invoke the logic

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
}

You can see the source code here: https://github.com/andresuarezz26/carpoolingapp

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

How to create a printable Twitter-Bootstrap page

There's a section of @media print code in the css file (Bootstrap 3.3.1 [UPDATE:] to 3.3.5), this strips virtually all the styling, so you get fairly bland print-outs even when it is working.

For now I've had to resort to stripping out the @media print section from bootstrap.css - which I'm really not happy about but my users want direct screen-grabs so this'll have to do for now. If anyone knows how to suppress it without changes to the bootstrap files I'd be very interested.

Here's the 'offending' code block, starts at line #192:

@media print {
  *,
  *:before,enter code here
  *:after {
    color: #000 !important;
    text-shadow: none !important;
    background: transparent !important;
    -webkit-box-shadow: none !important;
            box-shadow: none !important;
  }
  a,
  a:visited {
    text-decoration: underline;
  }
  a[href]:after {
    content: " (" attr(href) ")";
  }
  abbr[title]:after {
    content: " (" attr(title) ")";
  }
  a[href^="#"]:after,
  a[href^="javascript:"]:after {
    content: "";
  }
  pre,
  blockquote {
    border: 1px solid #999;

    page-break-inside: avoid;
  }
  thead {
    display: table-header-group;
  }
  tr,
  img {
    page-break-inside: avoid;
  }
  img {
    max-width: 100% !important;
  }
  p,
  h2,
  h3 {
    orphans: 3;
    widows: 3;
  }
  h2,
  h3 {
    page-break-after: avoid;
  }
  select {
    background: #fff !important;
  }
  .navbar {
    display: none;
  }
  .btn > .caret,
  .dropup > .btn > .caret {
    border-top-color: #000 !important;
  }
  .label {
    border: 1px solid #000;
  }
  .table {
    border-collapse: collapse !important;
  }
  .table td,
  .table th {
    background-color: #fff !important;
  }
  .table-bordered th,
  .table-bordered td {
    border: 1px solid #ddd !important;
  }
}

AngularJs - ng-model in a SELECT

You can also put the item with the default value selected out of the ng-repeat like follow :

<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
        <option value="yourDefaultValue">Default one</option>
        <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

and don't forget the value atribute if you leave it blank you will have the same issue.

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

Python: split a list based on a condition?

Problem with all proposed solutions is that it will scan and apply the filtering function twice. I'd make a simple small function like this:

def split_into_two_lists(lst, f):
    a = []
    b = []
    for elem in lst:
        if f(elem):
            a.append(elem)
        else:
            b.append(elem)
    return a, b

That way you are not processing anything twice and also are not repeating code.

CSS3 Box Shadow on Top, Left, and Right Only

use the spread value...

box-shadow has the following values

box-shadow: x y blur spread color;

so you could use something like..

box-shadow: 0px -10px 10px -10px black;

UPDATE: i'm adding a jsfiddle

Detecting when Iframe content has loaded (Cross browser)

For anyone using Ember, this should work as expected:

<iframe onLoad={{action 'actionName'}}  frameborder='0' src={{iframeSrc}} />

insert/delete/update trigger in SQL server

I agree with @Vishnu's answer. I would like to add that if you want to use the application user in your trigger you can use "context_info" to pass the info to the trigger.

I found following very helpful in doing that: http://jasondentler.com/blog/2010/01/exploiting-context_info-for-fun-and-audit

Can I export a variable to the environment from a bash script without sourcing it?

I don't think this can be done but I found a workaround using alias. It will only work when you place your script in your scripts directory, otherwise your alias will have an invalid name. The only point to the work around is to be able to have a function inside a file with the same name and not have to bother sourcing it before using it. Add the following code to ~/.bashrc:

alias myFunction='unalias myFunction && . myFunction && myFunction "$@"'

You can now call myFunction without sourcing it first.

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

For checking if the shiftkey is pressed while clicking with the mouse, there is an exact property in the click event object: shiftKey (and also for ctrl and alt and meta key): https://www.w3schools.com/jsref/event_shiftkey.asp

So using jQuery:

$('#anchor').on('click', function (e) {
    if (e.shiftKey) {
        // your code
    }
});

Eclipse HotKey: how to switch between tabs?

For some reason my Eclipse settings were corrupted so I had to manually edit the file /.plugins/org.eclipse.e4.workbench/workbench.xmi

I must have previously set Ctrl+Tab to Browser-like tab switching, and even resetting all key bindings in Eclipse preferences wouldn't get rid of the shortcuts (they were not displayed anywhere either). I opened the above mentioned file and removed the <bindings> elements marked with <tags>type:user</tags> related to the non-functioning shortcuts.

Checking Bash exit status of several commands efficiently

When I use ssh I need to distinct between problems caused by connection issues and error codes of remote command in errexit (set -e) mode. I use the following function:

# prepare environment on calling site:

rssh="ssh -o ConnectionTimeout=5 -l root $remote_ip"

function exit255 {
    local flags=$-
    set +e
    "$@"
    local status=$?
    set -$flags
    if [[ $status == 255 ]]
    then
        exit 255
    else
        return $status
    fi
}
export -f exit255

# callee:

set -e
set -o pipefail

[[ $rssh ]]
[[ $remote_ip ]]
[[ $( type -t exit255 ) == "function" ]]

rjournaldir="/var/log/journal"
if exit255 $rssh "[[ ! -d '$rjournaldir/' ]]"
then
    $rssh "mkdir '$rjournaldir/'"
fi
rconf="/etc/systemd/journald.conf"
if [[ $( $rssh "grep '#Storage=auto' '$rconf'" ) ]]
then
    $rssh "sed -i 's/#Storage=auto/Storage=persistent/' '$rconf'"
fi
$rssh systemctl reenable systemd-journald.service
$rssh systemctl is-enabled systemd-journald.service
$rssh systemctl restart systemd-journald.service
sleep 1
$rssh systemctl status systemd-journald.service
$rssh systemctl is-active systemd-journald.service

Regular Expression Validation For Indian Phone Number and Mobile number

All Landline Numbers and Mobile Number

^[\d]{2,4}[- ]?[\d]{3}[- ]?[\d]{3,5}|([0])?(\+\d{1,2}[- ]?)?[789]{1}\d{9}$

Selenium WebDriver and DropDown Boxes

public static void mulptiTransfer(WebDriver driver, By dropdownID, String text, By to)
{   
    String valuetext = null;
    WebElement element = locateElement(driver, dropdownID, 10);
    Select select = new Select(element);
    List<WebElement> options = element.findElements(By.tagName("option"));
    for (WebElement value: options) 
    {
        valuetext = value.getText();
        if (valuetext.equalsIgnoreCase(text))
        {
            try
            {
                select.selectByVisibleText(valuetext);
                locateElement(driver, to, 5).click();                           
                break;
            }
            catch (Exception e)
            {
                System.out.println(valuetext + "Value not found in Dropdown to Select");
            }       
        }
    }
}

How can moment.js be imported with typescript?

Still broken? Try uninstalling @types/moment.

So, I removed @types/moment package from the package.json file and it worked using:

import * as moment from 'moment'

Newer versions of moment don't require the @types/moment package as types are already included.

How to display raw html code in PRE or something like it but without escaping it

echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';

I think that's what you're looking for?

In other words, use htmlspecialchars() in PHP

Exception : AAPT2 error: check logs for details

Just add this line as per your compileSdkVersion

buildToolsVersion "27.0.3"

Update Build Tools Version

What is the "Temporary ASP.NET Files" folder for?

The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.

How does PHP 'foreach' actually work?

foreach supports iteration over three different kinds of values:

In the following, I will try to explain precisely how iteration works in different cases. By far the simplest case is Traversable objects, as for these foreach is essentially only syntax sugar for code along these lines:

foreach ($it as $k => $v) { /* ... */ }

/* translates to: */

if ($it instanceof IteratorAggregate) {
    $it = $it->getIterator();
}
for ($it->rewind(); $it->valid(); $it->next()) {
    $v = $it->current();
    $k = $it->key();
    /* ... */
}

For internal classes, actual method calls are avoided by using an internal API that essentially just mirrors the Iterator interface on the C level.

Iteration of arrays and plain objects is significantly more complicated. First of all, it should be noted that in PHP "arrays" are really ordered dictionaries and they will be traversed according to this order (which matches the insertion order as long as you didn't use something like sort). This is opposed to iterating by the natural order of the keys (how lists in other languages often work) or having no defined order at all (how dictionaries in other languages often work).

The same also applies to objects, as the object properties can be seen as another (ordered) dictionary mapping property names to their values, plus some visibility handling. In the majority of cases, the object properties are not actually stored in this rather inefficient way. However, if you start iterating over an object, the packed representation that is normally used will be converted to a real dictionary. At that point, iteration of plain objects becomes very similar to iteration of arrays (which is why I'm not discussing plain-object iteration much in here).

So far, so good. Iterating over a dictionary can't be too hard, right? The problems begin when you realize that an array/object can change during iteration. There are multiple ways this can happen:

  • If you iterate by reference using foreach ($arr as &$v) then $arr is turned into a reference and you can change it during iteration.
  • In PHP 5 the same applies even if you iterate by value, but the array was a reference beforehand: $ref =& $arr; foreach ($ref as $v)
  • Objects have by-handle passing semantics, which for most practical purposes means that they behave like references. So objects can always be changed during iteration.

The problem with allowing modifications during iteration is the case where the element you are currently on is removed. Say you use a pointer to keep track of which array element you are currently at. If this element is now freed, you are left with a dangling pointer (usually resulting in a segfault).

There are different ways of solving this issue. PHP 5 and PHP 7 differ significantly in this regard and I'll describe both behaviors in the following. The summary is that PHP 5's approach was rather dumb and lead to all kinds of weird edge-case issues, while PHP 7's more involved approach results in more predictable and consistent behavior.

As a last preliminary, it should be noted that PHP uses reference counting and copy-on-write to manage memory. This means that if you "copy" a value, you actually just reuse the old value and increment its reference count (refcount). Only once you perform some kind of modification a real copy (called a "duplication") will be done. See You're being lied to for a more extensive introduction on this topic.

PHP 5

Internal array pointer and HashPointer

Arrays in PHP 5 have one dedicated "internal array pointer" (IAP), which properly supports modifications: Whenever an element is removed, there will be a check whether the IAP points to this element. If it does, it is advanced to the next element instead.

While foreach does make use of the IAP, there is an additional complication: There is only one IAP, but one array can be part of multiple foreach loops:

// Using by-ref iteration here to make sure that it's really
// the same array in both loops and not a copy
foreach ($arr as &$v1) {
    foreach ($arr as &$v) {
        // ...
    }
}

To support two simultaneous loops with only one internal array pointer, foreach performs the following shenanigans: Before the loop body is executed, foreach will back up a pointer to the current element and its hash into a per-foreach HashPointer. After the loop body runs, the IAP will be set back to this element if it still exists. If however the element has been removed, we'll just use wherever the IAP is currently at. This scheme mostly-kinda-sort of works, but there's a lot of weird behavior you can get out of it, some of which I'll demonstrate below.

Array duplication

The IAP is a visible feature of an array (exposed through the current family of functions), as such changes to the IAP count as modifications under copy-on-write semantics. This, unfortunately, means that foreach is in many cases forced to duplicate the array it is iterating over. The precise conditions are:

  1. The array is not a reference (is_ref=0). If it's a reference, then changes to it are supposed to propagate, so it should not be duplicated.
  2. The array has refcount>1. If refcount is 1, then the array is not shared and we're free to modify it directly.

If the array is not duplicated (is_ref=0, refcount=1), then only its refcount will be incremented (*). Additionally, if foreach by reference is used, then the (potentially duplicated) array will be turned into a reference.

Consider this code as an example where duplication occurs:

function iterate($arr) {
    foreach ($arr as $v) {}
}

$outerArr = [0, 1, 2, 3, 4];
iterate($outerArr);

Here, $arr will be duplicated to prevent IAP changes on $arr from leaking to $outerArr. In terms of the conditions above, the array is not a reference (is_ref=0) and is used in two places (refcount=2). This requirement is unfortunate and an artifact of the suboptimal implementation (there is no concern of modification during iteration here, so we don't really need to use the IAP in the first place).

(*) Incrementing the refcount here sounds innocuous, but violates copy-on-write (COW) semantics: This means that we are going to modify the IAP of a refcount=2 array, while COW dictates that modifications can only be performed on refcount=1 values. This violation results in user-visible behavior change (while a COW is normally transparent) because the IAP change on the iterated array will be observable -- but only until the first non-IAP modification on the array. Instead, the three "valid" options would have been a) to always duplicate, b) do not increment the refcount and thus allowing the iterated array to be arbitrarily modified in the loop or c) don't use the IAP at all (the PHP 7 solution).

Position advancement order

There is one last implementation detail that you have to be aware of to properly understand the code samples below. The "normal" way of looping through some data structure would look something like this in pseudocode:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    code();
    move_forward(arr);
}

However foreach, being a rather special snowflake, chooses to do things slightly differently:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    move_forward(arr);
    code();
}

Namely, the array pointer is already moved forward before the loop body runs. This means that while the loop body is working on element $i, the IAP is already at element $i+1. This is the reason why code samples showing modification during iteration will always unset the next element, rather than the current one.

Examples: Your test cases

The three aspects described above should provide you with a mostly complete impression of the idiosyncrasies of the foreach implementation and we can move on to discuss some examples.

The behavior of your test cases is simple to explain at this point:

  • In test cases 1 and 2 $array starts off with refcount=1, so it will not be duplicated by foreach: Only the refcount is incremented. When the loop body subsequently modifies the array (which has refcount=2 at that point), the duplication will occur at that point. Foreach will continue working on an unmodified copy of $array.

  • In test case 3, once again the array is not duplicated, thus foreach will be modifying the IAP of the $array variable. At the end of the iteration, the IAP is NULL (meaning iteration has done), which each indicates by returning false.

  • In test cases 4 and 5 both each and reset are by-reference functions. The $array has a refcount=2 when it is passed to them, so it has to be duplicated. As such foreach will be working on a separate array again.

Examples: Effects of current in foreach

A good way to show the various duplication behaviors is to observe the behavior of the current() function inside a foreach loop. Consider this example:

foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 2 2 2 2 */

Here you should know that current() is a by-ref function (actually: prefer-ref), even though it does not modify the array. It has to be in order to play nice with all the other functions like next which are all by-ref. By-reference passing implies that the array has to be separated and thus $array and the foreach-array will be different. The reason you get 2 instead of 1 is also mentioned above: foreach advances the array pointer before running the user code, not after. So even though the code is at the first element, foreach already advanced the pointer to the second.

Now lets try a small modification:

$ref = &$array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here we have the is_ref=1 case, so the array is not copied (just like above). But now that it is a reference, the array no longer has to be duplicated when passing to the by-ref current() function. Thus current() and foreach work on the same array. You still see the off-by-one behavior though, due to the way foreach advances the pointer.

You get the same behavior when doing by-ref iteration:

foreach ($array as &$val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here the important part is that foreach will make $array an is_ref=1 when it is iterated by reference, so basically you have the same situation as above.

Another small variation, this time we'll assign the array to another variable:

$foo = $array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 1 1 1 1 1 */

Here the refcount of the $array is 2 when the loop is started, so for once we actually have to do the duplication upfront. Thus $array and the array used by foreach will be completely separate from the outset. That's why you get the position of the IAP wherever it was before the loop (in this case it was at the first position).

Examples: Modification during iteration

Trying to account for modifications during iteration is where all our foreach troubles originated, so it serves to consider some examples for this case.

Consider these nested loops over the same array (where by-ref iteration is used to make sure it really is the same one):

foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Output: (1, 1) (1, 3) (1, 4) (1, 5)

The expected part here is that (1, 2) is missing from the output because element 1 was removed. What's probably unexpected is that the outer loop stops after the first element. Why is that?

The reason behind this is the nested-loop hack described above: Before the loop body runs, the current IAP position and hash is backed up into a HashPointer. After the loop body it will be restored, but only if the element still exists, otherwise the current IAP position (whatever it may be) is used instead. In the example above this is exactly the case: The current element of the outer loop has been removed, so it will use the IAP, which has already been marked as finished by the inner loop!

Another consequence of the HashPointer backup+restore mechanism is that changes to the IAP through reset() etc. usually do not impact foreach. For example, the following code executes as if the reset() were not present at all:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
    var_dump($value);
    reset($array);
}
// output: 1, 2, 3, 4, 5

The reason is that, while reset() temporarily modifies the IAP, it will be restored to the current foreach element after the loop body. To force reset() to make an effect on the loop, you have to additionally remove the current element, so that the backup/restore mechanism fails:

$array = [1, 2, 3, 4, 5];
$ref =& $array;
foreach ($array as $value) {
    var_dump($value);
    unset($array[1]);
    reset($array);
}
// output: 1, 1, 3, 4, 5

But, those examples are still sane. The real fun starts if you remember that the HashPointer restore uses a pointer to the element and its hash to determine whether it still exists. But: Hashes have collisions, and pointers can be reused! This means that, with a careful choice of array keys, we can make foreach believe that an element that has been removed still exists, so it will jump directly to it. An example:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
$ref =& $array;
foreach ($array as $value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    reset($array);
    var_dump($value);
}
// output: 1, 4

Here we should normally expect the output 1, 1, 3, 4 according to the previous rules. How what happens is that 'FYFY' has the same hash as the removed element 'EzFY', and the allocator happens to reuse the same memory location to store the element. So foreach ends up directly jumping to the newly inserted element, thus short-cutting the loop.

Substituting the iterated entity during the loop

One last odd case that I'd like to mention, it is that PHP allows you to substitute the iterated entity during the loop. So you can start iterating on one array and then replace it with another array halfway through. Or start iterating on an array and then replace it with an object:

$arr = [1, 2, 3, 4, 5];
$obj = (object) [6, 7, 8, 9, 10];

$ref =& $arr;
foreach ($ref as $val) {
    echo "$val\n";
    if ($val == 3) {
        $ref = $obj;
    }
}
/* Output: 1 2 3 6 7 8 9 10 */

As you can see in this case PHP will just start iterating the other entity from the start once the substitution has happened.

PHP 7

Hashtable iterators

If you still remember, the main problem with array iteration was how to handle removal of elements mid-iteration. PHP 5 used a single internal array pointer (IAP) for this purpose, which was somewhat suboptimal, as one array pointer had to be stretched to support multiple simultaneous foreach loops and interaction with reset() etc. on top of that.

PHP 7 uses a different approach, namely, it supports creating an arbitrary amount of external, safe hashtable iterators. These iterators have to be registered in the array, from which point on they have the same semantics as the IAP: If an array element is removed, all hashtable iterators pointing to that element will be advanced to the next element.

This means that foreach will no longer use the IAP at all. The foreach loop will be absolutely no effect on the results of current() etc. and its own behavior will never be influenced by functions like reset() etc.

Array duplication

Another important change between PHP 5 and PHP 7 relates to array duplication. Now that the IAP is no longer used, by-value array iteration will only do a refcount increment (instead of duplication the array) in all cases. If the array is modified during the foreach loop, at that point a duplication will occur (according to copy-on-write) and foreach will keep working on the old array.

In most cases, this change is transparent and has no other effect than better performance. However, there is one occasion where it results in different behavior, namely the case where the array was a reference beforehand:

$array = [1, 2, 3, 4, 5];
$ref = &$array;
foreach ($array as $val) {
    var_dump($val);
    $array[2] = 0;
}
/* Old output: 1, 2, 0, 4, 5 */
/* New output: 1, 2, 3, 4, 5 */

Previously by-value iteration of reference-arrays was special cases. In this case, no duplication occurred, so all modifications of the array during iteration would be reflected by the loop. In PHP 7 this special case is gone: A by-value iteration of an array will always keep working on the original elements, disregarding any modifications during the loop.

This, of course, does not apply to by-reference iteration. If you iterate by-reference all modifications will be reflected by the loop. Interestingly, the same is true for by-value iteration of plain objects:

$obj = new stdClass;
$obj->foo = 1;
$obj->bar = 2;
foreach ($obj as $val) {
    var_dump($val);
    $obj->bar = 42;
}
/* Old and new output: 1, 42 */

This reflects the by-handle semantics of objects (i.e. they behave reference-like even in by-value contexts).

Examples

Let's consider a few examples, starting with your test cases:

  • Test cases 1 and 2 retain the same output: By-value array iteration always keep working on the original elements. (In this case, even refcounting and duplication behavior is exactly the same between PHP 5 and PHP 7).

  • Test case 3 changes: Foreach no longer uses the IAP, so each() is not affected by the loop. It will have the same output before and after.

  • Test cases 4 and 5 stay the same: each() and reset() will duplicate the array before changing the IAP, while foreach still uses the original array. (Not that the IAP change would have mattered, even if the array was shared.)

The second set of examples was related to the behavior of current() under different reference/refcounting configurations. This no longer makes sense, as current() is completely unaffected by the loop, so its return value always stays the same.

However, we get some interesting changes when considering modifications during iteration. I hope you will find the new behavior saner. The first example:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Old output: (1, 1) (1, 3) (1, 4) (1, 5)
// New output: (1, 1) (1, 3) (1, 4) (1, 5)
//             (3, 1) (3, 3) (3, 4) (3, 5)
//             (4, 1) (4, 3) (4, 4) (4, 5)
//             (5, 1) (5, 3) (5, 4) (5, 5) 

As you can see, the outer loop no longer aborts after the first iteration. The reason is that both loops now have entirely separate hashtable iterators, and there is no longer any cross-contamination of both loops through a shared IAP.

Another weird edge case that is fixed now, is the odd effect you get when you remove and add elements that happen to have the same hash:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
foreach ($array as &$value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    var_dump($value);
}
// Old output: 1, 4
// New output: 1, 3, 4

Previously the HashPointer restore mechanism jumped right to the new element because it "looked" like it's the same as the removed element (due to colliding hash and pointer). As we no longer rely on the element hash for anything, this is no longer an issue.

Android - get children inside a View?

Here is a suggestion: you can get the ID (specified e.g. by android:id="@+id/..My Str..) which was generated by R by using its given name (e.g. My Str). A code snippet using getIdentifier() method would then be:

public int getIdAssignedByR(Context pContext, String pIdString)
{
    // Get the Context's Resources and Package Name
    Resources resources = pContext.getResources();
    String packageName  = pContext.getPackageName();

    // Determine the result and return it
    int result = resources.getIdentifier(pIdString, "id", packageName);
    return result;
}

From within an Activity, an example usage coupled with findViewById would be:

// Get the View (e.g. a TextView) which has the Layout ID of "UserInput"
int rID = getIdAssignedByR(this, "UserInput")
TextView userTextView = (TextView) findViewById(rID);

Why doesn't TFS get latest get the latest?

It could happen when you use TFS from two different machines with the same account, if so you should compare to see changed files and check out them then get latest then undo pending changes to remove checkout

How to Convert double to int in C?

int b;
double a;
a=3669.0;
b=a;
printf("b=%d",b);

this code gives the output as b=3669 only you check it clearly.

MVC 4 Razor adding input type date

I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" })

NumPy array is not JSON serializable

use NumpyEncoder it will process json dump successfully.without throwing - NumPy array is not JSON serializable

import numpy as np
import json
from numpyencoder import NumpyEncoder
arr = array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64) 
json.dumps(arr,cls=NumpyEncoder)

Splitting a C++ std::string using tokens, e.g. ";"

You could use a string stream and read the elements into the vector.

Here are many different examples...

A copy of one of the examples:

std::vector<std::string> split(const std::string& s, char seperator)
{
   std::vector<std::string> output;

    std::string::size_type prev_pos = 0, pos = 0;

    while((pos = s.find(seperator, pos)) != std::string::npos)
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );

        output.push_back(substring);

        prev_pos = ++pos;
    }

    output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word

    return output;
}

What is the best open XML parser for C++?

I like the Gnome xml parser. It's open source (MIT License, so you can use it in commercial products), fast and has DOM and SAX based interfaces.

http://xmlsoft.org/

How to read Data from Excel sheet in selenium webdriver

i have used following method to use input data from excel sheet: Need to import following as well

import jxl.Workbook;

then

Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0); 
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();

it will Work

Create folder in Android

If you are trying to make more than just one folder on the root of the sdcard, ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"

then instead of folder.mkdir() you would use folder.mkdirs()

I've made this mistake in the past & I took forever to figure it out.

How to count the number of files in a directory using Python

While I agree with the answer provided by @DanielStutzbach: os.listdir() will be slightly more efficient than using glob.glob.

However, an extra precision, if you do want to count the number of specific files in folder, you want to use len(glob.glob()). For instance if you were to count all the pdfs in a folder you want to use:

pdfCounter = len(glob.glob1(myPath,"*.pdf"))

jQuery serialize does not register checkboxes

You Can Get inputs value with jquery serialize

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id="event_allDay" name="event_allDay" checked="checked" onchange="isChecked(this)" value="" />_x000D_
<script>_x000D_
    function isChecked(element) {_x000D_
        $(element).val($(element).is(':checked').toString());_x000D_
    }_x000D_
    isChecked('#event_allDay');_x000D_
</script>
_x000D_
_x000D_
_x000D_

Making the main scrollbar always visible

html {height: 101%;}

I use this cross browsers solution (note: I always use DOCTYPE declaration in 1st line, I don't know if it works in quirksmode, never tested it).

This will always show an ACTIVE vertical scroll bar in every page, vertical scrollbar will be scrollable only of few pixels.

When page contents is shorter than browser's visible area (view port) you will still see the vertical scrollbar active, and it will be scrollable only of few pixels.

In case you are obsessed with CSS validation (I'm obesessed only with HTML validation) by using this solution your CSS code would also validate for W3C because you are not using non standard CSS attributes like -moz-scrollbars-vertical

ExecuteNonQuery doesn't return results

The ExecuteNonQuery method is used for SQL statements that are not queries, such as INSERT, UPDATE, ... You want to use ExecuteScalar or ExecuteReader if you expect your statement to return results (i.e. a query).

What is the best way to left align and right align two div tags?

I used the below. The genre element will start where the DJ element ends,

<div>
<div style="width:50%; float:left">DJ</div>
<div>genre</div>
</div>

pardon the inline css.

Java: Check if command line arguments are null

if i want to check if any speicfic position of command line arguement is passed or not then how to check? like for example in some scenarios 2 command line args will be passed and in some only one will be passed then how do it check wheather the specfic commnad line is passed or not?

public class check {

public static void main(String[] args) {
if(args[0].length()!=0)
{
System.out.println("entered first if");
}
if(args[0].length()!=0 && args[1].length()!=0)
{
System.out.println("entered second if");
}
}
}

So in the above code if args[1] is not passed then i get java.lang.ArrayIndexOutOfBoundsException:

so how do i tackle this where i can check if second arguement is passed or not and if passed then enter it. need assistance asap.

How to make a Qt Widget grow with the window size?

You need to change the default layout type of top level QWidget object from Break layout type to other layout types (Vertical Layout, Horizontal Layout, Grid Layout, Form Layout). For example: enter image description here

To something like this:

enter image description here

HTML5 form validation pattern alphanumeric with spaces?

To avoid an input with only spaces, use: "[a-zA-Z0-9]+[a-zA-Z0-9 ]+".

eg: abc | abc aBc | abc 123 AbC 938234

To ensure, for example, that a first AND last name are entered, use a slight variation like

"[a-zA-Z]+[ ][a-zA-Z]+"

eg: abc def

What's the best way of scraping data from a website?

You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.

Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.

Tools

Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.

You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.

Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.

Language

PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.

A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.

Javascript-heavy sites

In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.

There are two approaches to this problem:

The low level approach:

You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.

The embedded browser approach:

Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.

If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.

You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.

Which approach is best?

That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.

The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.

Rate Limiting/Bot behaviour

You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.

Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.

You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.

Testing

Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.

There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.

The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.

You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.

Legal Issues

The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.

The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.

It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.

Who am I to write this giant wall of text anyway?

I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.

I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)

I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.

I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi
EOF

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    #!/bin/bash
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
    else
      exit 1
    fi
EOF

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

Ring Buffer in Java

Since Guava 15.0 (released September 2013) there's EvictingQueue:

A non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full. An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element. This is different from conventional bounded queues, which either block or reject new elements when full.

This class is not thread-safe, and does not accept null elements.

Example use:

EvictingQueue<String> queue = EvictingQueue.create(2);
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
System.out.print(queue); //outputs [c, d]

How do I make a transparent border with CSS?

Yep, you can use border: 1px solid transparent

Another solution is to use outline on hover (and set the border to 0) which doesn't affect the document flow:

li{
    display:inline-block;
    padding:5px;
    border:0;
}
li:hover{
    outline:1px solid #FC0;
}

NB. You can only set the outline as a sharthand property, not for individual sides. It's only meant to be used for debugging but it works nicely.

.append(), prepend(), .after() and .before()

There is no extra advantage for each of them. It totally depends on your scenario. Code below shows their difference.

    Before inserts your html here
<div id="mainTabsDiv">
    Prepend inserts your html here
    <div id="homeTabDiv">
        <span>
            Home
        </span>
    </div>
    <div id="aboutUsTabDiv">
        <span>
            About Us
        </span>
    </div>
    <div id="contactUsTabDiv">
        <span>
            Contact Us
        </span>
    </div>
    Append inserts your html here
</div>
After inserts your html here

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue = obj.srcElement.attributes.data.nodeValue;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue = obj.currentTarget.attributes.data.nodeValue;

Works in IE, Chrome and FF, I did not test Safari.

Can't ignore UserInterfaceState.xcuserstate

All Answer is great but here is the one will remove for every user if you work in different Mac (Home and office)

git rm --cache */UserInterfaceState.xcuserstate
git commit -m "Never see you again, UserInterfaceState"

Search for value in DataGridView in a column

It's better also to separate your logic in another method, or maybe in another class.

This method will help you retreive the DataGridViewCell object in which the text was found.

    /// <summary>
    /// Check if a given text exists in the given DataGridView at a given column index
    /// </summary>
    /// <param name="searchText"></param>
    /// <param name="dataGridView"></param>
    /// <param name="columnIndex"></param>
    /// <returns>The cell in which the searchText was found</returns>
    private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
    {
        DataGridViewCell cellWhereTextIsMet = null;

        // For every row in the grid (obviously)
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            // I did not test this case, but cell.Value is an object, and objects can be null
            // So check if the cell is null before using .ToString()
            if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
            {
                // the searchText is equals to the text in this cell.
                cellWhereTextIsMet = row.Cells[columnIndex];
                break;
            }
        }

        return cellWhereTextIsMet;
    }

    private void button_click(object sender, EventArgs e)
    {
        DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
        if (cell != null)
        {
            // Value exists in the grid
            // you can do extra stuff on the cell
            cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
        }
        else
        {
            // Value does not exist in the grid
        }
    }

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

If you don't want to use a separate JS library to create a custom control for that, you could use two confirm dialogs to do the checks:

if (confirm("Are you sure you want to quit?") ) {
    if (confirm("Save your work before leaving?") ) {
        // code here for save then leave (Yes)
    } else {
        //code here for no save but leave (No)
    }
} else {
    //code here for don't leave (Cancel)
}

Div side by side without float

You can try with margin for right div

margin: -200px 0 0 350px;

HSL to RGB color conversion

Shortest but precise - JS

Use this JS code (more: rgb2hsl, hsv2rgb rgb2hsv and hsl2hsv) - php here

// input: h in [0,360] and s,v in [0,1] - output: r,g,b in [0,1]
function hsl2rgb(h,s,l) 
{
  let a=s*Math.min(l,1-l);
  let f= (n,k=(n+h/30)%12) => l - a*Math.max(Math.min(k-3,9-k,1),-1);                 
  return [f(0),f(8),f(4)];
}   

_x000D_
_x000D_
// oneliner version
let hsl2rgb = (h,s,l, a=s*Math.min(l,1-l), f= (n,k=(n+h/30)%12) => l - a*Math.max(Math.min(k-3,9-k,1),-1)) => [f(0),f(8),f(4)];

// r,g,b are in [0-1], result e.g. #0812fa.
let rgb2hex = (r,g,b) => "#" + [r,g,b].map(x=>Math.round(x*255).toString(16).padStart(2,0) ).join('');


console.log(`hsl: (30,0.2,0.3) --> rgb: (${hsl2rgb(30,0.2,0.3)}) --> hex: ${rgb2hex(...hsl2rgb(30,0.2,0.3))}`);



// ---------------
// UX
// ---------------

rgb= [0,0,0];
hs= [0,0,0];

let $ = x => document.querySelector(x);

function changeRGB(i,e) {
  rgb[i]=e.target.value/255;
  hs = rgb2hsl(...rgb);
  refresh();
}

function changeHS(i,e) {
  hs[i]=e.target.value/(i?255:1);
  rgb= hsl2rgb(...hs);
  refresh();
}

function refresh() {
  rr = rgb.map(x=>x*255|0).join(', ')
  hh = rgb2hex(...rgb);
  tr = `RGB: ${rr}`
  th = `HSL: ${hs.map((x,i)=>i? (x*100).toFixed(2)+'%':x|0).join(', ')}`
  thh= `HEX: ${hh}`
  $('.box').style.backgroundColor=`rgb(${rr})`;  
  $('.infoRGB').innerHTML=`${tr}`;  
  $('.infoHS').innerHTML =`${th}\n${thh}`;  
  
  $('#r').value=rgb[0]*255;
  $('#g').value=rgb[1]*255;
  $('#b').value=rgb[2]*255;
  
  $('#h').value=hs[0];
  $('#s').value=hs[1]*255;
  $('#l').value=hs[2]*255;  
}

function rgb2hsl(r,g,b) {
  let a=Math.max(r,g,b), n=a-Math.min(r,g,b), f=(1-Math.abs(a+a-n-1)); 
  let h= n && ((a==r) ? (g-b)/n : ((a==g) ? 2+(b-r)/n : 4+(r-g)/n)); 
  return [60*(h<0?h+6:h), f ? n/f : 0, (a+a-n)/2];
}

refresh();
_x000D_
.box {
  width: 50px;
  height: 50px;
  margin: 20px;
}

body {
    display: flex;
}
_x000D_
<div>
<input id="r" type="range" min="0" max="255" oninput="changeRGB(0,event)">R<br>
<input id="g" type="range" min="0" max="255" oninput="changeRGB(1,event)">G<br>
<input id="b" type="range" min="0" max="255" oninput="changeRGB(2,event)">B<br>
<pre class="infoRGB"></pre>
</div> 

<div>
<div class="box hsl"></div>

</div>

<div>
<input id="h" type="range" min="0" max="360" oninput="changeHS(0,event)">H<br>
<input id="s" type="range" min="0" max="255" oninput="changeHS(1,event)">S<br>
<input id="l" type="range" min="0" max="255" oninput="changeHS(2,event)">L<br>
<pre class="infoHS"></pre><br>
</div>
_x000D_
_x000D_
_x000D_

Here is formula which I discover and precisely describe in wiki + error analysis,

enter image description here

Is an empty href valid?

While it may be completely valid HTML to not include an href, especially with an onclick handler, there are some things to consider: it will not be keyboard-focusable without having a tabindex value set. Furthermore, this will be inaccessible to screenreader software using Internet Explorer, as IE will report through the accessibility interfaces that any anchor element without an href attribute as not-focusable, regardless of whether the tabindex has been set.

So while the following may be completely valid:

<a class="arrow">Link content</a>

It's far better to explicitly add a null-effect href attribute

<a href="javascript:void(0);" class="arrow">Link content</a>

For full support of all users, if you're using the class with CSS to render an image, you should also include some text content, such as the title attribute to provide a textual description of what's going on.

<a href="javascript:void(0);" class="arrow" title="Go to linked content">Link content</a>

Check whether an input string contains a number in javascript

We can check it by using !/[^a-zA-Z]/.test(e)
Just run snippet and check.

_x000D_
_x000D_
function handleValueChange() {
  if (!/[^a-zA-Z]/.test(document.getElementById('textbox_id').value)) {
      var x = document.getElementById('result');
      x.innerHTML = 'String does not contain number';
  } else {
    var x = document.getElementById('result');
    x.innerHTML = 'String does contains number';
  }
}
_x000D_
input {
  padding: 5px;
}
_x000D_
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
_x000D_
_x000D_
_x000D_

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

Creating multiline strings in JavaScript

The equivalent in javascript is:

var text = `
This
Is
A
Multiline
String
`;

Here's the specification. See browser support at the bottom of this page. Here are some examples too.

ZIP file content type for HTTP request

If you want the MIME type for a file, you can use the following code:

- (NSString *)mimeTypeForPath:(NSString *)path
{
    // get a mime type for an extension using MobileCoreServices.framework

    CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
    assert(UTI != NULL);

    NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
    assert(mimetype != NULL);

    CFRelease(UTI);

    return mimetype;
}

In the case of a ZIP file, this will return application/zip.

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Input widths on Bootstrap 3

If you're looking to simply reduce or increase the width of Bootstrap's input elements to your liking, I would use max-width in the CSS.

Here is a very simple example I created:

    <form style="max-width:500px">

    <div class="form-group"> 
    <input type="text" class="form-control" id="name" placeholder="Name">
    </div>

    <div class="form-group">
    <input type="email" class="form-control" id="email" placeholder="Email Address">
    </div>

    <div class="form-group">
    <textarea class="form-control" rows="5" placeholder="Message"></textarea>
    </div>   

    <button type="submit" class="btn btn-primary">Submit</button>
    </form>

I've set the whole form's maximum width to 500px. This way you won't need to use any of Bootstrap's grid system and it will also keep the form responsive.

How can I use goto in Javascript?

Generally, I'd prefer not using GoTo for bad readability. To me, it's a bad excuse for programming simple iterative functions instead of having to program recursive functions, or even better (if things like a Stack Overflow is feared), their true iterative alternatives (which may sometimes be complex).

Something like this would do:

while(true) {
   alert("RINSE");
   alert("LATHER");
}

That right there is an infinite loop. The expression ("true") inside the parantheses of the while clause is what the Javascript engine will check for - and if the expression is true, it'll keep the loop running. Writing "true" here always evaluates to true, hence an infinite loop.

Select columns based on string match - dplyr::select

Within the dplyr world, try:

select(iris,contains("Sepal"))

See the Selection section in ?select for numerous other helpers like starts_with, ends_with, etc.

Vertically aligning CSS :before and :after content

You can also use tables to accomplish this, like:

.pdf {
  display: table;
}
.pdf:before {
  display: table-cell;
  vertical-align: middle;
}

Here is an example: https://jsfiddle.net/ar9fadd0/2/

EDIT: You can also use flex to accomplish this:

.pdf {
  display: flex;
}
.pdf:before {
  display: flex;
  align-items: center;
}

Here is an example: https://jsfiddle.net/ctqk0xq1/1/

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

It works for me...

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
    {
    $certCallback = @"
        using System;
        using System.Net;
        using System.Net.Security;
        using System.Security.Cryptography.X509Certificates;
        public class ServerCertificateValidationCallback
        {
            public static void Ignore()
            {
                if(ServicePointManager.ServerCertificateValidationCallback ==null)
                {
                    ServicePointManager.ServerCertificateValidationCallback += 
                        delegate
                        (
                            Object obj, 
                            X509Certificate certificate, 
                            X509Chain chain, 
                            SslPolicyErrors errors
                        )
                        {
                            return true;
                        };
                }
            }
        }
    "@
        Add-Type $certCallback
     }
    [ServerCertificateValidationCallback]::Ignore()

Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

How to compare times in Python?

You Can Use Timedelta fuction for x time increase comparision.

>>> import datetime 

>>> now = datetime.datetime.now()
>>> after_10_min = now + datetime.timedelta(minutes = 10)
>>> now > after_10_min 

False

Just A combination of these answers this And Roger

Pyinstaller setting icons don't change

I had similar problem. If no errors from pyinstaller try to change name of .exe file. It works for me

Show only two digit after decimal

First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.

And other aspect is providing proper result. So you want to truncate the number or round it.

So before you start you should ask your self, am i interested on the value or not.

To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

How to create PDF files in Python

I suggest Pdfkit. (installation guide)

It creates pdf from html files. I chose it to create pdf in 2 steps from my Python Pyramid stack:

  1. Rendering server-side with mako templates with the style and markup you want for you pdf document
  2. Executing pdfkit.from_string(...) method by passing the rendered html as parameter

This way you get a pdf document with styling and images supported.

You can install it as follows :

  • using pip

    pip install pdfkit

  • You will also need to install wkhtmltopdf (on Ubuntu).

Reset push notification settings for app

As ianolito said, setting the date should work:

You can achieve the latter without actually waiting a day by setting the system clock forward a day or more, turning the device off completely, then turning the device back on.

I noticed on my device (iPhone 4, iOS 6.1.2) setting the system clock a day forward or even a few days did not work for me. So I set the date forward a month and then it did work and my application showed the notifications prompt again.

Hope this helps for anyone, it can be kind of head aching!

Combination of async function + await + setTimeout

Made a util inspired from Dave's answer

Basically passed in a done callback to call when the operation is finished.

// Function to timeout if a request is taking too long
const setAsyncTimeout = (cb, timeout = 0) => new Promise((resolve, reject) => {
  cb(resolve);
  setTimeout(() => reject('Request is taking too long to response'), timeout);
});

This is how I use it:

try {
  await setAsyncTimeout(async done => {
    const requestOne = await someService.post(configs);
    const requestTwo = await someService.get(configs);
    const requestThree = await someService.post(configs);
    done();
  }, 5000); // 5 seconds max for this set of operations
}
catch (err) {
  console.error('[Timeout] Unable to complete the operation.', err);
}

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

How set background drawable programmatically in Android

try this.

 int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
 preview = (ImageView) findViewById(R.id.preview);
 preview.setBackgroundResource(res);

R Markdown - changing font size and font type in html output

I think fontsize: command in YAML only works for LaTeX / pdf. Apart, in standard latex classes (article, book, and report) only three font sizes are accepted (10pt, 11pt, and 12pt).

Regarding appearance (different font types and colors), you can specify a theme:. See Appearance and Style.

I guess, what you are looking for is your own css. Make a file called style.css, save it in the same folder as your .Rmd and include it in the YAML header:

---
output:
  html_document:
    css: style.css
---

In the css-file you define your font-type and size:

/* Whole document: */
body{
  font-family: Helvetica;
  font-size: 16pt;
}
/* Headers */
h1,h2,h3,h4,h5,h6{
  font-size: 24pt;
}

How to apply font anti-alias effects in CSS?

Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:

body { 
    -webkit-font-smoothing: antialiased;
    text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
    background: url('./images/background.png');
    text-align: left;
    margin: auto;

}

How do I access my webcam in Python?

OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work. As of 2019, you can install both of these libraries with pip: pip install numpy pip install opencv-python

More information on using OpenCV with Python.

An example copied from Displaying webcam feed using opencv and python:

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break
cv2.destroyWindow("preview")

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

To check if a grammar is LL(1), one option is to construct the LL(1) parsing table and check for any conflicts. These conflicts can be

  • FIRST/FIRST conflicts, where two different productions would have to be predicted for a nonterminal/terminal pair.
  • FIRST/FOLLOW conflicts, where two different productions are predicted, one representing that some production should be taken and expands out to a nonzero number of symbols, and one representing that a production should be used indicating that some nonterminal should be ultimately expanded out to the empty string.
  • FOLLOW/FOLLOW conflicts, where two productions indicating that a nonterminal should ultimately be expanded to the empty string conflict with one another.

Let's try this on your grammar by building the FIRST and FOLLOW sets for each of the nonterminals. Here, we get that

FIRST(X) = {a, b, z}
FIRST(Y) = {b, epsilon}
FIRST(Z) = {epsilon} 

We also have that the FOLLOW sets are

FOLLOW(X) = {$}
FOLLOW(Y) = {z}
FOLLOW(Z) = {z}

From this, we can build the following LL(1) parsing table:

    a    b    z   $
X   a    Yz   Yz  
Y        bZ   eps
Z             eps

Since we can build this parsing table with no conflicts, the grammar is LL(1).

To check if a grammar is LR(0) or SLR(1), we begin by building up all of the LR(0) configurating sets for the grammar. In this case, assuming that X is your start symbol, we get the following:

(1)
X' -> .X
X -> .Yz
X -> .a
Y -> .
Y -> .bZ

(2)
X' -> X.

(3)
X -> Y.z

(4)
X -> Yz.

(5)
X -> a.

(6)
Y -> b.Z
Z -> .

(7)
Y -> bZ.

From this, we can see that the grammar is not LR(0) because there are shift/reduce conflicts in states (1) and (6). Specifically, because we have the reduce items Z → . and Y → ., we can't tell whether to reduce the empty string to these symbols or to shift some other symbol. More generally, no grammar with ε-productions is LR(0).

However, this grammar might be SLR(1). To see this, we augment each reduction with the lookahead set for the particular nonterminals. This gives back this set of SLR(1) configurating sets:

(1)
X' -> .X
X -> .Yz [$]
X -> .a  [$]
Y -> .   [z]
Y -> .bZ [z]

(2)
X' -> X.

(3)
X -> Y.z [$]

(4)
X -> Yz. [$]

(5)
X -> a.  [$]

(6)
Y -> b.Z [z]
Z -> .   [z]

(7)
Y -> bZ. [z]

Now, we don't have any more shift-reduce conflicts. The conflict in state (1) has been eliminated because we only reduce when the lookahead is z, which doesn't conflict with any of the other items. Similarly, the conflict in (6) is gone for the same reason.

Hope this helps!

C# catch a stack overflow exception

Yes from CLR 2.0 stack overflow is considered a non-recoverable situation. So the runtime still shut down the process.

For details please see the documentation http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

Android Linear Layout - How to Keep Element At Bottom Of View?

I think it will be perfect solution:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- Other views -->
    <Space
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <!-- Target view below -->
    <View
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

</LinearLayout>

How to export JSON from MongoDB using Robomongo

Expanding on Anish's answer, I wanted something I can apply to any query to automatically output all fields vs. having to define them within the print statement. It can probably be simplified but this was something quick & dirty that works great:

var cursor = db.getCollection('foo').find({}, {bar: 1, baz: 1, created_at: 1, updated_at: 1}).sort({created_at: -1, updated_at: -1});

while (cursor.hasNext()) {
    var record = cursor.next();
    var output = "";
    for (var i in record) {
      output += record[i] + ",";
    };
    output = output.substring(0, output.length - 1);
    print(output);
}

jQuery: get data attribute

This works for me

$('.someclass').click(function() {
    $varName = $(this).data('fulltext');
    console.log($varName);
});

Angular 2 Routing run in new tab

This directive works as a [routerLink] replacement. All you have to do is to replace your [routerLink] usages with [link]. It works with ctrl+click, cmd+click, middle click.

import {Directive, HostListener, Input} from '@angular/core'
import {Router} from '@angular/router'
import _ from 'lodash'
import qs from 'qs'

@Directive({
  selector: '[link]'
})
export class LinkDirective {
  @Input() link: string

  @HostListener('click', ['$event'])
  onClick($event) {
    // ctrl+click, cmd+click
    if ($event.ctrlKey || $event.metaKey) {
      $event.preventDefault()
      $event.stopPropagation()
      window.open(this.getUrl(this.link), '_blank')
    } else {
      this.router.navigate(this.getLink(this.link))
    }
  }

  @HostListener('mouseup', ['$event'])
  onMouseUp($event) {
    // middleclick
    if ($event.which == 2) {

      $event.preventDefault()
      $event.stopPropagation()
      window.open(this.getUrl(this.link), '_blank')
    }
  }

  constructor(private router: Router) {}

  private getLink(link): any[] {
    if ( ! _.isArray(link)) {
      link = [link]
    }

    return link
  }

  private getUrl(link): string {
    let url = ''

    if (_.isArray(link)) {
      url = link[0]

      if (link[1]) {
        url += '?' + qs.stringify(link[1])
      }
    } else {
      url = link
    }

    return url
  }
}

jQuery datepicker, onSelect won't work

It should be "datepicker", not "datePicker" if you are using the jQuery UI DatePicker plugin. Perhaps, you have a different but similar plugin that doesn't support the select handler.

git revert back to certain commit

http://www.kernel.org/pub/software/scm/git/docs/git-revert.html

using git revert <commit> will create a new commit that reverts the one you dont want to have.

You can specify a list of commits to revert.

An alternative: http://git-scm.com/docs/git-reset

git reset will reset your copy to the commit you want.

In Firebase, is there a way to get the number of children of a node without loading all the node data?

This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.

This hinges on the fact that the Firebase REST API offers a shallow=true parameter.

Assume you have a post object and each one can have a number of comments:

{
 "posts": {
  "$postKey": {
   "comments": {
     ...  
   }
  }
 }
}

You obviously don't want to fetch all of the comments, just the number of comments.

Assuming you have the key for a post, you can send a GET request to https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.

This will return an object of key-value pairs, where each key is the key of a comment and its value is true:

{
 "comment1key": true,
 "comment2key": true,
 ...,
 "comment9999key": true
}

The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).

This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.

How to convert seconds to HH:mm:ss in moment.js

How to correctly use moment.js durations? | Use moment.duration() in codes

First, you need to import moment and moment-duration-format.

import moment from 'moment';
import 'moment-duration-format';

Then, use duration function. Let us apply the above example: 28800 = 8 am.

moment.duration(28800, "seconds").format("h:mm a");

Well, you do not have above type error. Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.

The solution is to transform seconds to milliseconds and use UTC time.

moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')

All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp

const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

Trying to check if username already exists in MySQL database using PHP

change your query to like.

$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");

However, MySQL is deprecated. You should instead use MySQLi or PDO

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

How to show shadow around the linearlayout in Android?

set this xml drwable as your background;---

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- Bottom 2dp Shadow -->
<item>
    <shape android:shape="rectangle" >
        <solid android:color="#d8d8d8" />-->Your shadow color<--

        <corners android:radius="15dp" />
    </shape>
</item>

<!-- White Top color -->
<item android:bottom="3px" android:left="3px" android:right="3px" android:top="3px">-->here you can customize the shadow size<---
    <shape android:shape="rectangle" >
        <solid android:color="#FFFFFF" />

        <corners android:radius="15dp" />
    </shape>
</item>

</layer-list>

How to format JSON in notepad++

You have to use the plugin manager of Notepad++ and search for the JSON plugin. There you can easily install it.

This answer explains it pretty good: How to reformat JSON in Notepad++?

HTTP Status 404 - The requested resource (/) is not available

If options under Server Locations are grayed out, note the message in the section title: "Server must be published with no modules present". To publish the server, right click the name of the server in the Server window and select "Publish".

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

There is one more way to solve this problem. 1)Go to Project Explorer. Go to the target folder of your project, right-click and delete the target folder. 2)Right-click on your project, select run as Maven Build. 3)After you get Build Success on the console; right click on the project folder and select refresh. After performing the above steps, try to run your project.Your problem should be solved now.

How to delete the last row of data of a pandas dataframe

DF[:-n]

where n is the last number of rows to drop.

To drop the last row :

DF = DF[:-1]

Change Project Namespace in Visual Studio

Just right click on the name you want to change (this could be namespace or whatever else) and select Refactor->Rename...

Enter new name, leave location as [Global Namespace], check preview if you want and you're done!

How do I set the size of an HTML text box?

Just use:

textarea {
    width: 200px;
}

or

input[type="text"] {
    width: 200px;
}

Depending on what you mean by 'textbox'.

Can I use jQuery with Node.js?

jQuery module can be installed using:

npm install jquery

Example:

var $ = require('jquery');
var http = require('http');

var options = {
    host: 'jquery.com',
    port: 80,
    path: '/'
};

var html = '';
http.get(options, function(res) {
res.on('data', function(data) {
    // collect the data chunks to the variable named "html"
    html += data;
}).on('end', function() {
    // the whole of webpage data has been collected. parsing time!
    var title = $(html).find('title').text();
    console.log(title);
 });
});

References of jQuery in Node.js** :

How do I remove a property from a JavaScript object?

@johnstock, we can also use JavaScript's prototyping concept to add method to objects to delete any passed key available in calling object.

Above answers are appreciated.

_x000D_
_x000D_
var myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

// 1st and direct way 
delete myObject.regex; // delete myObject["regex"]
console.log(myObject); // { ircEvent: 'PRIVMSG', method: 'newURI' }

// 2 way -  by using the concept of JavaScript's prototyping concept
Object.prototype.removeFromObjectByKey = function(key) {
  // If key exists, remove it and return true
  if (this[key] !== undefined) {
    delete this[key]
    return true;
  }
  // Else return false
  return false;
}

var isRemoved = myObject.removeFromObjectByKey('method')
console.log(myObject) // { ircEvent: 'PRIVMSG' }

// More examples
var obj = {
  a: 45,
  b: 56,
  c: 67
}
console.log(obj) // { a: 45, b: 56, c: 67 }

// Remove key 'a' from obj
isRemoved = obj.removeFromObjectByKey('a')
console.log(isRemoved); //true
console.log(obj); // { b: 56, c: 67 }

// Remove key 'd' from obj which doesn't exist
var isRemoved = obj.removeFromObjectByKey('d')
console.log(isRemoved); // false
console.log(obj); // { b: 56, c: 67 }
_x000D_
_x000D_
_x000D_

When is std::weak_ptr useful?

Apart from the other already mentioned valid use cases std::weak_ptr is an awesome tool in a multithreaded environment, because

  • It doesn't own the object and so can't hinder deletion in a different thread
  • std::shared_ptr in conjunction with std::weak_ptr is safe against dangling pointers - in opposite to std::unique_ptr in conjunction with raw pointers
  • std::weak_ptr::lock() is an atomic operation (see also About thread-safety of weak_ptr)

Consider a task to load all images of a directory (~10.000) simultaneously into memory (e.g. as a thumbnail cache). Obviously the best way to do this is a control thread, which handles and manages the images, and multiple worker threads, which load the images. Now this is an easy task. Here's a very simplified implementation (join() etc is omitted, the threads would have to be handled differently in a real implementation etc)

// a simplified class to hold the thumbnail and data
struct ImageData {
  std::string path;
  std::unique_ptr<YourFavoriteImageLibData> image;
};

// a simplified reader fn
void read( std::vector<std::shared_ptr<ImageData>> imagesToLoad ) {
   for( auto& imageData : imagesToLoad )
     imageData->image = YourFavoriteImageLib::load( imageData->path );
}

// a simplified manager
class Manager {
   std::vector<std::shared_ptr<ImageData>> m_imageDatas;
   std::vector<std::unique_ptr<std::thread>> m_threads;
public:
   void load( const std::string& folderPath ) {
      std::vector<std::string> imagePaths = readFolder( folderPath );
      m_imageDatas = createImageDatas( imagePaths );
      const unsigned numThreads = std::thread::hardware_concurrency();
      std::vector<std::vector<std::shared_ptr<ImageData>>> splitDatas = 
        splitImageDatas( m_imageDatas, numThreads );
      for( auto& dataRangeToLoad : splitDatas )
        m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
   }
};

But it becomes much more complicated, if you want to interrupt the loading of the images, e.g. because the user has chosen a different directory. Or even if you want to destroy the manager.

You'd need thread communication and have to stop all loader threads, before you may change your m_imageDatas field. Otherwise the loaders would carry on loading until all images are done - even if they are already obsolete. In the simplified example, that wouldn't be too hard, but in a real environment things can be much more complicated.

The threads would probably be part of a thread pool used by multiple managers, of which some are being stopped, and some aren't etc. The simple parameter imagesToLoad would be a locked queue, into which those managers push their image requests from different control threads with the readers popping the requests - in an arbitrary order - at the other end. And so the communication becomes difficult, slow and error-prone. A very elegant way to avoid any additional communication in such cases is to use std::shared_ptr in conjunction with std::weak_ptr.

// a simplified reader fn
void read( std::vector<std::weak_ptr<ImageData>> imagesToLoad ) {
   for( auto& imageDataWeak : imagesToLoad ) {
     std::shared_ptr<ImageData> imageData = imageDataWeak.lock();
     if( !imageData )
        continue;
     imageData->image = YourFavoriteImageLib::load( imageData->path );
   }
}

// a simplified manager
class Manager {
   std::vector<std::shared_ptr<ImageData>> m_imageDatas;
   std::vector<std::unique_ptr<std::thread>> m_threads;
public:
   void load( const std::string& folderPath ) {
      std::vector<std::string> imagePaths = readFolder( folderPath );
      m_imageDatas = createImageDatas( imagePaths );
      const unsigned numThreads = std::thread::hardware_concurrency();
      std::vector<std::vector<std::weak_ptr<ImageData>>> splitDatas = 
        splitImageDatasToWeak( m_imageDatas, numThreads );
      for( auto& dataRangeToLoad : splitDatas )
        m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
   }
};

This implementation is nearly as easy as the first one, doesn't need any additional thread communication, and could be part of a thread pool/queue in a real implementation. Since the expired images are skipped, and non-expired images are processed, the threads never would have to be stopped during normal operation. You could always safely change the path or destroy your managers, since the reader fn checks, if the owning pointer isn't expired.

How to enable PHP short tags?

If you are using Ubuntu with Apache+php5, then on current versions there are 2 places where you need to change to short_open_tag = On

  1. /etc/php5/apache2/php.ini - this is for the pages loaded through your web server (Apache)
  2. /etc/php5/cli/php.ini - this configuration is used when you launch your php files from command line, like: php yourscript.php - that goes for manually or cronjob executed php files directly on the server.

.NET obfuscation tools/strategy

I tried Eziriz demo version....I liked it. But never brought the software.

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

How do I get the current date and time in PHP?

// Set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2016 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2016 is on a Saturday
echo "July 1, 2016 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2016));

/* Use the constants in the format parameter */
// Prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// Prints something like: 2016-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));

How to check if another instance of the application is running

It's not sure what you mean with 'the program', but if you want to limit your application to one instance then you can use a Mutex to make sure that your application isn't already running.

[STAThread]
static void Main()
{
    Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
    try
    {
        if (mutex.WaitOne(0, false))
        {
            // Run the application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        else
        {
            MessageBox.Show("An instance of the application is already running.");
        }
    }
    finally
    {
        if (mutex != null)
        {
            mutex.Close();
            mutex = null;
        }
    }
}

How to $http Synchronous call with AngularJS

Here's a way you can do it asynchronously and manage things like you would normally. Everything is still shared. You get a reference to the object that you want updated. Whenever you update that in your service, it gets updated globally without having to watch or return a promise. This is really nice because you can update the underlying object from within the service without ever having to rebind. Using Angular the way it's meant to be used. I think it's probably a bad idea to make $http.get/post synchronous. You'll get a noticeable delay in the script.

app.factory('AssessmentSettingsService', ['$http', function($http) {
    //assessment is what I want to keep updating
    var settings = { assessment: null };

    return {
        getSettings: function () {
             //return settings so I can keep updating assessment and the
             //reference to settings will stay in tact
             return settings;
        },
        updateAssessment: function () {
            $http.get('/assessment/api/get/' + scan.assessmentId).success(function(response) {
                //I don't have to return a thing.  I just set the object.
                settings.assessment = response;
            });
        }
    };
}]);

    ...
        controller: ['$scope', '$http', 'AssessmentSettingsService', function ($scope, as) {
            $scope.settings = as.getSettings();
            //Look.  I can even update after I've already grabbed the object
            as.updateAssessment();

And somewhere in a view:

<h1>{{settings.assessment.title}}</h1>

background:none vs background:transparent what is the difference?

There is no difference between them.

If you don't specify a value for any of the half-dozen properties that background is a shorthand for, then it is set to its default value. none and transparent are the defaults.

One explicitly sets the background-image to none and implicitly sets the background-color to transparent. The other is the other way around.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used. I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.

ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;

Which version of C# am I using

The language version is chosen based on the project's target framework by default.

Each project may use a different version of .Net framework, the best suitable C# compiler will be chosen by default by looking at the target framework. From visual studio, UI will not allow the users to changes the language version, however, we can change the language version by editing the project file with addition of new property group. But this may cause compile/run time issues in existing code.

<PropertyGroup>  
<LangVersion>8.0</LangVersion>  
</PropertyGroup>

I could see the following from Microsoft docs.

The compiler determines a default based on these rules:

Target framework  version     C# language version default
.NET Core           3.x         C# 8.0
.NET Core           2.x         C# 7.3
.NET Standard       2.1         C# 8.0
.NET Standard       2.0         C# 7.3
.NET Standard       1.x         C# 7.3
.NET Framework      all         C# 7.3

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

To show a new Form on click of a button in C#

This worked for me using it in a toolstrip menu:

 private void calculatorToolStripMenuItem_Click(object sender, EventArgs e)
 {
     calculator form = new calculator();
     form.Show(); // or form.ShowDialog(this);
 }

How can I get the source code of a Python function?

I believe that variable names aren't stored in pyc/pyd/pyo files, so you can not retrieve the exact code lines if you don't have source files.