Programs & Examples On #Httpverbs

What is the main difference between PATCH and PUT request?

I spent couple of hours with google and found the answer here

PUT => If user can update all or just a portion of the record, use PUT (user controls what gets updated)

PUT /users/123/email
[email protected]

PATCH => If user can only update a partial record, say just an email address (application controls what can be updated), use PATCH.

PATCH /users/123
[description of changes]

Why Patch

PUT method need more bandwidth or handle full resources instead on partial. So PATCH was introduced to reduce the bandwidth.

Explanation about PATCH

PATCH is a method that is not safe, nor idempotent, and allows full and partial updates and side-effects on other resources.

PATCH is a method which enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.

PATCH /users/123
[
  { "op": "replace", "path": "/email", "value": "[email protected]" }
]

Here more information about put and patch

server error:405 - HTTP verb used to access this page is not allowed

I fixed mine by adding these lines on my IIS webconfig.

<httpErrors>
    <remove statusCode="405" subStatusCode="-1" />
    <error statusCode="405" prefixLanguageFilePath="" path="/my-page.htm" responseMode="ExecuteURL" />
</httpErrors>

Combine GET and POST request methods in Spring

Below is one of the way by which you can achieve that, may not be an ideal way to do.

Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.

@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
     //handle both get and post request here
     // first check request type and do respective actions needed for get and post.

    if(GET REQUEST){

     //WORK RELATED TO GET

    }else if(POST REQUEST){

      //WORK RELATED TO POST

    }

    commonMethod(param1, param2....);
}

Comparing results with today's date?

Building on the previous answers, please note an important point, you also need to manipulate your table column to ensure it does not contain the time fragment of the datetime datatype.

Below is a small sample script demonstrating the above:

select getdate()
--2012-05-01 12:06:51.413
select cast(getdate() as date)
--2012-05-01

--we're using sysobjects for the example
create table test (id int)
select * from sysobjects where cast(crdate as date) = cast(getdate() as date)
--resultset contains only objects created today
drop table test

I hope this helps.

EDIT:
Following @dwurf comment (thanks) about the effect the above example may have on performance, I would like to suggest the following instead. We create a date range between today at midnight (start of day) and the last millisecond of the day (SQL server count up to .997, that's why I'm reducing 3 milliseconds). In this manner we avoid manipulating the left side and avoid the performance impact.

select getdate()
--2012-05-01 12:06:51.413
select dateadd(millisecond, -3, cast(cast(getdate()+1 as date) as datetime))
--2012-05-01 23:59:59.997
select cast(getdate() as date)
--2012-05-01

create table test (id int)
select * from sysobjects where crdate between cast(getdate() as date) and dateadd(millisecond, -3, cast(cast(getdate()+1 as date) as datetime))
--resultset contains only objects created today
drop table test

Load local javascript file in chrome for testing?

Running a simple local HTTP server

To test such examples, one needs a local webserver. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer (or http.server, depending on the version of Python installed.)

# Install Python & try one of the following depending on your python version. if the version is 3.X
python3 -m http.server
# On windows try "python" instead of "python3", or "py -3"
# If Python version is 2.X
python -m SimpleHTTPServer

Encrypt & Decrypt using PyCrypto AES 256

Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes:

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):

    def __init__(self, key): 
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

How to make an HTTP get request with parameters

My preferred way is this. It handles the escaping and parsing for you.

WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");

The best way to remove duplicate values from NSMutableArray in Objective-C?

Note that if you have a sorted array, you don't need to check against every other item in the array, just the last item. This should be much faster than checking against all items.

// sortedSourceArray is the source array, already sorted
NSMutableArray *newArray = [[NSMutableArray alloc] initWithObjects:[sortedSourceArray objectAtIndex:0]];
for (int i = 1; i < [sortedSourceArray count]; i++)
{
    if (![[sortedSourceArray objectAtIndex:i] isEqualToString:[sortedSourceArray objectAtIndex:(i-1)]])
    {
        [newArray addObject:[tempArray objectAtIndex:i]];
    }
}

It looks like the NSOrderedSet answers that are also suggested require a lot less code, but if you can't use an NSOrderedSet for some reason, and you have a sorted array, I believe my solution would be the fastest. I'm not sure how it compares with the speed of the NSOrderedSet solutions. Also note that my code is checking with isEqualToString:, so the same series of letters will not appear more than once in newArray. I'm not sure if the NSOrderedSet solutions will remove duplicates based on value or based on memory location.

My example assumes sortedSourceArray contains just NSStrings, just NSMutableStrings, or a mix of the two. If sortedSourceArray instead contains just NSNumbers or just NSDates, you can replace

if (![[sortedSourceArray objectAtIndex:i] isEqualToString:[sortedSourceArray objectAtIndex:(i-1)]])

with

if ([[sortedSourceArray objectAtIndex:i] compare:[sortedSourceArray objectAtIndex:(i-1)]] != NSOrderedSame)

and it should work perfectly. If sortedSourceArray contains a mix of NSStrings, NSNumbers, and/or NSDates, it will probably crash.

How do I measure the execution time of JavaScript code with callbacks?

I had same issue while moving from AWS to Azure

For express & aws, you can already use, existing time() and timeEnd()

For Azure, use this: https://github.com/manoharreddyporeddy/my-nodejs-notes/blob/master/performance_timers_helper_nodejs_azure_aws.js

These time() and timeEnd() use the existing hrtime() function, which give high-resolution real time.

Hope this helps.

Is String.Contains() faster than String.IndexOf()?

If you really want to micro optimise your code your best approach is always benchmarking.

The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch

store and retrieve a class object in shared preference

Common shared preference (CURD) SharedPreference: to Store data in the form of value-key pairs with a simple Kotlin class.

var sp = SharedPreference(this);

Storing Data:

To store String, Int and Boolean data we have three methods with the same name and different parameters (Method overloading).

save("key-name1","string value")
save("key-name2",int value)
save("key-name3",boolean)

Retrieve Data: To Retrieve the data stored in SharedPreferences use the following methods.

sp.getValueString("user_name")
sp.getValueInt("user_id")
sp.getValueBoolean("user_session",true)

Clear All Data: To clear the entire SharedPreferences use the below code.

 sp.clearSharedPreference()

Remove Specific Data:

sp.removeValue("user_name")

Common Shared Preference Class

import android.content.Context
import android.content.SharedPreferences

class SharedPreference(private val context: Context) {
    private val PREFS_NAME = "coredata"
    private val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    //********************************************************************************************** save all
    //To Store String data
    fun save(KEY_NAME: String, text: String) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putString(KEY_NAME, text)
        editor.apply()
    }
    //..............................................................................................
    //To Store Int data
    fun save(KEY_NAME: String, value: Int) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putInt(KEY_NAME, value)
        editor.apply()
    }
    //..............................................................................................
    //To Store Boolean data
    fun save(KEY_NAME: String, status: Boolean) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putBoolean(KEY_NAME, status)
        editor.apply()
    }
    //********************************************************************************************** retrieve selected
    //To Retrieve String
    fun getValueString(KEY_NAME: String): String? {

        return sharedPref.getString(KEY_NAME, "")
    }
    //..............................................................................................
    //To Retrieve Int
    fun getValueInt(KEY_NAME: String): Int {

        return sharedPref.getInt(KEY_NAME, 0)
    }
    //..............................................................................................
    // To Retrieve Boolean
    fun getValueBoolean(KEY_NAME: String, defaultValue: Boolean): Boolean {

        return sharedPref.getBoolean(KEY_NAME, defaultValue)
    }
    //********************************************************************************************** delete all
    // To clear all data
    fun clearSharedPreference() {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.clear()
        editor.apply()
    }
    //********************************************************************************************** delete selected
    // To remove a specific data
    fun removeValue(KEY_NAME: String) {
        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.remove(KEY_NAME)
        editor.apply()
    }
}

Blog: https://androidkeynotes.blogspot.com/2020/02/shared-preference.html

How to output numbers with leading zeros in JavaScript?

function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}

jQuery - Disable Form Fields

The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true);

And to enable again you could do

$myForm.find(':input:disabled').prop('disabled',false);

How to enable scrolling on website that disabled scrolling?

In a browser like Chrome etc.:

  1. Inspect the code (for e.g. in Chrome press ctrl + shift + c);
  2. Set overflow: visible on body element (for e.g., <body style="overflow: visible">)
  3. Find/Remove any JavaScripts that may routinely be checking for removal of the overflow property:
    • To find such JavaScript code, you could for example, go through the code, or click on different JavaScript code in the code debugger console and hit backspace on your keyboard to remove it.
    • If you're having trouble finding it, you can simply try removing a couple of JavaScripts (you can of course simply press ctrl + z to undo whatever code you delete, or hit refresh to start over).

Good luck!

How to Solve Max Connection Pool Error

Check against any long running queries in your database.

Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)

You can use sql server profiler and filter on duration / reads to see which querys need optimization.

I also see you're probably keeping a global connection?

blnMainConnectionIsCreatedLocal

Let .net do the pooling for you and open / close your connection with a using statement.

Suggestions:

  1. Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
         conn.Open();
         // do some stuff
        } //conn disposed
    
  2. As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.

How can I use a custom font in Java?

From the Java tutorial, you need to create a new font and register it in the graphics environment:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));

After this step is done, the font is available in calls to getAvailableFontFamilyNames() and can be used in font constructors.

Parsing HTML using Python

I recommend lxml for parsing HTML. See "Parsing HTML" (on the lxml site).

In my experience Beautiful Soup messes up on some complex HTML. I believe that is because Beautiful Soup is not a parser, rather a very good string analyzer.

Can HTML be embedded inside PHP "if" statement?

Yes,

<?php
if ( $my_name == "someguy" ) {
    ?> HTML GOES HERE <?php;
}
?>

html select option separator

This one is best always.

<option>First</option>
<option disabled>_________</option>
<option>Second</option>
<option>Third</option>

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

