Programs & Examples On #Fogbugz api

fs.writeFile in a promise, asynchronous-synchronous stuff

For easy to use asynchronous convert all callback to promise use some library like "bluebird" .

      .then(function(results) {
                fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("JSON saved");
                        return results;
                    }
                })


            }).catch(function(err) {
                console.log(err);
            });

Try solution with promise (bluebird)

var amazon = require('amazon-product-api');
var fs = require('fs');
var Promise = require('bluebird');

var client = amazon.createClient({
    awsId: "XXX",
    awsSecret: "XXX",
    awsTag: "888"
});


var array = fs.readFileSync('./test.txt').toString().split('\n');
Promise.map(array, function (ASIN) {
    client.itemLookup({
        domain: 'webservices.amazon.de',
        responseGroup: 'Large',
        idType: 'ASIN',
        itemId: ASIN
    }).then(function(results) {
        fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log("JSON saved");
                return results;
            }
        })
    }).catch(function(err) {
        console.log(err);
    });
});

Setting environment variable in react-native?

I think something like the following library could help you out to solve the missing bit of the puzzle, the getPlatform() function.

https://github.com/joeferraro/react-native-env

const EnvironmentManager = require('react-native-env');

// read an environment variable from React Native
EnvironmentManager.get('SOME_VARIABLE')
  .then(val => {
    console.log('value of SOME_VARIABLE is: ', val);

  })
  .catch(err => {
    console.error('womp womp: ', err.message);
  });

The only problem I see with this, that it's async code. There is a pull request to support getSync. Check it out too.

https://github.com/joeferraro/react-native-env/pull/9

Create dataframe from a matrix

I've found the following "cheat" to work very neatly and error-free

> dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
> mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
> head(mat, 2) #this returns the number of rows indicated in a data frame format
> df <- data.frame(head(mat, 2)) #"data.frame" might not be necessary

Et voila!

open read and close a file in 1 line of code

If you want that warm and fuzzy feeling just go with with.

For python 3.6 I ran these two programs under a fresh start of IDLE, giving runtimes of:

0.002000093460083008  Test A
0.0020003318786621094 Test B: with guaranteed close

So not much of a difference.

#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Test A for reading a text file line-by-line into a list
#--------*---------*---------*---------*---------*---------*---------*---------*

import sys
import time

#                                  # MAINLINE
if __name__ == '__main__':
    print("OK, starting program...")

    inTextFile = '/Users/Mike/Desktop/garbage.txt'

#                                  # Test: A: no 'with;
    c=[]
    start_time = time.time()
    c = open(inTextFile).read().splitlines()
    print("--- %s seconds ---" % (time.time() - start_time))

    print("OK, program execution has ended.")
    sys.exit()                     # END MAINLINE

OUTPUT:

OK, starting program...
--- 0.002000093460083008 seconds ---
OK, program execution has ended.

#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Test B for reading a text file line-by-line into a list
#--------*---------*---------*---------*---------*---------*---------*---------*

import sys
import time

#                                  # MAINLINE
if __name__ == '__main__':
    print("OK, starting program...")

    inTextFile = '/Users/Mike/Desktop/garbage.txt'

#                                  # Test: B: using 'with'
    c=[]
    start_time = time.time()
    with open(inTextFile) as D: c = D.read().splitlines()
    print("--- %s seconds ---" % (time.time() - start_time))

    print("OK, program execution has ended.")
    sys.exit()                     # END MAINLINE

OUTPUT:

OK, starting program...
--- 0.0020003318786621094 seconds ---
OK, program execution has ended.

Find PHP version on windows command line

Easy Method is: Just copy the file cmd.exe from c:/windows/system32/ and paste it to C:\xampp\php\ and run it, when the cmd opens type " php -v " without quotes and hit enter... you will get your php version.. thank you

Adding click event for a button created dynamically using jQuery

Just create a button element with jQuery, and add the event handler when you create it :

var div = $('<div />', {'data-role' : 'fieldcontain'}),
    btn = $('<input />', {
              type  : 'button',
              value : 'Dynamic Button',
              id    : 'btn_a',
              on    : {
                 click: function() {
                     alert ( this.value );
                 }
              }
          });

div.append(btn).appendTo( $('#pg_menu_content').empty() );

FIDDLE

How to check if a word is an English word with Python?

Using a set to store the word list because looking them up will be faster:

with open("english_words.txt") as word_file:
    english_words = set(word.strip().lower() for word in word_file)

def is_english_word(word):
    return word.lower() in english_words

print is_english_word("ham")  # should be true if you have a good english_words.txt

To answer the second part of the question, the plurals would already be in a good word list, but if you wanted to specifically exclude those from the list for some reason, you could indeed write a function to handle it. But English pluralization rules are tricky enough that I'd just include the plurals in the word list to begin with.

As to where to find English word lists, I found several just by Googling "English word list". Here is one: http://www.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt You could Google for British or American English if you want specifically one of those dialects.

jQuery Data vs Attr?

You can use data-* attribute to embed custom data. The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.

jQuery .data() method allows you to get/set data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

jQuery .attr() method get/set attribute value for only the first element in the matched set.

Example:

<span id="test" title="foo" data-kind="primary">foo</span>

$("#test").attr("title");
$("#test").attr("data-kind");
$("#test").data("kind");
$("#test").data("value", "bar");

How to compute the sum and average of elements in an array?

Just for kicks:

var elmt = [0, 1, 2,3, 4, 7, 8, 9, 10, 11], l = elmt.length, i = -1, sum = 0;
for (; ++i < l; sum += elmt[i])
    ;
document.body.appendChild(document.createTextNode('The sum of all the elements is: ' + sum + ' The average of all the elements is: ' + (sum / l)));

Why java.security.NoSuchProviderException No such provider: BC?

For those who are using web servers make sure that the bcprov-jdk16-145.jar has been installed in you servers lib, for weblogic had to put the jar in:

<weblogic_jdk_home>\jre\lib\ext

Force Java timezone as GMT/UTC

The OP answered this question to change the default timezone for a single instance of a running JVM, set the user.timezone system property:

java -Duser.timezone=GMT ... <main-class>

If you need to set specific time zones when retrieving Date/Time/Timestamp objects from a database ResultSet, use the second form of the getXXX methods that takes a Calendar object:

Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
ResultSet rs = ...;
while (rs.next()) {
    Date dateValue = rs.getDate("DateColumn", tzCal);
    // Other fields and calculations
}

Or, setting the date in a PreparedStatement:

Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
PreparedStatement ps = conn.createPreparedStatement("update ...");
ps.setDate("DateColumn", dateValue, tzCal);
// Other assignments
ps.executeUpdate();

These will ensure that the value stored in the database is consistent when the database column does not keep timezone information.

The java.util.Date and java.sql.Date classes store the actual time (milliseconds) in UTC. To format these on output to another timezone, use SimpleDateFormat. You can also associate a timezone with the value using a Calendar object:

TimeZone tz = TimeZone.getTimeZone("<local-time-zone>");
//...
Date dateValue = rs.getDate("DateColumn");
Calendar calValue = Calendar.getInstance(tz);
calValue.setTime(dateValue);

Usefull Reference

https://docs.oracle.com/javase/9/troubleshoot/time-zone-settings-jre.htm#JSTGD377

https://confluence.atlassian.com/kb/setting-the-timezone-for-the-java-environment-841187402.html

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

CSS Printing: Avoiding cut-in-half DIVs between pages?

Using break-inside should work:

@media print {
  div {
    break-inside: avoid;
  }
}

It works on all major browsers:

  • Chrome 50+
  • Edge 12+
  • Firefox 65+
  • Opera 37+
  • Safari 10+

Using page-break-inside: avoid; instead should work too, but has been exactly deprecated by break-inside: avoid.

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

d = dict.fromkeys(a, 0)

a is the list, 0 is the default value. Pay attention not to set the default value to some mutable object (i.e. list or dict), because it will be one object used as value for every key in the dictionary (check here for a solution for this case). Numbers/strings are safe.

How to restrict UITextField to take only numbers in Swift?

The following is the code I used in Swift 3.0 adapted from Mr H's code. Differences are because:

a) Delegate function declaration has changed in Swift 3.0. New declaration here

b) NSCharacterSet declaration has changed.

