Programs & Examples On #Quantitative

0

MongoDB vs Firebase

Firebase provides some good features like real time change reflection , easy integration of authentication mechanism , and lots of other built-in features for rapid web development. Firebase, really makes Web development so simple that never exists. Firebase database is a fork of MongoDB.

What's the advantage of using Firebase over MongoDB?

You can take advantage of all built-in features of Firebase over MongoDB.

How to get coordinates of an svg element?

I use the consolidate function, like so:

 element.transform.baseVal.consolidate()

The .e and .f values correspond to the x and y coordinates

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Cannot set property 'innerHTML' of null

Let us first try to understand the root cause as to why it is happening in first place.

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?

The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.

How can you make it work as before?

You want to show the "hi" message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available. It is achievable in two ways:

  1. Reorder your scripts: This way your scripts get fired only after the DOM containing your hello id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.

_x000D_
_x000D_
    <!DOCTYPE HTML>_x000D_
    <html>_x000D_
    <head>_x000D_
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
    <title>Untitled Document</title>_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
    <div id="hello"></div>_x000D_
    _x000D_
    <script type ="text/javascript">_x000D_
        what();_x000D_
        function what(){_x000D_
            document.getElementById('hello').innerHTML = 'hi';_x000D_
        };_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

  1. Use event hooking: Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with hello id already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.

_x000D_
_x000D_
<!DOCTYPE HTML>_x000D_
        <html>_x000D_
        <head>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
        <title>Untitled Document</title>_x000D_
        <script type ="text/javascript">_x000D_
            window.onload = function() {_x000D_
            what();_x000D_
            function what(){_x000D_
                document.getElementById('hello').innerHTML = 'hi';_x000D_
            };_x000D_
        }_x000D_
        </script>_x000D_
        </head>_x000D_
        _x000D_
        <body>_x000D_
        <div id="hello"></div>_x000D_
        </body>_x000D_
        </html>
_x000D_
_x000D_
_x000D_

Change navbar text color Bootstrap

As of bootstrap 4, the answer is to simply set navbar-dark in the nav element, which will set the text and links to a light theme .

<nav class="navbar navbar-dark">

How do I remove the "extended attributes" on a file in Mac OS X?

Use the xattr command. You can inspect the extended attributes:

$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine

and use the -d option to delete one extended attribute:

$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms

you can also use the -c option to remove all extended attributes:

$ xattr -c s.7z
$ xattr s.7z

xattr -h will show you the command line options, and xattr has a man page.

Why am I getting a FileNotFoundError?

You might need to change your path by:

import os
path=os.chdir(str('Here should be the path to your file')) #This command changes directory

This is what worked for me at least! Hope it works for you too!

How to change maven java home

If you are dealing with multiple projects needing different Java versions to build, there is no need to set a new JAVA_HOME environment variable value for each build. Instead execute Maven like:

JAVA_HOME=/path/to/your/jdk mvn clean install

It will build using the specified JDK, but it won't change your environment variable.

Demo:

$ mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 11.0.6, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"

$ JAVA_HOME=/opt/jdk1.8.0_201 mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 1.8.0_201, vendor: Oracle Corporation, runtime: /opt/jdk1.8.0_201/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"

$ export | grep JAVA_HOME
declare -x JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

import React, { useRef, useState } from 'react'
...
const inputRef = useRef()
....
function chooseFile() {
  const { current } = inputRef
  (current || { click: () => {}}).click()
}
...
<input
   onChange={e => {
     setFile(e.target.files)
    }}
   id="select-file"
   type="file"
   ref={inputRef}
/>
<Button onClick={chooseFile} shadow icon="/upload.svg">
   Choose file
</Button>

the unique code that works to me using next.js enter image description here

add a temporary column with a value

select field1, field2, NewField = 'example' from table1 

Convert tuple to list and back

List to Tuple and back can be done as below

import ast, sys
input_str = sys.stdin.read()
input_tuple = ast.literal_eval(input_str)

l = list(input_tuple)
l.append('Python')
#print(l)
tuple_2 = tuple(l)

# Make sure to name the final tuple 'tuple_2'
print(tuple_2)

%Like% Query in spring JpaRepository

The spring data JPA query needs the "%" chars as well as a space char following like in your query, as in

@Query("Select c from Registration c where c.place like %:place%").

Cf. http://docs.spring.io/spring-data/jpa/docs/current/reference/html.

You may want to get rid of the @Queryannotation alltogether, as it seems to resemble the standard query (automatically implemented by the spring data proxies); i.e. using the single line

List<Registration> findByPlaceContaining(String place);

is sufficient.

C# ASP.NET MVC Return to Previous Page

For ASP.NET Core You can use asp-route-* attribute:

<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">

An example: Imagine that you have a Vehicle Controller with actions

Index

Details

Edit

and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.

//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
     ..............
     ..............
     public string ReturnUrl {get;set;}
}



Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>

Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>

Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
        <div class="box-footer">
            <a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
            <button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
        </div>
    </form>

In your controller:

