Programs & Examples On #Texttt

How to limit text width

Try

<div style="max-width:200px; word-wrap:break-word;">Texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt</div>

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

How do I check if an array includes a value in JavaScript?

A hopefully faster bidirectional indexOf / lastIndexOf alternative

2015

While the new method includes is very nice, the support is basically zero for now.

It's long time that I was thinking of way to replace the slow indexOf/lastIndexOf functions.

A performant way has already been found, looking at the top answers. From those I chose the contains function posted by @Damir Zekic which should be the fastest one. But it also states that the benchmarks are from 2008 and so are outdated.

I also prefer while over for, but for not a specific reason I ended writing the function with a for loop. It could be also done with a while --.

I was curious if the iteration was much slower if I check both sides of the array while doing it. Apparently no, and so this function is around two times faster than the top voted ones. Obviously it's also faster than the native one. This in a real world environment, where you never know if the value you are searching is at the beginning or at the end of the array.

When you know you just pushed an array with a value, using lastIndexOf remains probably the best solution, but if you have to travel through big arrays and the result could be everywhere, this could be a solid solution to make things faster.

Bidirectional indexOf/lastIndexOf

function bidirectionalIndexOf(a, b, c, d, e){
  for(c=a.length,d=c*1; c--; ){
    if(a[c]==b) return c; //or this[c]===b
    if(a[e=d-1-c]==b) return e; //or a[e=d-1-c]===b
  }
  return -1
}

//Usage
bidirectionalIndexOf(array,'value');

Performance test

http://jsperf.com/bidirectionalindexof

As test I created an array with 100k entries.

Three queries: at the beginning, in the middle & at the end of the array.

I hope you also find this interesting and test the performance.

Note: As you can see I slightly modified the contains function to reflect the indexOf & lastIndexOf output (so basically true with the index and false with -1). That shouldn't harm it.

The array prototype variant

Object.defineProperty(Array.prototype,'bidirectionalIndexOf',{value:function(b,c,d,e){
  for(c=this.length,d=c*1; c--; ){
    if(this[c]==b) return c; //or this[c]===b
    if(this[e=d-1-c] == b) return e; //or this[e=d-1-c]===b
  }
  return -1
},writable:false, enumerable:false});

// Usage
array.bidirectionalIndexOf('value');

The function can also be easily modified to return true or false or even the object, string or whatever it is.

And here is the while variant:

function bidirectionalIndexOf(a, b, c, d){
  c=a.length; d=c-1;
  while(c--){
    if(b===a[c]) return c;
    if(b===a[d-c]) return d-c;
  }
  return c
}

// Usage
bidirectionalIndexOf(array,'value');

How is this possible?

I think that the simple calculation to get the reflected index in an array is so simple that it's two times faster than doing an actual loop iteration.

Here is a complex example doing three checks per iteration, but this is only possible with a longer calculation which causes the slowdown of the code.

http://jsperf.com/bidirectionalindexof/2

What is considered a good response time for a dynamic, personalized web application?

There's a great deal of research on this. Here's a quick summary.

Response Times: The 3 Important Limits

by Jakob Nielsen on January 1, 1993

Summary: There are 3 main time limits (which are determined by human perceptual abilities) to keep in mind when optimizing web and application performance.

Excerpt from Chapter 5 in my book Usability Engineering, from 1993:

The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]:

  • 0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.
  • 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
  • 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

Locate the nginx.conf file my nginx is actually using

which nginx

will give you the path of the nginx being used


EDIT (2017-Jan-18)

Thanks to Will Palmer's comment on this answer, I have added the following...

If you've installed nginx via a package manager such as HomeBrew...

which nginx

may not give you the EXACT path to the nginx being used. You can however find it using

realpath $(which nginx)

and as mentioned by @Daniel Li

you can get configuration of nginx via his method

alternatively you can use this:

nginx -V

Deploy a project using Git push

git config --local receive.denyCurrentBranch updateInstead

Added in Git 2.3, this could be a good possibility: https://github.com/git/git/blob/v2.3.0/Documentation/config.txt#L2155

You set it on the server repository, and it also updates the working tree if it is clean.

There have been further improvements in 2.4 with the push-to-checkout hook and handling of unborn branches.

Sample usage:

git init server
cd server
touch a
git add .
git commit -m 0
git config --local receive.denyCurrentBranch updateInstead

cd ..
git clone server local
cd local
touch b
git add .
git commit -m 1
git push origin master:master

cd ../server
ls

Output:

a
b

This does have the following shortcomings mentioned on the GitHub announcement:

  • Your server will contain a .git directory containing the entire history of your project. You probably want to make extra sure that it cannot be served to users!
  • During deploys, it will be possible for users momentarily to encounter the site in an inconsistent state, with some files at the old version and others at the new version, or even half-written files. If this is a problem for your project, push-to-deploy is probably not for you.
  • If your project needs a "build" step, then you will have to set that up explicitly, perhaps via githooks.

But all of those points are out of the scope of Git and must be taken care of by external code. So in that sense, this, together with Git hooks, are the ultimate solution.

2D Euclidean vector rotations

Sounds easier to do with the standard classes:

std::complex<double> vecA(0,1);
std::complex<double> i(0,1); // 90 degrees
std::complex<double> r45(sqrt(2.0),sqrt(2.0));
vecA *= i;
vecA *= r45;

Vector rotation is a subset of complex multiplication. To rotate over an angle alpha, you multiply by std::complex<double> { cos(alpha), sin(alpha) }

How do I create batch file to rename large number of files in a folder?

You don't need a batch file, just do this from powershell :

powershell -C "gci | % {rni $_.Name ($_.Name -replace 'Vacation2010', 'December')}"

Is there a need for range(len(a))?

What if you need to access two elements of the list simultaneously?

for i in range(len(a[0:-1])):
    something_new[i] = a[i] * a[i+1]

You can use this, but it's probably less clear:

for i, _ in enumerate(a[0:-1]):
     something_new[i] = a[i] * a[i+1]

Personally I'm not 100% happy with either!

Benefits of EBS vs. instance-store (and vice-versa)

We like instance-store. It forces us to make our instances completely recyclable, and we can easily automate the process of building a server from scratch on a given AMI. This also means we can easily swap out AMIs. Also, EBS still has performance problems from time to time.

Does Java SE 8 have Pairs or Tuples?

Yes.

Map.Entry can be used as a Pair.

Unfortunately it does not help with Java 8 streams as the problem is that even though lambdas can take multiple arguments, the Java language only allows for returning a single value (object or primitive type). This implies that whenever you have a stream you end up with being passed a single object from the previous operation. This is a lack in the Java language, because if multiple return values was supported AND streams supported them we could have much nicer non-trivial tasks done by streams.

Until then, there is only little use.

EDIT 2018-02-12: While working on a project I wrote a helper class which helps handling the special case of having an identifier earlier in the stream you need at a later time but the stream part in between does not know about it. Until I get around to release it on its own it is available at IdValue.java with a unit test at IdValueTest.java

php static function

Simply, static functions function independently of the class where they belong.

$this means, this is an object of this class. It does not apply to static functions.

class test {
    public function sayHi($hi = "Hi") {
        $this->hi = $hi;
        return $this->hi;
    }
}
class test1 {
    public static function sayHi($hi) {
        $hi = "Hi";
        return $hi;
    }
}

//  Test
$mytest = new test();
print $mytest->sayHi('hello');  // returns 'hello'
print test1::sayHi('hello');    //  returns 'Hi'

NSDate get year/month/day

New In iOS 8

ObjC

NSDate *date = [NSDate date];
NSInteger era, year, month, day;
[[NSCalendar currentCalendar] getEra:&era year:&year month:&month day:&day fromDate:date];

Swift

let date = NSDate.init()
var era = 0, year = 0, month = 0, day = 0
NSCalendar.currentCalendar().getEra(&era, year:&year, month:&month, day:&day, fromDate: date)

Adding multiple columns AFTER a specific column in MySQL

ALTER TABLE listing ADD count INT(5), ADD log VARCHAR(200), ADD status VARCHAR(20) AFTER stat

It will give good results.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

Javascript: Call a function after specific time period

You can use JavaScript Timing Events to call function after certain interval of time:

This shows the alert box after 3 seconds:

setInterval(function(){alert("Hello")},3000);

You can use two method of time event in javascript.i.e.

  1. setInterval(): executes a function, over and over again, at specified time intervals
  2. setTimeout() : executes a function, once, after waiting a specified number of milliseconds

How to connect to a remote Windows machine to execute commands using python?

is it too late?

I personally agree with Beatrice Len, I used paramiko maybe is an extra step for windows, but I have an example project git hub, feel free to clone or ask me.

https://github.com/davcastroruiz/django-ssh-monitor

Wrap long lines in Python

You can use the fact that Python concatenates string literals which appear adjacent to each other:

>>> def fun():
...     print '{0} Here is a really long ' \
...           'sentence with {1}'.format(3, 5)

Simple PowerShell LastWriteTime compare

I have an example I would like to share

$File = "C:\Foo.txt"
#retrieves the Systems current Date and Time in a DateTime Format
$today = Get-Date
#subtracts 12 hours from the date to ensure the file has been written to recently
$today = $today.AddHours(-12)
#gets the last time the $file was written in a DateTime Format
$lastWriteTime = (Get-Item $File).LastWriteTime

#If $File doesn't exist we will loop indefinetely until it does exist.
# also loops until the $File that exists was written to in the last twelve hours
while((!(Test-Path $File)) -or ($lastWriteTime -lt $today))
{
    #if a file exists then the write time is wrong so update it
    if (Test-Path $File)
    {
        $lastWriteTime = (Get-Item $File).LastWriteTime
    }
    #Sleep for 5 minutes
    $time = Get-Date
    Write-Host "Sleep" $time
    Start-Sleep -s 300;
}

Operation is not valid due to the current state of the object, when I select a dropdown list

I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.

Open another page in php

<?php
    header("Location: index.html");
?>

Just make sure nothing is actually written to the page prior to this code, or it won't work.

Best way to store chat messages in a database?

If you can avoid the need for concurrent writes to a single file, it sounds like you do not need a database to store the chat messages.

Just append the conversation to a text file (1 file per user\conversation). and have a directory/ file structure

Here's a simplified view of the file structure:

chat-1-bob.txt
        201101011029, hi
        201101011030, fine thanks.

chat-1-jen.txt
        201101011030, how are you?
        201101011035, have you spoken to bill recently?

chat-2-bob.txt
        201101021200, hi
        201101021222, about 12:22
chat-2-bill.txt
        201101021201, Hey Bob,
        201101021203, what time do you call this?

You would then only need to store the userid, conversation id (guid ?) & a reference to the file name.

I think you will find it hard to get a more simple scaleable solution.

You can use LOAD_FILE to get the data too see: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

If you have a requirement to rebuild a conversation you will need to put a value (date time) alongside your sent chat message (in the file) to allow you to merge & sort the files, but at this point it is probably a good idea to consider using a database.

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

I was able to do this with the following classes in my project

d-flex justify-content-end

<div class="col-lg-6 d-flex justify-content-end">

Can you use if/else conditions in CSS?

I am surprised that nobody has mentioned CSS pseudo-classes, which are also a sort-of conditionals in CSS. You can do some pretty advanced things with this, without a single line of JavaScript.