func textField(_ shouldChangeCharactersIntextField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{

        let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

        let components = string.components(separatedBy: inverseSet)

        let filtered = components.joined(separator: "")

        return string == filtered

}

How do I use reflection to invoke a private method?

Could you not just have a different Draw method for each type that you want to Draw? Then call the overloaded Draw method passing in the object of type itemType to be drawn.

Your question does not make it clear whether itemType genuinely refers to objects of differing types.

How do I close a tkinter window?

def quit1():
     root.destroy()

Button(root, text="Quit", command=quit1).pack()
root.mainloop()

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

Creating a JSON Array in node js

This one helped me,

res.format({
        json:function(){
                            var responseData    = {};
                            responseData['status'] = 200;
                            responseData['outputPath']  = outputDirectoryPath;
                            responseData['sourcePath']  = url;
                            responseData['message'] = 'Scraping of requested resource initiated.';
                            responseData['logfile'] = logFileName;
                            res.json(JSON.stringify(responseData));
                        }
    });

SQL Server Insert if not exists

You could use the GO command. That will restart the execution of SQL statements after an error. In my case I have a few 1000 INSERT statements, where a handful of those records already exist in the database, I just don't know which ones. I found that after processing a few 100, execution just stops with an error message that it can't INSERT as the record already exists. Quite annoying, but putting a GO solved this. It may not be the fastest solution, but speed was not my problem.

GO
INSERT INTO mytable (C1,C2,C3) VALUES(1,2,3)
GO
INSERT INTO mytable (C1,C2,C3) VALUES(4,5,6)
 etc ...

Should URL be case sensitive?

URLs should be case insensitive unless there is a good reason why they are should not be.

This is not mandatory (it is not any part of an RFC) but it makes the communication and storage of URLs far more reliable.

If I have two pages on a website:

http://stackoverflow.com/ABOUT.html

and

http://stackoverflow.com/about.html

How should they differ? Maybe one is written 'shouting style' (caps) - but from an IA point of view, the distinction should never be made by a change in the case of the URL.

Moreover, it is easy to implement this in Apache - just use CheckSpelling On from mod_Speling.

Static way to get 'Context' in Android?

I think you need a body for the getAppContext() method:

public static Context getAppContext()
   return MyApplication.context; 

Custom "confirm" dialog in JavaScript?

SweetAlert

You should take a look at SweetAlert as an option to save some work. It's beautiful from the default state and is highly customizable.

Confirm Example

sweetAlert(
  {
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",   
    showCancelButton: true,   
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!"
  }, 
  deleteIt()
);

Sample Alert

Defining TypeScript callback type

I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.

the syntax is the following:

public myCallback: (name: type) => returntype;

In my example, it would be

class CallbackTest
{
    public myCallback: () => void;

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}

Get hostname of current request in node.js Express

If you're talking about an HTTP request, you can find the request host in:

request.headers.host

But that relies on an incoming request.

More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest

If you're looking for machine/native information, try the process object.

WCF service startup error "This collection already contains an address with scheme http"

Did you see this - http://kb.discountasp.net/KB/a799/error-accessing-wcf-service-this-collection-already.aspx

You can resolve this error by changing the web.config file.

With ASP.NET 4.0, add the following lines to your web.config:

<system.serviceModel> 
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
</system.serviceModel> 

With ASP.NET 2.0/3.0/3.5, add the following lines to your web.config:

<system.serviceModel> 
     <serviceHostingEnvironment> 
          <baseAddressPrefixFilters> 
               <add prefix="http://www.YourHostedDomainName.com"/> 
          </baseAddressPrefixFilters> 
     </serviceHostingEnvironment> 
</system.serviceModel> 

How can I check if an argument is defined when starting/calling a batch file?

This is the same as the other answers, but uses only one label and puts the usage first, which additionally makes it serve as a kind of documentation commend of the script which is also usually placed at the top:

@echo off
:: add other test for the arguments here...
if not [%1]==[] goto main
:: --------------------------
echo This command does something.
echo.
echo %0 param%%1 param%%2
echo       param%%1 the file to operate on
echo       param%%1 another file

:: --------------------------
exit /B 1

:main
:: --------------------------
echo do something with all arguments (%%* == %*) here...

However, if you don't have to use cmd/batch, use bash on WSL or powershell, they have more sane syntax and less arcane features.

make *** no targets specified and no makefile found. stop

If you create Makefile in the VSCode, your makefile doesnt run. I don't know the cause of this issue. Maybe the configuration of the file is not added to system. But I solved this way. delete created makefile, then go to project directory and right click mouse later create a file and named Makefile. After fill the Makefile and run it. It will work.

SDK Manager.exe doesn't work

The way I solved your last problem was by right clicking the android.bat file, and chose edit with notepad++. I then went down to the part of the program where it had this bit of code:

cd /d %~dp0

It was also some other lines of code, but I deleted them. After deleting these other lines I simply just wrote(under the cd /d %~dp0):

cd Program Files

cd java

cd jdk1.7.0_03

cd bin

I dont know here you java.exe file is located but mine was at lest located there.

Common MySQL fields and their appropriate data types

Here are some common datatypes I use (I am not much of a pro though):

| Column           | Data type     | Note
| ---------------- | ------------- | -------------------------------------
| id               | INTEGER       | AUTO_INCREMENT, UNSIGNED                                                          |  
| uuid             | CHAR(36)      | or CHAR(16) binary                                                                |  
| title            | VARCHAR(255)  |                                                                                   |  
| full name        | VARCHAR(70)   |                                                                                   |  
| gender           | TINYINT       | UNSIGNED                                                                          |  
| description      | TINYTEXT      | often may not be enough, use TEXT 
                                     instead          
| post body        | TEXT          |                                                                                   |  
| email            | VARCHAR(255)  |                                                                                   |  
| url              | VARCHAR(2083) | MySQL version < 5.0.3 - use TEXT                                                  |  
| salt             | CHAR(x)       | randomly generated string, usually of 
                                     fixed length (x)    
| digest (md5)     | CHAR(32)      |                                                                                   |  
| phone number     | VARCHAR(20)   |                                                                                   |  
| US zip code      | CHAR(5)       | Use CHAR(10) if you store extended 
                                     codes      
| US/Canada p.code | CHAR(6)       |                                                                                   |  
| file path        | VARCHAR(255)  |                                                                                   |  
| 5-star rating    | DECIMAL(3,2)  | UNSIGNED                                                                          |  
| price            | DECIMAL(10,2) | UNSIGNED                                                                          |  
| date (creation)  | DATE/DATETIME | usually displayed as initial date of 
                                     a post                                       |  
| date (tracking)  | TIMESTAMP     | can be used for tracking changes in a 
                                     post                                        |  
| tags, categories | TINYTEXT      | comma separated values *                                                          |  
| status           | TINYINT(1)    | 1 – published, 0 – unpublished, … You 
                                     can also use ENUM for human-readable 
                                     values
| json data        | JSON          | or LONGTEXT       

What is use of c_str function In c++

c_str() converts a C++ string into a C-style string which is essentially a null terminated array of bytes. You use it when you want to pass a C++ string into a function that expects a C-style string (e.g. a lot of the Win32 API, POSIX style functions, etc).

How to disable HTML button using JavaScript?

Since this setting is not an attribute

It is an attribute.

Some attributes are defined as boolean, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled", you include only the bold part. In HTML 4, you should include only the bold part as the full version is marked as a feature with limited support (although that is less true now then when the spec was written).

As of HTML 5, the rules have changed and now you include only the name and not the value. This makes no practical difference because the name and the value are the same.

The DOM property is also called disabled and is a boolean that takes true or false.

foo.disabled = true;

In theory you can also foo.setAttribute('disabled', 'disabled'); and foo.removeAttribute("disabled"), but I wouldn't trust this with older versions of Internet Explorer (which are notoriously buggy when it comes to setAttribute).

Find the day of a week

Use the lubridate package and function wday:

library(lubridate)
df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed   Wed   Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

`require': no such file to load -- mkmf (LoadError)

I also needed build-essential installed:

sudo apt-get install build-essential

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

For us, this error was because the developer's computer running the service had IIS configured to bind port 443 on 127.0.0.1 only.

In IIS Manager, right-click the web site and choose Edit Bindings. If the entry for Port 443 has IP Address 127.0.0.1, change it to *.

Prompt Dialog in Windows Forms

Unfortunately C# still doesn't offer this capability in the built in libs. The best solution at present is to create a custom class with a method that pops up a small form. If you're working in Visual Studio you can do this by clicking on Project >Add class

Add Class

Visual C# items >code >class Add Class 2

Name the class PopUpBox (you can rename it later if you like) and paste in the following code:

using System.Drawing;
using System.Windows.Forms;

namespace yourNameSpaceHere
{
    public class PopUpBox
    {
        private static Form prompt { get; set; }

        public static string GetUserInput(string instructions, string caption)
        {
            string sUserInput = "";
            prompt = new Form() //create a new form at run time
            {
                Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption,
                StartPosition = FormStartPosition.CenterScreen, TopMost = true
            };
            //create a label for the form which will have instructions for user input
            Label lblTitle = new Label() { Left = 50, Top = 20, Text = instructions, Dock = DockStyle.Top, TextAlign = ContentAlignment.TopCenter };
            TextBox txtTextInput = new TextBox() { Left = 50, Top = 50, Width = 400 };

            ////////////////////////////OK button
            Button btnOK = new Button() { Text = "OK", Left = 250, Width = 100, Top = 70, DialogResult = DialogResult.OK };
            btnOK.Click += (sender, e) => 
            {
                sUserInput = txtTextInput.Text;
                prompt.Close();
            };
            prompt.Controls.Add(txtTextInput);
            prompt.Controls.Add(btnOK);
            prompt.Controls.Add(lblTitle);
            prompt.AcceptButton = btnOK;
            ///////////////////////////////////////

            //////////////////////////Cancel button
            Button btnCancel = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.Cancel };
            btnCancel.Click += (sender, e) => 
            {
                sUserInput = "cancel";
                prompt.Close();
            };
            prompt.Controls.Add(btnCancel);
            prompt.CancelButton = btnCancel;
            ///////////////////////////////////////

            prompt.ShowDialog();
            return sUserInput;
        }

        public void Dispose()
        {prompt.Dispose();}
    }
}

You will need to change the namespace to whatever you're using. The method returns a string, so here's an example of how to implement it in your calling method:

bool boolTryAgain = false;

do
{
    string sTextFromUser = PopUpBox.GetUserInput("Enter your text below:", "Dialog box title");
    if (sTextFromUser == "")
    {
        DialogResult dialogResult = MessageBox.Show("You did not enter anything. Try again?", "Error", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            boolTryAgain = true; //will reopen the dialog for user to input text again
        }
        else if (dialogResult == DialogResult.No)
        {
            //exit/cancel
            MessageBox.Show("operation cancelled");
            boolTryAgain = false;
        }//end if
    }
    else
    {
        if (sTextFromUser == "cancel")
        {
            MessageBox.Show("operation cancelled");
        }
        else
        {
            MessageBox.Show("Here is the text you entered: '" + sTextFromUser + "'");
            //do something here with the user input
        }

    }
} while (boolTryAgain == true);

This method checks the returned string for a text value, empty string, or "cancel" (the getUserInput method returns "cancel" if the cancel button is clicked) and acts accordingly. If the user didn't enter anything and clicked OK it will tell the user and ask them if they want to cancel or re-enter their text.

Post notes: In my own implementation I found that all of the other answers were missing 1 or more of the following:

  • A cancel button
  • The ability to contain symbols in the string sent to the method
  • How to access the method and handle the returned value.

Thus, I have posted my own solution. I hope someone finds it useful. Credit to Bas and Gideon + commenters for your contributions, you helped me to come up with a workable solution!

What are projection and selection?

Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.

System.Timers.Timer vs System.Threading.Timer

The two classes are functionally equivalent, except that System.Timers.Timer has an option to invoke all its timer expiration callbacks through ISynchronizeInvoke by setting SynchronizingObject. Otherwise, both timers invoke expiration callbacks on thread pool threads.

When you drag a System.Timers.Timer onto a Windows Forms design surface, Visual Studio sets SynchronizingObject to the form object, which causes all expiration callbacks to be called on the UI thread.

overlay opaque div over youtube iframe

Information from the Official Adobe site about this issue

The issue is when you embed a youtube link:

https://www.youtube.com/embed/kRvL6K8SEgY

in an iFrame, the default wmode is windowed which essentially gives it a z-index greater then everything else and it will overlay over anything.

Try appending this GET parameter to your URL:

wmode=opaque

like so:

https://www.youtube.com/embed/kRvL6K8SEgY?wmode=opaque

Make sure its the first parameter in the URL. Other parameters must go after

In the iframe tag:

Example:

<iframe class="youtube-player" type="text/html" width="520" height="330" src="http://www.youtube.com/embed/NWHfY_lvKIQ?wmode=opaque" frameborder="0"></iframe>

Check if passed argument is file or directory in Bash

#!/bin/bash                                                                                               
echo "Please Enter a file name :"                                                                          
read filename                                                                                             
if test -f $filename                                                                                      
then                                                                                                      
        echo "this is a file"                                                                             
else                                                                                                      
        echo "this is not a file"                                                                         
fi 

Javascript string replace with regex to strip off illegal characters

Put them in brackets []:

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

Detect the Enter key in a text input field

event.key === "Enter"

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

const node = document.getElementsByClassName("input")[0];
node.addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        // Do work
    }
});

Modern style, with lambda and destructuring

node.addEventListener('keyup', ({key}) => {
    if (key === "Enter") return false
})

If you must use jQuery:

$(document).keyup(function(event) {
    if ($(".input1").is(":focus") && event.key == "Enter") {
        // Do work
    }
});

Mozilla Docs

Supported Browsers

How can I disable the default console handler, while using the java logging API?

This is strange but Logger.getLogger("global") does not work in my setup (as well as Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)).

However Logger.getLogger("") does the job well.

Hope this info also helps somebody...

Getting value from table cell in JavaScript...not jQuery

function GetCellValues() {
    var table = document.getElementById('mytable');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            alert(table.rows[r].cells[c].innerHTML);
        }
    }
}

How to obtain the location of cacerts of the default java installation?

You can also consult readlink -f "which java". However it might not work for all binary wrappers. It is most likely better to actually start a Java class.

Calculating the sum of two variables in a batch script

You can solve any equation including adding with this code:

@echo off

title Richie's Calculator 3.0

:main

echo Welcome to Richie's Calculator 3.0

echo Press any key to begin calculating...

pause>nul

echo Enter An Equation

echo Example: 1+1

set /p 

set /a sum=%equation%

echo.

echo The Answer Is:

echo %sum%

echo.

echo Press any key to return to the main menu

pause>nul

cls

goto main

Convert regular Python string to raw string

Raw strings are not a different kind of string. They are a different way of describing a string in your source code. Once the string is created, it is what it is.

CodeIgniter - File upload required validation

CodeIgniter file upload optionally ...works perfectly..... :)

---------- controller ---------

function file()
{
 $this->load->view('includes/template', $data);
}

function valid_file()
{
 $this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');

 if ($this->form_validation->run()==FALSE) 
 {
    $this->file();
 }
 else
 {
  $config['upload_path']   = './documents/';
  $config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
  $config['max_size']      = '1000';
  $config['max_width']     = '1024';
  $config['max_height']    = '768';

  $this->load->library('upload', $config);

  if ( !$this->upload->do_upload('userfile',FALSE))
  {
    $this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());

    if($_FILES['userfile']['error'] != 4)
    {
        return false;
    }

  }
  else
  {
    return true;
  }
}

i just use this lines which makes it optionally,

if($_FILES['userfile']['error'] != 4)
{
 return false;
}

$_FILES['userfile']['error'] != 4 is for file required to upload.

you can make it unnecessary by using $_FILES['userfile']['error'] != 4, then it will pass this error for file required and works great with other types of errors if any by using return false , hope it works for u ....

How can I strip first X characters from string using sed?

Another way, using cut instead of sed.

result=`echo $pid | cut -c 5-`

Xcode 6: Keyboard does not show up in simulator

To enable/disable simulator keyboard,

? + K (Ctrl + k)

To disable input from your keyboard,

iOS Simulator -> Hardware -> Keyboard -> Uncheck "Connect Hardware Keyboard"

frequent issues arising in android view, Error parsing XML: unbound prefix

As you mention, you need to specify the right namespace. You also see this error with an incorrect namespace.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:padding="10dip">

will not work.

Change:

xmlns="http://schemas.android.com/apk/res/android"

to

xmlns:android="http://schemas.android.com/apk/res/android"

The error message is referring to everything that starts "android:" as the XML does not know what the "android:" namespace is.

xmlns:android defines it.

How to make audio autoplay on chrome

Solution without using iframe, or javascript:

<embed src="silence.mp3" type="audio/mp3" autostart="true" hidden="true">
        <audio id="player" autoplay controls><source src="source/audio.mp3" type="audio/mp3"></audio>

With this solution, the open/save dialog of Internet Explorer is also avoided.

_x000D_
_x000D_
   <embed src="http://deinesv.cf/silence.mp3" type="audio/mp3" autostart="true" hidden="true">
        <audio id="player" autoplay controls><source src="https://freemusicarchive.org/file/music/ccCommunity/Mild_Wild/a_Alright_Okay_b_See_Through/Mild_Wild_-_Alright_Okay.mp3" type="audio/mp3"></audio>
_x000D_
_x000D_
_x000D_

How can I access Oracle from Python?

If you are using virtualenv, it is not as trivial to get the driver using the installer. What you can do then: install it as described by Devon. Then copy over cx_Oracle.pyd and the cx_Oracle-XXX.egg-info folder from Python\Lib\site-packages into the Lib\site-packages from your virtual env. Of course, also here, architecture and version are important.

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

Add centered text to the middle of a <hr/>-like line

_x000D_
_x000D_
.orSpan{_x000D_
  position: absolute;_x000D_
  margin-top: -1.3rem;_x000D_
  margin-left:50%;_x000D_
  padding:0 5px;_x000D_
  background-color: white;_x000D_
}
_x000D_
<div>_x000D_
   <hr> <span class="orSpan">OR</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You may required to adjust the margin property

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Making use of the tricks in "Getting the last argument passed to a shell script" we can make a simple shell function that should work no matter how many files you want to move:

# Bash only
mvdir() { mkdir -p "${@: -1}" && mv "$@"; }

# Other shells may need to search for the last argument
mvdir() { for last; do true; done; mkdir -p "$last" && mv "$@"; }

How to load a text file into a Hive table stored as sequence files

The simple way is to create table as textfile and move the file to the appropriate location

CREATE EXTERNAL TABLE mytable(col1 string, col2 string)
row format delimited fields terminated by '|' stored as textfile;

Copy the file to the HDFS Location where table is created.
Hope this helps!!!

Highlight Bash/shell code in Markdown files

Using the knitr package:

```{r, engine='bash', code_block_name} ...

E.g.:

```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```

You can also use:

  • engine='sh' for shell
  • engine='python' for Python
  • engine='perl', engine='haskell' and a bunch of other C-like languages and even gawk, AWK, etc.

Best way to do nested case statement logic in SQL Server

We can combine multiple conditions together to reduce the performance overhead.

Let there are three variables a b c on which we want to perform cases. We can do this as below:

CASE WHEN a = 1 AND b = 1 AND c = 1 THEN '1'
     WHEN a = 0 AND b = 0 AND c = 1 THEN '0'
ELSE '0' END,

python time + timedelta equivalent

If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. If you go past midnight, it just wraps around:

>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'

It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime

The documentation is at http://tgs.github.io/nptime/

Paste multiple columns together

# your starting data..
data <- data.frame('a' = 1:3, 'b' = c('a','b','c'), 'c' = c('d', 'e', 'f'), 'd' = c('g', 'h', 'i')) 

# columns to paste together
cols <- c( 'b' , 'c' , 'd' )

# create a new column `x` with the three columns collapsed together
data$x <- apply( data[ , cols ] , 1 , paste , collapse = "-" )

# remove the unnecessary columns
data <- data[ , !( names( data ) %in% cols ) ]

How do I get a file name from a full path with PHP?

The basename function should give you what you want:

Given a string containing a path to a file, this function will return the base name of the file.

For instance, quoting the manual's page:

<?php
    $path = "/home/httpd/html/index.php";
    $file = basename($path);         // $file is set to "index.php"
    $file = basename($path, ".php"); // $file is set to "index"
?>

Or, in your case:

$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));