How to Determine the Screen Height and Width in Flutter

The below code doesn't return the correct screen size sometimes:

MediaQuery.of(context).size

I tested on SAMSUNG SM-T580, which returns {width: 685.7, height: 1097.1} instead of the real resolution 1920x1080.

Please use:

import 'dart:ui';

window.physicalSize;

Is there a way to make Firefox ignore invalid ssl-certificates?

Create some nice new 10 year certificates and install them. The procedure is fairly easy.

Start at (1B) Generate your own CA (Certificate Authority) on this web page: Creating Certificate Authorities and self-signed SSL certificates and generate your CA Certificate and Key. Once you have these, generate your Server Certificate and Key. Create a Certificate Signing Request (CSR) and then sign the Server Key with the CA Certificate. Now install your Server Certificate and Key on the web server as usual, and import the CA Certificate into Internet Explorer's Trusted Root Certification Authority Store (used by the Flex uploader and Chrome as well) and into Firefox's Certificate Manager Authorities Store on each workstation that needs to access the server using the self-signed, CA-signed server key/certificate pair.

You now should not see any warning about using self-signed Certificates as the browsers will find the CA certificate in the Trust Store and verify the server key has been signed by this trusted certificate. Also in e-commerce applications like Magento, the Flex image uploader will now function in Firefox without the dreaded "Self-signed certificate" error message.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

Before running the unit tests, just remove the runtime tags from app.config file. Problem will be solved.

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Yes. you can use SimpleDateFormat like this.

SimpleDateFormat formatter, FORMATTER;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String oldDate = "2011-03-10T11:54:30.207Z";
Date date = formatter.parse(oldDate.substring(0, 24));
FORMATTER = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
System.out.println("OldDate-->"+oldDate);
System.out.println("NewDate-->"+FORMATTER.format(date));

Output OldDate-->2011-03-10T11:54:30.207Z NewDate-->10-Mar-2011 11:54:30.207

How to disable a ts rule for a specific line?

You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

You can always temporarily cast $ to any:

delete ($ as any).summernote.options.keyMap.pc.TAB

which will allow you to access whatever properties you want.


Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

How are Anonymous inner classes used in Java?

new Thread() {
        public void run() {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                System.out.println("Exception message: " + e.getMessage());
                System.out.println("Exception cause: " + e.getCause());
            }
        }
    }.start();

This is also one of the example for anonymous inner type using thread

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

IEnumerable vs List - What to Use? How do they work?

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

enter image description here enter image description here

Visual Studio: Relative Assembly References Paths

Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.

I have done this several times under svn and under cvs.

php form action php self

The easiest way to do it is leaving action blank action="" or omitting it completely from the form tag, however it is bad practice (if at all you care about it).

Incase you do care about it, the best you can do is:

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="<?php echo($_SERVER['PHP_SELF'] . http_build_query($_GET));?>">

The best thing about using this is that even arrays are converted so no need to do anything else for any kind of data.

Replace \n with <br />

thatLine = thatLine.replace('\n', '<br />')

str.replace() returns a copy of the string, it doesn't modify the string you pass in.

How to subtract X day from a Date object in Java?

You can easily subtract with calendar with SimpleDateFormat

 public static String subtractDate(String time,int subtractDay) throws ParseException {


        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
        cal.setTime(sdf.parse(time));
        cal.add(Calendar.DATE,-subtractDay);
        String wantedDate = sdf.format(cal.getTime());

        Log.d("tag",wantedDate);
        return wantedDate;

    }

How to make a gui in python

Using Qt in Python is a really pleasant experience: http://wiki.python.org/moin/PyQt

For the quick tutorial: http://zetcode.com/tutorials/pyqt4/

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For anyone wondering about the difference between -1.#IND00 and -1.#IND (which the question specifically asked, and none of the answers address):

-1.#IND00

This specifically means a non-zero number divided by zero, e.g. 3.14 / 0 (source)

-1.#IND (a synonym for NaN)

This means one of four things (see wiki from source):

1) sqrt or log of a negative number

2) operations where both variables are 0 or infinity, e.g. 0 / 0

3) operations where at least one variable is already NaN, e.g. NaN * 5

4) out of range trig, e.g. arcsin(2)

ResultSet exception - before start of result set

You have to do a result.next() before you can access the result. It's a very common idiom to do

ResultSet rs = stmt.executeQuery();
while (rs.next())
{
   int foo = rs.getInt(1);
   ...
}

Where is the correct location to put Log4j.properties in an Eclipse project?

The safest way IMO is to point at the file in your run/debug config

-Dlog4j.configuration=file:mylogging.properties

! Be aware: when using the eclipse launch configurations the specification of the file: protocol is mandatory.

In this way the logger will not catch any logging.properties that come before in the classpath nor the default one in the JDK.