Some pseudo-classes:

  • :active - Is the element being clicked?
  • :checked - Is the radio/checkbox/option checked? (This allows for conditional styling through the use of a checkbox!)
  • :empty - Is the element empty?
  • :fullscreen - Is the document in full-screen mode?
  • :focus - Does the element have keyboard focus?
  • :focus-within - Does the element, or any of its children, have keyboard focus?
  • :has([selector]) - Does the element contain a child that matches [selector]? (Sadly, not supported by any of the major browsers.)
  • :hover - Does the mouse hover over this element?
  • :in-range/:out-of-range - Is the input value between/outside min and max limits?
  • :invalid/:valid - Does the form element have invalid/valid contents?
  • :link - Is this an unvisited link?
  • :not() - Invert the selector.
  • :target - Is this element the target of the URL fragment?
  • :visited - Has the user visited this link before?

Example:

_x000D_
_x000D_
div { color: white; background: red }_x000D_
input:checked + div { background: green }
_x000D_
<input type=checkbox>Click me!_x000D_
<div>Red or green?</div>
_x000D_
_x000D_
_x000D_

ASP.NET IIS Web.config [Internal Server Error]

If you have python, you can use a package called iis_bridge that solves the problem. To install:

pip install iis_bridge

then in the python console:

import iis_bridge as iis
iis.install()

How to Publish Web with msbuild?

You can Publish the Solution with desired path by below code, Here PublishInDFolder is the name that has the path where we need to publish(we need to create this in below pic)

You can create publish file like this

Add below 2 lines of code in batch file(.bat)

@echo OFF 
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsMSBuildCmd.bat"
MSBuild.exe  D:\\Solution\\DataLink.sln /p:DeployOnBuild=true /p:PublishProfile=PublishInDFolder
pause

Google maps API V3 - multiple markers on exact same spot

Check out Marker Clusterer for V3 - this library clusters nearby points into a group marker. The map zooms in when the clusters are clicked. I'd imagine when zoomed right in you'd still have the same problem with markers on the same spot though.

Simple (non-secure) hash function for JavaScript?

// Simple but unreliable function to create string hash by Sergey.Shuchkin [t] gmail.com
// alert( strhash('http://www.w3schools.com/js/default.asp') ); // 6mn6tf7st333r2q4o134o58888888888
function strhash( str ) {
    if (str.length % 32 > 0) str += Array(33 - str.length % 32).join("z");
    var hash = '', bytes = [], i = j = k = a = 0, dict = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','1','2','3','4','5','6','7','8','9'];
    for (i = 0; i < str.length; i++ ) {
        ch = str.charCodeAt(i);
        bytes[j++] = (ch < 127) ? ch & 0xFF : 127;
    }
    var chunk_len = Math.ceil(bytes.length / 32);   
    for (i=0; i<bytes.length; i++) {
        j += bytes[i];
        k++;
        if ((k == chunk_len) || (i == bytes.length-1)) {
            a = Math.floor( j / k );
            if (a < 32)
                hash += '0';
            else if (a > 126)
                hash += 'z';
            else
                hash += dict[  Math.floor( (a-32) / 2.76) ];
            j = k = 0;
        }
    }
    return hash;
}

Access key value from Web.config in Razor View-MVC3 ASP.NET

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

How to parse SOAP XML?

One of the simplest ways to handle namespace prefixes is simply to strip them from the XML response before passing it through to simplexml such as below:

$your_xml_response = '<Your XML here>';
$clean_xml = str_ireplace(['SOAP-ENV:', 'SOAP:'], '', $your_xml_response);
$xml = simplexml_load_string($clean_xml);

This would return the following:

SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
            [PaymentNotification] => SimpleXMLElement Object
                (
                    [payment] => SimpleXMLElement Object
                        (
                            [uniqueReference] => ESDEUR11039872
                            [epacsReference] => 74348dc0-cbf0-df11-b725-001ec9e61285
                            [postingDate] => 2010-11-15T15:19:45
                            [bankCurrency] => EUR
                            [bankAmount] => 1.00
                            [appliedCurrency] => EUR
                            [appliedAmount] => 1.00
                            [countryCode] => ES
                            [bankInformation] => Sean Wood
                            [merchantReference] => ESDEUR11039872
                        )

                )

        )

)

Black transparent overlay on image hover with only CSS?

I'd suggest using a pseudo element in place of the overlay element. Because pseudo elements can't be added on enclosed img elements, you would still need to wrap the img element though.

LIVE EXAMPLE HERE -- EXAMPLE WITH TEXT

<div class="image">
    <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>

As for the CSS, set optional dimensions on the .image element, and relatively position it. If you are aiming for a responsive image, just omit the dimensions and this will still work (example). It's just worth noting that the dimensions must be on the parent element as opposed to the img element itself, see.

.image {
    position: relative;
    width: 400px;
    height: 400px;
}

Give the child img element a width of 100% of the parent and add vertical-align:top to fix the default baseline alignment issues.

.image img {
    width: 100%;
    vertical-align: top;
}

As for the pseudo element, set a content value and absolutely position it relative to the .image element. A width/height of 100% will ensure that this works with varying img dimensions. If you want to transition the element, set an opacity of 0 and add the transition properties/values.

.image:after {
    content: '\A';
    position: absolute;
    width: 100%; height:100%;
    top:0; left:0;
    background:rgba(0,0,0,0.6);
    opacity: 0;
    transition: all 1s;
    -webkit-transition: all 1s;
}

Use an opacity of 1 when hovering over the pseudo element in order to facilitate the transition:

.image:hover:after {
    opacity: 1;
}

END RESULT HERE


If you want to add text on hover:

For the simplest approach, just add the text as the pseudo element's content value:

EXAMPLE HERE

.image:after {
    content: 'Here is some text..';
    color: #fff;

    /* Other styling.. */
}

That should work in most instances; however, if you have more than one img element, you might not want the same text to appear on hover. You could therefore set the text in a data-* attribute and therefore have unique text for every img element.

EXAMPLE HERE

.image:after {
    content: attr(data-content);
    color: #fff;
}

With a content value of attr(data-content), the pseudo element adds the text from the .image element's data-content attribute:

<div data-content="Text added on hover" class="image">
    <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>

You can add some styling and do something like this:

EXAMPLE HERE

In the above example, the :after pseudo element serves as the black overlay, while the :before pseudo element is the caption/text. Since the elements are independent of each other, you can use separate styling for more optimal positioning.

.image:after, .image:before {
    position: absolute;
    opacity: 0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.image:after {
    content: '\A';
    width: 100%; height:100%;
    top: 0; left:0;
    background:rgba(0,0,0,0.6);
}
.image:before {
    content: attr(data-content);
    width: 100%;
    color: #fff;
    z-index: 1;
    bottom: 0;
    padding: 4px 10px;
    text-align: center;
    background: #f00;
    box-sizing: border-box;
    -moz-box-sizing:border-box;
}
.image:hover:after, .image:hover:before {
    opacity: 1;
}

Using CSS :before and :after pseudo-elements with inline CSS?

You can use the data in inline

 <style>   
 td { text-align: justify; }
 td:after { content: attr(data-content); display: inline-block; width: 100%; }
</style>

<table><tr><td data-content="post"></td></tr></table>

How to create unit tests easily in eclipse

To create a test case template:

"New" -> "JUnit Test Case" -> Select "Class under test" -> Select "Available methods". I think the wizard is quite easy for you.

Remove padding or margins from Google Charts

It's missing in the docs (I'm using version 43), but you can actually use the right and bottom property of the chart area:

var options = {
  chartArea:{
    left:10,
    right:10, // !!! works !!!
    bottom:20,  // !!! works !!!
    top:20,
    width:"100%",
    height:"100%"
  }
};

So it's possible to use full responsive width & height and prevent any axis labels or legends from being cropped.

Sum a list of numbers in Python

You can also do the same using recursion:

Python Snippet:

def sumOfArray(arr, startIndex):
    size = len(arr)
    if size == startIndex:  # To Check empty list
        return 0
    elif startIndex == (size - 1): # To Check Last Value
        return arr[startIndex]
    else:
        return arr[startIndex] + sumOfArray(arr, startIndex + 1)


print(sumOfArray([1,2,3,4,5], 0))

Is it possible to get only the first character of a String?

Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.

              String mob=edit_mobile.getText().toString();
                    if (mob.length() >= 10) {
                        if (mob.contains("+91")) {
                            mob= mob.substring(3, 13);
                        }
                        if (mob.substring(0, 1).contains("0")) {
                            mob= mob.substring(1, 11);
                        }
                        if (mob.contains("+")) {
                            mob= mob.replace("+", "");
                        }
                        mob= mob.substring(0, 10);
                        Log.i("mob", mob);

                    }

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase)

Strings and character with printf

%c

is designed for a single character a char, so it print only one element.Passing the char array as a pointer you are passing the address of the first element of the array(that is a single char) and then will be printed :

s

printf("%c\n",*name++);

will print

i

and so on ...

Pointer is not needed for the %s because it can work directly with String of characters.

JavaScript seconds to time string with format hh:mm:ss

Here is my vision of solution. You can try my snippet below.

_x000D_
_x000D_
function secToHHMM(sec) {_x000D_
  var d = new Date();_x000D_
  d.setHours(0);_x000D_
  d.setMinutes(0);_x000D_
  d.setSeconds(0);_x000D_
  d = new Date(d.getTime() + sec*1000);_x000D_
  return d.toLocaleString('en-GB').split(' ')[1];_x000D_
};_x000D_
_x000D_
alert( 'One hour: ' + secToHHMM(60*60) ); // '01:00:00'_x000D_
alert( 'One hour five minutes: ' + secToHHMM(60*60 + 5*60) ); // '01:05:00'_x000D_
alert( 'One hour five minutes 23 seconds: ' + secToHHMM(60*60 + 5*60 + 23) ); // '01:05:23'
_x000D_
_x000D_
_x000D_

How do I cancel an HTTP fetch() request?

TL/DR:

fetch now supports a signal parameter as of 20 September 2017, but not all browsers seem support this at the moment.

2020 UPDATE: Most major browsers (Edge, Firefox, Chrome, Safari, Opera, and a few others) support the feature, which has become part of the DOM living standard. (as of 5 March 2020)

This is a change we will be seeing very soon though, and so you should be able to cancel a request by using an AbortControllers AbortSignal.

Long Version

How to:

The way it works is this:

Step 1: You create an AbortController (For now I just used this)

const controller = new AbortController()

Step 2: You get the AbortControllers signal like this:

const signal = controller.signal

Step 3: You pass the signal to fetch like so:

fetch(urlToFetch, {
    method: 'get',
    signal: signal, // <------ This is our AbortSignal
})

Step 4: Just abort whenever you need to:

controller.abort();

Here's an example of how it would work (works on Firefox 57+):

_x000D_
_x000D_
<script>_x000D_
    // Create an instance._x000D_
    const controller = new AbortController()_x000D_
    const signal = controller.signal_x000D_
_x000D_
    /*_x000D_
    // Register a listenr._x000D_
    signal.addEventListener("abort", () => {_x000D_
        console.log("aborted!")_x000D_
    })_x000D_
    */_x000D_
_x000D_
_x000D_
    function beginFetching() {_x000D_
        console.log('Now fetching');_x000D_
        var urlToFetch = "https://httpbin.org/delay/3";_x000D_
_x000D_
        fetch(urlToFetch, {_x000D_
                method: 'get',_x000D_
                signal: signal,_x000D_
            })_x000D_
            .then(function(response) {_x000D_
                console.log(`Fetch complete. (Not aborted)`);_x000D_
            }).catch(function(err) {_x000D_
                console.error(` Err: ${err}`);_x000D_
            });_x000D_
    }_x000D_