You'll get:

string(10) "Output.map"

Getting the index of a particular item in array

The previous answers will only work if you know the exact value you are searching for - the question states that only a partial value is known.

Array.FindIndex(authors, author => author.Contains("xyz"));

This will return the index of the first item containing "xyz".

Java Array, Finding Duplicates

You can also work with Set, which doesn't allow duplicates in Java..

    for (String name : names)
    {         
      if (set.add(name) == false) 
         { // your duplicate element }
    }

using add() method and check return value. If add() returns false it means that element is not allowed in the Set and that is your duplicate.

Using BufferedReader to read Text File

private void readFile() throws Exception {
      AsynchronousFileChannel input=AsynchronousFileChannel.open(Paths.get("E:/dicom_server_storage/abc.txt"),StandardOpenOption.READ);
      ByteBuffer buffer=ByteBuffer.allocate(1024);
      input.read(buffer,0,null,new CompletionHandler<Integer,Void>(){
        @Override public void completed(    Integer result,    Void attachment){
          System.out.println("Done reading the file.");
        }
        @Override public void failed(    Throwable exc,    Void attachment){
          System.err.println("An error occured:" + exc.getMessage());
        }
      }
    );
      System.out.println("This thread keeps on running");
      Thread.sleep(100);
    }

How to generate a random String in Java

Random ran = new Random();
int top = 3;
char data = ' ';
String dat = "";

for (int i=0; i<=top; i++) {
  data = (char)(ran.nextInt(25)+97);
  dat = data + dat;
}

System.out.println(dat);

DOS: find a string, if found then run another script

We have two commands, first is "condition_command", second is "result_command". If we need run "result_command" when "condition_command" is successful (errorlevel=0):

condition_command && result_command

If we need run "result_command" when "condition_command" is fail:

condition_command || result_command

Therefore for run "some_command" in case when we have "string" in the file "status.txt":

find "string" status.txt 1>nul && some_command

in case when we have not "string" in the file "status.txt":

find "string" status.txt 1>nul || some_command

Removing the password from a VBA project

My 2 cents on Excel 2016:

  1. open the xls file with Notepad++
  2. Search for DPB= and replace it with DPx=
  3. Save the file
  4. Open the file, open the VB Editor, open modules will not work (error 40230)
  5. Save the file as xlsm
  6. It works

Select last N rows from MySQL

You can do it with a sub-query:

SELECT * FROM (
    SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC

This will select the last 50 rows from table, and then order them in ascending order.

Plot multiple boxplot in one graph

Using base graphics, we can use at = to control box position , combined with boxwex = for the width of the boxes. The 1st boxplot statement creates a blank plot. Then add the 2 traces in the following two statements.

Note that in the following, we use df[,-1] to exclude the 1st (id) column from the values to plot. With different data frames, it may be necessary to change this to subset for whichever columns contain the data you want to plot.

boxplot(df[,-1], boxfill = NA, border = NA) #invisible boxes - only axes and plot area
boxplot(df[df$id=="Good", -1], xaxt = "n", add = TRUE, boxfill="red", 
  boxwex=0.25, at = 1:ncol(df[,-1]) - 0.15) #shift these left by -0.15
boxplot(df[df$id=="Bad", -1], xaxt = "n", add = TRUE, boxfill="blue", 
  boxwex=0.25, at = 1:ncol(df[,-1]) + 0.15) #shift to the right by +0.15

enter image description here

Some dummy data:

df <- data.frame(
  id = c(rep("Good",200), rep("Bad", 200)),
  F1 = c(rnorm(200,10,2), rnorm(200,8,1)),
  F2 = c(rnorm(200,7,1),  rnorm(200,6,1)),
  F3 = c(rnorm(200,6,2),  rnorm(200,9,3)),
  F4 = c(rnorm(200,12,3), rnorm(200,8,2)))

How to disable the back button in the browser using JavaScript

One cannot disable the browser back button functionality. The only thing that can be done is prevent them.

The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:

<script>
    function preventBack() {
        window.history.forward();
    }

    setTimeout("preventBack()", 0);
    window.onunload = function() {
        null
    };
</script>

Suppose there are two pages Page1.php and Page2.php and Page1.php redirects to Page2.php.

Hence to prevent user from visiting Page1.php using the back button you will need to place the above script in the head section of Page1.php.

For more information: Reference

Swift how to sort array of custom objects by property value

In Swift 3.0

images.sort(by: { (first: imageFile, second: imageFile) -> Bool in
    first. fileID < second. fileID
})

.do extension in web pages?

It is whatever it is configured to be on that particular web server. A web server could be configured to run .pl files with the php module and .aspx files with perl, although that would be silly. There are no scripts involved with most web servers, instead you'd have to look in your apache configuration files (or equivalent, if using different server software). If you have permission to edit the server config file, then you could make files ending in .do run as php, if that's what you're after.

Ruby on Rails: How do I add placeholder text to a f.text_field?

With rails >= 3.0, you can simply use the placeholder option.

f.text_field :attr, placeholder: "placeholder text"

adding and removing classes in angularJs using ng-click

I want to add or remove "active" class in my code dynamically on ng-click, here what I have done.

<ul ng-init="selectedTab = 'users'">
   <li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li>
   <li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li>
</ul>

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

You can do this go to Settings > Storage, clicking on the setting menu icon in the top right hand corner and selecting "USB computer connection". I then changed the storage mode to "Camera (PTP)". Done try re installing the driver from device manager.

Use of var keyword in C#

You don't have to write out the type name and no this is not less performant as the type is resolved at compile time.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

MySQL Stored procedure variables from SELECT statements

I am facing a strange behavior.

SELECT INTO and SET Both works for some variables and not for others. Event syntaxes are the same

SET @Invoice_UserId :=  (SELECT UserId FROM invoice WHERE InvoiceId = @Invoice_Id  LIMIT 1); -- Working
                SET @myamount := (SELECT amount FROM invoice WHERE InvoiceId = @Invoice_Id LIMIT 1); - Not working
SELECT  Amount INTO @myamount FROM invoice WHERE InvoiceId = 29  LIMIT 1; - Not working

If I run these queries directly then works, but not working in stored procedure.

How to create jar file with package structure?

From the directory containing the com folder:

$ jar cvf asd.jar com
added manifest
adding: com/(in = 0) (out= 0)(stored 0%)
adding: com/cdy/(in = 0) (out= 0)(stored 0%)
adding: com/cdy/ws/(in = 0) (out= 0)(stored 0%)
adding: com/cdy/ws/a.class(in = 0) (out= 0)(stored 0%)
adding: com/cdy/ws/b.class(in = 0) (out= 0)(stored 0%)
adding: com/cdy/ws/c.class(in = 0) (out= 0)(stored 0%)

$ jar -tf asd.jar 
META-INF/
META-INF/MANIFEST.MF
com/
com/cdy/
com/cdy/ws/
com/cdy/ws/a.class
com/cdy/ws/b.class
com/cdy/ws/c.class

Wordpress - Images not showing up in the Media Library

How did you upload those images; via FTP or through WP uploader? You have to upload images THROUGH WP uploader in order to show them in the image library.

How to embed a .mov file in HTML?

Well, if you don't want to do the work yourself (object elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/

Django CSRF check failing with an Ajax POST request

The accepted answer is most likely a red herring. The difference between Django 1.2.4 and 1.2.5 was the requirement for a CSRF token for AJAX requests.

I came across this problem on Django 1.3 and it was caused by the CSRF cookie not being set in the first place. Django will not set the cookie unless it has to. So an exclusively or heavily ajax site running on Django 1.2.4 would potentially never have sent a token to the client and then the upgrade requiring the token would cause the 403 errors.

The ideal fix is here: http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#page-uses-ajax-without-any-html-form
but you'd have to wait for 1.4 unless this is just documentation catching up with the code

Edit

Note also that the later Django docs note a bug in jQuery 1.5 so ensure you are using 1.5.1 or later with the Django suggested code: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

Can I scale a div's height proportionally to its width using CSS?

One way usefull when you work with images, but can be used as workaround otherwise:

<html>
<head>
</head>
<style>
    #someContainer {
        width:50%;
        position: relative;
    }
    #par {
        width: 100%;
        background-color:red;
    }
    #image {
        width: 100%;
        visibility: hidden;
    }
    #myContent {
        position:absolute;
    }