Also, consider actually use the log4j.xml which has a richer expression syntax and will allow more things (log4j.xml tahe precedence over log4j.properties.

How do I prevent a Gateway Timeout with FastCGI on Nginx

If you use unicorn.

Look at top on your server. Unicorn likely is using 100% of CPU right now. There are several reasons of this problem.

  • You should check your HTTP requests, some of their can be very hard.

  • Check unicorn's version. May be you've updated it recently, and something was broken.

Visual Studio 2017: Display method references

For display references on the top of method you have to enabled the CodeLens option in Visual Studio Professional and Visual Studio Enterprise.

Use below steps to enabled it.

1. Go to Tools and then select Options :

enter image description here

2. Then Select Text Editor -> All Languages -> CodeLens

enter image description here

3. Click on check box to Enable Code Lens: enter image description here

Now you can see the references on the top of methods.

This will not work for VS - Community Edition.

Cheers!

Set Windows process (or user) memory limit

No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.

The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.

The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.

static function in C

C programmers use the static attribute to hide variable and function declarations inside modules, much as you would use public and private declarations in Java and C++. C source files play the role of modules. Any global variable or function declared with the static attribute is private to that module. Similarly, any global variable or function declared without the static attribute is public and can be accessed by any other module. It is good programming practice to protect your variables and functions with the static attribute wherever possible.

PHP decoding and encoding json with unicode characters

$json = array('tag' => 'Odómetro'); // Original array
$json = json_encode($json); // {"Tag":"Od\u00f3metro"}
$json = json_decode($json); // Od\u00f3metro becomes  Odómetro
echo $json->{'tag'}; // Odómetro
echo utf8_decode($json->{'tag'}); // Odómetro

You were close, just use utf8_decode.

Oracle SQL - select within a select (on the same table!)

SELECT eh."Gc_Staff_Number",
       eh."Start_Date",
       MAX(eh2."End_Date") AS "End_Date"
FROM   "Employment_History" eh
LEFT JOIN  "Employment_History" eh2
ON eh."Employee_Number" = eh2."Employee_Number" and eh2."Current_Flag" != 'Y'
WHERE  eh."Current_Flag" = 'Y' 
GROUP BY eh."Gc_Staff_Number",
       eh."Start_Date

Why I can't access remote Jupyter Notebook server?

I'm using Anaconda3 on Windows 10. When you install it rembember to flag "add to Enviroment Variables".


Prerequisite: A notebook configuration file

Check to see if you have a notebook configuration file, jupyter_notebook_config.py. The default location for this file is your Jupyter folder located in your home directory:

  • Windows: C:\\Users\\USERNAME\\.jupyter\\jupyter_notebook_config.py
  • OS X: /Users/USERNAME/.jupyter/jupyter_notebook_config.py
  • Linux: /home/USERNAME/.jupyter/jupyter_notebook_config.py

If you don't already have a Jupyter folder, or if your Jupyter folder doesn't contain a notebook configuration file, run the following command:

$ jupyter notebook --generate-config

This command will create the Jupyter folder if necessary, and create notebook configuration file, jupyter_notebook_config.py, in this folder.


By default, Jupyter Notebook only accepts connections from localhost.

Edit the jupyter_notebook_config.py file as following to accept all incoming connections:

c.NotebookApp.allow_origin = '*' #allow all origins

You'll also need to change the IPs that the notebook will listen on:

c.NotebookApp.ip = '0.0.0.0' # listen on all IPs

Insert images to XML file

I always convert the byte data to a Base64 encoding and then insert the image.

This is also the way that Word does it, for it's XML files (not that Word is a good example on how to work with XML :P).

Difficulty with ng-model, ng-repeat, and inputs

I just updated AngularJs to 1.1.2 and have no problem with it. I guess this bug was fixed.

http://ci.angularjs.org/job/angular.js-pete/57/artifact/build/angular.js

JAVA_HOME directory in Linux

On the Terminal, type:

echo "$JAVA_HOME"

If you are not getting anything, then your environment variable JAVA_HOME has not been set. You can try using "locate java" to try and discover where your installation of Java is located.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

iPhone - Get Position of UIView within entire UIWindow

Swift 3, with extension:

extension UIView{
    var globalPoint :CGPoint? {
        return self.superview?.convert(self.frame.origin, to: nil)
    }

    var globalFrame :CGRect? {
        return self.superview?.convert(self.frame, to: nil)
    }
}

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Spring Data and Native Query with pagination

Try this:

public interface UserRepository extends JpaRepository<User, Long> {
  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1 ORDER BY /*#pageable*/",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}

("/* */" for Oracle notation)

Why are the Level.FINE logging messages not showing?

Tried other variants, this can be proper

    Logger logger = Logger.getLogger(MyClass.class.getName());        
    Level level = Level.ALL;
    for(Handler h : java.util.logging.Logger.getLogger("").getHandlers())    
        h.setLevel(level);
    logger.setLevel(level);
// this must be shown
    logger.fine("fine");
    logger.info("info");

Adding a custom header to HTTP request using angular.js

Basic authentication using HTTP POST method:

$http({
    method: 'POST',
    url: '/API/authenticate',
    data: 'username=' + username + '&password=' + password + '&email=' + email,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

...and GET method call with header:

$http({
    method: 'GET',
    url: '/books',
    headers: {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json',
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

Multi value Dictionary

I know this is an old thread, but - since it's not been mentioned this works

  Dictionary<string, object> LookUp = new Dictionary<string, object>();
  LookUp.Add("bob", new { age = "23", height = "2.1m", weight = "110kg"});
  LookUp.Add("jasper", new { age = "33", height = "1.75m", weight = "90kg"});
  foreach(KeyValuePair<string, object> entry in LookUp )
  {
      object person = entry.Value;
      Console.WriteLine("Person name:" + entry.Key + " Age: "  + person.age);          
  }

How to reload a page using JavaScript

Thank you, this post was very helpful, not only to reload the page with the suggested answer, but also as well to give me the idea to place a jQuery UI icon to a button:

<button style="display:block; vertical-align:middle; height:2.82em;"
        title="Cargar nuevamente el código fuente sin darle un [Enter] a la dirección en la barra de direcciones"
        class="ui-state-active ui-corner-all ui-priority-primary" 
        onclick="javascript:window.location.reload(true);">
    <span style="display:inline-block;" class="ui-icon ui-icon-refresh"></span>
    &nbsp;[<b>CARGAR NUEVAMENTE</b>]&nbsp;
</button>

Edited to show how this looks like when included in a project

2016-07-02

My apologies as this is a personal project that implies using jQuery UI, Themeroller, Icons framework, methods like jQuery tabs, but it's in Spanish ;)

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

creating batch script to unzip a file without additional zip tools

If you have PowerShell 5.0 or higher (pre-installed with Windows 10 and Windows Server 2016):

powershell Expand-Archive your.zip -DestinationPath your_destination

How to manually install a pypi module without pip/easy_install?

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contianed herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install

EDIT- thanks to kwatford (see first comment)

To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.

The docs say:

Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:

More details can be found here: http://docs.python.org/2.7/install/index.html

How to escape indicator characters (i.e. : or - ) in YAML

I came here trying to get my Azure DevOps Command Line task working. The thing that worked for me was using the pipe (|) character. Using > did not work.

Example:

steps:
- task: CmdLine@2
  inputs:
    script: |
      echo "Selecting Mono version..."
      /bin/bash -c "sudo $AGENT_HOMEDIRECTORY/scripts/select-xamarin-sdk.sh 5_18_1"
      echo "Selecting Xcode version..."
      /bin/bash -c "echo '##vso[task.setvariable variable=MD_APPLE_SDK_ROOT;]'/Applications/Xcode_10.2.1.app;sudo xcode-select --switch /Applications/Xcode_10.2.1.app/Contents/Developer"

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)

I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.

Hope that helps.

How to get the sign, mantissa and exponent of a floating point number

You're &ing the wrong bits. I think you want:

s = *ptr >> 31;
e = *ptr & 0x7f800000;
e >>= 23;
m = *ptr & 0x007fffff;

Remember, when you &, you are zeroing out bits that you don't set. So in this case, you want to zero out the sign bit when you get the exponent, and you want to zero out the sign bit and the exponent when you get the mantissa.

Note that the masks come directly from your picture. So, the exponent mask will look like:

0 11111111 00000000000000000000000

and the mantissa mask will look like:

0 00000000 11111111111111111111111

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

It works for me after getting rid of "::1" in /etc/hosts.

MongoError: connect ECONNREFUSED 127.0.0.1:27017

most probably your mongo db service is not started. For ubuntu : sudo service mongod start For windows : go to services and start the MongoDB service

also install link for mondoDB service https://www.mongodb.com/download-center/community

I had this problem and i solved it thanks to this man's answer https://stackoverflow.com/a/47433551/7917608

What are best practices for REST nested resources?

I've tried both design strategies - nested and non-nested endpoints. I've found that:

  1. if the nested resource has a primary key and you don't have its parent primary key, the nested structure requires you to get it, even though the system doesn't actually require it.

  2. nested endpoints typically require redundant endpoints. In other words, you will more often than not, need the additional /employees endpoint so you can get a list of employees across departments. If you have /employees, what exactly does /companies/departments/employees buy you?

  3. nesting endpoints don't evolve as nicely. E.g. you might not need to search for employees now but you might later and if you have a nested structure, you have no choice but to add another endpoint. With a non-nested design, you just add more parameters, which is simpler.

  4. sometimes a resource could have multiple types of parents. Resulting in multiple endpoints all returning the same resource.

  5. redundant endpoints makes the docs harder to write and also makes the api harder to learn.

In short, the non-nested design seems to allow a more flexible and simpler endpoint schema.

Maximum length for MySQL type text

Acording to http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html, the limit is L + 2 bytes, where L < 2^16, or 64k.

You shouldn't need to concern yourself with limiting it, it's automatically broken down into chunks that get added as the string grows, so it won't always blindly use 64k.

Mapping composite keys using EF code first

Through Configuration, you can do this:

Model1
{
    int fk_one,
    int fk_two
}

Model2
{
    int pk_one,
    int pk_two,
}

then in the context config

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Model1>()
            .HasRequired(e => e.Model2)
            .WithMany(e => e.Model1s)
            .HasForeignKey(e => new { e.fk_one, e.fk_two })
            .WillCascadeOnDelete(false);
    }
}

How does BitLocker affect performance?

I used to use the PGP disk encryption product on a laptop (and ran NTFS compressed on top of that!). It didn't seem to have much effect if the amount of disk to be read was small; and most software sources aren't huge by disk standards.

You have lots of RAM and pretty fast processors. I spent most of my time thinking, typing or debugging.

I wouldn't worry very much about it.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

Diagrams are back as of the June 11 2019 release

Download latest

as stated:

Yes, we’ve heard the feedback; Database Diagrams is back.

SQL Server Management Studio (SSMS) 18.1 is now generally available


?? Latest Version Does Not Included It ??

Sadly, the last version of SSMS to have database diagrams as a feature was version v17.9.

Since that version, the newer preview versions starting at v18.* have, in their words "...feature has been deprecated".

Hope is not lost though, for one can still download and use v17.9 to use database diagrams which as an aside for this question is technically not a ER diagramming tool.


As of this writing it is unclear if the release version of 18 will have the feature, I hope so because it is a feature I use extensively.

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

How to install Android SDK on Ubuntu?

Android SDK Manager

Get it from the Snap Store

sudo snap install androidsdk

Usage

You can use the sdkmanager to perform the following tasks.

List installed and available packages

androidsdk --list [options]

Install packages

androidsdk packages [options]

The packages argument is an SDK-style path as shown with the --list command, wrapped in quotes (for example, "build-tools;29.0.0" or "platforms;android-28"). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.

For example, here's how to install the latest platform tools (which includes adb and fastboot) and the SDK tools for API level 28:

androidsdk "platform-tools" "platforms;android-28"

Alternatively, you can pass a text file that specifies all packages:

androidsdk --package_file=package_file [options]

The package_file argument is the location of a text file in which each line is an SDK-style path of a package to install (without quotes).

To uninstall, simply add the --uninstall flag:

androidsdk --uninstall packages [options]
androidsdk --uninstall --package_file=package_file [options]

Update all installed packages

androidsdk --update [options]

Note

androidsdk it is snap wraper of sdkmanager all options of sdkmanager work with androidsdk

Location of installed android sdk files : /home/user/AndroidSDK

See all sdkmanager options in google documentation

Accessing the last entry in a Map

When using numbers as the key, I suppose you could also try this:

        Map<Long, String> map = new HashMap<>();
        map.put(4L, "The First");
        map.put(6L, "The Second");
        map.put(11L, "The Last");

        long lastKey = 0;
        //you entered Map<Long, String> entry
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            lastKey = entry.getKey();
        }
        System.out.println(lastKey); // 11

How to check if function exists in JavaScript?

Didn't see this suggested: me.onChange && me.onChange(str);

Basically if me.onChange is undefined (which it will be if it hasn't been initiated) then it won't execute the latter part. If me.onChange is a function, it will execute me.onChange(str).

You can even go further and do:

me && me.onChange && me.onChange(str);

in case me is async as well.

Server.Mappath in C# classlibrary

Use this System.Web.Hosting.HostingEnvironment.MapPath().

HostingEnvironment.MapPath("~/file")

Wonder why nobody mentioned it here.

How to subtract X days from a date using Java calendar?

You could use the add method and pass it a negative number. However, you could also write a simpler method that doesn't use the Calendar class such as the following

public static void addDays(Date d, int days)
{
    d.setTime( d.getTime() + (long)days*1000*60*60*24 );
}

This gets the timestamp value of the date (milliseconds since the epoch) and adds the proper number of milliseconds. You could pass a negative integer for the days parameter to do subtraction. This would be simpler than the "proper" calendar solution:

public static void addDays(Date d, int days)
{
    Calendar c = Calendar.getInstance();
    c.setTime(d);
    c.add(Calendar.DATE, days);
    d.setTime( c.getTime().getTime() );
}

Note that both of these solutions change the Date object passed as a parameter rather than returning a completely new Date. Either function could be easily changed to do it the other way if desired.

Force LF eol in git repo and working copy

Starting with git 2.10 (released 2016-09-03), it is not necessary to enumerate each text file separately. Git 2.10 fixed the behavior of text=auto together with eol=lf. Source.

.gitattributes file in the root of your git repository:

* text=auto eol=lf

Add and commit it.

Afterwards, you can do following to steps and all files are normalized now:

git rm --cached -r .  # Remove every file from git's index.
git reset --hard      # Rewrite git's index to pick up all the new line endings.

Source: Answer by kenorb.

PHP - how to create a newline character?

I have also tried this combination within both the single quotes and double quotes. But none has worked. Instead of using \n better use <br/> in the double quotes. Like this..

$variable = "and";
echo "part 1 $variable part 2<br/>";
echo "part 1 ".$variable." part 2";

How to find NSDocumentDirectory in Swift?

More convenient Swift 3 method:

let documentsUrl = FileManager.default.urls(for: .documentDirectory, 
                                             in: .userDomainMask).first!

Java synchronized block vs. Collections.synchronizedMap

That looks correct to me. If I were to change anything, I would stop using the Collections.synchronizedMap() and synchronize everything the same way, just to make it clearer.

Also, I'd replace

  if (synchronizedMap.containsKey(key)) {
    synchronizedMap.get(key).add(value);
  }
  else {
    List<String> valuesList = new ArrayList<String>();
    valuesList.add(value);
    synchronizedMap.put(key, valuesList);
  }

with

List<String> valuesList = synchronziedMap.get(key);
if (valuesList == null)
{
  valuesList = new ArrayList<String>();
  synchronziedMap.put(key, valuesList);
}
valuesList.add(value);

Python error: AttributeError: 'module' object has no attribute

When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.

bind/unbind service example (android)

Add these methods to your Activity:

private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
        myServiceBinder = ((MyService.MyBinder) binder).getService();
        Log.d("ServiceConnection","connected");
        showServiceData();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
};

public Handler myHandler = new Handler() {
    public void handleMessage(Message message) {
        Bundle data = message.getData();
    }
};

public void doBindService() {
    Intent intent = null;
    intent = new Intent(this, BTService.class);
    // Create a new Messenger for the communication back
    // From the Service to the Activity
    Messenger messenger = new Messenger(myHandler);
    intent.putExtra("MESSENGER", messenger);

    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

@Override
protected void onResume() {

    Log.d("activity", "onResume");
    if (myService == null) {
        doBindService();
    }
    super.onResume();
}

@Override
protected void onPause() {
    //FIXME put back

    Log.d("activity", "onPause");
    if (myService != null) {
        unbindService(myConnection);
        myService = null;
    }
    super.onPause();
}

Note, that when binding to a service only the onCreate() method is called in the service class. In your Service class you need to define the myBinder method:

private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;

@Override
public IBinder onBind(Intent arg0) {
    Bundle extras = arg0.getExtras();
    Log.d("service","onBind");
    // Get messager from the Activity
    if (extras != null) {
        Log.d("service","onBind with extra");
        outMessenger = (Messenger) extras.get("MESSENGER");
    }
    return mBinder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

After you defined these methods you can reach the methods of your service at your Activity:

private void showServiceData() {  
    myServiceBinder.myMethod();
}

and finally you can start your service when some event occurs like _BOOT_COMPLETED_

public class MyReciever  extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("android.intent.action.BOOT_COMPLETED")) {
            Intent service = new Intent(context, myService.class);
            context.startService(service);
        }
    }
}

note that when starting a service the onCreate() and onStartCommand() is called in service class and you can stop your service when another event occurs by stopService() note that your event listener should be registerd in your Android manifest file:

<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

Change icon-bar (?) color in bootstrap

In bootstrap 4.3.1 I can change the background color of the toggler icon to white via the css code.

.navbar-toggler{
  background-color:white;
  }

And in my opinion the so changed icon looks fine as well on light as on dark background.

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

Command to run a .bat file

Can refer to here: https://ss64.com/nt/start.html

start "" /D F:\- Big Packets -\kitterengine\Common\ /W Template.bat

HTML Input - already filled in text

TO give the prefill value in HTML Side as below:

HTML:

<input type="text" id="abc" value="any value">

JQUERY:

$(document).ready(function ()
 {
  $("#abc").val('any value');
 });

This certificate has an invalid issuer Apple Push Services

This is not actually a development issue. It happens due to expiration of the Apple Worldwide Developer Relations Intermediate Certificate issued by Apple Worldwide Developer Relations Certificate Authority. WWDRCA issues the certificate to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

To resolve this issue, you have to follow the below steps:

  1. Open Keychain Access
  2. Go to View -> Show Expired Certificates

Enter image description here

  1. Go to System in Keychain Enter image description here

  2. Here you find that "Apple Worldwide Developer Relations Certificate Authority" is marked as expired. So delete it. Also check under Login Tab and delete expired WWDRCA.

  3. Download new WWDR Intermediate Certificate from here(The renewed Apple Worldwide Developer Relations Certification Intermediate Certificate will expire on February 7, 2023).

  4. Install it by double clicking on it.

If you still face any issue with your iOS apps, Mac apps, Safari extensions, Apple Wallet and Safari push notifications, then please follow this link of expiration.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

Add Whatsapp function to website, like sms, tel

Rahul's answer gives me an error: You seem to be trying to send a WhatsApp message to a phone number that is not registered with WhatsApp..., even though I'm sending it to a registered WhatsApp number.

This, however works:

<li><a href="intent:0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end"><i class="fa fa-whatsapp"></i>+237 655 421 621</li>

How to view query error in PDO PHP

I'm guessing that your complaint is that the exception is not firing. PDO is most likely configured to not throw exceptions. Enable them with this:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

For me, it was all about setting up my web server to use the latest-and-greatest tech to support my ASP.NET 5 application!

The following URL gave me all the tips I needed:

https://docs.asp.net/en/1.0.0-rc1/publishing/iis-with-msdeploy.html

Hope this helps :)

Rearrange columns using cut

Using sed

Use sed with basic regular expression's nested subexpressions to capture and reorder the column content. This approach is best suited when there are a limited number of cuts to reorder columns, as in this case.

The basic idea is to surround interesting portions of the search pattern with \( and \), which can be played back in the replacement pattern with \# where # represents the sequential position of the subexpression in the search pattern.

For example:

$ echo "foo bar" | sed "s/\(foo\) \(bar\)/\2 \1/"

yields:

bar foo

Text outside a subexpression is scanned but not retained for playback in the replacement string.

Although the question did not discuss fixed width columns, we will discuss here as this is a worthy measure of any solution posed. For simplicity let's assume the file is space delimited although the solution can be extended for other delimiters.

Collapsing Spaces

To illustrate the simplest usage, let's assume that multiple spaces can be collapsed into single spaces, and the the second column values are terminated with EOL (and not space padded).

File:

bash-3.2$ cat f
Column1    Column2
str1       1
str2       2
str3       3
bash-3.2$ od -a f
0000000    C   o   l   u   m   n   1  sp  sp  sp  sp   C   o   l   u   m
0000020    n   2  nl   s   t   r   1  sp  sp  sp  sp  sp  sp  sp   1  nl
0000040    s   t   r   2  sp  sp  sp  sp  sp  sp  sp   2  nl   s   t   r
0000060    3  sp  sp  sp  sp  sp  sp  sp   3  nl 
0000072

Transform:

bash-3.2$ sed "s/\([^ ]*\)[ ]*\([^ ]*\)[ ]*/\2 \1/" f
Column2 Column1
1 str1
2 str2
3 str3
bash-3.2$ sed "s/\([^ ]*\)[ ]*\([^ ]*\)[ ]*/\2 \1/" f | od -a
0000000    C   o   l   u   m   n   2  sp   C   o   l   u   m   n   1  nl
0000020    1  sp   s   t   r   1  nl   2  sp   s   t   r   2  nl   3  sp
0000040    s   t   r   3  nl
0000045

Preserving Column Widths

Let's now extend the method to a file with constant width columns, while allowing columns to be of differing widths.

File:

bash-3.2$ cat f2
Column1    Column2
str1       1
str2       2
str3       3
bash-3.2$ od -a f2
0000000    C   o   l   u   m   n   1  sp  sp  sp  sp   C   o   l   u   m
0000020    n   2  nl   s   t   r   1  sp  sp  sp  sp  sp  sp  sp   1  sp
0000040   sp  sp  sp  sp  sp  nl   s   t   r   2  sp  sp  sp  sp  sp  sp
0000060   sp   2  sp  sp  sp  sp  sp  sp  nl   s   t   r   3  sp  sp  sp
0000100   sp  sp  sp  sp   3  sp  sp  sp  sp  sp  sp  nl
0000114

Transform:

bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f2
Column2 Column1
1       str1      
2       str2      
3       str3      
bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f2 | od -a
0000000    C   o   l   u   m   n   2  sp   C   o   l   u   m   n   1  sp
0000020   sp  sp  nl   1  sp  sp  sp  sp  sp  sp  sp   s   t   r   1  sp
0000040   sp  sp  sp  sp  sp  nl   2  sp  sp  sp  sp  sp  sp  sp   s   t
0000060    r   2  sp  sp  sp  sp  sp  sp  nl   3  sp  sp  sp  sp  sp  sp
0000100   sp   s   t   r   3  sp  sp  sp  sp  sp  sp  nl 
0000114

Lastly although the question's example does not have strings of unequal length, this sed expression support this case.

File:

bash-3.2$ cat f3
Column1    Column2
str1       1      
string2    2      
str3       3      

Transform:

bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f3
Column2 Column1   
1       str1      
2       string2   
3       str3    
bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f3 | od -a
0000000    C   o   l   u   m   n   2  sp   C   o   l   u   m   n   1  sp
0000020   sp  sp  nl   1  sp  sp  sp  sp  sp  sp  sp   s   t   r   1  sp
0000040   sp  sp  sp  sp  sp  nl   2  sp  sp  sp  sp  sp  sp  sp   s   t
0000060    r   i   n   g   2  sp  sp  sp  nl   3  sp  sp  sp  sp  sp  sp
0000100   sp   s   t   r   3  sp  sp  sp  sp  sp  sp  nl 
0000114

Comparison to other methods of column reordering under shell

  • Surprisingly for a file manipulation tool, awk is not well-suited for cutting from a field to end of record. In sed this can be accomplished using regular expressions, e.g. \(xxx.*$\) where xxx is the expression to match the column.

  • Using paste and cut subshells gets tricky when implementing inside shell scripts. Code that works from the commandline fails to parse when brought inside a shell script. At least this was my experience (which drove me to this approach).

No matching bean of type ... found for dependency

Multiple things can cause this, I didn't bother to check your entire repository, so I'm going out on a limb here.

First off, you could be missing an annotation (@Service or @Component) from the implementation of com.example.my.services.user.UserService, if you're using annotations for configuration. If you're using (only) xml, you're probably missing the <bean> -definition for the UserService-implementation.

If you're using annotations and the implementation is annotated correctly, check that the package where the implementation is located in is scanned (check your <context:component-scan base-package= -value).

Getting the parent div of element

If you are looking for a particular type of element that is further away than the immediate parent, you can use a function that goes up the DOM until it finds one, or doesn't:

// Find first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
  tagName = tagName.toLowerCase();

  while (el && el.parentNode) {
    el = el.parentNode;
    if (el.tagName && el.tagName.toLowerCase() == tagName) {
      return el;
    }
  }

  // Many DOM methods return null if they don't 
  // find the element they are searching for
  // It would be OK to omit the following and just
  // return undefined
  return null;
}