_x000D_
_x000D_
    function abortFetching() {_x000D_
        console.log('Now aborting');_x000D_
        // Abort._x000D_
        controller.abort()_x000D_
    }_x000D_
_x000D_
</script>_x000D_
_x000D_
_x000D_
_x000D_
<h1>Example of fetch abort</h1>_x000D_
<hr>_x000D_
<button onclick="beginFetching();">_x000D_
    Begin_x000D_
</button>_x000D_
<button onclick="abortFetching();">_x000D_
    Abort_x000D_
</button>
_x000D_
_x000D_
_x000D_

Sources:

Converting from a string to boolean in Python?

you could always do something like

myString = "false"
val = (myString == "true")

the bit in parens would evaluate to False. This is just another way to do it without having to do an actual function call.

Visual Studio Code how to resolve merge conflicts with git?

  1. Click "Source Control" button on left.
  2. See MERGE CHANGES in sidebar.
  3. Those files have merge conflicts.

VS Code > Source Control > Merge Changes (Example)

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

How do I add Git version control (Bitbucket) to an existing source code folder?

User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:

  1. Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:

    Create repository on Bitbucket

  2. Fill in the form, click next and then you automatically go to this page:

    Create repository from scratch or add existing files

  3. Choose to add existing files and you go to this page:

    Enter image description here

  4. You use those commands and you upload the existing files to Bitbucket. After that, the files are online.

SmartGit Installation and Usage on Ubuntu

Seems a bit too late, but there is a PPA repository with SmartGit, enjoy! =)

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

What you're looking at is called a Ternary Operator, and you can find the PHP implementation here. It's an if else statement.

if (isset($_GET['something']) == true) {
    thing = isset($_GET['something']);
} else {
    thing = "";
}

How to count occurrences of a column value efficiently in SQL?

Here's another solution. this one uses very simple syntax. The first example of the accepted solution did not work on older versions of Microsoft SQL (i.e 2000)

SELECT age, count(*)
FROM Students 
GROUP by age
ORDER BY age

How to install a plugin in Jenkins manually

Yes, you can. Download the plugin (*.hpi file) and put it in the following directory:

<jenkinsHome>/plugins/

Afterwards you will need to restart Jenkins.

android asynctask sending callbacks to ui

I will repeat what the others said, but will just try to make it simpler...

First, just create the Interface class

public interface PostTaskListener<K> {
    // K is the type of the result object of the async task 
    void onPostTask(K result);
}

Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.

public static class LoadData extends AsyncTask<Void, Void, String> {

    private PostTaskListener<String> postTaskListener;

    protected LoadData(PostTaskListener<String> postTaskListener){
        this.postTaskListener = postTaskListener;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null && postTaskListener != null)
            postTaskListener.onPostTask(result);
    }
}

Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:

...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
    @Override
    public void onPostTask(String result) {
        //Your post execution task code
    }
}

// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);

Done!

Calling a particular PHP function on form submit

you don't need this code

<?php
function display()
{
echo "hello".$_POST["studentname"];
}
?>

Instead, you can check whether the form is submitted by checking the post variables using isset.

here goes the code

if(isset($_POST)){
echo "hello ".$_POST['studentname'];
}

click here for the php manual for isset

How to set a single, main title above all the subplots with Pyplot?

Use pyplot.suptitle or Figure.suptitle:

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
    ax=fig.add_subplot(2,2,i)        
    ax.imshow(data)

fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()

enter image description here

How do I represent a time only value in .NET?

As others have said, you can use a DateTime and ignore the date, or use a TimeSpan. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use the LocalTime type to represent a time of day.

One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...

(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)

How to search in an array with preg_match?

You can use array_walk to apply your preg_match function to each element of the array.

http://us3.php.net/array_walk

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

How can I control the width of a label tag?

Using CSS, of course...

label { display: block; width: 100px; }

The width attribute is deprecated, and CSS should always be used to control these kinds of presentational styles.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound  
FROM sys.sql_modules  
WHERE object_id = OBJECT_ID('your View Name');  

Calculate number of hours between 2 dates in PHP

your answer is:

round((strtotime($day2) - strtotime($day1))/(60*60))

Equals(=) vs. LIKE

This is a copy/paste of another answer of mine for question SQL 'like' vs '=' performance:

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='12345678'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

Disable Chrome strict MIME type checking

In my case, I turned off X-Content-Type-Options on nginx then works fine. But make sure this declines your security level a little. Would be a temporally fix.

# Not work
add_header X-Content-Type-Options nosniff;
# OK (comment out)
#add_header X-Content-Type-Options nosniff;

It'll be the same for apache.

<IfModule mod_headers.c>
  #Header set X-Content-Type-Options nosniff
</IfModule>

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Maybe this can help:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: basic-auth-server.herokuapp.com
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
paths:
  /:
    get:
      security:
        - Bearer: []
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

You can copy&paste it out here: http://editor.swagger.io/#/ to check out the results.

There are also several examples in the swagger editor web with more complex security configurations which could help you.

How to plot multiple functions on the same figure, in Matplotlib?

Just use the function plot as follows

figure()
...
plot(t, a)
plot(t, b)
plot(t, c)

Implementing a Custom Error page on an ASP.Net website

<customErrors defaultRedirect="~/404.aspx" mode="On">
    <error statusCode="404" redirect="~/404.aspx"/>
</customErrors>

Code above is only for "Page Not Found Error-404" if file extension is known(.html,.aspx etc)

Beside it you also have set Customer Errors for extension not known or not correct as

.aspwx or .vivaldo. You have to add httperrors settings in web.config

<httpErrors  errorMode="Custom"> 
       <error statusCode="404" prefixLanguageFilePath="" path="/404.aspx"         responseMode="Redirect" />
</httpErrors>
<modules runAllManagedModulesForAllRequests="true"/>

it must be inside the <system.webServer> </system.webServer>

Best way to find the intersection of multiple sets?

I believe the simplest thing to do is:

#assuming three sets
set1 = {1,2,3,4,5}
set2 = {2,3,8,9}
set3 = {2,10,11,12}

#intersection
set4 = set1 & set2 & set3

set4 will be the intersection of set1 , set2, set3 and will contain the value 2.

print(set4)

set([2])

How can I print out all possible letter combinations a given phone number can represent?

Here is one for pain C. This one is likley not efficet (in fact I don't think it is at all). But there are some intresting aspects to it.

  1. It take a number and converts it into a string
  2. It just raises the seed number once each time to create the next sequential string

Whats nice about this is that there is no real limit to the size of the string (no character limit) This allows you to generate longer and longer strings if need be just by waiting.

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

#define CHARACTER_RANGE 95  //  The range of valid password characters
#define CHARACTER_OFFSET 32 //  The offset of the first valid character

void main(int argc, char *argv[], char *env[])
{
    int i;

    long int string;
    long int worker;
    char *guess;    //  Current Generation
    guess = (char*)malloc(1);   //  Allocate it so free doesn't fail

    int cur;

    for ( string = 0; ; string++ )
    {
        worker = string;

        free(guess);
        guess = (char*)malloc((string/CHARACTER_RANGE+1)*sizeof(char)); //  Alocate for the number of characters we will need

        for ( i = 0; worker > 0 && i < string/CHARACTER_RANGE + 1; i++ )    //  Work out the string
        {
            cur = worker % CHARACTER_RANGE; //  Take off the last digit
            worker = (worker - cur) / CHARACTER_RANGE;  //  Advance the digits
            cur += CHARACTER_OFFSET;

            guess[i] = cur;
        }
        guess[i+1] = '\0';  //  NULL terminate our string

        printf("%s\t%d\n", guess, string);
    }
}

how to create a login page when username and password is equal in html

Doing password checks on client side is unsafe especially when the password is hard coded.

The safest way is password checking on server side, but even then the password should not be transmitted plain text.

Checking the password client side is possible in a "secure way":

  • The password needs to be hashed
  • The hashed password is used as part of a new url

Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).

python: Change the scripts working directory to the script's own directory

Don't do this.

Your scripts and your data should not be mashed into one big directory. Put your code in some known location (site-packages or /var/opt/udi or something) separate from your data. Use good version control on your code to be sure that you have current and previous versions separated from each other so you can fall back to previous versions and test future versions.

Bottom line: Do not mingle code and data.

Data is precious. Code comes and goes.

Provide the working directory as a command-line argument value. You can provide a default as an environment variable. Don't deduce it (or guess at it)

Make it a required argument value and do this.

import sys
import os
working= os.environ.get("WORKING_DIRECTORY","/some/default")
if len(sys.argv) > 1: working = sys.argv[1]
os.chdir( working )

Do not "assume" a directory based on the location of your software. It will not work out well in the long run.

MySQL my.cnf file - Found option without preceding group

it is because of letters or digit infront of [mysqld] just check the leeters or digit anything is not required before [mysqld]

it may be something like

0[mysqld] then this error will occur

C# - Fill a combo box with a DataTable

You need to set the binding context of the ToolStripComboBox.ComboBox.

Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.

I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem?

If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express.

var languages = new string[2];
languages[0] = "English";
languages[1] = "German";

DataSet myDataSet = new DataSet();

// --- Preparation
DataTable lTable = new DataTable("Lang");
DataColumn lName = new DataColumn("Language", typeof(string));
lTable.Columns.Add(lName);

for (int i = 0; i < languages.Length; i++)
{
    DataRow lLang = lTable.NewRow();
    lLang["Language"] = languages[i];
    lTable.Rows.Add(lLang);
}
myDataSet.Tables.Add(lTable);

toolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView;
toolStripComboBox1.ComboBox.DisplayMember = "Language";

toolStripComboBox1.ComboBox.BindingContext = this.BindingContext;

Inserting a Python datetime.datetime object into MySQL

If you're just using a python datetime.date (not a full datetime.datetime), just cast the date as a string. This is very simple and works for me (mysql, python 2.7, Ubuntu). The column published_date is a MySQL date field, the python variable publish_date is datetime.date.

# make the record for the passed link info
sql_stmt = "INSERT INTO snippet_links (" + \
    "link_headline, link_url, published_date, author, source, coco_id, link_id)" + \
    "VALUES(%s, %s, %s, %s, %s, %s, %s) ;"

sql_data = ( title, link, str(publish_date), \
             author, posted_by, \
             str(coco_id), str(link_id) )

try:
    dbc.execute(sql_stmt, sql_data )
except Exception, e:
    ...

Error related to only_full_group_by when executing a query in MySql

I am using Laravel 5.3, mysql 5.7.12, on laravel homestead (0.5.0, I believe)

Even after explicitly setting editing /etc/mysql/my.cnf to reflect:

[mysqld]
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

I was still receiving the error.

I had to change config/database.php from true to false:

    'mysql' => [
        'strict' => false, //behave like 5.6
        //'strict' => true //behave like 5.7
    ], 

Further reading:

https://laracasts.com/discuss/channels/servers/set-set-sql-mode-on-homestead https://mattstauffer.co/blog/strict-mode-and-other-mysql-customizations-in-laravel-5-2

Oracle: SQL query to find all the triggers belonging to the tables?

Use the Oracle documentation and search for keyword "trigger" in your browser.