</style>
<div id="someContainer">
    <div id="par">
        <div id="myContent">
            <p>
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </p>    
        </div>
        <img src="yourImage" id="image"/>
    </div>
</div>
</html>

To use replace yourImage with your image url. You use image with width / height ratio you desire.

div id="myContent" is here as example of workaround where myContent will overlay over image.

This works like: Parent div will adopt to the height of image, image height will adopt to width of parent. However image is hidden.

Utility of HTTP header "Content-Type: application/force-download" for mobile?

To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type

$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php

Add CSS to <head> with JavaScript?

Edit: As Atspulgs comment suggest, you can achieve the same without jQuery using the querySelector:

document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';

Older answer below.


You could use the jQuery library to select your head element and append HTML to it, in a manner like:

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

You can find a complete tutorial for this problem here

Remote Procedure call failed with sql server 2008 R2

I just had the same issue and was able to solve it by installing Service Pack 1.

Count elements with jQuery

var count_elements = $('.class').length;

From: http://api.jquery.com/size/

The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.

Please see:

http://api.jquery.com/size/

http://api.jquery.com/length/

Enzyme - How to access and set <input> value?

This works for me using enzyme 2.4.1:

const wrapper = mount(<EditableText defaultValue="Hello" />);
const input = wrapper.find('input');

console.log(input.node.value);

Regular Expression to match valid dates

This is not an appropriate use of regular expressions. You'd be better off using

[0-9]{2}/[0-9]{2}/[0-9]{4}

and then checking ranges in a higher-level language.

How to convert Map keys to array?

Array.from(myMap.keys()) does not work in google application scripts.

Trying to use it results in the error TypeError: Cannot find function from in object function Array() { [native code for Array.Array, arity=1] }.

To get a list of keys in GAS do this:

var keysList = Object.keys(myMap);

Reading Xml with XmlReader in C#

I am not experiented .But i think XmlReader is unnecessary. It is very hard to use.
XElement is very easy to use.
If you need performance ( faster ) you must change file format and use StreamReader and StreamWriter classes.

How to Export Private / Secret ASC Key to Decrypt GPG Files

Similar to @Wolfram J's answer, here is a method to encrypt your private key with a passphrase:

gpg --output - --armor --export $KEYID | \
    gpg --output private_key.asc --armor --symmetric --cipher-algo AES256

And a corresponding method to decrypt:

gpg private_key.asc

Create a Date with a set timezone without using a string representation

getTimeZoneOffset is minus for UTC + z.

var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
    d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
}

Handling 'Sequence has no elements' Exception

You are using linq's First() method, which as per the documentation throws an InvalidOperationException if you are calling it on an empty collection.

If you expect the result of your query to be empty sometimes, you likely want to use FirstOrDefault(), which will return null if the collection is empty, instead of throwing an exception.

"undefined" function declared in another file?

I ran into the same issue with Go11, just wanted to share how I did solve it for helping others just in case they run into the same issue.

I had my Go project outside $GOPATH, so I had to turned on GO111MODULE=on without this option turned on, it will give you this issue; even if you you try to build or test the whole package or directory it won't be solved without GO111MODULE=on

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

Best way to get application folder path

Root directory:

DriveInfo cDrive = new DriveInfo(System.Environment.CurrentDirectory);
var driverPath = cDrive.RootDirectory;

Download & Install Xcode version without Premium Developer Account

Yes,
You can download Xcode with/without Paid (Premium) Apple Developer Account from below links.

Xcode 11

Xcode 10


For non-premium account/apple id: (Download Xcode 10 without Paid (Premium) Apple Developer Account from below link)

Apple Download Portal

Look at here: How to install & set command line tool


See here for older versions of Xcode (Which may need to authenticate your apple account):

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

If you have

@Transactional // Spring Transactional
class MyDao extends Dao {
}

and super-class

class Dao {
    public void save(Entity entity) { getEntityManager().merge(entity); }
}

and you call

@Autowired MyDao myDao;
myDao.save(entity);

you won't get a Spring TransactionInterceptor (that gives you a transaction).

This is what you need to do:

@Transactional 
class MyDao extends Dao {
    public void save(Entity entity) { super.save(entity); }
}

Unbelievable but true.

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

This works too:

System.DateTime dTime = DateTime.Now();

// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0); 

System.DateTime result = dTime + tSpan;

To subtract a year:

DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);

jQuery Popup Bubble/Tooltip

Sounds to me you dn't want the mouse over events: you want the jQuery hover() event.

And what you seem to want is a "rich" tooltip, in which case I suggest jQuery tooltip. With the bodyHandler option you can put arbitrary HTML in.

Axios Delete request with body and headers?

For Delete, you will need to do as per the following

axios.delete("/<your endpoint>", { data:<"payload object">})

It worked for me.

Allow anonymous authentication for a single folder in web.config?

<location path="ForAll/Demo.aspx">
 <system.web>
  <authorization>
    <allow users="*" />
  </authorization>
 </system.web>
</location>

In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder

Redirect From Action Filter Attribute

This works for me (asp.net core 2.1)

using JustRide.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MyProject.Web.Filters
{
    public class IsAuthenticatedAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.HttpContext.User.Identity.IsAuthenticated)
                context.Result = new RedirectToActionResult(nameof(AccountController.Index), "Account", null);
        }
    }
}



[AllowAnonymous, IsAuthenticated]
public IActionResult Index()
{
    return View();
}

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

One trick you can use to increase the number of concurrent connections is to host your images from a different sub domain. These will be treated as separate requests, each domain is what will be limited to the concurrent maximum.

IE6, IE7 - have a limit of two. IE8 is 6 if you have a broadband - 2 (if it's a dial up).

Conversion of Char to Binary in C

Your code is very vague and not understandable, but I can provide you with an alternative.

First of all, if you want temp to go through the whole string, you can do something like this:

char *temp;
for (temp = your_string; *temp; ++temp)
    /* do something with *temp */

The term *temp as the for condition simply checks whether you have reached the end of the string or not. If you have, *temp will be '\0' (NUL) and the for ends.

Now, inside the for, you want to find the bits that compose *temp. Let's say we print the bits:

for (as above)
{
    int bit_index;
    for (bit_index = 7; bit_index >= 0; --bit_index)
    {
        int bit = *temp >> bit_index & 1;
        printf("%d", bit);
    }
    printf("\n");
}

To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7 to bit_index = sizeof(*temp)*8-1

How to set environment variable for everyone under my linux system?

Some interesting excerpts from the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc.

So have a look at /etc/profile or /etc/bash.bashrc, these files are the right places for global settings. Put something like this in them to set up an environement variable:

export MY_VAR=xxx

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

all i found solution for whatever you all get the exception like.. org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]..

the problem with bulid path of the jars..

To over come this problem.. place all jars in "WebContent/lib" whatever you need to in your project. i hope it will useful to you...

Is it better in C++ to pass by value or pass by constant reference?

Edit: New article by Dave Abrahams on cpp-next:

Want speed? Pass by value.


Pass by value for structs where the copying is cheap has the additional advantage that the compiler may assume that the objects don't alias (are not the same objects). Using pass-by-reference the compiler cannot assume that always. Simple example:

foo * f;

void bar(foo g) {
    g.i = 10;
    f->i = 2;
    g.i += 5;
}

the compiler can optimize it into

g.i = 15;
f->i = 2;

since it knows that f and g doesn't share the same location. if g was a reference (foo &), the compiler couldn't have assumed that. since g.i could then be aliased by f->i and have to have a value of 7. so the compiler would have to re-fetch the new value of g.i from memory.

For more pratical rules, here is a good set of rules found in Move Constructors article (highly recommended reading).

  • If the function intends to change the argument as a side effect, take it by non-const reference.
  • If the function doesn't modify its argument and the argument is of primitive type, take it by value.
  • Otherwise take it by const reference, except in the following cases
    • If the function would then need to make a copy of the const reference anyway, take it by value.

"Primitive" above means basically small data types that are a few bytes long and aren't polymorphic (iterators, function objects, etc...) or expensive to copy. In that paper, there is one other rule. The idea is that sometimes one wants to make a copy (in case the argument can't be modified), and sometimes one doesn't want (in case one wants to use the argument itself in the function if the argument was a temporary anyway, for example). The paper explains in detail how that can be done. In C++1x that technique can be used natively with language support. Until then, i would go with the above rules.