The most accurate way to check JS object's type?

Accepted answer is correct, but I like to define this little utility in most projects I build.

var types = {
   'get': function(prop) {
      return Object.prototype.toString.call(prop);
   },
   'null': '[object Null]',
   'object': '[object Object]',
   'array': '[object Array]',
   'string': '[object String]',
   'boolean': '[object Boolean]',
   'number': '[object Number]',
   'date': '[object Date]',
}

Used like this:

if(types.get(prop) == types.number) {

}

If you're using angular you can even have it cleanly injected:

angular.constant('types', types);

Include headers when using SELECT INTO OUTFILE?

I had no luck with any of these, so after finding a solution, I wanted to add it to the prior answers. Python==3.8.6 MySQL==8.0.19

(Forgive my lack of SO formatting foo. Somebody please clean up.)

Note a couple of things:

First, the query to return column names is unforgiving of punctuation. Using ` backticks or leaving out ' quote around the 'schema_name' and 'table_name' will throw an "unknown column" error.

WHERE TABLE_SCHEMA = 'schema' AND TABLE_NAME = 'table'

Second, the column header names return as a single-entity tuple with all the column names concatenated in one quoted string. Convert to quoted list was easy, but not intuitive (for me at least).

headers_list = headers_result[0].split(",")

Third, cursor must be buffered or the "lazy" thing will not fetch your results as you need them. For very large tables, memory could be an issue. Perhaps chunking would solve that problem.

cur = db.cursor(buffered=True)

Last, all types of UNION attempts yielded errors for me. By zipping the whole mess into a list of dicts, it became trivial to write to a csv, using csv.DictWriter.

headers_sql = """   
SELECT 
GROUP_CONCAT(CONCAT(COLUMN_NAME) ORDER BY ORDINAL_POSITION)   
FROM INFORMATION_SCHEMA.COLUMNS   
WHERE TABLE_SCHEMA = 'schema' AND TABLE_NAME = 'table';   
"""" 

cur = db.cursor(buffered=True) 
cur.execute(header_sql) 
headers_result = cur.fetchone() 
headers_list = headers_result[0].split(",")

rows_sql = """   SELECT * FROM schema.table;   """" 

data = cur.execute(rows_sql) 
data_rows = cur.fetchall() 
data_as_list_of_dicts = [dict(zip(headers_list, row)) for row in data_rows]

with open(csv_destination_file, 'w', encoding='utf-8') as destination_file_opened: 
    dict_writer = csv.DictWriter(destination_file_opened, fieldnames=headers_list) 
    dict_writer.writeheader()   for dict in dict_list:
        dict_writer.writerow(dict)

how to break the _.each function in underscore.js

Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.

Can not find module “@angular-devkit/build-angular”

If you are using angular version 8 please run the below command to fix this issue.

ng update @angular/cli @angular/core

Show which git tag you are on?

git describe is a porcelain command, which you should avoid:

http://git-blame.blogspot.com/2013/06/checking-current-branch-programatically.html

Instead, I used:

git name-rev --tags --name-only $(git rev-parse HEAD)

Recording video feed from an IP camera over a network

about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.

Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.

So i found the solution!

If you want something done right, do it yourself.

I present to you Shinobi! Shinobi : The Open Source CCTV Platform

enter image description here

Requery a subform from another form?

I tried several solutions above, but none solved my problem. Solution to refresh a subform in a form after saving data to database:

Me.subformname.Requery

It worked fine for me. Good luck.

VBA to copy a file from one directory to another

This method is even easier if you're ok with fewer options:

FileCopy source, destination

Update with two tables?

The answers didn't work for me with postgresql 9.1+

This is what I had to do (you can check more in the manual here)

UPDATE schema.TableA as A
SET "columnA" = "B"."columnB"
FROM schema.TableB as B
WHERE A.id = B.id;

You can omit the schema, if you are using the default schema for both tables.

Insert Data Into Tables Linked by Foreign Key

Use stored procedures.

And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

JavaScript Object Id

If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:

// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
  if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
  return objIdMap.get(object);
}

var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3

Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.

How do I create an Excel chart that pulls data from multiple sheets?

Use the Chart Wizard.

On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.

Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.

Select your new series.

There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.

Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.

Hope that helps.

EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.

.ssh directory not being created

I am assuming that you have enough permissions to create this directory.

To fix your problem, you can either ssh to some other location:

ssh [email protected]

and accept new key - it will create directory ~/.ssh and known_hosts underneath, or simply create it manually using

mkdir ~/.ssh
chmod 700 ~/.ssh

Note that chmod 700 is an important step!

After that, ssh-keygen should work without complaints.

jQuery delete all table rows except first

Consider a table with id tbl: the jQuery code would be:

$('#tbl tr:not(:first)').remove();

Change Schema Name Of Table In SQL

ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]

I always have to use the brackets when I use the ALTER SCHEMA query in SQL, or I get an error message.

c++ compile error: ISO C++ forbids comparison between pointer and integer

"y" is a string/array/pointer. 'y' is a char/integral type

How to do associative array/hashing in JavaScript

In C# the code looks like:

Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);

or

var dictionary = new Dictionary<string, int> {
    {"sample1", 1},
    {"sample2", 2}
};

In JavaScript:

var dictionary = {
    "sample1": 1,
    "sample2": 2
}

A C# dictionary object contains useful methods, like dictionary.ContainsKey()

In JavaScript, we could use the hasOwnProperty like:

if (dictionary.hasOwnProperty("sample1"))
    console.log("sample1 key found and its value is"+ dictionary["sample1"]);

mysql is not recognised as an internal or external command,operable program or batch

MYSQL_HOME:

C:\Program Files\MySQL\MySQL Server 5.0

Path:

%MYSQL_HOME%\bin;

jquery save json data object in cookie

use JSON.stringify(userData) to coverty json object to string.

var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));

and for getting back from cookie use JSON.parse()

var data=JSON.parse($.cookie("basket-data"))

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

How can I listen for a click-and-hold in jQuery?

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})

Java - sending HTTP parameters via POST method easily

In a GET request, the parameters are sent as part of the URL.

In a POST request, the parameters are sent as a body of the request, after the headers.

To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

This code should get you started:

String urlParameters  = "param1=a&param2=b&param3=c";
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
String request        = "http://example.com/index.php";
URL    url            = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
   wr.write( postData );
}

How to add a new column to a CSV file?

import csv
with open('input.csv','r') as csvinput:
    with open('output.csv', 'w') as csvoutput:
        writer = csv.writer(csvoutput)

        for row in csv.reader(csvinput):
            if row[0] == "Name":
                writer.writerow(row+["Berry"])
            else:
                writer.writerow(row+[row[0]])

Maybe something like that is what you intended?

Also, csv stands for comma separated values. So, you kind of need commas to separate your values like this I think:

Name,Code
blackberry,1
wineberry,2
rasberry,1
blueberry,1
mulberry,2

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Are there bookmarks in Visual Studio Code?

Yes, via extensions. Try Bookmarks extension on marketplace.visualstudio.com

Hit Ctrl+Shift+P and type the install extensions and press enter, then type Bookmark and press enter.

enter image description here

Next you may wish to customize what keys are used to make a bookmark and move to it. For that see this question.

ImportError: Cannot import name X

This is a circular dependency. we can solve this problem by using import module or class or function where we needed. if we use this approach, we can fix circular dependency

A.py

from B import b2
def a1():
    print('a1')
    b2()

B.py

def b1():
   from A import a1
   print('b1')
   a1()

def b2():
   print('b2')
if __name__ == '__main__':
   b1() 

How to set Default Controller in asp.net MVC 4 & MVC 5

In case you have only one controller and you want to access every action on root you can skip controller name like this

routes.MapRoute(
        "Default", 
        "{action}/{id}", 
        new { controller = "Home", action = "Index", 
        id = UrlParameter.Optional }
);

Is there any difference between "!=" and "<>" in Oracle Sql?

Actually, there are four forms of this operator:

<>
!=
^=

and even

¬= -- worked on some obscure platforms in the dark ages

which are the same, but treated differently when a verbatim match is required (stored outlines or cached queries).

define() vs. const

Most of these answers are wrong or are only telling half the story.

  1. You can scope your constants by using namespaces.
  2. You can use the "const" keyword outside of class definitions. However, just like in classes the values assigned using the "const" keyword must be constant expressions.

For example:

const AWESOME = 'Bob'; // Valid

Bad example:

const AWESOME = whatIsMyName(); // Invalid (Function call)
const WEAKNESS = 4+5+6; // Invalid (Arithmetic) 
const FOO = BAR . OF . SOAP; // Invalid (Concatenation)

To create variable constants use define() like so:

define('AWESOME', whatIsMyName()); // Valid
define('WEAKNESS', 4 + 5 + 6); // Valid
define('FOO', BAR . OF . SOAP); // Valid

Normalization in DOM parsing with java - how does it work?

The rest of the sentence is:

where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"

And the same goes for attributes: <foo bar="Hello world"/>, comments, etc.

Date Difference in php on days?

Below code will give the output for number of days, by taking out the difference between two dates..

$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);

Get Mouse Position

import java.awt.MouseInfo;
import java.util.concurrent.TimeUnit;

public class Cords {

    public static void main(String[] args) throws InterruptedException {

        //get cords of mouse code, outputs to console every 1/2 second
        //make sure to import and include the "throws in the main method"

        while(true == true)
        {
        TimeUnit.SECONDS.sleep(1/2);
        double mouseX = MouseInfo.getPointerInfo().getLocation().getX();
        double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
        System.out.println("X:" + mouseX);
        System.out.println("Y:" + mouseY);
        //make sure to import 
        }

    }

}

Combining node.js and Python

I'd recommend using some work queue using, for example, the excellent Gearman, which will provide you with a great way to dispatch background jobs, and asynchronously get their result once they're processed.

The advantage of this, used heavily at Digg (among many others) is that it provides a strong, scalable and robust way to make workers in any language to speak with clients in any language.

Why is an OPTIONS request sent and can I disable it?

For a developer who understands the reason it exists but needs to access an API that doesn't handle OPTIONS calls without auth, I need a temporary answer so I can develop locally until the API owner adds proper SPA CORS support or I get a proxy API up and running.

I found you can disable CORS in Safari and Chrome on a Mac.

Disable same origin policy in Chrome

Chrome: Quit Chrome, open an terminal and paste this command: open /Applications/Google\ Chrome.app --args --disable-web-security --user-data-dir

Safari: Disabling same-origin policy in Safari

If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.

"Application tried to present modally an active controller"?

In my case i was trying to present the viewController (i have the reference of the viewController in the TabBarViewController) from different view controllers and it was crashing with the above message. In that case to avoid presenting you can use

viewController.isBeingPresented

!viewController.isBeingPresented {
          // Present your ViewController only if its not present to the user currently.
}

Might help someone.

Javascript: Extend a Function

The other methods are great but they don't preserve any prototype functions attached to init. To get around that you can do the following (inspired by the post from Nick Craver).

(function () {
    var old_prototype = init.prototype;
    var old_init = init;
    init = function () {
        old_init.apply(this, arguments);
        // Do something extra
    };
    init.prototype = old_prototype;
}) ();

How do I set vertical space between list items?

Add a margin to your li tags. That will create space between the li and you can use line-height to set the spacing to the text within the li tags.

How can I do string interpolation in JavaScript?

Since ES6, if you want to do string interpolation in object keys, you will get a SyntaxError: expected property name, got '${' if you do something like:

let age = 3
let obj = { `${age}`: 3 }

You should do the following instead:

let obj = { [`${age}`]: 3 }

java.lang.NoClassDefFoundError: Could not initialize class XXX

I had the same exception, this is how I solved the problem:

Preconditions:

  1. Junit class (and test), that extended another class.

  2. ApplicationContext initialized using spring, that init the project.

  3. The Application context was initialized in @Before method

Solution:

Init the application context from @BeforeClass method, since the parent class also required some classes that were initialized from within the application context.

Hope this will help.

How to merge 2 JSON objects from 2 files using jq?

First, {"value": .value} can be abbreviated to just {value}.

Second, the --argfile option (available in jq 1.4 and jq 1.5) may be of interest as it avoids having to use the --slurp option.

Putting these together, the two objects in the two files can be combined in the specified way as follows:

$ jq -n --argfile o1 file1 --argfile o2 file2 '$o1 * $o2 | {value}'

The '-n' flag tells jq not to read from stdin, since inputs are coming from the --argfile options here.

Note on --argfile

The jq manual deprecates --argfile because its semantics are non-trivial: if the specified input file contains exactly one JSON entity, then that entity is read as is; otherwise, the items in the stream are wrapped in an array.

If you are uncomfortable using --argfile, there are several alternatives you may wish to consider. In doing so, be assured that using --slurpfile does not incur the inefficiencies of the -s command-line option when the latter is used with multiple files.

How do I activate a specific workbook and a specific sheet?

You do not need to activate the sheet (you'll take a huge performance hit for doing so, actually). Since you are declaring an object for the sheet, when you call the method starting with "wb." you are selecting that object. For example, you can jump in between workbooks without activating anything like here:

Sub Test()

Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test1.xls")
Dim wb2 As Excel.Workbook
Set wb2 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test2.xls")

wb1.Sheets("Sheet1").Cells(1, 1).Value = 24
wb2.Sheets("Sheet1").Cells(1, 1).Value = 24
wb1.Sheets("Sheet1").Cells(2, 1).Value = 54

End Sub

See line breaks and carriage returns in editor

Try the following command.

:set binary

In VIM, this should do the same thing as using the "-b" command line option. If you put this in your startup (i.e. .vimrc) file, it will always be in place for you.

On many *nix systems, there is a "dos2unix" or "unix2dos" command that can process the file and correct any suspected line ending issues. If there is no problem with the line endings, the files will not be changed.

in a "using" block is a SqlConnection closed on return or exception?

Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.

From MSDN:

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

Binary Serialization method works fine but in my tests it showed to be 10x slower than a non-serialization implementation of clone. Tested it on Dictionary<string , List<double>>

Get length of array?

Compilating answers here and there, here's a complete set of arr tools to get the work done:

Function getArraySize(arr As Variant)
' returns array size for a n dimention array
' usage result(k) = size of the k-th dimension

Dim ndims As Long
Dim arrsize() As Variant
ndims = getDimensions(arr)
ReDim arrsize(ndims - 1)
For i = 1 To ndims
    arrsize(i - 1) = getDimSize(arr, i)
Next i
getArraySize = arrsize
End Function

Function getDimSize(arr As Variant, dimension As Integer)
' returns size for the given dimension number
    getDimSize = UBound(arr, dimension) - LBound(arr, dimension) + 1
End Function

Function getDimensions(arr As Variant) As Long
' returns number of dimension in an array (ex. sheet range = 2 dimensions)
    On Error GoTo Err
    Dim i As Long
    Dim tmp As Long
    i = 0
    Do While True
        i = i + 1
        tmp = UBound(arr, i)
    Loop
Err:
    getDimensions = i - 1
End Function

Find and Replace string in all files recursive using grep and sed

sed expression needs to be quoted

sed -i "s/$oldstring/$newstring/g"

How to read and write excel file

Sure , you will find the code below useful and easy to read and write. This is a util class which you can use in your main method and then you are good to use all methods below.

     public class ExcelUtils {
     private static XSSFSheet ExcelWSheet;
     private static XSSFWorkbook ExcelWBook;
     private static XSSFCell Cell;
     private static XSSFRow Row;
     File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
     public void setExcelFile(File Path, String SheetName) throws Exception                

    try {
        FileInputStream ExcelFile = new FileInputStream(Path);
        ExcelWBook = new XSSFWorkbook(ExcelFile);
        ExcelWSheet = ExcelWBook.getSheet(SheetName);
    } catch (Exception e) {
        throw (e);
    }

}


      public static String getCellData(int RowNum, int ColNum) throws Exception {

    try {
        Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
        String CellData = Cell.getStringCellValue();
        return CellData;
    } catch (Exception e) {

        return "";

    }

}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {

    try {
        Row = ExcelWSheet.createRow(RowNum - 1);
        Cell = Row.createCell(ColNum - 1);
        Cell.setCellValue(Result);
        FileOutputStream fileOut = new FileOutputStream(Path);
        ExcelWBook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (Exception e) {

        throw (e);

    }

}

}

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

Why is vertical-align:text-top; not working in CSS

The vertical-align attribute is for inline elements only. It will have no effect on block level elements, like a div. Also text-top only moves the text to the top of the current font size. If you would like to vertically align an inline element to the top just use this.

vertical-align: top;

The paragraph tag is not outdated. Also, the vertical-align attribute applied to a span element may not display as intended in some mozilla browsers.

How to delete a record by id in Flask-SQLAlchemy

Just want to share another option:

# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)

# commit (or flush)
session.commit()

http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting

In this example, the following codes shall works fine:

obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()

How to instantiate, initialize and populate an array in TypeScript?

An other solution:

interface bar {
    length: number;
}

bars = [{
  length: 1
} as bar];

Disable/turn off inherited CSS3 transitions

Based on W3schools default transition value is: all 0s ease 0s, which should be the cross-browser compatible way of disabling the transition.

Here is a link: https://www.w3schools.com/cssref/css3_pr_transition.asp

How to loop through all but the last item of a list?

If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).

from itertools import tee, izip, chain

def pairwise(seq):
    a,b = tee(seq)
    b.next()
    return izip(a,b)

for current_item, next_item in pairwise(y):
    if compare(current_item, next_item):
        # do what you have to do

If you need to compare the last value to some special value, chain that value to the end

for current, next_item in pairwise(chain(y, [None])):

Change the bullet color of list

I would recommend you to use background-image instead of default list.

.listStyle {
    list-style: none;
    background: url(image_path.jpg) no-repeat left center;
    padding-left: 30px;
    width: 20px;
    height: 20px;
}

Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:

.liststyle{
    list-style: none;
    margin: 0;
    padding: 0;
}
.liststyle:before {
    content: "• ";
    color: red; /* or whatever color you prefer */
    font-size: 20px;/* or whatever the bullet size you prefer */
}

How do I search for an object by its ObjectId in the mongo console?

If you're using Node.js:

> var ObjectId = require('mongodb').ObjectId; 
> var id = req.params.gonderi_id;       
> var o_id = new ObjectId(id);
> db.test.find({_id:o_id})

Edit: corrected to new ObjectId(id), not new ObjectID(id)

Lazy Method for Reading Big File in Python?

If your computer, OS and python are 64-bit, then you can use the mmap module to map the contents of the file into memory and access it with indices and slices. Here an example from the documentation:

import mmap
with open("hello.txt", "r+") as f:
    # memory-map the file, size 0 means whole file
    map = mmap.mmap(f.fileno(), 0)
    # read content via standard file methods
    print map.readline()  # prints "Hello Python!"
    # read content via slice notation
    print map[:5]  # prints "Hello"
    # update content using slice notation;
    # note that new content must have same size
    map[6:] = " world!\n"
    # ... and read again using standard file methods
    map.seek(0)
    print map.readline()  # prints "Hello  world!"
    # close the map
    map.close()

If either your computer, OS or python are 32-bit, then mmap-ing large files can reserve large parts of your address space and starve your program of memory.

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

In iOS 10+

Apple enabled the attribute playsinline in all browsers on iOS 10, so this works seamlessly:

<video src="file.mp4" playsinline>

In iOS 8 and iOS 9

Short answer: use iphone-inline-video, it enables inline playback and syncs the audio.

Long answer: You can work around this issue by simulating the playback by skimming the video instead of actually .play()'ing it.

What is the most effective way for float and double comparison?

Be extremely careful using any of the other suggestions. It all depends on context.

I have spent a long time tracing a bugs in a system that presumed a==b if |a-b|<epsilon. The underlying problems were:

  1. The implicit presumption in an algorithm that if a==b and b==c then a==c.

  2. Using the same epsilon for lines measured in inches and lines measured in mils (.001 inch). That is a==b but 1000a!=1000b. (This is why AlmostEqual2sComplement asks for the epsilon or max ULPS).

  3. The use of the same epsilon for both the cosine of angles and the length of lines!

  4. Using such a compare function to sort items in a collection. (In this case using the builtin C++ operator == for doubles produced correct results.)

Like I said: it all depends on context and the expected size of a and b.

BTW, std::numeric_limits<double>::epsilon() is the "machine epsilon". It is the difference between 1.0 and the next value representable by a double. I guess that it could be used in the compare function but only if the expected values are less than 1. (This is in response to @cdv's answer...)

Also, if you basically have int arithmetic in doubles (here we use doubles to hold int values in certain cases) your arithmetic will be correct. For example 4.0/2.0 will be the same as 1.0+1.0. This is as long as you do not do things that result in fractions (4.0/3.0) or do not go outside of the size of an int.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

As you can see here:

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Difference between @GetMapping & @RequestMapping

@GetMapping supports the consumes attribute like @RequestMapping.

What is the easiest way to parse an INI file in Java?

Or with standard Java API you can use java.util.Properties:

Properties props = new Properties();
try (FileInputStream in = new FileInputStream(path)) {
    props.load(in);
}

How do I convert hex to decimal in Python?

>>> int("0xff", 16)
255

or

>>> int("FFFF", 16)
65535

Read the docs.

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

CodeIgniter: How to use WHERE clause and OR clause

Active record method or_where is to be used:

$this->db->select("*")
->from("table_name")
->where("first", $first)
->or_where("second", $second);

How can I find my Apple Developer Team id and Team Agent Apple ID?

If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.

Applications -> Utilities -> Keychain Access.

Under the 'login' Keychain, go into the 'Certificates' category.

Scroll to find your development or distribution certificate. They will read:

iPhone Distribution: Team Name (certificate id)

or

iPhone Developer: Team Name (certificate id)

Simply double-click on the item, and the

"Organizational Unit"

is the "Team ID"

enter image description here

Note that this is the only way to find your

"Personal team" ID

You can not find the "Personal team" ID on the Apple web interface.

For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.

Java: Enum parameter in method

I like this a lot better. reduces the if/switch, just do.

private enum Alignment { LEFT, RIGHT;

void process() {
//Process it...
} 
};    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  align.process();
}

of course, it can be:

String process(...) {
//Process it...
} 

Help with packages in java - import does not work

Yes, this is a classpath issue. You need to tell the compiler and runtime that the directory where your .class files live is part of the CLASSPATH. The directory that you need to add is the parent of the "com" directory at the start of your package structure.

You do this using the -classpath argument for both javac.exe and java.exe.

Should also ask how the 3rd party classes you're using are packaged. If they're in a JAR, and I'd recommend that you have them in one, you add the .jar file to the classpath:

java -classpath .;company.jar foo.bar.baz.YourClass

Google for "Java classpath". It'll find links like this.

One more thing: "import" isn't loading classes. All it does it save you typing. When you include an import statement, you don't have to use the fully-resolved class name in your code - you can type "Foo" instead of "com.company.thing.Foo". That's all it's doing.

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

SQL Stored Procedure: If variable is not null, update statement

Use a T-SQL IF:

IF @ABC IS NOT NULL AND @ABC != -1
    UPDATE [TABLE_NAME] SET XYZ=@ABC

Take a look at the MSDN docs.

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Why not use Double or Float to represent currency?

Most answers have highlighted the reasons why one should not use doubles for money and currency calculations. And I totally agree with them.

It doesn't mean though that doubles can never be used for that purpose.

I have worked on a number of projects with very low gc requirements, and having BigDecimal objects was a big contributor to that overhead.

It's the lack of understanding about double representation and lack of experience in handling the accuracy and precision that brings about this wise suggestion.

You can make it work if you are able to handle the precision and accuracy requirements of your project, which has to be done based on what range of double values is one dealing with.

You can refer to guava's FuzzyCompare method to get more idea. The parameter tolerance is the key. We dealt with this problem for a securities trading application and we did an exhaustive research on what tolerances to use for different numerical values in different ranges.

Also, there might be situations when you're tempted to use Double wrappers as a map key with hash map being the implementation. It is very risky because Double.equals and hash code for example values "0.5" & "0.6 - 0.1" will cause a big mess.

How to change the datetime format in pandas

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

Windows service on Local Computer started and then stopped error

EventLog.Log should be set as "Application"

What difference does .AsNoTracking() make?

If you have something else altering the DB (say another process) and need to ensure you see these changes, use AsNoTracking(), otherwise EF may give you the last copy that your context had instead, hence it being good to usually use a new context every query:

http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/

'sudo gem install' or 'gem install' and gem locations

Installing Ruby gems on a Mac is a common source of confusion and frustration. Unfortunately, most solutions are incomplete, outdated, and provide bad advice. I'm glad the accepted answer here says to NOT use sudo, which you should never need to do, especially if you don't understand what it does. While I used RVM years ago, I would recommend chruby in 2020.

Some of the other answers here provide alternative options for installing gems, but they don't mention the limitations of those solutions. What's missing is an explanation and comparison of the various options and why you might choose one over the other. I've attempted to cover most common scenarios in my definitive guide to installing Ruby gems on a Mac.

Downloading a file from spring controllers

  1. Return ResponseEntity<Resource> from a handler method
  2. Specify Content-Type explicitly
  3. Set Content-Disposition if necessary:
    1. filename
    2. type
      1. inline to force preview in a browser
      2. attachment to force a download
@Controller
public class DownloadController {
    @GetMapping("/downloadPdf.pdf")
    // 1.
    public ResponseEntity<Resource> downloadPdf() {
        FileSystemResource resource = new FileSystemResource("/home/caco3/Downloads/JMC_Tutorial.pdf");
        // 2.
        MediaType mediaType = MediaTypeFactory
                .getMediaType(resource)
                .orElse(MediaType.APPLICATION_OCTET_STREAM);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        // 3
        ContentDisposition disposition = ContentDisposition
                // 3.2
                .inline() // or .attachment()
                // 3.1
                .filename(resource.getFilename())
                .build();
        headers.setContentDisposition(disposition);
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
    }
}

Explanation

Return ResponseEntity<Resource>

When you return a ResponseEntity<Resource>, the ResourceHttpMessageConverter kicks in and writes an appropriate response.

The resource could be:

Be aware of possibly wrong Content-Type header set (see FileSystemResource is returned with content type json). That's why this answer suggests setting the Content-Type explicitly.

Specify Content-Type explicitly:

Some options are:

The MediaTypeFactory allows to discover the MediaType appropriate for the Resource (see also /org/springframework/http/mime.types file)

Set Content-Disposition if necessary:

Sometimes it is necessary to force a download in a browser or to make the browser open a file as a preview. You can use the Content-Disposition header to satisfy this requirement:

The first parameter in the HTTP context is either inline (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present).

In the Spring Framework a ContentDisposition can be used.

To preview a file in a browser:

ContentDisposition disposition = ContentDisposition
        .builder("inline") // Or .inline() if you're on Spring MVC 5.3+
        .filename(resource.getFilename())
        .build();

To force a download:

ContentDisposition disposition = ContentDisposition
        .builder("attachment") // Or .attachment() if you're on Spring MVC 5.3+
        .filename(resource.getFilename())
        .build();

Use InputStreamResource carefully:

Since an InputStream can be read only once, Spring won't write Content-Length header if you return an InputStreamResource (here is a snippet of code from ResourceHttpMessageConverter):

@Override
protected Long getContentLength(Resource resource, @Nullable MediaType contentType) throws IOException {
    // Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
    // Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
    if (InputStreamResource.class == resource.getClass()) {
        return null;
    }
    long contentLength = resource.contentLength();
    return (contentLength < 0 ? null : contentLength);
}

In other cases it works fine:

~ $ curl -I localhost:8080/downloadPdf.pdf  | grep "Content-Length"
Content-Length: 7554270

Validate phone number using javascript

Can any one explain why??

This happening because your regular expression doesn't end with any anchor meta-character such as the end of line $ or a word boundary \b.

So when you ask the regex engine whether 123-345-34567 is valid phone number it will try to find a match within this string, so it matches 123- with this part (\([0-9]{3}\) |[0-9]{3}-) then it matches 345- with this part [0-9]{3}- then it matches 3456 with this part [0-9]{4}.

Now the engine finds that it has walked the entire regex and found a string inside your input that matches the regex although a character was left - the number 7- in the input string, so it stops and returns success because it found a sub-string that matches.

If you had included $ or \b at the end of your regex, the engine walks the same way as before then it tries to match $ or \b but finds the last number - the 7 - and it is not a word boundary \b nor a an end of line $ so it stops and fails to find a match.

How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

Install tkinter for Python

Fedora release 25 (Twenty Five)

dnf install python3-tkinter

This worked for me.

Java, How to add values to Array List used as value in HashMap

String courseID = "Comp-101";
List<String> scores = new ArrayList<String> ();
scores.add("100");
scores.add("90");
scores.add("80");
scores.add("97");

Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
myMap.put(courseID, scores);

Hope this helps!

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Count indexes using "for" in Python

This?

for i in range(0,5): 
 print(i)

Android Studio AVD - Emulator: Process finished with exit code 1

This works to me:

click in Sdk manager in SDK Tools and: enter image description here

Unistal and install the Android Emulator: enter image description here

Hope to help!

How to pass data in the ajax DELETE request other than headers

Read this Bug Issue: http://bugs.jquery.com/ticket/11586

Quoting the RFC 2616 Fielding

The DELETE method requests that the origin server delete the resource identified by the Request-URI.

So you need to pass the data in the URI

$.ajax({
    url: urlCall + '?' + $.param({"Id": Id, "bolDeleteReq" : bolDeleteReq}),
    type: 'DELETE',
    success: callback || $.noop,
    error: errorCallback || $.noop
});

Concatenate string with field value in MySQL

SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2  FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = query2

How to add an image to a JPanel?

JPanel is almost always the wrong class to subclass. Why wouldn't you subclass JComponent?

There is a slight problem with ImageIcon in that the constructor blocks reading the image. Not really a problem when loading from the application jar, but maybe if you're potentially reading over a network connection. There's plenty of AWT-era examples of using MediaTracker, ImageObserver and friends, even in the JDK demos.

Find PHP version on windows command line

xampp control panel->shell->type php-v you get the version of php of your xampp installed

DB(mariadb/mysql)version type localhost/phpmyadmin in url click enter click on sql type select version(); enter to get the mysql or mariaDb version

What to return if Spring MVC controller method doesn't return value?

There is nothing wrong with returning a void @ResponseBody and you should for POST requests.

Use HTTP status codes to define errors within exception handler routines instead as others are mentioning success status. A normal method as you have will return a response code of 200 which is what you want, any exception handler can then return an error object and a different code (i.e. 500).

port 8080 is already in use and no process using 8080 has been listed

PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn which will show the process names (but must be run under an administrator account).

Having said that, I would expect the find "8080" to find it...

Another thing to do is just visit http://localhost:8080 - on that port, chances are it's a web server of some description.

How to get current user in asp.net core

Most of the answers show how to best handle HttpContext from the documentation, which is also what I went with.

I did want to mention that you'll want to check you project settings when debugging, the default is Enable Anonymous Authentication = true.

Can I do Model->where('id', ARRAY) multiple where conditions?

If you need by several params:

$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
                  ->whereNotIn('id', $not_ids)
                  ->where('status', 1)
                  ->get();

How can I get onclick event on webview in android?

I took a look at this and I found that a WebView doesn't seem to send click events to an OnClickListener. If anyone out there can prove me wrong or tell me why then I'd be interested to hear it.

What I did find is that a WebView will send touch events to an OnTouchListener. It does have its own onTouchEvent method but I only ever seemed to get MotionEvent.ACTION_MOVE using that method.

So given that we can get events on a registered touch event listener, the only problem that remains is how to circumvent whatever action you want to perform for a touch when the user clicks a URL.

This can be achieved with some fancy Handler footwork by sending a delayed message for the touch and then removing those touch messages if the touch was caused by the user clicking a URL.

Here's an example:

public class WebViewClicker extends Activity implements OnTouchListener, Handler.Callback {

private static final int CLICK_ON_WEBVIEW = 1;
private static final int CLICK_ON_URL = 2;

private final Handler handler = new Handler(this);

private WebView webView;
private WebViewClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.web_view_clicker);

    webView = (WebView)findViewById(R.id.web);
    webView.setOnTouchListener(this);

    client = new WebViewClient(){ 
        @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            handler.sendEmptyMessage(CLICK_ON_URL);
            return false;
        } 
    }; 

    webView.setWebViewClient(client);
    webView.setVerticalScrollBarEnabled(false);
    webView.loadUrl("http://www.example.com");
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (v.getId() == R.id.web && event.getAction() == MotionEvent.ACTION_DOWN){
        handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
    }
    return false;
}

@Override
public boolean handleMessage(Message msg) {
    if (msg.what == CLICK_ON_URL){
        handler.removeMessages(CLICK_ON_WEBVIEW);
        return true;
    }
    if (msg.what == CLICK_ON_WEBVIEW){
        Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}
}


Hope this helps.

Excel VBA Run-time Error '32809' - Trying to Understand it

Error 32,809: Copying the corrupt sheet to a new sheet and changing the name or deleting the corrupt sheet works for me. Additionally, I went to the SHEET Module of the corrupt sheet and removed the coding from the sheet Module associated with the corrupt sheet. That ALSO cured the problem for me. [ The sheet modules can have routines that are triggered by events specific to that worksheet.] So in my case, I think it was a corrupt Sheet Module, not corrupt data on the worksheet itself.

How to get row from R data.frame

Logical indexing is very R-ish. Try:

 x[ x$A ==5 & x$B==4.25 & x$C==4.5 , ] 

Or:

subset( x, A ==5 & B==4.25 & C==4.5 )

How to playback MKV video in web browser?

<video controls width=800 autoplay>
    <source src="file path here">
</video>

This will display the video (.mkv) using Google Chrome browser only.

SQL Server Installation - What is the Installation Media Folder?

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

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

What does it mean if a Python object is "subscriptable" or not?

As a corollary to the earlier answers here, very often this is a sign that you think you have a list (or dict, or other subscriptable object) when you do not.

For example, let's say you have a function which should return a list;

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']

Now when you call that function, and something_happens() for some reason does not return a True value, what happens? The if fails, and so you fall through; gimme_things doesn't explicitly return anything -- so then in fact, it will implicitly return None. Then this code:

things = gimme_things()
print("My first thing is {0}".format(things[0]))

will fail with "NoneType object is not subscriptable" because, well, things is None and so you are trying to do None[0] which doesn't make sense because ... what the error message says.

There are two ways to fix this bug in your code -- the first is to avoid the error by checking that things is in fact valid before attempting to use it;

things = gimme_things()
if things:
    print("My first thing is {0}".format(things[0]))
else:
    print("No things")  # or raise an error, or do nothing, or ...

or equivalently trap the TypeError exception;

things = gimme_things()
try:
    print("My first thing is {0}".format(things[0]))
except TypeError:
    print("No things")  # or raise an error, or do nothing, or ...

Another is to redesign gimme_things so that you make sure it always returns a list. In this case, that's probably the simpler design because it means if there are many places where you have a similar bug, they can be kept simple and idiomatic.

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']
    else:  # make sure we always return a list, no matter what!
        logging.info("Something didn't happen; return empty list")
        return []

Of course, what you put in the else: branch depends on your use case. Perhaps you should raise an exception when something_happens() fails, to make it more obvious and explicit where something actually went wrong? Adding exceptions to your own code is an important way to let yourself know exactly what's up when something fails!

(Notice also how this latter fix still doesn't completely fix the bug -- it prevents you from attempting to subscript None but things[0] is still an IndexError when things is an empty list. If you have a try you can do except (TypeError, IndexError) to trap it, too.)

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

Find the location of a character in string

You can make the output just 4 and 24 using unlist:

unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))
[1]  4 24

Convert text to columns in Excel using VBA

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .'s (eg .Range) they refer to the With statement object

Show loading screen when navigating between routes in Angular 2

You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.

How to use Google Translate API in my Java application?

You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS.
1) Create new script with such code on google script:

var mock = {
  parameter:{
    q:'hello',
    source:'en',
    target:'fr'
  }
};


function doGet(e) {
  e = e || mock;

  var sourceText = ''
  if (e.parameter.q){
    sourceText = e.parameter.q;
  }

  var sourceLang = '';
  if (e.parameter.source){
    sourceLang = e.parameter.source;
  }

  var targetLang = 'en';
  if (e.parameter.target){
    targetLang = e.parameter.target;
  }

  var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});

  return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);
}

2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.
google script deploy

3) Use this java code for testing your API:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Translator {

    public static void main(String[] args) throws IOException {
        String text = "Hello world!";
        //Translated text: Hallo Welt!
        System.out.println("Translated text: " + translate("en", "de", text));
    }

    private static String translate(String langFrom, String langTo, String text) throws IOException {
        // INSERT YOU URL HERE
        String urlStr = "https://your.google.script.url" +
                "?q=" + URLEncoder.encode(text, "UTF-8") +
                "&target=" + langTo +
                "&source=" + langFrom;
        URL url = new URL(urlStr);
        StringBuilder response = new StringBuilder();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }

}

As it is free, there are QUATA LIMITS: https://docs.google.com/macros/dashboard

Java: Casting Object to Array type

Your values object is obviously an Object[] containing a String[] containing the values.

String[] stringValues = (String[])values[0];

Verify object attribute value with mockito

Another easy way to do so:

import org.mockito.BDDMockito;    
import static org.mockito.Matchers.argThat;
import org.mockito.ArgumentMatcher;

BDDMockito.verify(mockedObject)
        .someMethodOnMockedObject(argThat(new ArgumentMatcher<TypeOfMethodArg>() {

            @Override
            public boolean matches(Object argument) {
                final TypeOfMethodArg castedArg = (TypeOfMethodArg) argument;

                // Make your verifications and return a boolean to say if it matches or not
                boolean isArgMarching = true;

                return isArgMarching;
            }
        }));

How to make borders collapse (on a div)?

Why not use outline? it is what you want outline:1px solid red;

Simple regular expression for a decimal with a precision of 2

Won't you need to take the e in e666.76 into account?

With

(e|0-9)\d*\d.\d{1,2)