This approach should work with other metadata type questions.

How to use local docker images with Minikube?

  1. setup minikube docker-env
  2. again build the same docker image (using minikube docker-env)
  3. change imagePullPolicy to Never in your deployment

actually what happens here , your Minikube can't recognise your docker daemon as it is independent service.You have to first set your minikube-docker environment use below command to check

 "eval $(minikube docker-env)"

If you run below command it will show where your minikube looks for docker.

~$ minikube docker-env
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.37.192:2376"
export DOCKER_CERT_PATH="/home/ubuntu/.minikube/certs"
export MINIKUBE_ACTIVE_DOCKERD="minikube"

**# To point your shell to minikube's docker-daemon, run:**
# eval $(minikube -p minikube docker-env)

You have to again build images once you setup minikube docker-env else it will fail.

GCM with PHP (Google Cloud Messaging)

Here is android code for PHP code of above posted by @Elad Nava

MainActivity.java (Launcher Activity)

public class MainActivity extends AppCompatActivity {
    String PROJECT_NUMBER="your project number/sender id";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        GCMClientManager pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
        pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
            @Override
            public void onSuccess(String registrationId, boolean isNewRegistration) {

                Log.d("Registration id", registrationId);
                //send this registrationId to your server
            }

            @Override
            public void onFailure(String ex) {
                super.onFailure(ex);
            }
        });
    }
}

GCMClientManager.java

public class GCMClientManager {
    // Constants
    public static final String TAG = "GCMClientManager";
    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "your sender id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    // Member variables
    private GoogleCloudMessaging gcm;
    private String regid;
    private String projectNumber;
    private Activity activity;
    public GCMClientManager(Activity activity, String projectNumber) {
        this.activity = activity;
        this.projectNumber = projectNumber;
        this.gcm = GoogleCloudMessaging.getInstance(activity);
    }
    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }
    // Register if needed or fetch from local store
    public void registerIfNeeded(final RegistrationCompletedHandler handler) {
        if (checkPlayServices()) {
            regid = getRegistrationId(getContext());
            if (regid.isEmpty()) {
                registerInBackground(handler);
            } else { // got id from cache
                Log.i(TAG, regid);
                handler.onSuccess(regid, false);
            }
        } else { // no play services
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }
    /**
     * Registers the application with GCM servers asynchronously.
     * <p>
     * Stores the registration ID and app versionCode in the application's
     * shared preferences.
     */
    private void registerInBackground(final RegistrationCompletedHandler handler) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(getContext());
                    }
                    InstanceID instanceID = InstanceID.getInstance(getContext());
                    regid = instanceID.getToken(projectNumber, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                    Log.i(TAG, regid);
                    // Persist the regID - no need to register again.
                    storeRegistrationId(getContext(), regid);
                } catch (IOException ex) {
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential back-off.
                    handler.onFailure("Error :" + ex.getMessage());
                }
                return regid;
            }
            @Override
            protected void onPostExecute(String regId) {
                if (regId != null) {
                    handler.onSuccess(regId, true);
                }
            }
        }.execute(null, null, null);
    }
    /**
     * Gets the current registration ID for application on GCM service.
     * <p>
     * If result is empty, the app needs to register.
     *
     * @return registration ID, or empty string if there is no existing
     *     registration ID.
     */
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }
    /**
     * Stores the registration ID and app versionCode in the application's
     * {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId registration ID
     */
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }
    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getContext().getSharedPreferences(context.getPackageName(),
                Context.MODE_PRIVATE);
    }
    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
            }
            return false;
        }
        return true;
    }
    private Context getContext() {
        return activity;
    }
    private Activity getActivity() {
        return activity;
    }
    public static abstract class RegistrationCompletedHandler {
        public abstract void onSuccess(String registrationId, boolean isNewRegistration);
        public void onFailure(String ex) {
            // If there is an error, don't just keep trying to register.
            // Require the user to click a button again, or perform
            // exponential back-off.
            Log.e(TAG, ex);
        }
    }
}

PushNotificationService.java (Notification generator)

public class PushNotificationService extends GcmListenerService{

    public static int MESSAGE_NOTIFICATION_ID = 100;

    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        sendNotification("Hi-"+message, "My App sent you a message");
    }

    private void sendNotification(String title, String body) {
        Context context = getBaseContext();
        NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher).setContentTitle(title)
                .setContentText(body);
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.gcm.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".PushNotificationService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="package.gcmdemo" />
        </intent-filter>
    </receiver>
</application>

I lose my data when the container exits

the similar problem (and no way Dockerfile alone could fix it) brought me to this page.

stage 0: for all, hoping Dockerfile could fix it: until --dns and --dns-search will appear in Dockerfile support - there is no way to integrate intranet based resources into.

stage 1: after building image using Dockerfile (by the way it's a serious glitch Dockerfile must be in the current folder), having an image to deploy what's intranet based, by running docker run script. example: docker run -d \ --dns=${DNSLOCAL} \ --dns=${DNSGLOBAL} \ --dns-search=intranet \ -t pack/bsp \ --name packbsp-cont \ bash -c " \ wget -r --no-parent http://intranet/intranet-content.tar.gz \ tar -xvf intranet-content.tar.gz \ sudo -u ${USERNAME} bash --norc"

stage 2: applying docker run script in daemon mode providing local dns records to have ability to download and deploy local stuff.

important point: run script should be ending with something like /usr/bin/sudo -u ${USERNAME} bash --norc to keep container running even after the installation scripts finishes.

no, it's not possible to run container in interactive mode for the full automation matter as it will remain inside internal shall command prompt until CTRL-p CTRL-q being pressed.

no, if interacting bash will not be executed at the end of the installation script, the container will terminate immediately after finishes script execution, loosing all installation results.

stage 3: container is still running in background but it's unclear whether container has ended installation procedure or not yet. using following block to determine execution procedure finishes: while ! docker container top ${CONTNAME} | grep "00[[:space:]]\{12\}bash \--norc" - do echo "." sleep 5 done the script will proceed further only after completed installation. and this is the right moment to call: commit, providing current container id as well as destination image name (it may be the same as on the build/run procedure but appended with the local installation purposes tag. example: docker commit containerID pack/bsp:toolchained. see this link on how to get proper containerID

stage 4: container has been updated with the local installs as well as it has been committed into newly assigned image (the one having purposes tag added). it's safe now to stop container running. example: docker stop packbsp-cont

stage5: any moment the container with local installs require to run, start it with the image previously saved. example: docker run -d -t pack/bsp:toolchained

Jquery mouseenter() vs mouseover()

You see the behavior when your target element contains child elements:

http://jsfiddle.net/ZCWvJ/7/

Each time your mouse enters or leaves a child element, mouseover is triggered, but not mouseenter.

_x000D_
_x000D_
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
  var el = $("#" + e.type);_x000D_
  var n = +el.text();_x000D_
  el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
  padding: 0 20px 20px 0;_x000D_
  background-color: #eee;_x000D_
  margin-bottom: 10px;_x000D_
  width: 90px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
  float: left;_x000D_
  margin: 20px 0 0 20px;_x000D_
  height: 25px;_x000D_
  width: 25px;_x000D_
  background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I select an element in jQuery by using a variable for the ID?

The shortest way would be:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

Return different type of data from a method in java?

I know this is late but I thought it'd be helpful to someone who'll come searching for an answer to this. You can use a Bundle to return multiple datatype values without creating another method. I tried it and worked perfectly.

In Your MainActivity where you call the method:

Bundle myBundle = method();
String myString = myBundle.getString("myS");
String myInt = myBundle.getInt("myI");

Method:

public Bundle method() {
    mBundle = new Bundle();
    String typicalString = "This is String";
    Int typicalInt = 1;
    mBundle.putString("myS", typicalString);
    mBundle.putInt("myI", typicalInt);
    return mBundle;
}

P.S: I'm not sure if it's OK to implement a Bundle like this, but for me, it worked out perfectly.

Escaping backslash in string - javascript

Escape the backslash character.

foo.split('\\')

How can I check if my Element ID has focus?

This is a block element, in order for it to be able to receive focus, you need to add tabindex attribute to it, as in

<div id="myID" tabindex="1"></div>

Tabindex will allow this element to receive focus. Use tabindex="-1" (or indeed, just get rid of the attribute alltogether) to disallow this behaviour.

And then you can simply

if ($("#myID").is(":focus")) {...}

Or use the

$(document.activeElement)

As been suggested previously.

Tomcat 7 is not running on browser(http://localhost:8080/ )

It will be proxy configuration of your browser. In NetWork Setting, use no proxy

For Manual proxy configuration add exception(No Proxy for in Firefox) like localhost:8080, localhost.

This Handler class should be static or leaks might occur: IncomingHandler

I'm confused. The example I found avoids the static property entirely and uses the UI thread:

    public class example extends Activity {
        final int HANDLE_FIX_SCREEN = 1000;
        public Handler DBthreadHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                int imsg;
                imsg = msg.what;
                if (imsg == HANDLE_FIX_SCREEN) {
                    doSomething();
                }
            }
        };
    }

The thing I like about this solution is there is no problem trying to mix class and method variables.

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

Using jQuery UI in combination with the excellent datetimepicker plugin from http://trentrichardson.com/examples/timepicker/

You can specify the dateFormat and timeFormat

$('#datepicker').datetimepicker({
    dateFormat: "yy-mm-dd",
    timeFormat:  "hh:mm:ss"
});

How to reset db in Django? I get a command 'reset' not found error

  1. Just manually delete you database. Ensure you create backup first (in my case db.sqlite3 is my database)

  2. Run this command manage.py migrate

How to set timeout in Retrofit library?

These answers were outdated for me, so here's how it worked out.

Add OkHttp, in my case the version is 3.3.1:

compile 'com.squareup.okhttp3:okhttp:3.3.1'

Then before building your Retrofit, do this:

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .build();
return new Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

How to send a JSON object using html form data

The accepted answer is out of date; nowadays you can simply add enctype="application/json" to your form tag and the browser will jsonify the data automatically.

The spec for this behavior is here: https://www.w3.org/TR/html-json-forms/

Join/Where with LINQ and Lambda

This linq query Should work for you. It will get all the posts that have post meta.

var query = database.Posts.Join(database.Post_Metas,
                                post => post.postId, // Primary Key
                                meta => meat.postId, // Foreign Key
                                (post, meta) => new { Post = post, Meta = meta });

Equivalent SQL Query

Select * FROM Posts P
INNER JOIN Post_Metas pm ON pm.postId=p.postId

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

try if install lampp