Examples: To make a string uppercase and return the uppercase version, one should always pass by value: One has to take a copy of it anyway (one couldn't change the const reference directly) - so better make it as transparent as possible to the caller and make that copy early so that the caller can optimize as much as possible - as detailed in that paper:

my::string uppercase(my::string s) { /* change s and return it */ }

However, if you don't need to change the parameter anyway, take it by reference to const:

bool all_uppercase(my::string const& s) { 
    /* check to see whether any character is uppercase */
}

However, if you the purpose of the parameter is to write something into the argument, then pass it by non-const reference

bool try_parse(T text, my::string &out) {
    /* try to parse, write result into out */
}

Is there a concurrent List in Java's JDK?

There is a concurrent list implementation in java.util.concurrent. CopyOnWriteArrayList in particular.

How do I output an ISO 8601 formatted string in JavaScript?

If you don't need to support IE7, the following is a great, concise hack:

JSON.parse(JSON.stringify(new Date()))

How to convert InputStream to FileInputStream

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

How to create multiple page app using react

This is a broad question and there are multiple ways you can achieve this. In my experience, I've seen a lot of single page applications having an entry point file such as index.js. This file would be responsible for 'bootstrapping' the application and will be your entry point for webpack.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application';

const root = document.getElementById('someElementIdHere');

ReactDOM.render(
  <Application />,
  root,
);

Your <Application /> component would contain the next pieces of your app. You've stated you want different pages and that leads me to believe you're using some sort of routing. That could be included into this component along with any libraries that need to be invoked on application start. react-router, redux, redux-saga, react-devtools come to mind. This way, you'll only need to add a single entry point into your webpack configuration and everything will trickle down in a sense.

When you've setup a router, you'll have options to set a component to a specific matched route. If you had a URL of /about, you should create the route in whatever routing package you're using and create a component of About.js with whatever information you need.

How to convert std::string to LPCSTR?

str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).

IllegalMonitorStateException on wait() call

wait is defined in Object, and not it Thread. The monitor on Thread is a little unpredictable.

Although all Java objects have monitors, it is generally better to have a dedicated lock:

private final Object lock = new Object();

You can get slightly easier to read diagnostics, at a small memory cost (about 2K per process) by using a named class:

private static final class Lock { }
private final Object lock = new Lock();

In order to wait or notify/notifyAll an object, you need to be holding the lock with the synchronized statement. Also, you will need a while loop to check for the wakeup condition (find a good text on threading to explain why).

synchronized (lock) {
    while (!isWakeupNeeded()) {
        lock.wait();
    }
}

To notify:

synchronized (lock) {
    makeWakeupNeeded();
    lock.notifyAll();
}

It is well worth getting to understand both Java language and java.util.concurrent.locks locks (and java.util.concurrent.atomic) when getting into multithreading. But use java.util.concurrent data structures whenever you can.

Rails: How to run `rails generate scaffold` when the model already exists?

TL;DR: rails g scaffold_controller <name>

Even though you already have a model, you can still generate the necessary controller and migration files by using the rails generate option. If you run rails generate -h you can see all of the options available to you.

Rails:
  controller
  generator
  helper
  integration_test
  mailer
  migration
  model
  observer
  performance_test
  plugin
  resource
  scaffold
  scaffold_controller
  session_migration
  stylesheets

If you'd like to generate a controller scaffold for your model, see scaffold_controller. Just for clarity, here's the description on that:

Stubs out a scaffolded controller and its views. Pass the model name, either CamelCased or under_scored, and a list of views as arguments. The controller name is retrieved as a pluralized version of the model name.

To create a controller within a module, specify the model name as a path like 'parent_module/controller_name'.

This generates a controller class in app/controllers and invokes helper, template engine and test framework generators.

To create your resource, you'd use the resource generator, and to create a migration, you can also see the migration generator (see, there's a pattern to all of this madness). These provide options to create the missing files to build a resource. Alternatively you can just run rails generate scaffold with the --skip option to skip any files which exist :)

I recommend spending some time looking at the options inside of the generators. They're something I don't feel are documented extremely well in books and such, but they're very handy.

CodeIgniter: Load controller within controller

Load it like this

$this->load->library('../controllers/instructor');

and call the following method:

$this->instructor->functioname()

This works for CodeIgniter 2.x.

Disable back button in react navigation

1) To make the back button disappear in react-navigation v2 or newer:

navigationOptions:  {
    title: 'MyScreen',
    headerLeft: null
}

2) If you want to clean navigation stack:

Assuming you are on the screen from which you want to navigate from:

If you are using react-navigation version v5 or newer you can use navigation.reset or CommonActions.reset:

 // Replace current navigation state with a new one,
 // index value will be the current active route:

navigation.reset({
  index: 0,
  routes: [{ name: 'Profile' }],
});

Source and more info here: https://reactnavigation.org/docs/navigation-prop/#reset

Or:

navigation.dispatch(
  CommonActions.reset({
    index: 1,
    routes: [
      { name: 'Home' },
      {
        name: 'Profile',
        params: { user: 'jane' },
      },
    ],
  })
);

Source and more info here: https://reactnavigation.org/docs/navigation-actions/#reset

For older versions of react-navigation:

v2-v4 use StackActions.reset(...)

import { StackActions, NavigationActions } from 'react-navigation';

const resetAction = StackActions.reset({
  index: 0, // <-- currect active route from actions array
  actions: [
    NavigationActions.navigate({ routeName: 'myRouteWithDisabledBackFunctionality' }),
  ],
});

this.props.navigation.dispatch(resetAction);

v1 use NavigationActions.reset

3) For android you will also have to disable the hardware back button using the BackHandler:

http://reactnative.dev/docs/backhandler.html

or if you want to use hooks:

https://github.com/react-native-community/hooks#usebackhandler

otherwise the app will close at android hardware back button press if navigation stack is empty.

iOS: Compare two dates

I take it you are asking what the return value is in the comparison function.

If the dates are equal then returning NSOrderedSame

If ascending ( 2nd arg > 1st arg ) return NSOrderedAscending

If descending ( 2nd arg < 1st arg ) return NSOrderedDescending

Postman: How to make multiple requests at the same time

In postman's collection runner you can't make simultaneous asynchronous requests, so instead use Apache JMeter instead. It allows you to add multiple threads and add synchronizing timer to it

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

how to loop through json array in jquery?

Try this:

var data = jQuery.parseJSON(response);
$.each(data, function(key, item) 
{
   console.log(item.com);
});

or

var data = $.parseJSON(response);

$(data).each(function(i,val)
 {
    $.each(val,function(key,val)
  {
          console.log(key + " : " + val);     
  });
});

Alternative for frames in html5 using iframes

While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

Holy molly, I had to do all this in order for it to work. A picture is worth a thousand words.

  • If you get this error while archiving then continue reading.

    Enter image description here

  • Go to your app and click on the general tab. Under the signing section, uncheck "Automatically manage signing". As soon as you do that you will get a status of red error as shown below.

    Enter image description here

  • Now here's the tricky part. You need to uncheck "Automatically manage Signing" in both the targets under your project. This step is very important.

    Enter image description here

  • Now go under "build settings" tab of each of those targets and set "iOS Developer" under code signing identity. Do the same steps for your "PROJECT".

    Enter image description here

  • Now do Xcode ? Product ? Clean. Close your project in Xcode and reopen it again.

  • After this go to the general tab of each of your targets and check "Automatically manage signing" and under team drop down select your developer account

    Enter image description here

  • Do an archive of your project again and everything should work.

Really, Apple? Was this supposed to make our lives easier?

Save Javascript objects in sessionStorage

You can create 2 wrapper methods for saving and retrieving object from session storage.

function saveSession(obj) {
  sessionStorage.setItem("myObj", JSON.stringify(obj));
  return true;
}

function getSession() {
  var obj = {};
  if (typeof sessionStorage.myObj !== "undefined") {
    obj = JSON.parse(sessionStorage.myObj);
  }
  return obj;
}

Use it like this:- Get object, modify some data, and save back.

var obj = getSession();

obj.newProperty = "Prod"

saveSession(obj);

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

Just like that nice warning you got, you are trying to do something that is an Anti-Pattern in React. This is a no-no. React is intended to have an unmount happen from a parent to child relationship. Now if you want a child to unmount itself, you can simulate this with a state change in the parent that is triggered by the child. let me show you in code.

class Child extends React.Component {
    constructor(){}
    dismiss() {
        this.props.unmountMe();
    } 
    render(){
        // code
    }
}

class Parent ...
    constructor(){
        super(props)
        this.state = {renderChild: true};
        this.handleChildUnmount = this.handleChildUnmount.bind(this);
    }
    handleChildUnmount(){
        this.setState({renderChild: false});
    }
    render(){
        // code
        {this.state.renderChild ? <Child unmountMe={this.handleChildUnmount} /> : null}
    }

}

this is a very simple example. but you can see a rough way to pass through to the parent an action

That being said you should probably be going through the store (dispatch action) to allow your store to contain the correct data when it goes to render

I've done error/status messages for two separate applications, both went through the store. It's the preferred method... If you'd like I can post some code as to how to do that.

EDIT: Here is how I set up a notification system using React/Redux/Typescript

Few things to note first. this is in typescript so you would need to remove the type declarations :)

I am using the npm packages lodash for operations, and classnames (cx alias) for inline classname assignment.

The beauty of this setup is I use a unique identifier for each notification when the action creates it. (e.g. notify_id). This unique ID is a Symbol(). This way if you want to remove any notification at any point in time you can because you know which one to remove. This notification system will let you stack as many as you want and they will go away when the animation is completed. I am hooking into the animation event and when it finishes I trigger some code to remove the notification. I also set up a fallback timeout to remove the notification just in case the animation callback doesn't fire.

notification-actions.ts

import { USER_SYSTEM_NOTIFICATION } from '../constants/action-types';

interface IDispatchType {
    type: string;
    payload?: any;
    remove?: Symbol;
}

export const notifySuccess = (message: any, duration?: number) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: true, message, notify_id: Symbol(), duration } } as IDispatchType);
    };
};

export const notifyFailure = (message: any, duration?: number) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: false, message, notify_id: Symbol(), duration } } as IDispatchType);
    };
};

export const clearNotification = (notifyId: Symbol) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, remove: notifyId } as IDispatchType);
    };
};

notification-reducer.ts

const defaultState = {
    userNotifications: []
};

export default (state: ISystemNotificationReducer = defaultState, action: IDispatchType) => {
    switch (action.type) {
        case USER_SYSTEM_NOTIFICATION:
            const list: ISystemNotification[] = _.clone(state.userNotifications) || [];
            if (_.has(action, 'remove')) {
                const key = parseInt(_.findKey(list, (n: ISystemNotification) => n.notify_id === action.remove));
                if (key) {
                    // mutate list and remove the specified item
                    list.splice(key, 1);
                }
            } else {
                list.push(action.payload);
            }
            return _.assign({}, state, { userNotifications: list });
    }
    return state;
};

app.tsx

in the base render for your application you would render the notifications

render() {
    const { systemNotifications } = this.props;
    return (
        <div>
            <AppHeader />
            <div className="user-notify-wrap">
                { _.get(systemNotifications, 'userNotifications') && Boolean(_.get(systemNotifications, 'userNotifications.length'))
                    ? _.reverse(_.map(_.get(systemNotifications, 'userNotifications', []), (n, i) => <UserNotification key={i} data={n} clearNotification={this.props.actions.clearNotification} />))
                    : null
                }
            </div>
            <div className="content">
                {this.props.children}
            </div>
        </div>
    );
}

user-notification.tsx

user notification class

/*
    Simple notification class.

    Usage:
        <SomeComponent notifySuccess={this.props.notifySuccess} notifyFailure={this.props.notifyFailure} />
        these two functions are actions and should be props when the component is connect()ed

    call it with either a string or components. optional param of how long to display it (defaults to 5 seconds)
        this.props.notifySuccess('it Works!!!', 2);
        this.props.notifySuccess(<SomeComponentHere />, 15);
        this.props.notifyFailure(<div>You dun goofed</div>);

*/

interface IUserNotifyProps {
    data: any;
    clearNotification(notifyID: symbol): any;
}

export default class UserNotify extends React.Component<IUserNotifyProps, {}> {
    public notifyRef = null;
    private timeout = null;