// GET: Vehicle/Edit/5
    public ActionResult Edit(int id,string previous)
    {
            var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
            var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
    //or by this code if you are not use automapper
    var viewModel = new VehicleViewModel();

    if (!string.IsNullOrWhiteSpace(previous)
                viewModel.ReturnUrl = previous;
            else
                viewModel.ReturnUrl = "Index";
            return View(viewModel);
        }



[HttpPost]
    public IActionResult Edit(VehicleViewModel model, string previous)
    {
            if (!string.IsNullOrWhiteSpace(previous))
                model.ReturnUrl = previous;
            else
                model.ReturnUrl = "Index";
            ............. 
            .............
            return RedirectToAction(model.ReturnUrl);
    }

How to set the margin or padding as percentage of height of parent container?

Other way to center one line text is:

.parent{
  position: relative;
}

.child{
   position: absolute;
   top: 50%;
   line-height: 0;
}

or just

.parent{
  overflow: hidden; /* if this ins't here the parent will adopt the 50% margin of the child */
}

.child{
   margin-top: 50%;
   line-height: 0;
}

how to calculate binary search complexity

The time complexity of the binary search algorithm belongs to the O(log n) class. This is called big O notation. The way you should interpret this is that the asymptotic growth of the time the function takes to execute given an input set of size n will not exceed log n.

This is just formal mathematical lingo in order to be able to prove statements, etc. It has a very straightforward explanation. When n grows very large, the log n function will out-grow the time it takes to execute the function. The size of the "input set", n, is just the length of the list.

Simply put, the reason binary search is in O(log n) is that it halves the input set in each iteration. It's easier to think about it in the reverse situation. On x iterations, how long list can the binary search algorithm at max examine? The answer is 2^x. From this we can see that the reverse is that on average the binary search algorithm needs log2 n iterations for a list of length n.

If why it is O(log n) and not O(log2 n), it's because simply put again - Using the big O notation constants don't count.

How do I determine whether an array contains a particular value in Java?

Instead of using the quick array initialisation syntax too, you could just initialise it as a List straight away in a similar manner using the Arrays.asList method, e.g.:

public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");

Then you can do (like above):

STRINGS.contains("the string you want to find");

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

if [ -n "$var" -a -e "$var" ]; then
    do something ...
fi

 

Command line: search and replace in all filenames matched by grep

Do you mean search and replace a string in all files matched by grep?

perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`

Edit

Since this seems to be a fairly popular question thought I'd update.

Nowadays I mostly use ack-grep as it's more user-friendly. So the above command would be:

perl -p -i -e 's/old/new/g' `ack -l searchpattern`

To handle whitespace in file names you can run:

ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

you can do more with ack-grep. Say you want to restrict the search to HTML files only:

ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

And if white space is not an issue it's even shorter:

perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files

Why do we use arrays instead of other data structures?

Not all programs do the same thing or run on the same hardware.

This is usually the answer why various language features exist. Arrays are a core computer science concept. Replacing arrays with lists/matrices/vectors/whatever advanced data structure would severely impact performance, and be downright impracticable in a number of systems. There are any number of cases where using one of these "advanced" data collection objects should be used because of the program in question.

In business programming (which most of us do), we can target hardware that is relatively powerful. Using a List in C# or Vector in Java is the right choice to make in these situations because these structures allow the developer to accomplish the goals faster, which in turn allows this type of software to be more featured.

When writing embedded software or an operating system an array may often be the better choice. While an array offers less functionality, it takes up less RAM, and the compiler can optimize code more efficiently for look-ups into arrays.

I am sure I am leaving out a number of the benefits for these cases, but I hope you get the point.

How can I display a JavaScript object?

Here's a way to do it:

console.log("%o", obj);

HQL "is null" And "!= null" on an Oracle column

No. See also this link Handle conditional null in HQL for tips and tricks on how to handle comparisons with both null and non-null values.

How to swap String characters in Java?

String.toCharArray() will give you an array of characters representing this string.

You can change this without changing the original string (swap any characters you require), and then create a new string using String(char[]).

Note that strings are immutable, so you have to create a new string object.

TypeError: $(...).DataTable is not a function

I got this error because I found out that I referenced jQuery twice.

The first time: on the master page (_Layout.cshtml) in ASP.NET MVC, and then again on one current page so I commented out the one on the master page.

If you are using ASP.NET MVC this snippet could help you

@*@Scripts.Render("~/bundles/jquery")*@//comment this line 
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

and in the current page I added these lines

<script src="~/scripts/jquery-1.10.2.js"></script>

<!-- #region datatables files -->
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<!-- #endregion -->

Hope this help you even if don't use ASP.NET MVC

Jquery - animate height toggle

I just thought to give you the reason why your solution did not work:

When $(document).ready() is executed only the $('#topbar-show') selector can find a matching element from the DOM. The #topbar-show element has not been created yet.

To get past this problem, you may use live event bindings

$('#topbar-show').live('click',function(e){});
$('#topbar-hide').live('click',function(e){});

This is the most simple way to fix you solution. The rest of these answer go further to provide you a better solutions instead that do not modify the hopefully permanent id attribute.

How can one pull the (private) data of one's own Android app?

Newer versions of Android Studio include the Device File Explorer which I've found to be a handy GUI method of downloading files from my development Nexus 7.

You Must make sure you have enabled USB Debugging on the device

  1. Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar to open the Device File Explorer.
  2. Select a device from the drop down list.
  3. Interact with the device content in the file explorer window. Right-click on a file or directory to create a new file or directory, save the selected file or directory to your machine, upload, delete, or synchronize. Double-click a file to open it in Android Studio.

    Android Studio saves files you open this way in a temporary directory outside of your project. If you make modifications to a file you opened using the Device File Explorer, and would like to save your changes back to the device, you must manually upload the modified version of the file to the device.

file explorer

Full Documentation

Django 1.7 - makemigrations not detecting changes

I recently upgraded Django from 1.6 to 1.8 and had few apps and migrations for them. I used south and schemamigrations for creating migrations in Django 1.6, which is dropped in Django 1.8.

When I added new models after upgrade, the makemigrations command wasn't detecting any changes. And then I tried the solution suggested by @drojf (1st answer), it worked fine, but failed to apply fake initial migration (python manage.py --fake-initial). I was doing this as my tables (old tables) were already created.

Finally this worked for me, removed new models (or model changes) from models.py and then had to delete (or rename for safety backup) migrations folder of all apps and run python manage.py makemigrations for all apps, then did python manage.py migrate --fake-initial. This worked like a charm. Once initial migration is created for all apps and fake initial migrated, then added new models and followed regular process of makemigrations and migrate on that app. The changes were detected now and everything went fine.

I just thought of sharing it here, if someone faces same problem (having schemamigrations of south for their apps), it might help them :)

How to remove only 0 (Zero) values from column in excel 2010

Easiest way for me was to create an extra column with an if statement to essentially use as a copy past clipboard.

=IF(desired cell = 0, "", desired cell)

That should return a corrected column which then you can copy and paste back over the original column AS TEXT--if you just copy paste a circular reference occurs and all the data is "erased" from both columns. Don't fret if you didn't read this carefully Ctrl+Z is your best friend...

'was not declared in this scope' error

Here's a simplified example based on of your problem:

if (test) 
{//begin scope 1
    int y = 1; 
}//end scope 1
else 
{//begin scope 2
    int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope

In the above version you have a variable called y that is confined to scope 1, and another different variable called y that is confined to scope 2. You then try to refer to a variable named y after the end of the if, and not such variable y can be seen because no such variable exists in that scope.

You solve the problem by placing y in the outermost scope which contains all references to it:

int y;
if (test) 
{
    y = 1; 
}
else 
{
    y = 2;
}
int x = y;

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

Login to remote site with PHP cURL

Panama Jack Example not work for me - Give Fatal error: Call to undefined function build_unique_path(). I used this code - (more simple - my opinion) :


// options
$login_email = '[email protected]';
$login_pass = 'alabala4807';
$cookie_file_path = "/tmp/cookies.txt";
$LOGINURL = "http://alabala.com/index.php?route=account/login";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";

// begin script
$ch = curl_init();

// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";

// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);

// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// execute session to get cookies and required form inputs
$content = curl_exec($ch);

// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['email'] = $login_email;
$fields['password'] = $login_pass;

// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);

// perform login
$result = curl_exec($ch);

print $result;

function getFormFields($data)
{
if (preg_match('/()/is', $data, $matches)) {
$inputs = getInputs($matches[1]);

return $inputs;
} else {
die('didnt find login form');
}
}

function getInputs($form)
{
$inputs = array();
$elements = preg_match_all("/(]+>)/is", $form, $matches);
if ($elements > 0) {
for($i = 0;$i $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];

$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}

$inputs[$name] = $value;
}
}
}

return $inputs;
}

$grab_url='http://grab.url/alabala';

//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, $grab_url);
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);

var_dump($html);
die;

What does it mean "No Launcher activity found!"

You have not included Launcher intent filter in activity you want to appear first, so it does not know which activity to start when application launches, for this tell the system by including launcher filter intent in manifest.xml

build maven project with propriatery libraries included

Why not run something like Nexus, your own maven repo that you can upload 3rd party proprietary jar files, and also proxy other public repositories, to save on bandwith?

This also has some good reasons to run your own maven repository manager.

this.getClass().getClassLoader().getResource("...") and NullPointerException

When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.

splitting a string based on tab in the file

You can use regex here:

>>> import re
>>> strs = "foo\tbar\t\tspam"
>>> re.split(r'\t+', strs)
['foo', 'bar', 'spam']

update:

You can use str.rstrip to get rid of trailing '\t' and then apply regex.

>>> yas = "yas\t\tbs\tcda\t\t"
>>> re.split(r'\t+', yas.rstrip('\t'))
['yas', 'bs', 'cda']

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

How to get the path of src/test/resources directory in JUnit?

Use .getAbsolutePath() on your File object.

getClass().getResource("somefile").getFile().getAbsolutePath()

What is the difference between char * const and const char *?

Another thumb rule is to check where const is:

  1. before * => value stored is constant
  2. after * => pointer itself is constant

Access to ES6 array element index inside for-of loop

In a for..of loop we can achieve this via array.entries(). array.entries returns a new Array iterator object. An iterator object knows how to access items from an iterable one at the time, while keeping track of its current position within that sequence.

When the next() method is called on the iterator key value pairs are generated. In these key value pairs the array index is the key and the array item is the value.

_x000D_
_x000D_
let arr = ['a', 'b', 'c'];_x000D_
let iterator = arr.entries();_x000D_
console.log(iterator.next().value); // [0, 'a']_x000D_
console.log(iterator.next().value); // [1, 'b']
_x000D_
_x000D_
_x000D_

A for..of loop is basically a construct which consumes an iterable and loops through all elements (using an iterator under the hood). We can combine this with array.entries() in the following manner:

_x000D_
_x000D_
array = ['a', 'b', 'c'];_x000D_
_x000D_
for (let indexValue of array.entries()) {_x000D_
  console.log(indexValue);_x000D_
}_x000D_
_x000D_
_x000D_
// we can use array destructuring to conveniently_x000D_
// store the index and value in variables_x000D_
for (let [index, value] of array.entries()) {_x000D_
   console.log(index, value);_x000D_
}
_x000D_
_x000D_
_x000D_

How can I pass request headers with jQuery's getJSON() method?

I think you could set the headers and still use getJSON() like this:

$.ajaxSetup({
  headers : {
    'Authorization' : 'Basic faskd52352rwfsdfs',
    'X-PartnerKey' : '3252352-sdgds-sdgd-dsgs-sgs332fs3f'
  }
});
$.getJSON('http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json', function(json) { alert("Success"); }); 

How to correctly use the extern keyword in C

"extern" changes the linkage. With the keyword, the function / variable is assumed to be available somewhere else and the resolving is deferred to the linker.

There's a difference between "extern" on functions and on variables: on variables it doesn't instantiate the variable itself, i.e. doesn't allocate any memory. This needs to be done somewhere else. Thus it's important if you want to import the variable from somewhere else. For functions, this only tells the compiler that linkage is extern. As this is the default (you use the keyword "static" to indicate that a function is not bound using extern linkage) you don't need to use it explicitly.

jQuery Combobox/select autocomplete?

Have a look at the following example of the jQueryUI Autocomplete, as it is keeping a select around and I think that is what you are looking for. Hope this helps.

http://jqueryui.com/demos/autocomplete/#combobox

HTML Table width in percentage, table rows separated equally

you can try this, I would do it with CSS, but i think you want it with tables without CSS.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <body leftmargin=0 rightmargin=0>
      <table cellpadding="0" cellspacing="0" width="100%" border="1" height="350px"> 
         <tr>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
         </tr>
      </table> 
   </body>
</html>

How to remove all click event handlers using jQuery?

Is there a way to remove all previous click events that have been assigned to a button?

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});

How to write inside a DIV box with javascript

_x000D_
_x000D_
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
_x000D_
_x000D_

How to increase the execution timeout in php?

First check the php.ini file path by phpinfo(); and then changed PHP.INI params:

upload_max_filesize = 1000M
memory_limit = 1500M
post_max_size = 1500M
max_execution_time = 30

restarted Apache

set_time_limit(0); // safe_mode is off

ini_set('max_execution_time', 500); //500 seconds

Note: you can also use command to find php.ini in Linux

locate `php.ini`

Permanently add a directory to PYTHONPATH?

Adding export PYTHONPATH="${PYTHONPATH}:/my/other/path" to the ~/.bashrc might not work if PYTHONPATH does not currently exist (because of the :).

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

Adding the above to my ~/.bashrc did the trick for me on Ubuntu 16.04

How to prevent form from being submitted?

Try this one...

HTML Code

<form class="submit">
    <input type="text" name="text1"/>
    <input type="text" name="text2"/>
    <input type="submit" name="Submit" value="submit"/>
</form>

jQuery Code

$(function(){
    $('.submit').on('submit', function(event){
        event.preventDefault();
        alert("Form Submission stopped.");
    });
});

or

$(function(){
    $('.submit').on('submit', function(event){
       event.preventDefault();
       event.stopPropagation();
       alert("Form Submission prevented / stopped.");
    });
});

What is meant by the term "hook" in programming?

Oftentimes hooking refers to Win32 message hooking or the Linux/OSX equivalents, but more generically hooking is simply notifying another object/window/program/etc that you want to be notified when a specified action happens. For instance: Having all windows on the system notify you as they are about to close.

As a general rule, hooking is somewhat hazardous since doing it without understanding how it affects the system can lead to instability or at the very leas unexpected behaviour. It can also be VERY useful in certain circumstances, thought. For instance: FRAPS uses it to determine which windows it should show it's FPS counter on.

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

You can, if uploading an entire folder is an option for you

<input type="file" webkitdirectory directory multiple/>

change event will contain:

.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"

How to print an exception in Python?

Python 3: logging

Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)

Logging an exception can be done with the module-level function logging.exception() like so:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

Output:

ERROR:root:An exception was thrown!
Traceback (most recent call last):
  File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

Notes:

  • the function logging.exception() should only be called from an exception handler

  • the logging module should not be used inside a logging handler to avoid a RecursionError (thanks @PrakharPandey)


Alternative log-levels

It's also possible to log the exception with another log-level by using the keyword argument exc_info=True like so:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)

How to solve privileges issues when restore PostgreSQL Database

To solve the issue you must assign the proper ownership permissions. Try the below which should resolve all permission related issues for specific users but as stated in the comments this should not be used in production:

root@server:/var/log/postgresql# sudo -u postgres psql
psql (8.4.4)
Type "help" for help.

postgres=# \du
               List of roles
    Role name    | Attributes  | Member of
-----------------+-------------+-----------
 <user-name>    | Superuser   | {}
                 : Create DB
 postgres       | Superuser   | {}
                 : Create role
                 : Create DB

postgres=# alter role <user-name> superuser;
ALTER ROLE
postgres=#

So connect to the database under a Superuser account sudo -u postgres psql and execute a ALTER ROLE <user-name> Superuser; statement.

Keep in mind this is not the best solution on multi-site hosting server so take a look at assigning individual roles instead: https://www.postgresql.org/docs/current/static/sql-set-role.html and https://www.postgresql.org/docs/current/static/sql-alterrole.html.

Copy text from nano editor to shell

Select the text in nano with the mouse and then right click on the mouse. Text is now copied to your clipboard. If it does not work try to start nano with the mouse option on : nano -m filename

Calling async method on button click

use below code

 Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));

Prepend line to beginning of a file

Different Idea:

(1) You save the original file as a variable.

(2) You overwrite the original file with new information.

(3) You append the original file in the data below the new information.

Code:

with open(<filename>,'r') as contents:
      save = contents.read()
with open(<filename>,'w') as contents:
      contents.write(< New Information >)
with open(<filename>,'a') as contents:
      contents.write(save)

How to change the color of text in javafx TextField?

Setting the -fx-text-fill works for me.

See below:

if (passed) {
    resultInfo.setText("Passed!");
    resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
    resultInfo.setText("Failed!");
    resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}

HttpClient won't import in Android Studio

HttpClient is not supported any more in sdk 23. Android 6.0 (API Level 23) release removes support for the Apache HTTP client. You have to use

android {
    useLibrary 'org.apache.http.legacy'
    .
    .
    .

and also add below code snippet in your dependency :

//http final solution for web-service (including file uploading)

compile('org.apache.httpcomponents:httpmime:4.3.6') {
        exclude module: 'httpclient'
}
 compile 'org.apache.httpcomponents:httpclient-android:4.3.5'

It will also help you while you use Use MultipartEntity for File upload.

Hide horizontal scrollbar on an iframe?

set scrolling="no" attribute in your iframe.

How to install Android Studio on Ubuntu?

I was just investigating this issue now, you should use Ubuntu Make

Which "is a command line tool which allows you to download the latest version of popular developer tools on your installation"

Submit form using <a> tag

you can do it like this with raw javascript

<html>
    <body>
        <form id="my_form" method="post" action="mailto://[email protected]">
            <a href="javascript:{}" onclick="document.getElementById('my_form').submit();">submit</a>
        </form>
    </body>
</html>

For those asking why I have a href element in my anchor tag, its because it's a compulsory part of an anchor tag, it may well work without but it's not to spec. So if you want to guarantee rendering etc you must give the engine a fully formed tag. So the above achieves this. You will see href="#" used sometimes but this is not always wanted as the browser will change the page position.

OS X cp command in Terminal - No such file or directory

I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).

I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.

So, as an example:

cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]

Transactions in .net

There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):

using (IDbTransaction tran = conn.BeginTransaction()) {
    try {
        // your code
        tran.Commit();
    }  catch {
        tran.Rollback();
        throw;
    }
}

Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.

The alternative is an ambient transaction; new in .NET 2.0, the TransactionScope object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).

For example:

using(TransactionScope tran = new TransactionScope()) {
    CallAMethodThatDoesSomeWork();
    CallAMethodThatDoesSomeMoreWork();
    tran.Complete();
}

Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.

If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.

The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).

All in all, a very, very useful object.

Some caveats:

  • On SQL Server 2000, a TransactionScope will go to DTC immediately; this is fixed in SQL Server 2005 and above, it can use the LTM (much less overhead) until you talk to 2 sources etc, when it is elevated to DTC.
  • There is a glitch that means you might need to tweak your connection string

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

This is working very fast,and efficient in SQL. Suppose you have Table Sample with 4 column a,b,c,d where a,b,d are int and c column is Varchar(50).

CREATE TABLE [dbo].[Sample](
[a] [int] NULL,
[b] [int] NULL,
[c] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[D] [int] NULL
)

So you cant inset multiple records in this table using following query without repeating insert statement,

DECLARE @LIST VARCHAR(MAX)
SET @LIST='SELECT 1, 1, ''Charan Ghate'',11
     SELECT 2,2, ''Mahesh More'',12
     SELECT 3,3,''Mahesh Nikam'',13
     SELECT 4,4, ''Jay Kadam'',14'
INSERT SAMPLE (a, b, c,d) EXEC(@LIST)

Also With C# using SqlBulkCopy bulkcopy = new SqlBulkCopy(con)

You can insert 10 rows at a time

   DataTable dt = new DataTable();
        dt.Columns.Add("a");
        dt.Columns.Add("b");
        dt.Columns.Add("c");
        dt.Columns.Add("d");
        for (int i = 0; i < 10; i++)
        {
            DataRow dr = dt.NewRow();
            dr["a"] = 1;
            dr["b"] = 2;
            dr["c"] = "Charan";
            dr["d"] = 4;
            dt.Rows.Add(dr);
        }
        SqlConnection con = new SqlConnection("Connection String");
        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(con))
        {
            con.Open();
            bulkcopy.DestinationTableName = "Sample";
            bulkcopy.WriteToServer(dt);
            con.Close();
        }

C++ convert string to hexadecimal and vice versa

I think there is a much simpler and more elegant solution. Some of the above-mentioned methods may even throw unhandled exceptions in some cases. Here is a fool-proof (as in never goes wrong) and very fast code. Just try it and compare the results in terms of speed and compactness:

#include <string>

// Convert string of chars to its representative string of hex numbers
void stream2hex(const std::string str, std::string& hexstr, bool capital = false)
{
    hexstr.resize(str.size() * 2);
    const size_t a = capital ? 'A' - 1 : 'a' - 1;

    for (size_t i = 0, c = str[0] & 0xFF; i < hexstr.size(); c = str[i / 2] & 0xFF)
    {
        hexstr[i++] = c > 0x9F ? (c / 16 - 9) | a : c / 16 | '0';
        hexstr[i++] = (c & 0xF) > 9 ? (c % 16 - 9) | a : c % 16 | '0';
    }
}

// Convert string of hex numbers to its equivalent char-stream
void hex2stream(const std::string hexstr, std::string& str)
{
    str.resize((hexstr.size() + 1) / 2);

    for (size_t i = 0, j = 0; i < str.size(); i++, j++)
    {
        str[i] = (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) << 4, j++;
        str[i] |= (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) & 0xF;
    }
}

Test the code:

#include <iostream>
int main()
{
    std::string s = "Hello World!";
    std::cout << "original string: " << s << '\n';
    stream2hex(s, s);
    std::cout << "hex format: " << s << '\n';
    hex2stream(s, s);
    std::cout << "original one: " << s << '\n';
}

and the result is:

original string: Hello World!
hex format: 48656C6C6F20576F726C6421
original one: Hello World!

Exit single-user mode

Even I come across same problem, not able to find active connections to my_db to kill it but still shows same error. I end up disconnecting all possible SSMS connections for any database on the Server, create a new connection from SSMS and change it to Multi user.

-- Actual Code to change my_db to multi user mode
USE MASTER;
GO
ALTER DATABASE [my_db] SET MULTI_USER

Note: This seems to be a possible bug in SQL Server 2005!

REST API Login Pattern

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

How it works in practice

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

Hope this will helps you to find the proper solution!

Get custom product attributes in Woocommerce

Most updated:

$product->get_attribute( 'your_attr' );

You will need to define $product if it's not on the page.

Bootstrap close responsive menu "on click"

Bootstrap 4 solution without any Javascript

Add attributes data-toggle="collapse" data-target="#navbarSupportedContent.show" to the div <div class="collapse navbar-collapse">

Make sure you provide the correct id in data-target

<div className="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show">

.show is to avoid menu flickering in large resolutions

_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown_x000D_
        </a>_x000D_
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
          <a class="dropdown-item" href="#">Action</a>_x000D_
          <a class="dropdown-item" href="#">Another action</a>_x000D_
          <div class="dropdown-divider"></div>_x000D_
          <a class="dropdown-item" href="#">Something else here</a>_x000D_
        </div>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link disabled" href="#">Disabled</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
    <form class="form-inline my-2 my-lg-0">_x000D_
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
    </form>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

check if directory exists and delete in one command unix

Here is another one liner:

[[ -d /tmp/test ]] && rm -r /tmp/test
  • && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero)

HTML image bottom alignment inside DIV container

This is your code: http://jsfiddle.net/WSFnX/

Using display: table-cell is fine, provided that you're aware that it won't work in IE6/7. Other than that, it's safe: Is there a disadvantage of using `display:table-cell`on divs?

To fix the space at the bottom, add vertical-align: bottom to the actual imgs:

http://jsfiddle.net/WSFnX/1/

Removing the space between the images boils down to this: bikeshedding CSS3 property alternative?

So, here's a demo with the whitespace removed in your HTML: http://jsfiddle.net/WSFnX/4/

How to add multiple jar files in classpath in linux

For linux users, you should know the following:

  1. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override). Using -cp (--classpath) requires that you keep track of all the directories manually and copy-paste that line every time you run the program (not preferable IMO).

  2. The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:

    export CLASSPATH=.
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
    

    In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.

  3. echo $CLASSPATH
    

    is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.

  4. Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

def getAny(dic, keys, default=None):
    return (keys or default) and dic.get(keys[0], 
                                         getAny( dic, keys[1:], default=default))

or even better, without recursion and more clear:

def getAny(dic, keys, default=None):
    for k in keys: 
        if k in dic:
           return dic[k]
    return default

Then that could be used in a way similar to the dict.get method, like:

getAny(myDict, keySet)

and even have a default result in case of no keys found at all:

getAny(myDict, keySet, "not found")

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Suppose we have streaming in video tag and id is video - <video id="video"></video> then we should have following code -

var videoEl = document.getElementById('video');
// now get the steam 
stream = videoEl.srcObject;
// now get all tracks
tracks = stream.getTracks();
// now close each track by having forEach loop
tracks.forEach(function(track) {
   // stopping every track
   track.stop();
});
// assign null to srcObject of video
videoEl.srcObject = null;

How to get changes from another branch

You can use rebase, for instance, git rebase our-team when you are on your branch featurex

It will move the start point of the branch at the end of your our-team branch, merging all changes in your featurex branch.

Push existing project into Github

This one worked for me (just keep it for reference when in need)

# Go into your existing directory and run below commands
cd docker-spring-boot
echo "# docker-spring-boot" >> README.md
git init
git add -A
git commit -m "first commit"
git branch -M master
git remote add origin https://github.com/devopsmaster/docker-spring-boot.git
git push -u origin master
                

onchange event for html.dropdownlist

You can try this if you are passing a value to the action method.

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })

Remove the query string in case of no parameter passing.

Creating virtual directories in IIS express

IIS express configuration is managed by applicationhost.config.
You can find it in

Users\<username>\Documents\IISExpress\config folder.

Inside you can find the sites section that hold a section for each IIS Express configured site.

Add (or modify) a site section like this:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
   </application>
   <application path="/OffSiteStuff" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="d:\temp\SubFolderApp" />
   </application>
    <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Practically you need to add a new application tag in your site for each virtual directory. You get a lot of flexibility because you can set different configuration for the virtual directory (for example a different .Net Framework version)

EDIT Thanks to Fevzi Apaydin to point to a more elegant solution.

You can achieve same result by adding one or more virtualDirectory tag to the Application tag:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
     <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
   </application>
    <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Reference:

Converting a view to Bitmap without displaying it in Android?

I used this just a few days ago:

fun generateBitmapFromView(view: View): Bitmap {
    val specWidth = View.MeasureSpec.makeMeasureSpec(1324, View.MeasureSpec.AT_MOST)
    val specHeight = View.MeasureSpec.makeMeasureSpec(521, View.MeasureSpec.AT_MOST)
    view.measure(specWidth, specHeight)
    val width = view.measuredWidth
    val height = view.measuredHeight
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    view.layout(view.left, view.top, view.right, view.bottom)
    view.draw(canvas)
    return bitmap
}

This code is based in this gist

Difference between HashSet and HashMap?

Differences between HashSet and HashMap in Java

HashSet internally uses HashMap to store objects.when add(String) method called it calls HahsMap put(key,value) method where key=String object & value=new Object(Dummy).so it maintain no duplicates because keys are nothing but Value Object.

the Objects which are stored as key in Hashset/HashMap should override hashcode & equals contract.

Keys which are used to access/store value objects in HashMap should declared as Final because when it is modified Value object can't be located & returns null.

How to Auto resize HTML table cell to fit the text size

You can try this:

HTML

<table>
    <tr>
        <td class="shrink">element1</td>
        <td class="shrink">data</td>
        <td class="shrink">junk here</td>
        <td class="expand">last column</td>
    </tr>
    <tr>
        <td class="shrink">elem</td>
        <td class="shrink">more data</td>
        <td class="shrink">other stuff</td>
        <td class="expand">again, last column</td>
    </tr>
    <tr>
        <td class="shrink">more</td>
        <td class="shrink">of </td>
        <td class="shrink">these</td>
        <td class="expand">rows</td>
    </tr>
</table>

CSS

table {
    border: 1px solid green;
    border-collapse: collapse;
    width:100%;
}

table td {
    border: 1px solid green;
}

table td.shrink {
    white-space:nowrap
}
table td.expand {
    width: 99%
}

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

There's a simpler way I found when running Linux Mint.

  1. Ensure you install the Guest Additions from the command line and that you have the folder(s) shared with "automount" and "make permanent" settings selected within "Shared Folders" tab of the Machine Settings
  2. Launch the User management application from Application/Settings/System Setting/ menu selection (requires sudo) from within the Mint menu
  3. In the "Privileges and Groups" tab, check the box next to the "vboxsf" group, and then apply and ok your way back out.

Any user within the vboxsf group has full access to any shared folders on each boot with no manual mounting or unmounting

I usually do the following in addition to the above just to have quick access

  1. Open the Dolphin file manager and navigate to /media/
  2. Right-Click on the shared folder and click "Add to Places"

How do I print the full value of a long string in gdb?

The printf command will print the complete strings:

(gdb) printf "%s\n", string

How to convert JSON object to JavaScript array?

You can insert object items to an array as this

_x000D_
_x000D_
let obj = {_x000D_
  '1st': {_x000D_
    name: 'stackoverflow'_x000D_
  },_x000D_
  '2nd': {_x000D_
    name: 'stackexchange'_x000D_
  }_x000D_
};_x000D_
 _x000D_
 let wholeArray = Object.keys(obj).map(key => obj[key]);_x000D_
 _x000D_
 console.log(wholeArray);
_x000D_
_x000D_
_x000D_

pandas get column average/mean

Do try to give print (df.describe()) a shot. I hope it will be very helpful to get an overall description of your dataframe.

how to parse xml to java object?

JAXB is a reliable choice as it does xml to java classes mapping smoothely. But there are other frameworks available, here is one such:

https://code.google.com/p/xmappr/

How to prevent http file caching in Apache httpd (MAMP)

Without mod_expires it will be harder to set expiration headers on your files. For anything generated you can certainly set some default headers on the answer, doing the job of mod_expires like that:

<?php header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); ?>

(taken from: Stack Overflow answer from @brianegge, where the mod_expires solution is also explained)

Now this won't work for static files, like your javascript files. As for static files there is only apache (without any expiration module) between the browser and the source file. To prevent caching of javascript files, which is done on your browser, you can use a random token at the end of the js url, something like ?rd=45642111, so the url looks like:

<script type="texte/javascript" src="my/url/myjs.js?rd=4221159546">

If this url on the page is generated by a PHP file you can simply add the random part with PHP. This way of randomizing url by simply appending random query string parameters is the base thing upôn no-cache setting of ajax jQuery request for example. The browser will never consider 2 url having different query strings to be the same, and will never use the cached version.

EDIT

Note that you should alos test mod_headers. If you have mod_headers you can maybe set the Expires headers directly with the Header keyword.

Why is there no Constant feature in Java?

What does const mean
First, realize that the semantics of a "const" keyword means different things to different people:

  • read-only reference - Java final semantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiable
  • readable-only reference - C const pointer/reference semantics - means this reference cannot be used to modify the instance (e.g. cannot assign to instance variables, cannot invoke mutable methods) - affects the reference variable only, so a non-const reference pointing to the same instance could modify the instance
  • immutable object - means the instance itself cannot be modified - applies to instance, so any non-const reference would not be allowed or could not be used to modify the instance
  • some combination of the the above?
  • others?

Why or Why Not const
Second, if you really want to dig into some of the "pro" vs "con" arguments, see the discussion under this request for enhancement (RFE) "bug". This RFE requests a "readable-only reference"-type "const" feature. Opened in 1999 and then closed/rejected by Sun in 2005, the "const" topic was vigorously debated:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070

While there are a lot of good arguments on both sides, some of the oft-cited (but not necessarily compelling or clear-cut) reasons against const include:

  • may have confusing semantics that may be misused and/or abused (see the What does const mean above)
  • may duplicate capability otherwise available (e.g. designing an immutable class, using an immutable interface)
  • may be feature creep, leading to a need for other semantic changes such as support for passing objects by value

Before anyone tries to debate me about whether these are good or bad reasons, note that these are not my reasons. They are simply the "gist" of some of the reasons I gleaned from skimming the RFE discussion. I don't necessarily agree with them myself - I'm simply trying to cite why some people (not me) may feel a const keyword may not be a good idea. Personally, I'd love more "const" semantics to be introduced to the language in an unambiguous manner.

Adding CSRFToken to Ajax request

You can use this:

var token = "SOME_TOKEN";

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  jqXHR.setRequestHeader('X-CSRF-Token', token);
});

From documentation:

jQuery.ajaxPrefilter( [dataTypes ], handler(options, originalOptions, jqXHR) )

Description: Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().

Read

Convert List<Object> to String[] in Java

Java 8 has the option of using streams like:

List<Object> lst = new ArrayList<>();
String[] strings = lst.stream().toArray(String[]::new);

Fit website background image to screen size

This worked for me:

body {
  background-image:url(../IMAGES/background.jpg);
  background-position: center center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

Java Read Large Text File With 70million line of text

If you are looking out at performance, you could have a look at the java.nio.* packages - those are supposedly faster than java.io.*

How to properly and completely close/reset a TcpClient connection?

Have you tried calling TcpClient.Dispose() explicitly?

And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?

How to condense if/else into one line in Python?

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

MySQL - Trigger for updating same table after insert

DELIMITER $$

DROP TRIGGER IF EXISTS `setEditStatus`$$
CREATE TRIGGER `setEditStatus` **BEFORE** INSERT on ACCOUNTS
FOR EACH ROW BEGIN

    SET NEW.STATUS = 'E';

END$$

DELIMITER ;

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

converting numbers in to words C#

public static string NumberToWords(int number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];
            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

Get the current fragment object

Try this,

Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);

this will give u the current fragment, then you may compare it to the fragment class and do your stuffs.

    if (currentFragment instanceof NameOfYourFragmentClass) {
     Log.v(TAG, "find the current fragment");
  }

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

Flutter plugin not installed error;. When running flutter doctor

You can just install the Flutter and Dart plugin in the android studio by following these steps:

  1. Start the Android Studio application
  2. Open plugin preferences (Preferences>Plugins on macOS, File>Settings>Plugins on Windows & Linux).
  3. Select Marketplace…, search the Flutter plugin, and click install.
  4. Click Yes when prompted to install the Dart plugin.
  5. Click on Apply and OK.
  6. Click "Restart" on the popup.

The below image indicates where you should do it

enter image description here

Dynamically load JS inside JS

Necromancing.

I use this to load dependant scripts;
it works with IE8+ without adding any dependency on another library like jQuery !

var cScriptLoader = (function ()
{
    function cScriptLoader(files)
    {
        var _this = this;
        this.log = function (t)
        {
            console.log("ScriptLoader: " + t);
        };
        this.withNoCache = function (filename)
        {
            if (filename.indexOf("?") === -1)
                filename += "?no_cache=" + new Date().getTime();
            else
                filename += "&no_cache=" + new Date().getTime();
            return filename;
        };
        this.loadStyle = function (filename)
        {
            // HTMLLinkElement
            var link = document.createElement("link");
            link.rel = "stylesheet";
            link.type = "text/css";
            link.href = _this.withNoCache(filename);
            _this.log('Loading style ' + filename);
            link.onload = function ()
            {
                _this.log('Loaded style "' + filename + '".');
            };
            link.onerror = function ()
            {
                _this.log('Error loading style "' + filename + '".');
            };
            _this.m_head.appendChild(link);
        };
        this.loadScript = function (i)
        {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = _this.withNoCache(_this.m_js_files[i]);
            var loadNextScript = function ()
            {
                if (i + 1 < _this.m_js_files.length)
                {
                    _this.loadScript(i + 1);
                }
            };
            script.onload = function ()
            {
                _this.log('Loaded script "' + _this.m_js_files[i] + '".');
                loadNextScript();
            };
            script.onerror = function ()
            {
                _this.log('Error loading script "' + _this.m_js_files[i] + '".');
                loadNextScript();
            };
            _this.log('Loading script "' + _this.m_js_files[i] + '".');
            _this.m_head.appendChild(script);
        };
        this.loadFiles = function ()
        {
            // this.log(this.m_css_files);
            // this.log(this.m_js_files);
            for (var i = 0; i < _this.m_css_files.length; ++i)
                _this.loadStyle(_this.m_css_files[i]);
            _this.loadScript(0);
        };
        this.m_js_files = [];
        this.m_css_files = [];
        this.m_head = document.getElementsByTagName("head")[0];
        // this.m_head = document.head; // IE9+ only
        function endsWith(str, suffix)
        {
            if (str === null || suffix === null)
                return false;
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
        for (var i = 0; i < files.length; ++i)
        {
            if (endsWith(files[i], ".css"))
            {
                this.m_css_files.push(files[i]);
            }
            else if (endsWith(files[i], ".js"))
            {
                this.m_js_files.push(files[i]);
            }
            else
                this.log('Error unknown filetype "' + files[i] + '".');
        }
    }
    return cScriptLoader;
})();
var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();

If you are interested in the typescript-version used to create this:

class cScriptLoader {
    private m_js_files: string[];
    private m_css_files: string[];
    private m_head:HTMLHeadElement;
    
    private log = (t:any) =>
    {
        console.log("ScriptLoader: " + t);
    }
    
    
    constructor(files: string[]) {
        this.m_js_files = [];
        this.m_css_files = [];
        this.m_head = document.getElementsByTagName("head")[0];
        // this.m_head = document.head; // IE9+ only
        
        
        function endsWith(str:string, suffix:string):boolean 
        {
            if(str === null || suffix === null)
                return false;
                
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
        
        
        for(let i:number = 0; i < files.length; ++i) 
        {
            if(endsWith(files[i], ".css"))
            {
                this.m_css_files.push(files[i]);
            }
            else if(endsWith(files[i], ".js"))
            {
                this.m_js_files.push(files[i]);
            }
            else
                this.log('Error unknown filetype "' + files[i] +'".');
        }
        
    }
    
    
    public withNoCache = (filename:string):string =>
    {
        if(filename.indexOf("?") === -1)
            filename += "?no_cache=" + new Date().getTime();
        else
            filename += "&no_cache=" + new Date().getTime();
            
        return filename;    
    }
    

    public loadStyle = (filename:string) =>
    {
        // HTMLLinkElement
        let link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = this.withNoCache(filename);
        
        this.log('Loading style ' + filename);
        link.onload = () =>
        {
            this.log('Loaded style "' + filename + '".');
            
        };
        
        link.onerror = () =>
        {
            this.log('Error loading style "' + filename + '".');
        };
        
        this.m_head.appendChild(link);
    }
    
    
    public loadScript = (i:number) => 
    {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = this.withNoCache(this.m_js_files[i]);
        
        var loadNextScript = () => 
        {
            if (i + 1 < this.m_js_files.length)
            {
                this.loadScript(i + 1);
            }
        }
        
        script.onload = () =>
        {
            this.log('Loaded script "' + this.m_js_files[i] + '".');
            loadNextScript();
        };
        
        
        script.onerror = () =>
        {
            this.log('Error loading script "' + this.m_js_files[i] + '".');
            loadNextScript();
        };
        
        
        this.log('Loading script "' + this.m_js_files[i] + '".');
        this.m_head.appendChild(script);
    }
    
    public loadFiles = () => 
    {
        // this.log(this.m_css_files);
        // this.log(this.m_js_files);
        
        for(let i:number = 0; i < this.m_css_files.length; ++i)
            this.loadStyle(this.m_css_files[i])
        
        this.loadScript(0);
    }
    
}


var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();

If it's to load a dynamic list of scripts, write the scripts into an attribute, such as data-main, e.g. <script src="scriptloader.js" data-main="file1.js,file2.js,file3.js,etc." ></script>
and do a element.getAttribute("data-main").split(',')

such as

var target = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  // Note: this is for IE as IE doesn't support currentScript
  // this does not work if you have deferred loading with async
  // e.g. <script src="..." async="async" ></script>
  // https://web.archive.org/web/20180618155601/https://www.w3schools.com/TAgs/att_script_async.asp
  return scripts[scripts.length - 1];
})();

target.getAttribute("data-main").split(',')

to obtain the list.

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

DFS is more space-efficient than BFS, but may go to unnecessary depths.

Their names are revealing: if there's a big breadth (i.e. big branching factor), but very limited depth (e.g. limited number of "moves"), then DFS can be more preferrable to BFS.


On IDDFS

It should be mentioned that there's a less-known variant that combines the space efficiency of DFS, but (cummulatively) the level-order visitation of BFS, is the iterative deepening depth-first search. This algorithm revisits some nodes, but it only contributes a constant factor of asymptotic difference.

Django - limiting query results

Django querysets are lazy. That means a query will hit the database only when you specifically ask for the result.

So until you print or actually use the result of a query you can filter further with no database access.

As you can see below your code only executes one sql query to fetch only the last 10 items.

In [19]: import logging                                 
In [20]: l = logging.getLogger('django.db.backends')    
In [21]: l.setLevel(logging.DEBUG)                      
In [22]: l.addHandler(logging.StreamHandler())      
In [23]: User.objects.all().order_by('-id')[:10]          
(0.000) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" ORDER BY "auth_user"."id" DESC LIMIT 10; args=()
Out[23]: [<User: hamdi>]

Disable pasting text into HTML form

what about using CSS on UIWebView? something like

<style type="text/css">
<!—-
    * {
        -webkit-user-select: none;
    }
-->
</style>

also you can read detail about block copy-paste using CSS http://rakaz.nl/2009/09/iphone-webapps-101-getting-safari-out-of-the-way.html

jQuery: Best practice to populate drop down?

Below is the Jquery way of populating a drop down list whose id is "FolderListDropDown"

$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        var elem = $("<option></option>");
        elem.attr("value", result[i].ImageFolderID);
        elem.text(result[i].Name);
        elem.appendTo($("select#FolderListDropDown"));
     }
});

Python method for reading keypress?

It's really late now but I made a quick script which works for Windows, Mac and Linux, simply by using each command line:

import os, platform

def close():
    if platform.system() == "Windows":
        print("Press any key to exit . . .")
        os.system("pause>nul")
        exit()
    
    elif platform.system() == "Linux":
        os.system("read -n1 -r -p \"Press any key to exit . . .\" key")
        exit()
    
    elif platform.system() == "Darwin":
        print("Press any key to exit . . .")
        os.system("read -n 1 -s -p \"\"")
        exit()
    
    else:
        exit()

It uses only inbuilt functions, and should work for all three (although I've only tested Windows and Linux...).

Expansion of variables inside single quotes in a command in Bash

Inside single quotes everything is preserved literally, without exception.

That means you have to close the quotes, insert something, and then re-enter again.

'before'"$variable"'after'
'before'"'"'after'
'before'\''after'

Word concatenation is simply done by juxtaposition. As you can verify, each of the above lines is a single word to the shell. Quotes (single or double quotes, depending on the situation) don't isolate words. They are only used to disable interpretation of various special characters, like whitespace, $, ;... For a good tutorial on quoting see Mark Reed's answer. Also relevant: Which characters need to be escaped in bash?

Do not concatenate strings interpreted by a shell

You should absolutely avoid building shell commands by concatenating variables. This is a bad idea similar to concatenation of SQL fragments (SQL injection!).

Usually it is possible to have placeholders in the command, and to supply the command together with variables so that the callee can receive them from the invocation arguments list.

For example, the following is very unsafe. DON'T DO THIS

script="echo \"Argument 1 is: $myvar\""
/bin/sh -c "$script"

If the contents of $myvar is untrusted, here is an exploit:

myvar='foo"; echo "you were hacked'

Instead of the above invocation, use positional arguments. The following invocation is better -- it's not exploitable:

script='echo "arg 1 is: $1"'
/bin/sh -c "$script" -- "$myvar"

Note the use of single ticks in the assignment to script, which means that it's taken literally, without variable expansion or any other form of interpretation.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

Yes, it is possible. You have to do something like this:

if(isset($_POST['submit']))
{
  $type_id = ($_POST['type_id'] == '' ? "null" : "'".$_POST['type_id']."'");
  $sql = "INSERT INTO `table` (`type_id`) VALUES (".$type_id.")";
}

It checks if the $_POST['type_id'] variable has an empty value. If yes, it assign NULL as a string to it. If not, it assign the value with ' to it for the SQL notation

Present and dismiss modal view controller

Swift

self.dismissViewControllerAnimated(true, completion: nil)

XPath test if node value is number

The shortest possible way to test if the value contained in a variable $v can be used as a number is:

number($v) = number($v)

You only need to substitute the $v above with the expression whose value you want to test.

Explanation:

number($v) = number($v) is obviously true, if $v is a number, or a string that represents a number.

It is true also for a boolean value, because a number(true()) is 1 and number(false) is 0.

Whenever $v cannot be used as a number, then number($v) is NaN

and NaN is not equal to any other value, even to itself.

Thus, the above expression is true only for $v whose value can be used as a number, and false otherwise.

How to remove all of the data in a table using Django

Use this syntax to delete the rows also to redirect to the homepage (To avoid page load errors) :

def delete_all(self):
  Reporter.objects.all().delete()
  return HttpResponseRedirect('/')

Angular2 Material Dialog css, dialog size

There are two ways which we can use to change size of your MatDialog component in angular material

1) From Outside Component Which Call Dialog Component

import { MatDialog, MatDialogConfig, MatDialogRef } from '@angular/material';


dialogRef: MatDialogRef <any> ;

constructor(public dialog: MatDialog) { }

openDialog() {
        this.dialogRef = this.dialog.open(TestTemplateComponent, {
            height: '40%',
            width: '60%'
        });
        this.dialogRef.afterClosed().subscribe(result => {
            this.dialogRef = null;
        });
    }

2) From Inside Dialog Component. dynamically change its size

import { MatDialog, MatDialogConfig, MatDialogRef } from '@angular/material';

constructor(public dialogRef: MatDialogRef<any>) { }

 ngOnInit() {
        this.dialogRef.updateSize('80%', '80%');
    }

use updateSize() in any function in dialog component. it will change dialog size automatically.

for more information check this link https://material.angular.io/components/component/dialog

How to PUT a json object with an array using curl

Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.

curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \
     http://example.com/service

Using the exact JSON data from the question, the full command line would become:

curl -H 'Content-Type: application/json' -X PUT \
    -d '{"tags":["tag1","tag2"],
         "question":"Which band?",
         "answers":[{"id":"a0","answer":"Answer1"},
                    {"id":"a1","answer":"answer2"}]}' \
    http://example.com/service

Note: JSON data wrapped only for readability, not valid for curl request.

What is the best/safest way to reinstall Homebrew?

Update 10/11/2020 to reflect the latest brew changes.

Brew already provide a command to uninstall itself (this will remove everything you installed with Homebrew):

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

If you failed to run this command due to permission (like run as second user), run again with sudo

Then you can install again:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

java.lang.IllegalAccessError: tried to access method

I was getting this error on a Spring Boot application where a @RestController ApplicationInfoResource had a nested class ApplicationInfo.

It seems the Spring Boot Dev Tools was using a different class loader.

The exception I was getting

2017-05-01 17:47:39.588 WARN 1516 --- [nio-8080-exec-9] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.IllegalAccessError: tried to access class com.gt.web.rest.ApplicationInfo from class com.gt.web.rest.ApplicationInfoResource$$EnhancerBySpringCGLIB$$59ce500c

Solution

I moved the nested class ApplicationInfo to a separate .java file and got rid of the problem.

How do I use the built in password reset/change views with my own templates

You just need to wrap the existing functions and pass in the template you want. For example:

from django.contrib.auth.views import password_reset

def my_password_reset(request, template_name='path/to/my/template'):
    return password_reset(request, template_name)

To see this just have a look at the function declartion of the built in views:

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L74

How can I return the sum and average of an int array?

You have tried the wrong variable, ints is not the correct name of the argument.

public int Sum(params int[] customerssalary)
{
    return customerssalary.Sum();
}

public double Avg(params int[] customerssalary)
{
    return customerssalary.Average();
}

But do you think that these methods are really needed?

How can I do an asc and desc sort using underscore.js?

The Array prototype's reverse method modifies the array and returns a reference to it, which means you can do this:

var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();

Also, the underscore documentation reads:

In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

which means you can also use .reverse() while chaining:

var sortedDescAndFiltered = _.chain(collection)
    .sortBy('propertyName')
    .reverse()
    .filter(_.property('isGood'))
    .value();

How to set host_key_checking=false in ansible inventory file?

In /etc/ansible/ansible.cfg uncomment the line:

host_key_check = False

and in /etc/ansible/hosts uncomment the line

client_ansible ansible_ssh_host=10.1.1.1 ansible_ssh_user=root ansible_ssh_pass=12345678

That's all

What do .c and .h file extensions mean to C?

.c : 'C' source code
.h : Header file

Usually, the .c files contain the implementation, and .h files contain the "interface" of an implementation.

How do I remove the non-numeric character from a string in java?

Are you removing or splitting? This will remove all the non-numeric characters.

myStr = myStr.replaceAll( "[^\\d]", "" )

How to import existing Git repository into another?

See Basic example in this article and consider such mapping on repositories:

  • A <-> YYY,
  • B <-> XXX

After all activity described in this chapter (after merging), remove branch B-master:

$ git branch -d B-master

Then, push changes.

It works for me.

C# DateTime to "YYYYMMDDHHMMSS" format

You've just got to be careful between months (MM) and minutes (mm):

DateTime dt = DateTime.Now; // Or whatever
string s = dt.ToString("yyyyMMddHHmmss");

(Also note that HH is 24 hour clock, whereas hh would be 12 hour clock, usually in conjunction with t or tt for the am/pm designator.)

If you want to do this as part of a composite format string, you'd use:

string s = string.Format("The date/time is: {0:yyyyMMddHHmmss}", dt);

For further information, see the MSDN page on custom date and time formats.

How to add a class to body tag?

I had the same problem,

<body id="body">

Add an ID tag to the body:

$('#body').attr('class',json.class); // My class comes from Ajax/JSON, but change it to whatever you require.

Then switch the class for the body's using the id. This has been tested in Chrome, Internet Explorer, and Safari.

How to float a div over Google Maps?

Try this:

<style>
   #wrapper { position: relative; }
   #over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>

<div id="wrapper">
   <div id="google_map">

   </div>

   <div id="over_map">

   </div>
</div>

Relative imports - ModuleNotFoundError: No module named x

TL;DR: You can't do relative imports from the file you execute since __main__ module is not a part of a package.

Absolute imports - import something available on sys.path

Relative imports - import something relative to the current module, must be a part of a package

If you're running both variants in exactly the same way, one of them should work. Here is an example that should help you understand what's going on. Let's add another main.py file with the overall directory structure like this:

.
./main.py
./ryan/__init__.py
./ryan/config.py
./ryan/test.py

And let's update test.py to see what's going on:

# config.py
debug = True
# test.py
print(__name__)

try:
    # Trying to find module in the parent package
    from . import config
    print(config.debug)
    del config
except ImportError:
    print('Relative import failed')

try:
    # Trying to find module on sys.path
    import config
    print(config.debug)
except ModuleNotFoundError:
    print('Absolute import failed')
# main.py
import ryan.test

Let's run test.py first:

$ python ryan/test.py
__main__
Relative import failed
True

Here "test" is the __main__ module and doesn't know anything about belonging to a package. However import config should work, since the ryan folder will be added to sys.path.

Let's run main.py instead:

$ python main.py
ryan.test
True
Absolute import failed

And here test is inside of the "ryan" package and can perform relative imports. import config fails since implicit relative imports are not allowed in Python 3.

Hope this helped.

P.S.: If you're sticking with Python 3 there is no more need for __init__.py files.

How can I change or remove HTML5 form validation default error messages?

To prevent the browser validation message from appearing in your document, with jQuery:

$('input, select, textarea').on("invalid", function(e) {
    e.preventDefault();
});

Add ArrayList to another ArrayList in java

The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop. Each iterations NodeList is enlarged by new elements.

  1. After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))

  2. After second loop NodeList has 10 elements (PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd) and list has 2 elements (NodeList (with 10 elements), NodeList (with 10 elements))

To get you expectations you must replace

NodeList.addAll(nodes);
list.add(NodeList)

by

List childrenList = new ArrayList(nodes);
list.add(childrenList);

PS. Your code is not readable, keep Java code conventions to have readble code. For example is hard to recognize if NodeList is a class or object

How do I enumerate through a JObject?

For people like me, linq addicts, and based on svick's answer, here a linq approach:

using System.Linq;
//...
//make it linq iterable. 
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();

Now you can make linq expressions like:

JToken x = obj_linq
          .Where( d => d.Key == "my_key")
          .Select(v => v)
          .FirstOrDefault()
          .Value;
string y = ((JValue)x).Value;

Or just:

var y = obj_linq
       .Where(d => d.Key == "my_key")
       .Select(v => ((JValue)v.Value).Value)
       .FirstOrDefault();

Or this one to iterate over all data:

obj_linq.ToList().ForEach( x => { do stuff } ); 

"Could not find a valid gem in any repository" (rubygame and others)

Maybe you should try

gem list -r

then

gem install -r rubygame

Also note that with rvmon MacosX (Lion in my case) you should install ruby-1.9.3-p194 (for Xcode 4.x compiler considerations) then

rvm rubygems current

and in my case I had to use

rvm use ruby-1.9.3-p194@global

(which contains bundler, rake, rubygems-bundlerand rvm)

and not

rvm use ruby-1.9.3-p194

(which is empty)

Comparing two strings in C?

You are currently comparing the addresses of the two strings.

Use strcmp to compare the values of two char arrays

 if (strcmp(namet2, nameIt2) != 0)

How do I use installed packages in PyCharm?

Add path in PyCharm 2017

File -> Settings (or Ctrl+Alt+S) -> Project -> Project Interpreter

enter image description here Show all

enter image description here Select bottom icon on the right side

enter image description here Click on the plus button to add new path to your module

How to post data using HttpClient?

Try to use this:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}

Indenting code in Sublime text 2?

Select all code that you intend to indent, then hit Ctrl + ] in Sublime text to indent.

For macOS users, use command + ] to indent, and command + [ to un-indent.

Get startup type of Windows service using PowerShell

You can also use the sc tool to set it.

You can also call it from PowerShell and add additional checks if needed. The advantage of this tool vs. PowerShell is that the sc tool can also set the start type to auto delayed.

# Get Service status
$Service = "Wecsvc"
sc.exe qc $Service

# Set Service status
$Service = "Wecsvc"
sc.exe config $Service start= delayed-auto

CSS - display: none; not working

This is because the inline style display:block is overwriting your CSS. You'll need to either remove this inline style or use:

#tfl {
  display: none !important;
}

This overrides inline styles. Note that using !important is generally not recommended unless it's a last resort.

No Activity found to handle Intent : android.intent.action.VIEW

Url addresses must be preceded by http://

Uri uri = Uri.parse("www.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);

throws an ActivityNotFoundException. If you prepend "http://", problem solved.

Uri uri = Uri.parse("http://www.google.com");

SELECT from nothing?

I'm using firebird First of all, create a one column table named "NoTable" like this

CREATE TABLE NOTABLE 
(
  NOCOLUMN              INTEGER
);
INSERT INTO NOTABLE VALUES (0); -- You can put any value

now you can write this

select 'hello world' as name

from notable

you can add any column you want to be shown

How do I check if an index exists on a table field in MySQL?

you can use the following SQL statement to check the given column on table was indexed or not

select  a.table_schema, a.table_name, a.column_name, index_name
from    information_schema.columns a
join    information_schema.tables  b on a.table_schema  = b.table_schema and
                                    a.table_name = b.table_name and 
                                    b.table_type = 'BASE TABLE'
left join (
 select     concat(x.name, '/', y.name) full_path_schema, y.name index_name
 FROM   information_schema.INNODB_SYS_TABLES  as x
 JOIN   information_schema.INNODB_SYS_INDEXES as y on x.TABLE_ID = y.TABLE_ID
 WHERE  x.name = 'your_schema'
 and    y.name = 'your_column') d on concat(a.table_schema, '/', a.table_name, '/', a.column_name) = d.full_path_schema
where   a.table_schema = 'your_schema'
and     a.column_name  = 'your_column'
order by a.table_schema, a.table_name;

since the joins are against INNODB_SYS_*, so the match indexes only came from INNODB tables only

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

What is the difference between SessionState and ViewState?

SessionState

  • Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
  • Can be persisted in a Database, useful for Web Farms / Web Gardens.
  • Is Cleared when the session dies - usually after 20min of inactivity.

ViewState

  • Is sent back and forth between the server and client, taking up bandwidth.
  • Has no expiration date.
  • Is useful in a Web Farm / Web Garden

Replace all double quotes within String

I know the answer is already accepted here, but I just wanted to share what I found when I tried to escape double quotes and single quotes.

Here's what I have done: and this works :)

to escape double quotes:

    if(string.contains("\"")) {
        string = string.replaceAll("\"", "\\\\\"");
    }

and to escape single quotes:

    if(string.contains("\'")) {
        string = string.replaceAll("\'", "\\\\'");
    }

PS: Please note the number of backslashes used above.

How can I get an HTTP response body as a string?

Here are two examples from my working project.

  1. Using EntityUtils and HttpEntity

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    
  2. Using BasicResponseHandler

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler().handleResponse(response);
    System.out.println(responseString);
    

Notice: Trying to get property of non-object error

@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error

Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid'] instead of $objData->token

Multiple WHERE Clauses with LINQ extension methods

Just use the && operator like you would with any other statement that you need to do boolean logic.

if (useAdditionalClauses)
{
  results = results.Where(
                  o => o.OrderStatus == OrderStatus.Open 
                  && o.CustomerID == customerID)     
}

How to use environment variables in docker compose

Since 1.25.4, docker-compose supports the option --env-file that enables you to specify a file containing variables.

Yours should look like this:

hostname=my-host-name

And the command:

docker-compose --env-file /path/to/my-env-file config

How to change the default port of mysql from 3306 to 3360

Actually, you can just run the service using /mysqld --PORT 1234, it would force mysql to run on the specified port without change the cnf/ini file.

I just cought a case that cnf didn't work. It was weired... so I just use the cmd line as the shortcut and it works!

Adding POST parameters before submit

If you want to add parameters without modifying the form, you have to serialize the form, add your parameters and send it with AJAX:

var formData = $("#commentForm").serializeArray();
formData.push({name: "url", value: window.location.pathname});
formData.push({name: "time", value: new Date().getTime()});

$.post("api/comment", formData, function(data) {
  // request has finished, check for errors
  // and then for example redirect to another page
});

See .serializeArray() and $.post() documentation.

What size do you use for varchar(MAX) in your parameter declaration?

For those of us who did not see -1 by Michal Chaniewski, the complete line of code:

cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text";

How can I count text lines inside an DOM element? Can I?

One solution is to enclose every word in a span tag using script. Then if the Y dimension of a given span tag is less than that of it's immediate predecessor then a line break has occurred.

Eclipse - debugger doesn't stop at breakpoint

Fix could be as simple as clicking run/skip all breakpoints. Worked for me.

How to display length of filtered ng-repeat data

The easiest way if you have

<div ng-repeat="person in data | filter: query"></div>

Filtered data length

<div>{{ (data | filter: query).length }}</div>

android pinch zoom

For android 2.2+ (api level8), you can use ScaleGestureDetector.

you need a member:

private ScaleGestureDetector mScaleDetector;

in your constructor (or onCreate()) you add:

mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
    }
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
        return false;
    }
});

You override onTouchEvent:

@Override
public boolean onTouchEvent(MotionEvent event) {
    mScaleDetector.onTouchEvent(event);
    return true;
}

If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().

Precision String Format Specifier In Swift

I don't know about two decimal places, but here's how you can print floats with zero decimal places, so I'd imagine that can be 2 place, 3, places ... (Note: you must convert CGFloat to Double to pass to String(format:) or it will see a value of zero)

func logRect(r: CGRect, _ title: String = "") {
    println(String(format: "[ (%.0f, %.0f), (%.0f, %.0f) ] %@",
        Double(r.origin.x), Double(r.origin.y), Double(r.size.width), Double(r.size.height), title))
}

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Upload Image using POST form data in Python-requests

For Rest API to upload images from host to host:

import urllib2
import requests

api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'

img_file = urllib2.urlopen(image_url)

response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)

You can use option verify set to False to omit SSL verification for HTTPS requests.

case in sql stored procedure on SQL Server

Try this

If @NewStatus  = 'InOffice' 
BEGIN
     Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'OutOffice'
BEGIN
    Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'Home'
BEGIN
    Update tblEmployee set Home = -1 where EmpID = @EmpID
END

npm check and update package if needed

  • To update a single local package:

    1. First find out your outdated packages:

      npm outdated

    2. Then update the package or packages that you want manually as:

      npm update --save package_name

This way it is not necessary to update your local package.json file.

Note that this will update your package to the latest version.

  • If you write some version in your package.json file and do:

    npm update package_name

    In this case you will get just the next stable version (wanted) regarding the version that you wrote in your package.json file.

And with npm list (package_name) you can find out the current version of your local packages.

How to subtract hours from a date in Oracle so it affects the day also

Others have commented on the (incorrect) use of 2/11 to specify the desired interval.

I personally however prefer writing things like that using ANSI interval literals which makes reading the query much easier:

sysdate - interval '2' hour

It also has the advantage of being portable, many DBMS support this. Plus I don't have to fire up a calculator to find out how many hours the expression means - I'm pretty bad with mental arithmetics ;)

What's the difference between the 'ref' and 'out' keywords?

Out: A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function. Output parameters are like reference parameters, except that they transfer data out of the method rather than into it.

The following example illustrates this:

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void getValue(out int x )
      {
         int temp = 5;
         x = temp;
      }

      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* local variable definition */
         int a = 100;

         Console.WriteLine("Before method call, value of a : {0}", a);

         /* calling a function to get the value */
         n.getValue(out a);

         Console.WriteLine("After method call, value of a : {0}", a);
         Console.ReadLine();

      }
   }
}

ref: A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.

In C#, you declare the reference parameters using the ref keyword. The following example demonstrates this:

using System;
namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void swap(ref int x, ref int y)
      {
         int temp;

         temp = x; /* save the value of x */
         x = y;   /* put y into x */
         y = temp; /* put temp into y */
       }

      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* local variable definition */
         int a = 100;
         int b = 200;

         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);

         /* calling a function to swap the values */
         n.swap(ref a, ref b);

         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);

         Console.ReadLine();

      }
   }
}

Doctrine 2 ArrayCollection filter method

The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities

$idsToFilter = array(1,2,3,4);

$member->getComments()->filter(
    function($entry) use ($idsToFilter) {
       return in_array($entry->getId(), $idsToFilter);
    }
); 

Hashmap with Streams in Java 8 Streams to collect value of Map

If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst :

Optional<List> o = id1.entrySet()
                      .stream()
                      .filter( e -> e.getKey() == 1)
                      .map(Map.Entry::getValue)
                      .findFirst();

In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :

List<List> list = id1.entrySet()
                     .stream()
                     .filter(.. some predicate...)
                     .map(Map.Entry::getValue)
                     .collect(Collectors.toList());

Simple search MySQL database using php

I think its works for everyone

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search</title>
</head>

<body>
    <form action="" method="post">
        <input type="text" placeholder="Search" name="search">
        <button type="submit" name="submit">Search</button>
    </form>
</body>

</html>
<?php


if (isset($_POST['submit'])) {
    $searchValue = $_POST['search'];
    $con = new mysqli("localhost", "root", "", "testing");
    if ($con->connect_error) {
        echo "connection Failed: " . $con->connect_error;
    } else {
        $sql = "SELECT * FROM customer_info WHERE name OR email LIKE '%$searchValue%'";

        $result = $con->query($sql);
        while ($row = $result->fetch_assoc()) {
            echo $row['name'] . "<br>";
            echo $row['email'] . "<br>";
        }

      
    }   
}



?>

GROUP BY having MAX date

Another way that doesn't use group by:

SELECT * FROM tblpm n 
  WHERE date_updated=(SELECT date_updated FROM tblpm n 
                        ORDER BY date_updated desc LIMIT 1)

Regarding Java switch statements - using return and omitting breaks in each case

From human intelligence view your code is fine. From static code analysis tools view there are multiple returns, which makes it harder to debug. e.g you cannot set one and only breakpoint immediately before return.

Further you would not hard code the 4 slider steps in an professional app. Either calculate the values by using max - min, etc., or look them up in an array:

public static final double[] SLIDER_VALUES = {1.0, 0.9, 0.8, 0.7, 0.6};
public static final double SLIDER_DEFAULT = 1.0;


private double translateSlider(int sliderValue) {
  double result = SLIDER_DEFAULT;
  if (sliderValue >= 0 && sliderValue < SLIDER_VALUES.length) {
      ret = SLIDER_VALUES[sliderValue];
  }

  return result;
}

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:

JavaFX/OpenJFX 8 - Rich client application platform for Java

You can install it via:

sudo apt-get install openjfx

It provides the following JAR files to the OpenJDK installation on Ubuntu systems:

/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfxswt.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/ant-javafx.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/javafx-mx.jar

If you want to have sources available, for example for debugging, you can additionally install:

sudo apt-get install openjfx-source

Changing background color of selected item in recyclerview

What I did to achieve this was actually taking a static variable to store the last clicked position of the item in the RecyclerView and then notify the adapter to update the layout at the position on the last clicked position i.e. notifyItemChanged(lastClickedPosition) whenever a new position is clicked. Calling notifyDataSetChanged() on the whole layout is very costly and unfeasible so doing this for only one position is much better.

Here's the code for this:

public class RecyclerDataAdapter extends RecyclerView.Adapter<RecyclerDataAdapter.ViewHolder> {

private String android_versionnames[];
private Context mContext;
private static lastClickedPosition = -1; // Variable to store the last clicked item position


    public RecyclerDataAdapter(Context context,String android_versionnames[]){
        this.android_versionnames = android_versionnames;
        this.mContext = context;
        }
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.row_layout,
                parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.tv1.setText(android_versionnames[position]);    
        holder.itemView.setBackgroundColor(mContext.getResources().
        getColor(R.color.cardview_light_background));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                    
            v.setBackgroundColor(mContext.getResources().
            getColor(R.color.dark_background));
                if (lastClickedPosition != -1)
                    notifyItemChanged(lastClickedPosition);
                lastClickedPosition = position;
            }
        });
    }


    @Override
    public int getItemCount() {
        return android_versionnames.length;
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tv1;

        public ViewHolder(final View itemView) {
            super(itemView);
            tv1=(TextView)itemView.findViewById(R.id.txtView1);
        }
    }
}

So we will be actually updating only the intended item and not re-running unnecessary updates to the items which have not even been changed.

Escape Character in SQL Server

To escape ' you simly need to put another before: ''

As the second answer shows it's possible to escape single quote like this:

select 'it''s escaped'

result will be

it's escaped

If you're concatenating SQL into a VARCHAR to execute (i.e. dynamic SQL), then I'd recommend parameterising the SQL. This has the benefit of helping guard against SQL injection plus means you don't have to worry about escaping quotes like this (which you do by doubling up the quotes).

e.g. instead of doing

DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
EXECUTE(@SQL)

try this:

DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = @Field1'
EXECUTE sp_executesql @SQL, N'@Field1 VARCHAR(10)', 'AAA'

How do I display a text file content in CMD?

If you want it to display the content of the file live, and update when the file is altered, just use this script:

@echo off
:start
cls
type myfile.txt
goto start

That will repeat forever until you close the cmd window.

How to open .mov format video in HTML video Tag?

You can use Controls attribute

<video id="sampleMovie" src="HTML5Sample.mov" controls></video>

What's the difference between [ and [[ in Bash?

In bash, contrary to [, [[ prevents word splitting of variable values.

How do I install package.json dependencies in the current directory using npm

Running:

npm install

from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).

You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.

To prevent this, just create a symlink to the relocated node_modules from your app dir:

ln -s ../node_modules node_modules

Java equivalent to Explode and Implode(PHP)

if you are talking about in the reference of String Class. so you can use

subString/split

for Explode & use String

concate

for Implode.

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

How to hide only the Close (x) button?

If you really want to hide it, as in "not visible", then you will probably have to create a borderless form and draw the caption components yourself. VisualStyles library has the Windows Elements available. You would also have to add back in the functionality of re-sizing the form or moving the form by grabbing the caption bar. Not to mention the system menu in the corner.

In most cases, it's hard to justify having the "close" button not available, especially when you want a modal form with minimizing capabilities. Minimizing a modal form really makes no sense.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

If you (or a helpful admin) runs Set-ExecutionPolicy as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)

NB.: On a 64-bit OS you need to run Set-ExecutionPolicy for 32-bit and 64-bit PowerShell separately.

CSS @font-face not working in ie

I have found if the font face declarations are inside a media query IE (both edge and 11) won't load them; they need to be the first thing declared in the stylesheet and not wrapped in a media query

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

Get date from input form within PHP

    <?php
if (isset($_POST['birthdate'])) {
    $timestamp = strtotime($_POST['birthdate']); 
    $date=date('d',$timestamp);
    $month=date('m',$timestamp);
    $year=date('Y',$timestamp);
}
?>  

PostgreSQL IF statement

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM orders) THEN
      DELETE FROM orders;
   ELSE
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...

Or:

    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...

Alternative

The additional SELECT is not needed. This does the same, faster:

DO
$do$
BEGIN
   DELETE FROM orders;
   IF NOT FOUND THEN
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

jQuery: Change button text on click

its work short code

$('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
} else { $(this).text('See Less'); } });

How to call Stored Procedures with EntityFramework?

Once your stored procedure is imported in your model, you can right click in it (from the model browser, in the Context.Store/Stored Procedures section), and click Add Function Import. If you need a complex type as a result, you can create it right there.

Return value in a Bash function

Another way to achive this is name references (requires Bash 4.3+).

function example {
  local -n VAR=$1
  VAR=foo
}

example RESULT
echo $RESULT

Dealing with HTTP content in HTTPS pages

Sometimes like in facebook apps we can not have non-secure contents in secure page. also we can not make local those contents. for example an app which will load in iFrame is not a simple content and we can not make it local.

I think we should never load http contents in https, also we should not fallback https page to http version to prevent error dialog.

the only way which will ensure user's security is to use https version of all contents, http://web.archive.org/web/20120502131549/http://developers.facebook.com/blog/post/499/

How to execute an SSIS package from .NET?

So there is another way you can actually fire it from any language. The best way I think, you can just create a batch file which will call your .dtsx package.

Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.

Below is a blog for more details..

https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/

Happy coding.. :)

Thanks, Ayan

How do I programmatically click a link with javascript?

Many of the above methods have been deprecated. It is now recommended to use the constructor found here

function clickAnchorTag() {
    var event = document.createEvent('MouseEvent');
    event = new CustomEvent('click');
    var a = document.getElementById('nameOfID');
    a.dispatchEvent(event);
}

This will cause the anchor tag to be clicked, but it wont show if pop-up blockers are active so the user will need to allow pop-ups.

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Maybe Eclipse WTP plugin has been accidently removed. Have you tried re-installing WTP using this location ? If I were you I would have reinstall Eclipse from strach or even better try Spring ToolSuite which integrates with Google Plugin for Eclipse seamlessly (usign Extenstions tab on STS Dashboard)

How do I test axios in Jest?

I've done this with nock, like so:

import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'

axios.defaults.adapter = httpAdapter

describe('foo', () => {
    it('bar', () => {
        nock('https://example.com:443')
            .get('/example')
            .reply(200, 'some payload')

        // test...
    })
})

Date / Timestamp to record when a record was added to the table?

You can pass GetDate() function as an parameter to your insert query e.g

Insert into table (col1,CreatedOn) values (value1,Getdate())

Maven Could not resolve dependencies, artifacts could not be resolved

My EAR project had 2 modules *.ear and *.war and I got this dependency error on *.war project when trying mvn eclipse:eclipse. Resolved it by fixing utf-8 encoding issue in the *.war project. mvn -X or -e options weren't of help here.

Print in one line dynamically

for Python 2.7

for x in range(0, 3):
    print x,

for Python 3

for x in range(0, 3):
    print(x, end=" ")

How to change the background color of the options menu?

protected void setMenuBackground() {
    getLayoutInflater().setFactory(new Factory() {
        @Override
        public View onCreateView (String name, Context context, AttributeSet attrs) {
            if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
                try {
                    // Ask our inflater to create the view
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView(name, null, attrs);
                    // Kind of apply our own background
                    new Handler().post( new Runnable() {
                        public void run () {
                            view.setBackgroundResource(R.drawable.gray_gradient_background);
                        }
                    });
                    return view;
                }
                catch (InflateException e) {
                }
                catch (ClassNotFoundException e) {
                }
            }
            return null;
        }
    });
}

this is XML file

gradient 
    android:startColor="#AFAFAF" 
    android:endColor="#000000"
    android:angle="270"
shape

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

MySQL Query - Records between Today and Last 30 Days

You need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

Also note that CURDATE() returns only the DATE portion of the date, so if you store create_date as a DATETIME with the time portion filled, this query will not select the today's records.

In this case, you'll need to use NOW instead:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

Unresolved external symbol in object files

sometimes if a new header file is added, and this error starts coming due to that, you need to add library as well to get rid of unresolved external symbol.

for example:

#include WtsApi32.h

will need:

#pragma comment(lib, "Wtsapi32.lib") 

How to skip to next iteration in jQuery.each() util?

The loop only breaks if you return literally false. Ex:

// this is how jquery calls your function
// notice hard comparison (===) against false
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
   break;
}

This means you can return anything else, including undefined, which is what you return if you return nothing, so you can simply use an empty return statement:

$.each(collection, function (index, item) {
   if (!someTestCondition)
      return; // go to next iteration

   // otherwise do something
});

It's possible this might vary by version; this is applicable for jquery 1.12.4. But really, when you exit out the bottom of the function, you are also returning nothing, and that's why the loop continues, so I would expect that there is no possibility whatsoever that returning nothing could not continue the loop. Unless they want to force everyone to start returning something to keep the loop going, returning nothing has to be a way to keep it going.

How to check internet access on Android? InetAddress never times out

Following is the code from my Utils class:

public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

How do I check in JavaScript if a value exists at a certain array index?

To check if it has never been defined or if it was deleted:

if(typeof arrayName[index]==="undefined"){
     //the index is not in the array
}

also works with associative arrays and arrays where you deleted some index

To check if it was never been defined, was deleted OR is a null or logical empty value (NaN, empty string, false):

if(typeof arrayName[index]==="undefined"||arrayName[index]){
     //the index is not defined or the value an empty value
}

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

fatal: 'origin' does not appear to be a git repository

$HOME/.gitconfig is your global config for git.
There are three levels of config files.

 cat $(git rev-parse --show-toplevel)/.git/config

(mentioned by bereal) is your local config, local to the repo you have cloned.

you can also type from within your repo:

git remote -v

And see if there is any remote named 'origin' listed in it.

If not, if that remote (which is created by default when cloning a repo) is missing, you can add it again:

git remote add origin url/to/your/fork

The OP mentions:

Doing git remote -v gives:

upstream git://git.moodle.org/moodle.git (fetch) 
upstream git://git.moodle.org/moodle.git (push)

So 'origin' is missing: the reference to your fork.
See "What is the difference between origin and upstream in github"

enter image description here