sudo chown www-data:www-data -R /opt/lampp/phpmyadmin/*
sudo chown www-data:www-data -R /opt/lampp/phpmyadmin

or if install phpmyadmin

sudo chown www-data:www-data -R /etc/phpmyadmin/*
sudo chown www-data:www-data -R /etc/phpmyadmin

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

mysql_fetch_array() expects parameter 1 to be resource boolean given in php error on server if you get this error : please select all privileges on your server. u will get the answer..

Is there a date format to display the day of the week in java?

I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:

new SimpleDateFormat("u").format(new Date());

returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

How to print star pattern in JavaScript in a very simple manner?

<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <p id="test"></p>
    </body>
    <script>
        //Declare Variable
        var i;
        for(i = 0; i <= 5; i++){
            document.write('*'.repeat(i).concat("<br>"))
        }
    </script>
</html>

Opening Chrome From Command Line

Have a look into the start command. It should do what you're trying to achieve.

Also, you might be able to leave out path to chrome. The following works on Windows 7:

start chrome "site1.com" "site2.com"

How to search for occurrences of more than one space between words in a line

Simple solution:

/\s{2,}/

This matches all occurrences of one or more whitespace characters. If you need to match the entire line, but only if it contains two or more consecutive whitespace characters:

/^.*\s{2,}.*$/

If the whitespaces don't need to be consecutive:

/^(.*\s.*){2,}$/

Difference Between $.getJSON() and $.ajax() in jQuery

There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.

$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.

Read More .. jquery-post-vs-get-vs-ajax

Get root view from current activity

Another Kotlin Extension solution

If your activity's view is declared in xml (ex activity_root.xml), open the xml and assign an id to the root view:

android:id="@+id/root_activity"

Now in your class, import the view using:

import kotlinx.android.synthetic.main.activity_root.root_activity

You can now use root_activity as the view.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I had this problem because I updated packages, which included Microsoft.AspNet.WebApi that has a reference to Newtonsoft.Json 4.5.6 and I already had version 6 installed. It wasn't clever enough to use the version 6.

To resolve it, after the WebApi update I opened the Tools > NuGet Package Manager > Pacakge Manager Console and ran:

 Update-Package Newtonsoft.Json

The log showed that the 6.0.x and 4.5.6 versions were all updated to the latest one and everything was fine.

I have a feeling this will come up again.

HTML Tags in Javascript Alert() method

alert() doesn't support HTML, but you have some alternatives to format your message.

You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:

...
.catch(function (error) {
  const alertMessage = `Error retrieving resource. Please make sure:
    • the resource server is accessible
    • you're logged in

    Error: ${error}`;
  window.alert(alertMessage);
}

Output: enter image description here

As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.

SQL Server - copy stored procedures from one db to another

use

select * from sys.procedures

to show all your procedures;

sp_helptext @objname = 'Procedure_name'

to get the code

and your creativity to build something to loop through them all and generate the export code :)

Express.js - app.listen vs server.listen

Just for punctuality purpose and extend a bit Tim answer.
From official documentation:

The app returned by express() is in fact a JavaScript Function, DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handle requests.

This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Use child_process.execSync but keep output in console

Simply:

 try {
    const cmd = 'git rev-parse --is-inside-work-tree';
    execSync(cmd).toString();
 } catch (error) {
    console.log(`Status Code: ${error.status} with '${error.message}'`;
 }

Ref: https://stackoverflow.com/a/43077917/104085

// nodejs
var execSync = require('child_process').execSync;

// typescript
const { execSync } = require("child_process");

 try {
    const cmd = 'git rev-parse --is-inside-work-tree';
    execSync(cmd).toString();
 } catch (error) {
    error.status;  // 0 : successful exit, but here in exception it has to be greater than 0
    error.message; // Holds the message you typically want.
    error.stderr;  // Holds the stderr output. Use `.toString()`.
    error.stdout;  // Holds the stdout output. Use `.toString()`.
 }

enter image description here

enter image description here

When command runs successful: enter image description here

How to join two sets in one line without using "|"

You could use or_ alias:

>>> from operator import or_
>>> from functools import reduce # python3 required
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])

python setup.py uninstall

I had run "python setup.py install" at some point in the past accidentally in my global environment, and had much difficulty uninstalling. These solutions didn't help. "pip uninstall " didn't work with "Can't uninstall 'splunk-appinspect'. No files were found to uninstall." "sudo pip uninstall " didn't work "Cannot uninstall requirement splunk-appinspect, not installed". I tried uninstalling pip, deleting the pip cache, searching my hard drive for the package, etc...

"pip show " eventually led me to the solution, the "Location:" was pointing to a directory, and renaming that directory caused the packaged to be removed from pip's list. I renamed the directory back, and it didn't reappear in pip's list, and now I can reinstall my package in a virtualenv.

What is "loose coupling?" Please provide examples

Tightly coupled code relies on a concrete implementation. If I need a list of strings in my code and I declare it like this (in Java)

ArrayList<String> myList = new ArrayList<String>();

then I'm dependent on the ArrayList implementation.

If I want to change that to loosely coupled code, I make my reference an interface (or other abstract) type.

List<String> myList = new ArrayList<String>();

This prevents me from calling any method on myList that's specific to the ArrayList implementation. I'm limited to only those methods defined in the List interface. If I decide later that I really need a LinkedList, I only need to change my code in one place, where I created the new List, and not in 100 places where I made calls to ArrayList methods.

Of course, you can instantiate an ArrayList using the first declaration and restrain yourself from not using any methods that aren't part of the List interface, but using the second declaration makes the compiler keep you honest.

What is the difference between a cer, pvk, and pfx file?

In Windows platform, these file types are used for certificate information. Normally used for SSL certificate and Public Key Infrastructure (X.509).

  • CER files: CER file is used to store X.509 certificate. Normally used for SSL certification to verify and identify web servers security. The file contains information about certificate owner and public key. A CER file can be in binary (ASN.1 DER) or encoded with Base-64 with header and footer included (PEM), Windows will recognize either of these layout.
  • PVK files: Stands for Private Key. Windows uses PVK files to store private keys for code signing in various Microsoft products. PVK is proprietary format.
  • PFX files Personal Exchange Format, is a PKCS12 file. This contains a variety of cryptographic information, such as certificates, root authority certificates, certificate chains and private keys. It’s cryptographically protected with passwords to keep private keys private and preserve the integrity of the root certificates. The PFX file is also used in various Microsoft products, such as IIS.

for more information visit:Certificate Files: .Cer x .Pvk x .Pfx

How to make MySQL table primary key auto increment with some prefix

If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.

Tables

CREATE TABLE table1_seq
(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
  id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);

Now the trigger

DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
  INSERT INTO table1_seq VALUES (NULL);
  SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;

Then you just insert rows to table1

INSERT INTO Table1 (name) 
VALUES ('Jhon'), ('Mark');

And you'll have

|      ID | NAME |
------------------
| LHPL001 | Jhon |
| LHPL002 | Mark |

Here is SQLFiddle demo

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Difference between adjustResize and adjustPan in android?

From the Android Developer Site link

"adjustResize"

The activity's main window is always resized to make room for the soft keyboard on screen.

"adjustPan"

The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.

according to your comment, use following in your activity manifest

<activity android:windowSoftInputMode="adjustResize"> </activity>

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];

jquery: get id from class selector

As of jQuery 1.6, you could (and some would say should) use .prop instead of .attr

$('.test').click(function(){
    alert($(this).prop('id'));
});

It is discussed further in this post: .prop() vs .attr()

Checking for a null object in C++

A reference can not be NULL. The interface makes you pass a real object into the function.

So there is no need to test for NULL. This is one of the reasons that references were introduced into C++.

Note you can still write a function that takes a pointer. In this situation you still need to test for NULL. If the value is NULL then you return early just like in C. Note: You should not be using exceptions when a pointer is NULL. If a parameter should never be NULL then you create an interface that uses a reference.

MVC4 input field placeholder

Of course it does:

@Html.TextBoxFor(x => x.Email, new { @placeholder = "Email" })

Java 8 stream reverse order

For the specific question of generating a reverse IntStream, try something like this:

static IntStream revRange(int from, int to) {
    return IntStream.range(from, to)
                    .map(i -> to - i + from - 1);
}

This avoids boxing and sorting.

For the general question of how to reverse a stream of any type, I don't know of there's a "proper" way. There are a couple ways I can think of. Both end up storing the stream elements. I don't know of a way to reverse a stream without storing the elements.

This first way stores the elements into an array and reads them out to a stream in reverse order. Note that since we don't know the runtime type of the stream elements, we can't type the array properly, requiring an unchecked cast.

@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
    Object[] temp = input.toArray();
    return (Stream<T>) IntStream.range(0, temp.length)
                                .mapToObj(i -> temp[temp.length - i - 1]);
}

Another technique uses collectors to accumulate the items into a reversed list. This does lots of insertions at the front of ArrayList objects, so there's lots of copying going on.

Stream<T> input = ... ;
List<T> output =
    input.collect(ArrayList::new,
                  (list, e) -> list.add(0, e),
                  (list1, list2) -> list1.addAll(0, list2));

It's probably possible to write a much more efficient reversing collector using some kind of customized data structure.

UPDATE 2016-01-29

Since this question has gotten a bit of attention recently, I figure I should update my answer to solve the problem with inserting at the front of ArrayList. This will be horribly inefficient with a large number of elements, requiring O(N^2) copying.

It's preferable to use an ArrayDeque instead, which efficiently supports insertion at the front. A small wrinkle is that we can't use the three-arg form of Stream.collect(); it requires the contents of the second arg be merged into the first arg, and there's no "add-all-at-front" bulk operation on Deque. Instead, we use addAll() to append the contents of the first arg to the end of the second, and then we return the second. This requires using the Collector.of() factory method.

The complete code is this:

Deque<String> output =
    input.collect(Collector.of(
        ArrayDeque::new,
        (deq, t) -> deq.addFirst(t),
        (d1, d2) -> { d2.addAll(d1); return d2; }));

The result is a Deque instead of a List, but that shouldn't be much of an issue, as it can easily be iterated or streamed in the now-reversed order.

Rollback transaction after @Test

You can disable the Rollback:

@TransactionConfiguration(defaultRollback = false)

Example:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@Transactional
@TransactionConfiguration(defaultRollback = false)
public class Test {
    @PersistenceContext
    private EntityManager em;

    @org.junit.Test
    public void menge() {
        PersistentObject object = new PersistentObject();
        em.persist(object);
        em.flush();
    }
}

Find length of 2D array Python

You can also use np.size(a,1), 1 here is the axis and this will give you the number of columns

How to Convert datetime value to yyyymmddhhmmss in SQL server?

20090320093349

SELECT CONVERT(VARCHAR,@date,112) + 
LEFT(REPLACE(CONVERT(VARCHAR,@date,114),':',''),6)

python .replace() regex

You can use the re module for regexes, but regexes are probably overkill for what you want. I might try something like

z.write(article[:article.index("</html>") + 7]

This is much cleaner, and should be much faster than a regex based solution.

How to do paging in AngularJS?

I recently implemented paging for the Built with Angular site. You chan checkout the source: https://github.com/angular/builtwith.angularjs.org

I'd avoid using a filter to separate the pages. You should break up the items into pages within the controller.

How to assign the output of a Bash command to a variable?

In shell you assign to a variable without the dollar-sign:

TEST=`pwd`
echo $TEST

that's better (and can be nested) but is not as portable as the backtics:

TEST=$(pwd)
echo $TEST

Always remember: the dollar-sign is only used when reading a variable.

How can I import a database with MySQL from terminal?

mysql -u username -ppassword dbname < /path/file-name.sql

example

mysql -u root -proot product < /home/myPC/Downloads/tbl_product.sql

Use this from terminal

How to change the new TabLayout indicator color and height

app:tabIndicatorColor="@android:color/white"

Redirect using AngularJS

With an example of the not-working code, it will be easy to answer this question, but with this information the best that I can think is that you are calling the $location.path outside of the AngularJS digest.

Try doing this on the directive scope.$apply(function() { $location.path("/route"); });

How to repeat a char using printf?

There is no such thing. You'll have to either write a loop using printf or puts, or write a function that copies the string count times into a new string.

Connect HTML page with SQL server using javascript

JavaScript is a client-side language and your MySQL database is going to be running on a server.

So you have to rename your file to index.php for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.

(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)

So after you renamed your file, go to the very top, before <html> or <!DOCTYPE html> and type:

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        /*Creating variables*/
        $name = $_POST["name"];
        $address = $_POST["address"];
        $age = $_POST["age"];


        $dbhost = "localhost"; /*most of the time it's localhost*/
        $username = "yourusername";
        $password = "yourpassword";
        $dbname = "mydatabase";

        $mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
        $query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
        mysqli_query($mysql, $query);
    }