    componentDidMount() {
        const duration: number = _.get(this.props, 'data.duration', '');
       
        this.notifyRef.style.animationDuration = duration ? `${duration}s` : '5s';

        
        // fallback incase the animation event doesn't fire
        const timeoutDuration = (duration * 1000) + 500;
        this.timeout = setTimeout(() => {
            this.notifyRef.classList.add('hidden');
            this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
        }, timeoutDuration);

        TransitionEvents.addEndEventListener(
            this.notifyRef,
            this.onAmimationComplete
        );
    }
    componentWillUnmount() {
        clearTimeout(this.timeout);

        TransitionEvents.removeEndEventListener(
            this.notifyRef,
            this.onAmimationComplete
        );
    }
    onAmimationComplete = (e) => {
        if (_.get(e, 'animationName') === 'fadeInAndOut') {
            this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
        }
    }
    handleCloseClick = (e) => {
        e.preventDefault();
        this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
    }
    assignNotifyRef = target => this.notifyRef = target;
    render() {
        const {data, clearNotification} = this.props;
        return (
            <div ref={this.assignNotifyRef} className={cx('user-notification fade-in-out', {success: data.isSuccess, failure: !data.isSuccess})}>
                {!_.isString(data.message) ? data.message : <h3>{data.message}</h3>}
                <div className="close-message" onClick={this.handleCloseClick}>+</div>
            </div>
        );
    }
}

How to Return partial view of another controller by controller?

Simply you could use:

PartialView("../ABC/XXX")

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

Return a value if no rows are found in Microsoft tSQL

SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS [Value]

FROM Sites S

WHERE S.Id = @SiteId and S.Status = 1 AND 
      (S.WebUserId = @WebUserId OR S.AllowUploads = 1)

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

I follwed the same tutorial but after some months I strangely got the error "403 Access Denied" while tryed to use Manager App. In this case I was using the ipaddress:8080 in the address bar and Tomcat Manager App didin't prompting for user/password. In case of localhost:8080 the error was "401", the dialogbox asking for username and password was displayed but the user not recognized.

I tried all the previous suggestions / solutions without lucky. The only way I found is been to repeat again the entire tutorial overwriting also the files. When finished, I found again the old deployed project into the webapps directory. Now Apache Tomcat/8.5.16 Manager App are working again. I do not know what happened I didn't understand also because I'm a newbie in Tomcat user

How to use Greek symbols in ggplot2?

Use expression(delta) where 'delta' for lowercase d and 'Delta' to get capital ?.

Here's full list of Greek characters:

? a alpha
? ß beta
G ? gamma
? d delta
? e epsilon
? ? zeta
? ? eta
T ? theta
? ? iota
? ? kappa
? ? lambda
? µ mu
? ? nu
? ? xi
? ? omicron
? p pi
? ? rho
S s sigma
? t tau
? ? upsilon
F f phi
? ? chi
? ? psi
O ? omega

EDIT: Copied from comments, when using in conjunction with other words use like: expression(Delta*"price")

Random word generator- Python

Solution for Python 3

For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.

import urllib.request

word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()

Output:

>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
 'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
 'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]

And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:

import random
upper_words = [word for word in words if word[0].isupper()]
name_words  = [word for word in upper_words if not word.isupper()]
rand_name   = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])

And some random names:

>>> for n in range(10):
        ' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])

    'Semiramis Sicilian'
    'Julius Genevieve'
    'Rwanda Cohn'
    'Quito Sutherland'
    'Eocene Wheller'
    'Olav Jove'
    'Weldon Pappas'
    'Vienna Leyden'
    'Io Dave'
    'Schwartz Stromberg'

What is a 'Closure'?

Closures provide JavaScript with state.

State in programming simply means remembering things.

Example

var a = 0;

a = a + 1; // => 1
a = a + 1; // => 2
a = a + 1; // => 3

In the case above, state is stored in the variable "a". We follow by adding 1 to "a" several times. We can only do that because we are able to "remember" the value. The state holder, "a", holds that value in memory.

Often, in programming languages, you want to keep track of things, remember information and access it at a later time.

This, in other languages, is commonly accomplished through the use of classes. A class, just like variables, keeps track of its state. And instances of that class, in turns, also have state within them. State simply means information that you can store and retrieve later.

Example

class Bread {
  constructor (weight) {
    this.weight = weight;
  }

  render () {
    return `My weight is ${this.weight}!`;
  }
}

How can we access "weight" from within the "render" method? Well, thanks to state. Each instance of the class Bread can render its own weight by reading it from the "state", a place in memory where we could store that information.

Now, JavaScript is a very unique language which historically does not have classes (it now does, but under the hood there's only functions and variables) so Closures provide a way for JavaScript to remember things and access them later.

Example

var n = 0;
var count = function () {
  n = n + 1;
  return n;
};

count(); // # 1
count(); // # 2
count(); // # 3

The example above achieved the goal of "keeping state" with a variable. This is great! However, this has the disadvantage that the variable (the "state" holder) is now exposed. We can do better. We can use Closures.

Example

var countGenerator = function () {
  var n = 0;
  var count = function () {
    n = n + 1;
    return n;
  };

  return count;
};

var count = countGenerator();
count(); // # 1
count(); // # 2
count(); // # 3

This is fantastic.

Now our "count" function can count. It is only able to do so because it can "hold" state. The state in this case is the variable "n". This variable is now closed. Closed in time and space. In time because you won't ever be able to recover it, change it, assign it a value or interact directly with it. In space because it's geographically nested within the "countGenerator" function.

Why is this fantastic? Because without involving any other sophisticated and complicated tool (e.g. classes, methods, instances, etc) we are able to 1. conceal 2. control from a distance

We conceal the state, the variable "n", which makes it a private variable! We also have created an API that can control this variable in a pre-defined way. In particular, we can call the API like so "count()" and that adds 1 to "n" from a "distance". In no way, shape or form anyone will ever be able to access "n" except through the API.

JavaScript is truly amazing in its simplicity.

Closures are a big part of why this is.

Send private messages to friends

No, this isn't possible. In order for you to send messages of any kind to a Facebook user, you need that user's permission to do so.

If someone logs into your site with Facebook Connect, they are explicitly agreeing to share their Facebook data with your site, and you will then be able to send that person a message through the normal channels. You would also be able to fetch their friend list. However, you can not send messages to the friends.

How to remove numbers from string using Regex.Replace?

Blow codes could help you...

Fetch Numbers:

return string.Concat(input.Where(char.IsNumber));

Fetch Letters:

return string.Concat(input.Where(char.IsLetter));

How to concatenate two layers in keras?

You can experiment with model.summary() (notice the concatenate_XX (Concatenate) layer size)

# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

You can view notebook here for detail: https://nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb

Two HTML tables side by side, centered on the page

Off the top of my head, you might try using the "margin: 0 auto" for #outer rather than #inner.

I often add background-color to my DIVs to see how they're laying out on the view. That might be a good way to diagnose what's going onn here.

Decimal separator comma (',') with numberDecimal inputType in EditText

you could use the following for different locales

private void localeDecimalInput(final EditText editText){

    DecimalFormat decFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
    DecimalFormatSymbols symbols=decFormat.getDecimalFormatSymbols();
    final String defaultSeperator=Character.toString(symbols.getDecimalSeparator());

    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(editable.toString().contains(defaultSeperator))
                editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
            else
                editText.setKeyListener(DigitsKeyListener.getInstance("0123456789" + defaultSeperator));
        }
    });
}

Returning value from Thread

You can use a local final variable array. The variable needs to be of non-primitive type, so you can use an array. You also need to synchronize the two threads, for example using a CountDownLatch:

public void test()
{   
    final CountDownLatch latch = new CountDownLatch(1);
    final int[] value = new int[1];
    Thread uiThread = new HandlerThread("UIHandler"){
        @Override
        public void run(){
            value[0] = 2;
            latch.countDown(); // Release await() in the test thread.
        }
    };
    uiThread.start();
    latch.await(); // Wait for countDown() in the UI thread. Or could uiThread.join();
    // value[0] holds 2 at this point.
}

You can also use an Executor and a Callable like this:

public void test() throws InterruptedException, ExecutionException
{   
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Integer> callable = new Callable<Integer>() {
        @Override
        public Integer call() {
            return 2;
        }
    };
    Future<Integer> future = executor.submit(callable);
    // future.get() returns 2 or raises an exception if the thread dies, so safer
    executor.shutdown();
}

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

pip broke. how to fix DistributionNotFound error?

I had this problem because I installed python/pip with a weird ~/.pydistutils.cfg that I didn't remember writing. Deleted it, reinstalled (with pybrew), and everything was fine.

Python urllib2: Receive JSON response from url

"""
Return JSON to webpage
Adding to wonderful answer by @Sanal
For Django 3.4
Adding a working url that returns a json (Source: http://www.jsontest.com/#echo)
"""

import json
import urllib

url = 'http://echo.jsontest.com/insert-key-here/insert-value-here/key/value'
respons = urllib.request.urlopen(url)
data = json.loads(respons.read().decode(respons.info().get_param('charset') or 'utf-8'))
return HttpResponse(json.dumps(data), content_type="application/json")

Select rows with same id but different value in another column

Join the same table back to itself. Use an inner join so that rows that don't match are discarded. In the joined set, there will be rows that have a matching ARIDNR in another row in the table with a different LIEFNR. Allow those ARIDNR to appear in the final set.

SELECT * FROM YourTable WHERE ARIDNR IN (
    SELECT a.ARIDNR FROM YourTable a
    JOIN YourTable b on b.ARIDNR = a.ARIDNR AND b.LIEFNR <> a.LIEFNR
)

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

How to use Tomcat 8 in Eclipse?

UPDATE: Eclipse Mars EE and later have native support for Tomcat8. Use this only if you have an earlier version of eclipse.


The latest version of Eclipse still does not support Tomcat 8, but you can add the new version of WTP and Tomcat 8 support will be added natively. To do this:

  • Download the latest version of Eclipse for Java EE
  • Go to the WTP downloads page, select the latest version (currently 3.6), and download the zip (under Traditional Zip Files...Web App Developers). Here's the current link.
  • Copy the all of the files in features and plugins directories of the downloaded WTP into the corresponding Eclipse directories in your Eclipse folder (overwriting the existing files).

Start Eclipse and you should have a Tomcat 8 option available when you go to deploy. enter image description here

How to copy JavaScript object to new variable NOT by reference?

Your only option is to somehow clone the object.

See this stackoverflow question on how you can achieve this.

For simple JSON objects, the simplest way would be:

var newObject = JSON.parse(JSON.stringify(oldObject));

if you use jQuery, you can use:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

In ES6 or TypeScript (2.1+):

var shallowCopy = { ...oldObject };

var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };

Note that if extraProp is also a property on oldObject, its value will not be used because the extraProp : "abc" is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

how to make window.open pop up Modal?

Modal Window using ExtJS approach.

In Main Window

<html>
<link rel="stylesheet" href="ext.css" type="text/css">
<head>    
<script type="text/javascript" src="ext-all.js"></script>

function openModalDialog() {
    Ext.onReady(function() {
        Ext.create('Ext.window.Window', {
        title: 'Hello',
        height: Ext.getBody().getViewSize().height*0.8,
        width: Ext.getBody().getViewSize().width*0.8,
        minWidth:'730',
        minHeight:'450',
        layout: 'fit',
        itemId : 'popUpWin',        
        modal:true,
        shadow:false,
        resizable:true,
        constrainHeader:true,
        items: [{
            xtype: 'box',
            autoEl: {
                     tag: 'iframe',
                     src: '2.html',
                     frameBorder:'0'
            }
        }]
        }).show();
  });
}
function closeExtWin(isSubmit) {
     Ext.ComponentQuery.query('#popUpWin')[0].close();
     if (isSubmit) {
          document.forms[0].userAction.value = "refresh";
          document.forms[0].submit();
    }
}
</head>
<body>
   <form action="abc.jsp">
   <a href="javascript:openModalDialog()"> Click to open dialog </a>
   </form>
</body>
</html>

In popupWindow 2.html

<html>
<head>
<script type="text\javascript">
function doSubmit(action) {
     if (action == 'save') {
         window.parent.closeExtWin(true);
     } else {
         window.parent.closeExtWin(false);
     }   
}
</script>
</head>
<body>
    <a href="javascript:doSubmit('save');" title="Save">Save</a>
    <a href="javascript:doSubmit('cancel');" title="Cancel">Cancel</a>
</body>
</html>

Adding system header search path to Xcode

To use quotes just for completeness.

"/Users/my/work/a project with space"/**

If not recursive, remove the /**

Save each sheet in a workbook to separate CSV files

Building on Graham's answer, the extra code saves the workbook back into it's original location in it's original format.

Public Sub SaveWorksheetsAsCsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long

 CurrentWorkbook = ThisWorkbook.FullName
 CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook

      SaveToDirectory = "C:\"

      For Each WS In ThisWorkbook.Worksheets
          WS.SaveAs SaveToDirectory & WS.Name, xlCSV
      Next

 Application.DisplayAlerts = False
  ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
 Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
'  about overwriting the original file.

End Sub

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

Type Checking: typeof, GetType, or is?

All are different.

  • typeof takes a type name (which you specify at compile time).
  • GetType gets the runtime type of an instance.
  • is returns true if an instance is in the inheritance tree.

Example

class Animal { } 
class Dog : Animal { }

void PrintTypes(Animal a) { 
    Console.WriteLine(a.GetType() == typeof(Animal)); // false 
    Console.WriteLine(a is Animal);                   // true 
    Console.WriteLine(a.GetType() == typeof(Dog));    // true
    Console.WriteLine(a is Dog);                      // true 
}

Dog spot = new Dog(); 
PrintTypes(spot);

What about typeof(T)? Is it also resolved at compile time?

Yes. T is always what the type of the expression is. Remember, a generic method is basically a whole bunch of methods with the appropriate type. Example:

string Foo<T>(T parameter) { return typeof(T).Name; }

Animal probably_a_dog = new Dog();
Dog    definitely_a_dog = new Dog();

Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"
Foo<Animal>(probably_a_dog); // this is exactly the same as above
Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.

Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"
Foo<Dog>(definitely_a_dog); // this is exactly the same as above.
Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal". 
Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"

How to duplicate sys.stdout to a log file?

Here is another solution, which is more general than the others -- it supports splitting output (written to sys.stdout) to any number of file-like objects. There's no requirement that __stdout__ itself is included.

import sys

class multifile(object):
    def __init__(self, files):
        self._files = files
    def __getattr__(self, attr, *args):
        return self._wrap(attr, *args)
    def _wrap(self, attr, *args):
        def g(*a, **kw):
            for f in self._files:
                res = getattr(f, attr, *args)(*a, **kw)
            return res
        return g

# for a tee-like behavior, use like this:
sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])

# all these forms work:
print 'abc'
print >>sys.stdout, 'line2'
sys.stdout.write('line3\n')

NOTE: This is a proof-of-concept. The implementation here is not complete, as it only wraps methods of the file-like objects (e.g. write), leaving out members/properties/setattr, etc. However, it is probably good enough for most people as it currently stands.

What I like about it, other than its generality, is that it is clean in the sense it doesn't make any direct calls to write, flush, os.dup2, etc.

SQL server stored procedure return a table

create procedure PSaleCForms
as
begin
declare 
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar    (max),invoicenumber     nvarchar(max),invoicedate datetime,sp decimal    18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for 
select x.DBTitle,y.CurrentFinancialYear from [Accounts     Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on        y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int)     when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr],     l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from     ['+@c+'].dbo.invoicemain i inner join  ['+@c+'].dbo.ledgermain l on     l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''

insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end

How do I format my oracle queries so the columns don't wrap?

set linesize 3000

set wrap off

set termout off

set pagesize 0 embedded on

set trimspool on

Try with all above values.

JDK was not found on the computer for NetBeans 6.5

What I have found, the correct way of doing it is: "C:\Program Files (x86)\netbeans-8.0.2-windows.exe" --javahome "C:\Program Files(x86)\Java\jdk1.7.0_51"

  1. at first, the setup of NetBeans must be saved on your hard disk
  2. go to the place where your setup is, click properties and copy the path.
  3. Add two back slashes in it and put it in double quotes like so: "C:\Program Files (x86)\netbeans-8.0.2-windows.exe"
  4. then go to the folder where your jdk is, click properties, copy the path, put double back slashes where necessary and then put it in double quotes: "C:\Program Files(x86)\Java\jdk1.7.0_51"
  5. then just follow the format of the first link given and you'll install it

Note: run this link in the command prompt

How to connect to a remote MySQL database with Java?

to access database from remote machine , you need to give grant all privileges to you data base.

run the following script to give permissions: GRANT ALL PRIVILEGES ON . TO user@'%' IDENTIFIED BY 'password';

Java: How to set Precision for double value?

To expand on @EJP, the concept of 'precision' when dealing with doubles is extremely fraught. As discussed in https://stackoverflow.com/a/3730040/390153 you can't even represent 0.1 as a double regardless of the precision, for the same reason you can't represent 1/3 in base 10 with finite precision.

You need to consider the problem you are trying to solve, and consider:

a) Should I be using doubles in the first place; if precision is a relevant concept, then using doubles may well be a mistake.

b) If doubles are appropriate, what do I mean by precision? If you are only talking about display, wrap the logic in a display function and you will only need to deal with it in one place; ie. apply the DRY principle.

Sorting A ListView By Column

Late to the party, here is a short one. It has these limitations:

  • It only does a plain string sort of the SubItems' Texts
  • It uses the ListView's Tag
  • It assumes all clicked columns will be filled

You can register & unregister any ListView to its service; make sure the Sorting is set to None..:

public static class LvSort
{
    static List<ListView> LVs = new List<ListView>();
    public static void registerLV(ListView lv)
    {
        if (!LVs.Contains(lv) && lv is ListView)
        {
            LVs.Add(lv);
            lv.ColumnClick +=Lv_ColumnClick;
        }
    }
    public static void unRegisterLV(ListView lv)
    {
        if (LVs.Contains(lv) && lv is ListView)
        {
            LVs.Remove(lv);
            lv.ColumnClick -=Lv_ColumnClick;
        }
    }

    private static void Lv_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListView lv = sender as ListView;
        if (lv == null) return;
        int c = e.Column;
        bool asc = (lv.Tag == null) || ( lv.Tag.ToString() != c+"");
        var items = lv.Items.Cast<ListViewItem>().ToList();
        var sorted =  asc ? items.OrderByDescending(x => x.SubItems[c].Text).ToList() :
                            items.OrderBy(x => x.SubItems[c].Text).ToList();
        lv.Items.Clear();
        lv.Items.AddRange(sorted.ToArray());
        if (asc) lv.Tag = c+""; else lv.Tag = null;
    }
}

To register simply do..:

public Form1()
{
    InitializeComponent();
    LvSort.registerLV(yourListView1);
}

Update:

Here is a slightly extended version that will let you sort all sorts of data types using any sorting rule you come up with. All you need to do is write a special string conversion for your data, add it to the function list and mark your columns. To do so simply put the column names appended with a marker string in the columns' Tags.

I have added one for sorting DataTimes and one for integers.

This version will also sort jagged ListViews, i.e. those with different numbers of subitems.

public static class LvCtl
{
    static List<ListView> LVs = new List<ListView>();

    delegate string  StringFrom (string s);

    static Dictionary<string, StringFrom> funx = new Dictionary<string, StringFrom>();

    public static void registerLV(ListView lv)
    {
        if (!LVs.Contains(lv) && lv is ListView)
        {
            LVs.Add(lv);
            lv.ColumnClick +=Lv_ColumnClick;

            funx.Add("", stringFromString);
            for (int i = 0; i <  lv.Columns.Count; i++)
            {
                if (lv.Columns[i].Tag == null) continue;
                string n = lv.Columns[i].Tag.ToString();
                if (n == "") continue;
                if (n.Contains("__date")) funx.Add(n, stringFromDate);
                if (n.Contains("__int")) funx.Add(n, stringFromInt);
                else funx.Add(n, stringFromString);
            }

        }
    }

    static string stringFromString(string s)
    {
        return s;
    }
    static string stringFromInt(string s)
    {
        int i = 0;
        int.TryParse(s, out i);
        return i.ToString("00000") ;
    }
    static string stringFromDate(string s)
    {
        DateTime dt = Convert.ToDateTime(s);
        return dt.ToString("yyyy.MM.dd HH.mm.ss");
    }

    private static void Lv_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListView lv = sender as ListView;
        if (lv == null) return;


        int c = e.Column;
        string nt = lv.Columns[c].Tag != null ? lv.Columns[c].Tag.ToString() : "";
        string n = nt.Replace("__", "§").Split('§')[0];

        bool asc = (lv.Tag == null) || ( lv.Tag.ToString() != c+"");
        var items = lv.Items.Cast<ListViewItem>().ToList();
        var sorted =  asc?
            items.OrderByDescending(x =>  funx[nt]( c < x.SubItems.Count ?
                                    x.SubItems[c].Text: "")).ToList() :
            items.OrderBy(x => funx[nt](c < x.SubItems.Count ?
                          x.SubItems[c].Text : "")).ToList();
        lv.Items.Clear();
        lv.Items.AddRange(sorted.ToArray());
        if (asc) lv.Tag = c+""; else lv.Tag = null;
    }

    public static void unRegisterLV(ListView lv)
    {
        if (LVs.Contains(lv) && lv is ListView)
        {
            LVs.Remove(lv);
            lv.ColumnClick -=Lv_ColumnClick;
        }
    }
}

Replace a value in a data frame based on a conditional (`if`) statement

You have created a factor variable in nm so you either need to avoid doing so or add an additional level to the factor attributes. You should also avoid using <- in the arguments to data.frame()

Option 1:

junk <- data.frame(x = rep(LETTERS[1:4], 3), y =letters[1:12], stringsAsFactors=FALSE)
junk$nm[junk$nm == "B"] <- "b"

Option 2:

levels(junk$nm) <- c(levels(junk$nm), "b")
junk$nm[junk$nm == "B"] <- "b"
junk

Determine direct shared object dependencies of a Linux binary?

ldd -v prints the dependency tree under "Version information:' section. The first block in that section are the direct dependencies of the binary.

See Hierarchical ldd(1)

How to reload the datatable(jquery) data?

For the newer versions use:

var datatable = $('#table').dataTable().api();

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Taken from: https://stackoverflow.com/a/27781459/4059810

Values of disabled inputs will not be submitted

Yes, all browsers should not submit the disabled inputs, as they are read-only.

More information (section 17.12.1)

Attribute definitions

disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:

  • Disabled controls do not receive focus.
  • Disabled controls are skipped in tabbing navigation.
  • Disabled controls cannot be successful.

The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.

This attribute is inherited but local declarations override the inherited value.

How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

<INPUT disabled name="fred" value="stone">

Note. The only way to modify dynamically the value of the disabled attribute is through a script.

Is there a better way to compare dictionary values

If you're just comparing for equality, you can just do this:

if not dict1 == dict2:
    match = False

Otherwise, the only major problem I see is that you're going to get a KeyError if there is a key in dict1 that is not in dict2, so you may want to do something like this:

for key in dict1:
    if not key in dict2 or dict1[key] != dict2[key]:
        match = False

You could compress this into a comprehension to just get the list of keys that don't match too:

mismatch_keys = [key for key in x if not key in y or x[key] != y[key]]
match = not bool(mismatch_keys) #If the list is not empty, they don't match 
for key in mismatch_keys:
    print key
    print '%s -> %s' % (dict1[key],dict2[key])

The only other optimization I can think of might be to use "len(dict)" to figure out which dict has fewer entries and loop through that one first to have the shortest loop possible.

How can I convert a Word document to PDF?

Check out docs-to-pdf-converter on github. Its a lightweight solution designed specifically for converting documents to pdf.

Why?

I wanted a simple program that can convert Microsoft Office documents to PDF but without dependencies like LibreOffice or expensive proprietary solutions. Seeing as how code and libraries to convert each individual format is scattered around the web, I decided to combine all those solutions into one single program. Along the way, I decided to add ODT support as well since I encountered the code too.

How to access remote server with local phpMyAdmin client?

Locate the file libraries/config.default.php

then find $cfg['AllowArbitraryServer'] = false;

then set It to true

note:

on ubuntu the file in the path /usr/share/phpmyadmin/libraries/config.default.php

then you will find a new filed name SERVER in the main PHPMyAdmin page, you can add any IP or localhost for the local database.

Remove object from a list of objects in python

If you know the array location you can can pass it into itself. If you are removing multiple items I suggest you remove them in reverse order.

#Setup array
array = [55,126,555,2,36]
#Remove 55 which is in position 0
array.remove(array[0])

Why do we have to specify FromBody and FromUri?

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

At most one parameter is allowed to read from the message body. So this will not work:

// Caution: Will not work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Please go through the website for more details: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Build Android Studio app via command line

1. Install Gradle and the Android SDK

Either

  • Install these however you see fit
  • Run ./gradlew, or gradlew.bat if on Windows
    • chmod +x ./gradlew may be necessary

From this point onwards, gradle refers to running Gradle whichever way you've chosen. Substitute accordingly.

2. Setup the Android SDK

  • If you've manually installed the SDK

    • export ANDROID_HOME=<install location>
    • You may want to put that in your ~/.profile if it's not done automatically
  • Accept the licenses: yes | sdkmanager --licenses

    • sdkmanager can be found in $ANDROID_HOME/tools/bin
    • sdkmanager may have to be run as root
  • Try running gradle

    • If there are complaints about licenses or SDKs not being found, fix the directory permissions
      • chown -R user:group $ANDROID_HOME
      • If you're reckless and/or the only user: chmod 777 -R $ANDROID_HOME

3. Building

  • gradle tasks lists all tasks that can be run
  • :app:[appname] is the prefix of all tasks, which you'll see in the Gradle logs when you're building
    • This can be excluded when running a task

Some essential tasks

  • gradle assemble: build all variants of your app
    • Resulting .apks are in app/[appname]/build/outputs/apk/[debug/release]
  • gradle assembleDebug or assembleRelease: build just the debug or release versions
  • gradle installDebug or installRelease build and install to an attached device
    • Have adb installed
    • Attach a device with USB debugging and USB file transfer enabled
    • Run adb devices, check that your device is listed and device is beside it

Automatically build and install upon changes

This avoids having to continuously run the same commands

gradle -t --continue installDebug
  • -t: aka --continuous, automatically re-runs the task after a file is changed
  • --continue: Continue after errors. Prevents stopping when errors occur

Run gradle -h for more help

Replacing H1 text with a logo image: best method for SEO and accessibility?

<h1>
  <a href="http://stackoverflow.com">
  Stack Overflow<img src="logo.png" alt="Stack Overflow" />
  </a>
</h1>

This was the good option for SEO because SEO gives the H1 tag high priority, inside the h1 tag should be your site name. Using this method if you search the site name in SEO it will show your site logo as well.

you want to hide the site name OR text please use text-indent in negative value. ex

h1 a {
 text-indent: -99999px;
}

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.

First, run following code in the console:

chcp 65001
set PYTHONIOENCODING=utf-8

Then, start python do anything you want.

How to terminate a Python script

A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.

Example:

#do stuff
if this == that:
  quit()

#define in Java

Manifold Preprocessor implemented as a javac compiler plugin is designed exclusively for conditional compilation of Java source code. It uses familiar C/C++ style of directives: #define, #undef, #if, #elif, #else, #endif, #error. and #warning.

It has Maven and Gradle plugins.

Difference between a SOAP message and a WSDL?

We can consider a telephone call In that Number is wsdl and exchange of information is soap.

WSDL is description how to connect with communication server.SOAP is have communication messages.

How to implement a Keyword Search in MySQL?

Personally, I wouldn't use the LIKE string comparison on the ID field or any other numeric field. It doesn't make sense for a search for ID# "216" to return 16216, 21651, 3216087, 5321668..., and so on and so forth; likewise with salary.

Also, if you want to use prepared statements to prevent SQL injections, you would use a query string like:

SELECT * FROM job WHERE `position` LIKE CONCAT('%', ? ,'%') OR ...

Calculate MD5 checksum for a file

This is how I do it:

using System.IO;
using System.Security.Cryptography;

public string checkMD5(string filename)
{
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(filename))
        {
            return Encoding.Default.GetString(md5.ComputeHash(stream));
        }
    }
}

Adding double quote delimiters into csv file

In Excel for Mac at least, you can do this by saving as "CSV for MS DOS" which adds double quotes for any field which needs them.

Assignment inside lambda expression in Python

Normal assignment (=) is not possible inside a lambda expression, although it is possible to perform various tricks with setattr and friends.

Solving your problem, however, is actually quite simple:

input = [Object(name=""), Object(name="fake_name"), Object(name="")]
output = filter(
    lambda o, _seen=set():
        not (not o and o in _seen or _seen.add(o)),
    input
    )

which will give you

[Object(Object(name=''), name='fake_name')]

As you can see, it's keeping the first blank instance instead of the last. If you need the last instead, reverse the list going in to filter, and reverse the list coming out of filter:

output = filter(
    lambda o, _seen=set():
        not (not o and o in _seen or _seen.add(o)),
    input[::-1]
    )[::-1]

which will give you

[Object(name='fake_name'), Object(name='')]

One thing to be aware of: in order for this to work with arbitrary objects, those objects must properly implement __eq__ and __hash__ as explained here.

Show two digits after decimal point in c++

It is possible to print a 15 decimal number in C++ using the following:

#include <iomanip>
#include <iostream>

cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();

return 0;

How can Bash execute a command in a different directory context?

(cd /path/to/your/special/place;/bin/your-special-command ARGS)

fetch gives an empty response body

This requires changes to the frontend JS and the headers sent from the backend.

Frontend

Remove "mode":"no-cors" in the fetch options.

fetch(
  "http://example.com/api/docs", 
  {
    // mode: "no-cors",
    method: "GET"
  }
)
  .then(response => response.text())
  .then(data => console.log(data))

Backend

When your server responds to the request, include the CORS headers specifying the origin from where the request is coming. If you don't care about the origin, specify the * wildcard.

The raw response should include a header like this.

Access-Control-Allow-Origin: *

How to encode a string in JavaScript for displaying in HTML?

Do not bother with encoding. Use a text node instead. Data in text node is guaranteed to be treated as text.

document.body.appendChild(document.createTextNode("Your&funky<text>here"))

Fastest way to check if a string matches a regexp in ruby?

Starting with Ruby 2.4.0, you may use RegExp#match?:

pattern.match?(string)

Regexp#match? is explicitly listed as a performance enhancement in the release notes for 2.4.0, as it avoids object allocations performed by other methods such as Regexp#match and =~:

Regexp#match?
Added Regexp#match?, which executes a regexp match without creating a back reference object and changing $~ to reduce object allocation.

How to add hyperlink in JLabel?

You can use this under an

actionListener ->  Runtime.getRuntime().exec("cmd.exe /c start chrome www.google.com")`

or if you want to use Internet Explorer or Firefox replace chrome with iexplore or firefox

How to extract 1 screenshot for a video with ffmpeg at a given time?

Use the -ss option:

ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
  • For JPEG output use -q:v to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.

  • The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.

  • Placing -ss before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg cli tool documentation:

-ss position (input/output)

When used as an input option (before -i), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.

position may be either in seconds or in hh:mm:ss[.xxx] form.

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

How do I download a binary file over HTTP?

Example 3 in the Ruby's net/http documentation shows how to download a document over HTTP, and to output the file instead of just loading it into memory, substitute puts with a binary write to a file, e.g. as shown in Dejw's answer.

More complex cases are shown further down in the same document.

How do I create a multiline Python string with inline variables?

NOTE: The recommended way to do string formatting in Python is to use format(), as outlined in the accepted answer. I'm preserving this answer as an example of the C-style syntax that's also supported.

# NOTE: format() is a better choice!
string1 = "go"
string2 = "now"
string3 = "great"

s = """
I will %s there
I will go %s
%s
""" % (string1, string2, string3)

print(s)

Some reading:

How to resolve the C:\fakepath?

You would be able to get at least temporary created copy of the file path on your machine. The only condition here is your input element should be within a form What you have to do else is putting in the form an attribute enctype, e.g.:

<form id="formid" enctype="multipart/form-data" method="post" action="{{url('/add_a_note' )}}">...</form>

enter image description here you can find the path string at the bottom. It opens stream to file and then deletes it.

Using media breakpoints in Bootstrap 4-alpha

Use breakpoint mixins like this:

.something {
    padding: 5px;
    @include media-breakpoint-up(sm) { 
        padding: 20px;
    }
    @include media-breakpoint-up(md) { 
        padding: 40px;
    }
}

v4 breakpoints reference

v4 alpha6 breakpoints reference


Below full options and values.

Breakpoint & up (toggle on value and above):

@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }

breakpoint & up values:

// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

breakpoint & down (toggle on value and down):

@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }

breakpoint & down values:

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }

// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }

// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }

// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width

breakpoint only:

@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }

breakpoint only values (toggle in between values only):

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

Difference between Destroy and Delete

Basically destroy runs any callbacks on the model while delete doesn't.

From the Rails API:

  • ActiveRecord::Persistence.delete

    Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

    The row is simply removed with an SQL DELETE statement on the record's primary key, and no callbacks are executed.

    To enforce the object's before_destroy and after_destroy callbacks or any :dependent association options, use #destroy.

  • ActiveRecord::Persistence.destroy

    Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted).

    There's a series of callbacks associated with destroy. If the before_destroy callback return false the action is cancelled and destroy returns false. See ActiveRecord::Callbacks for further details.

How do I change Bootstrap 3 column order on mobile layout?

You cannot change the order of columns in smaller screens but you can do that in large screens.

So change the order of your columns.

<!--Main Content-->
<div class="col-lg-9 col-lg-push-3">
</div>

<!--Sidebar-->
<div class="col-lg-3 col-lg-pull-9">
</div>

By default this displays the main content first.

So in mobile main content is displayed first.

By using col-lg-push and col-lg-pull we can reorder the columns in large screens and display sidebar on the left and main content on the right.

Working fiddle here.

How do I change the IntelliJ IDEA default JDK?

I am using IntelliJ 2020.3.1 and the File > Other Settings... menu option has disappeared. I went to Settings in the usual way and searched for "jdk". Under Build, Execution, Deployment > Build Tools > Maven > Importing I found the the setting that will solve my specific issue:

JDK for importer.

IntelliJ 2020.3 Settings dialog

How can I catch a ctrl-c event?

For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.

See here for an example.