?>
<!DOCTYPE html>
<html>
<head>.......
....
    <form method="post">
        <input name="name" type="text"/>
        <input name="address" type="text"/>
        <input name="age" type="text"/>
    </form>
....

How can I trigger a JavaScript event click

IE9+

function triggerEvent(el, type){
    var e = document.createEvent('HTMLEvents');
    e.initEvent(type, false, true);
    el.dispatchEvent(e);
}

Usage example:

var el = document.querySelector('input[type="text"]');
triggerEvent(el, 'mousedown');

Source: https://plainjs.com/javascript/events/trigger-an-event-11/

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

Even though Sheena's answer does the job, pip doesn't stop just there.

From Sheena's answer:

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

At the end of this, you'll end up with a .egg file in site-packages. As a user, this shouldn't bother you. You can import and uninstall the package normally. However, if you want to do it the pip way, you can continue the following steps.

In the site-packages directory,

  1. unzip <.egg file>
  2. rename the EGG-INFO directory as <pkg>-<version>.dist-info
  3. Now you'll see a separate directory with the package name, <pkg-directory>
  4. find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
  5. find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD. The >> is to prevent overwrite.

Now, looking at the site-packages directory, you'll never realize you installed without pip. To uninstall, just do the usual pip uninstall <pkg>.

What does "select count(1) from table_name" on any database tables mean?

Difference between count(*) and count(1) in oracle?

count(*) means it will count all records i.e each and every cell BUT

count(1) means it will add one pseudo column with value 1 and returns count of all records

Is a DIV inside a TD a bad idea?

No. Not necessarily.

If you need to place a DIV within a TD, be sure you're using the TD properly. If you don't care about tabular-data, and semantics, then you ultimately won't care about DIVs in TDs. I don't think there's a problem though - if you have to do it, you're fine.

According to the HTML Specification

A <div> can be placed where flow content is expected1, which is the <td> content model2.

jquery (or pure js) simulate enter key pressed for testing

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

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

My solution for changing seconds (number) to string format (for example: 'mm:ss'):

const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');

Write your seconds instead 'S' in example. And just use the 'formattedSeconds' where you need.

How to implement zoom effect for image view in android?

You could check the answer in a related question. https://stackoverflow.com/a/16894324/1465756

Just import library https://github.com/jasonpolites/gesture-imageview.

into your project and add the following in your layout file:

<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:gesture-image="http://schemas.polites.com/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">

<com.polites.android.GestureImageView
   android:id="@+id/image"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:src="@drawable/image"
   gesture-image:min-scale="0.1"
   gesture-image:max-scale="10.0"
   gesture-image:strict="false"/>`

Set value of hidden input with jquery

You should use val instead of value.

<script type="text/javascript" language="javascript">
$(document).ready(function () { 
    $('input[name="testing"]').val('Work!');
});
</script>

After installing with pip, "jupyter: command not found"

I'm on Mojave with Python 2.7 and after pip install --user jupyter the binary went here:

/Users/me/Library/Python//2.7/bin/jupyter

How to get the bluetooth devices as a list?

package com.sekurtrack.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);



        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

       /* BA = BluetoothAdapter.getDefaultAdapter();
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);*/

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };
}

How to Validate on Max File Size in Laravel?

According to the documentation:

$validator = Validator::make($request->all(), [
    'file' => 'max:500000',
]);

The value is in kilobytes. I.e. max:10240 = max 10 MB.

Compare two files in Visual Studio

Inspired by the accepted answer above, I found a very comfortable way how you can instantly compare two files with Visual Studio by using drag and drop or via the "Send To" context menu. It only requires a little preparation which you need to do once and then it is useful like a Swiss army knife.

Visual Studio already has everything you need, there are only some configuration steps required to make this working:

File compare using drag & drop

Preparation:

  1. Create a new batch file using your favorite text editor. Type the following:
@echo off
setlocal
set vspath=C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE
start "Compare files" /B /MIN "%vspath%\devenv.exe" /diff %2 %1 First:'%2' Second:'%1'

You might notice that I have reversed the %1 and %2 parameters in the batch. This is because I noticed that the file explorer passes the 2nd file as first parameter, then the 1st file as second parameter.

  1. Save this code as VS_FileCompare.cmd to use it, modify vspath if required to match the location of devenv.exe (depending on the Visual Studio version you're currently using, see footnote*) )

  2. Either create a shortcut named "File Compare" for VS_FileCompare.cmd and place it on the desktop (as used in the animation below), so it is always available to drag & drop files onto it or directly place the batch file on the desktop. That's all!

Usage:

  1. Open the Windows explorer via Win + E

  2. Select two files to compare in the explorer

  3. Drag and drop them as shown in the animation below: DragDropDemo

  4. After a few seconds (depending on the launch time of Visual Studio), the results will be shown in Visual Studio: Visual Studio View

Note: It does not harm if Visual Studio is already open. In this case it will just open up a new window within the running instance of Visual Studio. So you can compare multiple file pairs, but please ensure you have selected only 2 files at a time.


Alternative way: SendTo context menu

Here's an alternative how you can use the batch file VS_FileCompare.cmd mentioned in the section above. It allows to use the context menu's Send To folder to compare the files.

Preparation:

  1. Create a shortcut "Compare2Files VS" for the batch file VS_FileCompare.cmd and copy it into the SendTo folder. Open the Windows explorer via Win + E
  2. Open the SendTo folder by entering shell:sendto into the file explorer's address bar (as described here). Then, put the prepared shortcut into this folder.

Usage:

  1. Open the Windows explorer via Win + E

  2. Select two files to compare in the explorer

  3. Assuming the shortcut for the batch file VS_FileCompare.cmd is named "Compare2Files VS", you can select the two files, right-click and select Send To --> Compare2Files VS to invoke the compare as shown below: SendTo

  4. After a few seconds (depending on the launch time of Visual Studio), the results will be shown in Visual Studio: Visual Studio View

HINT: If you like the SendTo folder approach, there is more you can do - for example you can open a command shell directly via SendTo and it starts with the right path (the path where the selected file resides). Look here fo find out how to do that. You can even combine it with the script to gain elevated rights, with only a little extra effort.


MSDN References:


*) Footnote: Because vsPath (the path to DEVENV.exe) differs depending on your version of Visual Studio, I am describing how you can find it out (Windows 10):

  1. In the Windows start menu Windows Icon Small, locate the Visual Studio icon Visual Studio Icon Small
  2. Right-click to bring up the context menu. Select More > Open File Location.
    Windows Explorer opens with the Visual Studio shortcut highlighted.
  3. Right-Click on the Visual Studio and select Properties
  4. In the properties dialog, you can find the path in "Target:" VSProperties

Show default value in Spinner in android

Spinner don't support Hint, i recommend you to make a custom spinner adapter.

check this link : https://stackoverflow.com/a/13878692/1725748

Webdriver findElements By xpath

Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

How to push both key and value into an Array in Jquery

There are no keys in JavaScript arrays. Use objects for that purpose.

var obj = {};

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        obj[news.title] = news.link;
    });                      
});

// later:
$.each(obj, function (index, value) {
    alert( index + ' : ' + value );
});

In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).

However, In your case it is not really clear to me why you transfer data from the original object (data.news) at all. Why do you not simply pass a reference to that object around?


You can combine objects and arrays to achieve predictable iteration and key/value behavior:

var arr = [];

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        arr.push({
            title: news.title, 
            link:  news.link
        });
    });                      
});

// later:
$.each(arr, function (index, value) {
    alert( value.title + ' : ' + value.link );
});

Are SSL certificates bound to the servers ip address?

Most SSL certificates are bound to the hostname of the machine and not the ip address.

You might get a better answer if you ask this question on serverfault.com

How can I force WebKit to redraw/repaint to propagate style changes?

For some reason I couldn't get danorton's answer to work, I could see what it was supposed to do so I tweaked it a little bit to this:

$('#foo').css('display', 'none').height();
$('#foo').css('display', 'block');

and it worked for me.

Select All Rows Using Entity Framework

You can use this code to select all rows :

C# :

var allStudents = [modelname].[tablename].Select(x => x).ToList();

How can I get the current stack trace in Java?

You can use Apache's commons for that:

String fullStackTrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);

How can I make robocopy silent in the command line except for progress?

There's no need to redirect to a file and delete it later. Try:

Robocopy src dest > null 

How to refer environment variable in POM.xml?

I was struggling with the same thing, running a shell script that set variables, then wanting to use the variables in the shared-pom. The goal was to have environment variables replace strings in my project files using the com.google.code.maven-replacer-plugin.

Using ${env.foo} or ${env.FOO} didn't work for me. Maven just wasn't finding the variable. What worked was passing the variable in as a command-line parameter in Maven. Here's the setup:

  1. Set the variable in the shell script. If you're launching Maven in a sub-script, make sure the variable is getting set, e.g. using source ./maven_script.sh to call it from the parent script.

  2. In shared-pom, create a command-line param that grabs the environment variable:

<plugin>
  ...
  <executions>
    <executions>
    ...
      <execution>
      ...
        <configuration>
          <param>${foo}</param> <!-- Note this is *not* ${env.foo} -->
        </configuration>
  1. In com.google.code.maven-replacer-plugin, make the replacement value ${foo}.

  2. In my shell script that calls maven, add this to the command: -Dfoo=$foo

How do I use a Boolean in Python?

Boolean types are defined in documentation:
http://docs.python.org/library/stdtypes.html#boolean-values

Quoted from doc:

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

They are written as False and True, respectively.

So in java code remove braces, change true to True and you will be ok :)

How To Get Selected Value From UIPickerView

You can get the text of the selected item in any section of the picker using the same function that the pickerView does, from your custom ViewController class:

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component

using the selected item

[myPickerView selectedRowInComponent:0]

so to set the text of a label in a custom cell using the currently selected value from the 2nd section of myPickerView (a property of your view controller probably)

[cell.label setText:[self pickerView:myPickerView titleForRow:[myPickerView selectedRowInComponent:1] forComponent:1]];

Just change both :1s to :2s, etc for each section

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

How to split string and push in array using jquery

var string = 'a,b,c,d',
    strx   = string.split(',');
    array  = [];

array = array.concat(strx);
// ["a","b","c","d"]

How to include() all PHP files from a directory?

If your looking to include a bunch of classes without having to define each class at once you can use:

$directories = array(
            'system/',
            'system/db/',
            'system/common/'
);
foreach ($directories as $directory) {
    foreach(glob($directory . "*.php") as $class) {
        include_once $class;
    }
}

This way you can just define the class on the php file containing the class and not a whole list of $thisclass = new thisclass();

As for how well it handles all the files? I'm not sure there might be a slight speed decrease with this.

MySQL: can't access root account

You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).

So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND, CREATE, FLUSH PRIVILEGES, etc.) into init file (any file).

Here is my example of recovering root account:

echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql 
echo "FLUSH PRIVILEGES;" >> your_init_file.sql

and after you've created your file, you can run:

killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql

then to check if this worked, press Ctrl+Z and type: bg to run the process from the foreground into the background, then verify your access by:

mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                   |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |

See also:

visual c++: #include files from other projects in the same solution

Settings for compiler

In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration.

To access the project configuration:

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->C/C++->General.
  3. Set the path under Additional Include Directories.

How to include

To include the header file, simply write the following in your code:

#include "filename.h"

Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it.

If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point:

// In project settings
Additional Include Directories    ..\..\libroot

// In code
#include "lib1/lib1.h"    // path is relative to libroot
#include "lib2/lib2.h"    // path is relative to libroot

Setting for linker

If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol):

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->Linker->Input
  3. Enter the library under Additional Dependencies.

How to click a browser button with JavaScript automatically?

setInterval(function () {document.getElementById("myButtonId").click();}, 1000);

sql insert into table with select case values

You have the alias inside of the case, it needs to be outside of the END:

Insert into TblStuff (FullName,Address,City,Zip)
Select
  Case
    When Middle is Null 
    Then Fname + LName
    Else Fname +' ' + Middle + ' '+ Lname
  End as FullName,
  Case
    When Address2 is Null Then Address1
    else Address1 +', ' + Address2 
  End as  Address,
  City as City,
  Zip as Zip
from tblImport

How do I run Google Chrome as root?

  1. Go to /opt/google/chrome.

  2. Open google-chrome.

  3. Append current home for data directory. Replace this:

exec -a "$0" "$HERE/chrome" "$@"

With this:

exec -a "$0" "$HERE/chrome" "$@" --user-data-dir $HOME

For reference visit site this site, “How to run chrome as root user in Ubuntu.”

How do you run a command as an administrator from the Windows command line?

:: ------- Self-elevating.bat --------------------------------------
@whoami /groups | find "S-1-16-12288" > nul && goto :admin
set "ELEVATE_CMDLINE=cd /d "%~dp0" & call "%~f0" %*"
findstr "^:::" "%~sf0">temp.vbs
cscript //nologo temp.vbs & del temp.vbs & exit /b

::: Set objShell = CreateObject("Shell.Application")
::: Set objWshShell = WScript.CreateObject("WScript.Shell")
::: Set objWshProcessEnv = objWshShell.Environment("PROCESS")
::: strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
::: objShell.ShellExecute "cmd", "/c " & strCommandLine, "", "runas"
:admin -------------------------------------------------------------

@echo off
echo Running as elevated user.
echo Script file : %~f0
echo Arguments   : %*
echo Working dir : %cd%
echo.
:: administrator commands here
:: e.g., run shell as admin
cmd /k

For a demo: self-elevating.bat "path with spaces" arg2 3 4 "another long argument"

And this is another version that does not require creating a temp file.

<!-- : --- Self-Elevating Batch Script ---------------------------
@whoami /groups | find "S-1-16-12288" > nul && goto :admin
set "ELEVATE_CMDLINE=cd /d "%~dp0" & call "%~f0" %*"
cscript //nologo "%~f0?.wsf" //job:Elevate & exit /b

-->
<job id="Elevate"><script language="VBScript">
  Set objShell = CreateObject("Shell.Application")
  Set objWshShell = WScript.CreateObject("WScript.Shell")
  Set objWshProcessEnv = objWshShell.Environment("PROCESS")
  strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
  objShell.ShellExecute "cmd", "/c " & strCommandLine, "", "runas"
</script></job>
:admin -----------------------------------------------------------

@echo off
echo Running as elevated user.
echo Script file : %~f0
echo Arguments   : %*
echo Working dir : %cd%
echo.
:: administrator commands here
:: e.g., run shell as admin
cmd /k

What is the best way to convert an array to a hash in Ruby

Simply use Hash[*array_variable.flatten]

For example:

a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"

a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"

Using Array#flatten(1) limits the recursion so Array keys and values work as expected.

gdb: how to print the current line or find the current line number?

Command where or frame can be used. where command will give more info with the function name

Close a MessageBox after several seconds

There is an codeproject project avaliable HERE that provides this functuanility.

Following many threads here on SO and other boards this cant be done with the normal MessageBox.

Edit:

I have an idea that is a bit ehmmm yeah..

Use a timer and start in when the MessageBox appears. If your MessageBox only listens to the OK Button (only 1 possibility) then use the OnTick-Event to emulate an ESC-Press with SendKeys.Send("{ESC}"); and then stop the timer.

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

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

After reading through the above solutions, I used a CSS Grid solution.

  1. Create a div containing the h1 text and the image.
  2. Position the two items in the same cell and make them both relatively positioned.
  3. Use the old zeldman.com technique to hide the text using text-indent, white-space, and overflow properties.
<div class="title-stack">
    <h1 class="title-stack__title">StackOverflow</h1>
    <a href="#" class="title-stack__logo">
        <img src="/images/stack-overflow.png" alt="Stack Overflow">
    </a>
</div>
.title-stack {
    display: grid;
}
.title-stack__title, .title-stack__logo {
    grid-area: 1/1/1/1;
    position: relative;
}
.title-stack__title {
    z-index: 0;
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Starting with MySQL 8.0.4, they have changed the default authentication plugin for MySQL server from mysql_native_password to caching_sha2_password.

You can run the below command to resolve the issue.

sample username / password => student / pass123

ALTER USER 'student'@'localhost' IDENTIFIED WITH mysql_native_password BY 'pass123';

Refer the official page for details: MySQL Reference Manual

.htaccess rewrite subdomain to directory

I'm not a mod_rewrite expert, I often struggle with it, but I have done this on one of my sites, it might need other flags etc depending on your circumstances. I'm using this:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$
RewriteCond %{REQUEST_URI} !^/subdomains/subdomain
RewriteRule ^(.*)$ /subdomains/subdomain/$1 [L] 

Any other rewrite rules for the rest of the site must go afterwards to prevent them from interfering with your subdomain rewrites.

Working with dictionaries/lists in R

To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:

a) how to return all the VALUES of the dictionary:

>as.numeric(foo)
[1] 12 22 33

b) check whether dictionary CONTAINS KEY:

>'tic' %in% names(foo)
[1] TRUE

c) how to ADD NEW key, value pair to dictionary:

c(foo,tic2=44)

results:

tic       tac       toe     tic2
12        22        33        44 

d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)

e) how to DELETE pair BY KEY from dictionary:

foo<-foo[which(foo!=foo[["tac"]])]

How to decorate a class?

No one has explained that you can dynamically define classes. So you can have a decorator that defines (and returns) a subclass:

def addId(cls):

    class AddId(cls):

        def __init__(self, id, *args, **kargs):
            super(AddId, self).__init__(*args, **kargs)
            self.__id = id

        def getId(self):
            return self.__id

    return AddId

Which can be used in Python 2 (the comment from Blckknght which explains why you should continue to do this in 2.6+) like this:

class Foo:
    pass

FooId = addId(Foo)

And in Python 3 like this (but be careful to use super() in your classes):

@addId
class Foo:
    pass

So you can have your cake and eat it - inheritance and decorators!

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

How can I fill a div with an image while keeping it proportional?

You can achieve this using css flex properties. Please see the code below

_x000D_
_x000D_
.img-container {_x000D_
  border: 2px solid red;_x000D_
  justify-content: center;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  overflow: hidden;_x000D_
  _x000D_
}_x000D_
.img-container .img-to-fit {_x000D_
  flex: 1;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="img-container">_x000D_
  <img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to find my realm file?

Here is an easy solution.. I messed with this for awhile. I should point out, this is a specific set of instructions using Android Studio and the AVD Emulator.

1) Start the Emulator and run your app.

2) While the app is still running, open the Android Device Monitor. (its in the toolbar next to the AVD and SDK manager icons)

3) Click the File Explorer tab in the Device Monitor. There should be a lot of folders.

4) Navigate the following path: Data > Data > Your Package Name > files > Default.Realm (or whatever you named it)

Ex. If you are using one of the realm example projects, the path would be something like Data>Data>io.realm.examples.realmgridview>files>default.realm

5) Highlight the file, click the Floppy Disk icon in the upper right area "pull a file from the device"

6) Save it off to whereever you want and done.

Create two-dimensional arrays and access sub-arrays in Ruby

Here is the simple version

 #one
 a = [[0]*10]*10

 #two
row, col = 10, 10
a = [[0]*row]*col

Error: Argument is not a function, got undefined

I have encountered the same problem and in my case it was happening as a result of this problem:

I had the controllers defined in a separate module (called 'myApp.controllers') and injected to the main app module (called 'myApp') like this:

angular.module('myApp', ['myApp.controllers'])

A colleague pushed another controller module in a separate file but with the exact same name as mine (i.e. 'myApp.controllers' ) which caused this error. I think because Angular got confused between those controller modules. However the error message was not very helpful in discovering what is going wrong.

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

For those who are getting to this question via google... this error can also happen if you try to rename a field that is acting as a foreign key.

How to Add Date Picker To VBA UserForm

You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.

I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.

How to store arbitrary data for some HTML tags

So there should be four choices to do so:

  1. Put the data in the id attribute.
  2. Put the data in the arbitrary attribute
  3. Put the data in class attribute
  4. Put your data in another tag

http://www.shanison.com/?p=321

Bad Request, Your browser sent a request that this server could not understand

in my case:

in header

Content-Typespacespace

or

Content-Typetab

with two space or tab

when i remove it then it worked.

lodash multi-column sortBy descending

Is there some handy way of defining direction per column?

No. You cannot specify the sort order other than by a callback function that inverses the value. Not even this is possible for a multicolumn sort.

You might be able to do

 _.each(array_of_objects, function(o) {
     o.typeDesc = -o.type; // assuming a number
 });
 _.sortBy(array_of_objects, ['typeDesc', 'name'])

For everything else, you will need to resort to the native .sort() with a custom comparison function:

 array_of_objects.sort(function(a, b) {
     return a.type - b.type // asc
         || +(b.name>a.name)||-(a.name>b.name) // desc
         || …;
 });

Multiple models in a view

a simple way to do that

we can call all model first

@using project.Models

then send your model with viewbag

// for list
ViewBag.Name = db.YourModel.ToList();

// for one
ViewBag.Name = db.YourModel.Find(id);

and in view

// for list
List<YourModel> Name = (List<YourModel>)ViewBag.Name ;

//for one
YourModel Name = (YourModel)ViewBag.Name ;

then easily use this like Model

How to filter array in subdocument with MongoDB

Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

Result:

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

How to print matched regex pattern using awk?

If you know what column the text/pattern you're looking for (e.g. "yyy") is in, you can just check that specific column to see if it matches, and print it.

For example, given a file with the following contents, (called asdf.txt)

xxx yyy zzz

to only print the second column if it matches the pattern "yyy", you could do something like this:

awk '$2 ~ /yyy/ {print $2}' asdf.txt

Note that this will also match basically any line where the second column has a "yyy" in it, like these:

xxx yyyz zzz
xxx zyyyz

Remove new lines from string and replace with one empty space

You can remove new line and multiple white spaces.

$pattern = '~[\r\n\s?]+~';
$name="test1 /
                     test1";
$name = preg_replace( $pattern, "$1 $2",$name);

echo $name;

How to check if command line tools is installed

I think the simplest way which worked for me to find Command line tools is installed or not and its version irrespective of what macOS version is

$brew config

macOS: 10.14.2-x86_64
CLT: 10.1.0.0.1.1539992718
Xcode: 10.1

This when you have Command Line tools properly installed and paths set properly.

Earlier i got output as below
macOS: 10.14.2-x86_64
CLT: N/A
Xcode: 10.1

CLT was shown as N/A in spite of having gcc and make working fine and below outputs

$xcode-select -p              
/Applications/Xcode.app/Contents/Developer
$pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
$brew doctor
Your system is ready to brew.

Finally doing xcode-select --install resolved my issue of brew unable to find CLT for installing packages as below.

Installing sphinx-doc dependency: python
Warning: Building python from source:
  The bottle needs the Apple Command Line Tools to be installed.
  You can install them, if desired, with:
    xcode-select --install

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.

You can find creation/deletion of environments in the Anaconda documentation.

Hope this helped.

How to correct indentation in IntelliJ

Solution of unchecking comment at first column is partially working, because it works for line comments, but not block comments.

So, with lines like:

/* first line
 * second line
 * ...
 */

or

// line 1
// line 2
// line 3
...

they are indented with "Auto reformat", but lines like:

/* first line
   second line
   ...
 */

the identation will not be fixed.

So you should:

  • add * or // before each line of comments
  • then uncheck Keep when reformatting -> comment at first column
  • and Auto reformat.

NodeJs : TypeError: require(...) is not a function

I've faced to something like this too. in your routes file , export the function as an object like this :

 module.exports = {
     hbd: handlebar
 }

and in your app file , you can have access to the function by .hbd and there is no ptoblem ....!

Google.com and clients1.google.com/generate_204

with the massive remit by google to stop both spam and the scraping of their search database, I believe that this is part of the effort to track bots etc.

some simple anti bot pseudo could go like this.

On GET (google.*) Save RemoteEndPoint
{
    If RemoteEndPoint GETs (clients1.google.com/generate_204) Then
        Set botAlert_stage1 = false;
    Else
        Set botAlert_stage1 = true;
    End If
}

I also believe that the latest google frontpage 'theme' is also a new tool to help with the anti spam/bot activity.

** NOTE ** ipv6.google.com also includes this measure.

Just my unfounded unproofed two 2p.

Call to undefined method mysqli_stmt::get_result

Here is my alternative. It is object-oriented and is more like mysql/mysqli things.

class MMySqliStmt{
    private $stmt;
    private $row;

    public function __construct($stmt){
        $this->stmt = $stmt;
        $md = $stmt->result_metadata();
        $params = array();
        while($field = $md->fetch_field()) {
            $params[] = &$this->row[$field->name];
        }
        call_user_func_array(array($stmt, 'bind_result'), $params) or die('Sql Error');
    }

    public function fetch_array(){
        if($this->stmt->fetch()){
            $result = array();
            foreach($this->row as $k => $v){
                $result[$k] = $v;
            }
            return $result;
        }else{
            return false;
        }
    }

    public function free(){
        $this->stmt->close();
    }
}

Usage:

$stmt = $conn->prepare($str);
//...bind_param... and so on
if(!$stmt->execute())die('Mysql Query(Execute) Error : '.$str);
$result = new MMySqliStmt($stmt);
while($row = $result->fetch_array()){
    array_push($arr, $row);
    //for example, use $row['id']
}
$result->free();
//for example, use the $arr

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

When you are using Lombok builder you will get the above error.

 @JsonDeserialize(builder = StationResponse.StationResponseBuilder.class)
 public class StationResponse{
   //define required properties 
 }     

 @JsonIgnoreProperties(ignoreUnknown = true)
 @JsonPOJOBuilder(withPrefix = "")
 public static class StationResponseBuilder {}

Reference : https://projectlombok.org/features/Builder With Jackson

Why would you use String.Equals over ==?

I've just been banging my head against a wall trying to solve a bug because I read this page and concluded there was no meaningful difference when in practice there is so I'll post this link here in case anyone else finds they get different results out of == and equals.

Object == equality fails, but .Equals succeeds. Does this make sense?

string a = "x";
string b = new String(new []{'x'});

Console.WriteLine("x == x " + (a == b));//True
Console.WriteLine("object x == x " + ((object)a == (object)b));//False
Console.WriteLine("x equals x " + (a.Equals(b)));//True
Console.WriteLine("object x equals x " + (((object)a).Equals((object)b)));//True

How to control the line spacing in UILabel

I've found a way where you can set the real line height (not a factor) and it even renders live in Interface Builder. Just follow the instructions below. Code is written in Swift 4.


Step #1: Create a file named DesignableLabel.swift and insert the following code:

import UIKit

@IBDesignable
class DesignableLabel: UILabel {
    @IBInspectable var lineHeight: CGFloat = 20 {
        didSet {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.minimumLineHeight = lineHeight
            paragraphStyle.maximumLineHeight = lineHeight
            paragraphStyle.alignment = self.textAlignment

            let attrString = NSMutableAttributedString(string: text!)
            attrString.addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: attrString.length))
            attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attrString.length))
            attributedText = attrString
        }
    }
}

Step #2: Place a UILabel into a Storyboard/XIB and set its class to DesignableLabel. Wait for your project to build (build must succeed!).

Specifying the class to your UILabel


Step 3: Now you should see a new property in the properties pane named "Line Height". Just set the value you like and you should see the results immediately!

Set Line Height in properties

Datatables warning(table id = 'example'): cannot reinitialise data table

You have to destroy the datatable and empty the table body before binding DataTable by doing this below,

function Create() {
if ($.fn.DataTable.isDataTable('#dataTable')) {
    $('#dataTable').DataTable().destroy();
}
$('#dataTable tbody').empty();
//Here call the Datatable Bind function;} 

How to use custom packages

For this kind of folder structure:

main.go
mylib/
  mylib.go

The simplest way is to use this:

import (
    "./mylib"
)

How to prevent colliders from passing through each other?

1.) Never use MESH COLLIDER. Use combination of box and capsule collider.

2.) Check constraints in RigidBody. If you tick Freeze Position X than it will pass through the object on the X axis. (Same for y axis).

How to show live preview in a small popup of linked page on mouse over on link?

You can use an iframe to display a preview of the page on mouseover:

_x000D_
_x000D_
.box{_x000D_
    display: none;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    z-index: 100;_x000D_
}
_x000D_
This live preview for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
  <div class="box">_x000D_
    <iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
    </iframe>_x000D_
  </div> _x000D_
remains open on mouseover.
_x000D_
_x000D_
_x000D_

Here's an example with multiple live previews:

_x000D_
_x000D_
.box{_x000D_
    display: none;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    z-index: 100;_x000D_
}
_x000D_
Live previews for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
  <div class="box">_x000D_
     <iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
     </iframe>_x000D_
  </div> _x000D_
and <a href="https://www.jquery.com/">JQuery</a>_x000D_
  <div class="box">_x000D_
     <iframe src="https://www.jquery.com/" width = "500px" height = "500px">_x000D_
     </iframe>_x000D_
  </div> _x000D_
will appear when these links are moused over.
_x000D_
_x000D_
_x000D_

Pandas convert dataframe to array of tuples

Here's a vectorized approach (assuming the dataframe, data_set to be defined as df instead) that returns a list of tuples as shown:

>>> df.set_index(['data_date'])[['data_1', 'data_2']].to_records().tolist()

produces:

[(datetime.datetime(2012, 2, 17, 0, 0), 24.75, 25.03),
 (datetime.datetime(2012, 2, 16, 0, 0), 25.0, 25.07),
 (datetime.datetime(2012, 2, 15, 0, 0), 24.99, 25.15),
 (datetime.datetime(2012, 2, 14, 0, 0), 24.68, 25.05),
 (datetime.datetime(2012, 2, 13, 0, 0), 24.62, 24.77),
 (datetime.datetime(2012, 2, 10, 0, 0), 24.38, 24.61)]

The idea of setting datetime column as the index axis is to aid in the conversion of the Timestamp value to it's corresponding datetime.datetime format equivalent by making use of the convert_datetime64 argument in DF.to_records which does so for a DateTimeIndex dataframe.

This returns a recarray which could be then made to return a list using .tolist


More generalized solution depending on the use case would be:

df.to_records().tolist()                              # Supply index=False to exclude index

How to list all databases in the mongo shell?

Listing all the databases in mongoDB console is using the command show dbs.

For more information on this, refer the Mongo Shell Command Helpers that can be used in the mongo shell.

How can I apply a border only inside a table?

If you are doing what I believe you are trying to do, you'll need something a little more like this:

table {
  border-collapse: collapse;
}
table td, table th {
  border: 1px solid black;
}
table tr:first-child th {
  border-top: 0;
}
table tr:last-child td {
  border-bottom: 0;
}
table tr td:first-child,
table tr th:first-child {
  border-left: 0;
}
table tr td:last-child,
table tr th:last-child {
  border-right: 0;
}

jsFiddle Demo

The problem is that you are setting a 'full border' around all the cells, which make it appear as if you have a border around the entire table.

Cheers.

EDIT: A little more info on those pseudo-classes can be found on quirksmode, and, as to be expected, you are pretty much S.O.L. in terms of IE support.

'nuget' is not recognized but other nuget commands working

Retrieve nuget.exe from https://www.nuget.org/downloads. Copy it to a local folder and add that folder to the PATH environment variable.

This is will make nuget available globally, from any project.

How to read keyboard-input?

Non-blocking, multi-threaded example:

As blocking on keyboard input (since the input() function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.

This works by creating one thread to run in the background, continually calling input() and then passing any data it receives to a queue.

In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.

1. Bare Python 3 code example (no comments):

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()

2. Same Python 3 code as above, but with extensive explanatory comments:

"""
read_keyboard_input.py

Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018

References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html

To install PySerial: `sudo python3 -m pip install pyserial`

To run this program: `python3 this_filename.py`

"""

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        # Receive keyboard input from user.
        input_str = input()
        
        # Enqueue this input string.
        # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them 
        # which would otherwise need to be treated as one atomic operation.
        inputQueue.put(input_str)

def main():

    EXIT_COMMAND = "exit" # Command to exit this program

    # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
    # method calls in a row.  Use this if you have such a need, as follows:
    # 1. Pass queueLock as an input parameter to whichever function requires it.
    # 2. Call queueLock.acquire() to obtain the lock.
    # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
    # inputQueue.qsize(), followed by inputQueue.put(), for example.
    # 4. Call queueLock.release() to release the lock.
    # queueLock = threading.Lock() 

    #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
    inputQueue = queue.Queue()

    # Create & start a thread to read keyboard inputs.
    # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
    # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    # Main loop
    while (True):

        # Read keyboard inputs
        # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
        # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
        # example program, no locks are required.
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break # exit the while loop
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
        time.sleep(0.01) 
    
    print("End.")

# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'): 
    main()

Sample output:

$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.

The Python Queue library is thread-safe:

Note that Queue.put() and Queue.get() and other Queue class methods are thread-safe! That means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):

The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

References:

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html
  2. *****https://www.tutorialspoint.com/python/python_multithreading.htm
  3. *****https://en.wikibooks.org/wiki/Python_Programming/Threading
  4. Python: How do I make a subclass from a superclass?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html

Related/Cross-Linked:

  1. PySerial non-blocking read loop