Programs & Examples On #Virtualmode

What are some uses of template template parameters?

Here is a simple example taken from 'Modern C++ Design - Generic Programming and Design Patterns Applied' by Andrei Alexandrescu:

He uses a classes with template template parameters in order to implement the policy pattern:

// Library code
template <template <class> class CreationPolicy>
class WidgetManager : public CreationPolicy<Widget>
{
   ...
};

He explains: Typically, the host class already knows, or can easily deduce, the template argument of the policy class. In the example above, WidgetManager always manages objects of type Widget, so requiring the user to specify Widget again in the instantiation of CreationPolicy is redundant and potentially dangerous.In this case, library code can use template template parameters for specifying policies.

The effect is that the client code can use 'WidgetManager' in a more elegant way:

typedef WidgetManager<MyCreationPolicy> MyWidgetMgr;

Instead of the more cumbersome, and error prone way that a definition lacking template template arguments would have required:

typedef WidgetManager< MyCreationPolicy<Widget> > MyWidgetMgr;

How might I force a floating DIV to match the height of another floating DIV?

Flex does this by default.

<div id="flex">
 <div id="response">
 </div> 
 <div id="note">
 </div>
</div>   

CSS:

#flex{display:flex}
#response{width:65%}
#note{width:35%}

https://jsfiddle.net/784pnojq/1/

BONUS: multiple rows

https://jsfiddle.net/784pnojq/2/

How to compile and run a C/C++ program on the Android system

if you have installed NDK succesfully then start with it sample application

http://developer.android.com/sdk/ndk/overview.html#samples

if you are interested another ways of this then may this will help

http://shareprogrammingtips.blogspot.com/2018/07/cross-compile-cc-based-programs-and-run.html

I also want to know is it possible to push the compiled binary into android device or AVD and run using the terminal of the android device or AVD?

here you can see NestedVM

NestedVM provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes.


Example: Cross compile Hello world C program and run it on android

Difference between TCP and UDP?

Short and simple differences between Tcp and Udp protocol:

1) Tcp - Transmission control protocol and Udp - User datagram protocol.

2) Tcp is reliable protocol, Where as Udp is a unreliable protocol.

3) Tcp is a stream oriented, where as Udp is a message oriented protocol.

4) Tcp is a slower than Udp.

How do you convert a C++ string to an int?

#include <sstream>

// st is input string
int result;
stringstream(st) >> result;

Example for boost shared_mutex (multiple reads/one write)?

It looks like you would do something like this:

boost::shared_mutex _access;
void reader()
{
  // get shared access
  boost::shared_lock<boost::shared_mutex> lock(_access);

  // now we have shared access
}

void writer()
{
  // get upgradable access
  boost::upgrade_lock<boost::shared_mutex> lock(_access);

  // get exclusive access
  boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
  // now we have exclusive access
}

How to Automatically Close Alerts using Twitter Bootstrap

I needed a very simple solution to hide something after sometime and managed to get this to work:

In angular you can do this:

$timeout(self.hideError,2000);

Here is the function that i call when the timeout has been reached

 self.hideError = function(){
   self.HasError = false;
   self.ErrorMessage = '';
};

So now my dialog/ui can use those properties to hide elements.

Finding the source code for built-in Python functions?

2 methods,

  1. You can check usage about snippet using help()
  2. you can check hidden code for those modules using inspect

1) inspect:

use inpsect module to explore code you want... NOTE: you can able to explore code only for modules (aka) packages you have imported

for eg:

  >>> import randint  
  >>> from inspect import getsource
  >>> getsource(randint) # here i am going to explore code for package called `randint`

2) help():

you can simply use help() command to get help about builtin functions as well its code.

for eg: if you want to see the code for str() , simply type - help(str)

it will return like this,

>>> help(str)
Help on class str in module __builtin__:

class str(basestring)
 |  str(object='') -> string
 |
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |
 |  Method resolution order:
 |      str
 |      basestring
 |      object
 |
 |  Methods defined here:
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |
 |  __format__(...)
 |      S.__format__(format_spec) -> string
 |
 |      Return a formatted version of S as described by format_spec.
 |
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |
 |  __getattribute__(...)
-- More  --

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.

Remember to update your password if you've got the option selected 'Run whether user is logged on or not'

How do I put variables inside javascript strings?

Do that:

s = 'hello ' + my_name + ', how are you doing'

Update

With ES6, you could also do this:

s = `hello ${my_name}, how are you doing`

How to call JavaScript function instead of href in HTML

Your should also separate the javascript from the HTML.
HTML:

<a href="#" id="function-click"><img title="next page" alt="next page" src="/themes/me/img/arrn.png"></a>

javascript:

myLink = document.getElementById('function-click');
myLink.onclick = ShowOld(2367,146986,2);

Just make sure the last line in the ShowOld function is:

return false;

as this will stop the link from opening in the browser.

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

For this purpose and if i dont have boolean variable i use the following:

<li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">

how to redirect to home page

_x000D_
_x000D_
var url = location.href;_x000D_
var newurl = url.replace('some-domain.com','another-domain.com';);_x000D_
location.href=newurl;
_x000D_
_x000D_
_x000D_

See this answer https://stackoverflow.com/a/42291014/3901511

Get a UTC timestamp

new Date().getTime();

For more information, see @James McMahon's answer.

How to run SUDO command in WinSCP to transfer files from Windows to linux

I know this is old, but it is actually very possible.

  • Go to your WinSCP profile (Session > Sites > Site Manager)

  • Click on Edit > Advanced... > Environment > SFTP

  • Insert sudo su -c /usr/lib/sftp-server in "SFTP Server" (note this path might be different in your system)

  • Save and connect

Source

AWS Ubuntu 18.04: enter image description here

static files with express.js

If you have this setup

/app
   /public/index.html
   /media

Then this should get what you wanted

var express = require('express');
//var server = express.createServer();
// express.createServer()  is deprecated. 
var server = express(); // better instead
server.configure(function(){
  server.use('/media', express.static(__dirname + '/media'));
  server.use(express.static(__dirname + '/public'));
});

server.listen(3000);

The trick is leaving this line as last fallback

  server.use(express.static(__dirname + '/public'));

As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.

For example this line shows that index.html is supported https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

TextAppearance.Holo.Widget.ActionBar.Title appears to have been added in API Level 13. Make sure your build target is set to 13, not just 11.

AngularJS : How do I switch views from a controller function?

Without doing a full revamp of the default routing (#/ViewName) environment, I was able to do a slight modification of Cody's tip and got it working great.

the controller

.controller('GeneralCtrl', ['$route', '$routeParams', '$location',
        function($route, $routeParams, $location) {
            ...
            this.goToView = function(viewName){
                $location.url('/' + viewName);
            }
        }]
    );

the view

...
<li ng-click="general.goToView('Home')">HOME</li>
...

What brought me to this solution was when I was attempting to integrate a Kendo Mobile UI widget into an angular environment I was losing the context of my controller and the behavior of the regular anchor tag was also being hijacked. I re-established my context from within the Kendo widget and needed to use a method to navigate...this worked.

Thanks for the previous posts!

Export DataBase with MySQL Workbench with INSERT statements

In MySQL Workbench 6.1.

I had to click on the Apply changes button in the insertion panel (only once, because twice and MWB crashes...).

You have to do it for each of your table.

Apply changes button

Then export your schema :

Export schema

Check Generate INSERT statements for table

Check INSERT

It is okay !

Inserts ok

How do I read a file line by line in VB Script?

If anyone like me is searching to read only a specific line, example only line 18 here is the code:

filename = "C:\log.log"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 17
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close

How to detect a remote side socket close?

Since the answers deviate I decided to test this and post the result - including the test example.

The server here just writes data to a client and does not expect any input.

The server:

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
  out.println("output");
  if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
  System.out.println(clientSocket.isConnected());
  System.out.println(clientSocket.getInputStream().read());
        // thread sleep ...
  // break condition , close sockets and the like ...
}
  • clientSocket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • out.checkError() is true as soon as the client is disconnected so I recommend this

What are the main performance differences between varchar and nvarchar SQL Server data types?

Why, in all this discussion, has there been no mention of UTF-8? Being able to store the full unicode span of characters does not mean one has to always allocate two-bytes-per-character (or "code point" to use the UNICODE term). All of ASCII is UTF-8. Does SQL Server check for VARCHAR() fields that the text is strict ASCII (i.e. top byte bit zero)? I would hope not.

If then you want to store unicode and want compatibility with older ASCII-only applications, I would think using VARCHAR() and UTF-8 would be the magic bullet: It only uses more space when it needs to.

For those of you unfamiliar with UTF-8, might I recommend a primer.

No Main class found in NetBeans

Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.

public static void main(String[] args)

ios simulator: how to close an app

Window / Show Device Bezels

And now you can see the real device, so double tap on HOME button and kill you app

How to change the status bar color in Android?

Well, Izhar solution was OK but, personally, I am trying to avoid from code that looks as this:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//Do what you need for this SDK
};

As well, I don't like to duplicate code either. In your answer I have to add such line of code in all Activities:

setStatusBarColor(findViewById(R.id.statusBarBackground),getResources().getColor(android.R.color.white));

So, I took Izhar solution and used XML to get the same result: Create a layout for the StatusBar status_bar.xml

<View xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="@dimen/statusBarHeight"
     android:background="@color/primaryColorDark"
     android:elevation="@dimen/statusBarElevation">

Notice the height and elevation attributes, these will be set in values, values-v19, values-v21 further down.

Add this layout to your activities layout using include, main_activity.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/Black" >

<include layout="@layout/status_bar"/>
<include android:id="@+id/app_bar" layout="@layout/app_bar"/>
//The rest of your layout       
</RelativeLayout>

For the Toolbar, add top margin attribute:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="@color/primaryColor"
app:theme="@style/MyCustomToolBarTheme"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
android:elevation="@dimen/toolbarElevation"
android:layout_marginTop="@dimen/appBarTopMargin"
android:textDirection="ltr"
android:layoutDirection="ltr">

In your appTheme style-v19.xml and styles-v21.xml, add the windowTranslucent attr:

styles-v19.xml, v21:

<resources>
<item name="android:windowTranslucentStatus">true</item>
</resources>

And finally, on your dimens, dimens-v19, dimens-v21, add the values for the Toolbar topMargin, and the height of the statusBarHeight: dimens.xml for less than KitKat:

<resources>
<dimen name="toolbarElevation">4dp</dimen>
<dimen name="appBarTopMargin">0dp</dimen>
<dimen name="statusBarHeight">0dp</dimen>
</resources>

The status bar height is always 24dp dimens-v19.xml for KitKat and above:

<resources>
<dimen name="statusBarHeight">24dp</dimen>
<dimen name="appBarTopMargin">24dp</dimen>
</resources>

dimens-v21.xml for Lolipop, just add the elevation if needed:

<resources>
<dimen name="statusBarElevation">4dp</dimen>
</resources>

This is the result for Jellybean KitKat and Lollipop:

enter image description here

Adding a new array element to a JSON object

In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.

  elementToPush = [1, 2, 3]
  if (!obj.arr) this.$set(obj, "arr", [])
  obj.arr.push(elementToPush)  

(This answer may not be relevant to this particular question, but may help someone else)

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

Alter a MySQL column to be AUTO_INCREMENT

You must specify the type of the column before the auto_increment directive, i.e. ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT.

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Jquery-How to grey out the background while showing the loading icon over it

Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.

If the gif is displayed but not animating, see reference links at very bottom of this answer.

Displaying the gif + overlay, however, is easier than you might think.

All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.

So, when the button is pressed, just unhide those two divs. That's it!

jsFiddle Demo

_x000D_
_x000D_
$("#button").click(function() {_x000D_
    $('#myOverlay').show();_x000D_
    $('#loadingGIF').show();_x000D_
    setTimeout(function(){_x000D_
   $('#myOverlay, #loadingGIF').fadeOut();_x000D_
    },2500);_x000D_
});_x000D_
/*  Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
 $('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Update:

You might enjoy playing with the new backdrop-filter:blur(_px) css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)

References:

http://www.paulirish.com/2007/animated-gif-not-animating/

Animated GIF while loading page does not animate

https://wordpress.org/support/topic/animated-gif-not-working

http://forums.mozillazine.org/viewtopic.php?p=987829

Check if string ends with one of the strings from a list

Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

ImportError: No module named PIL

This worked for me on Ubuntu 16.04:

sudo apt-get install python-imaging

I found this on Wikibooks after searching for about half an hour.

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

How can I do division with variables in a Linux shell?

Those variables are shell variables. To expand them as parameters to another program (ie expr), you need to use the $ prefix:

expr $x / $y

The reason it complained is because it thought you were trying to operate on alphabetic characters (ie non-integer)

If you are using the Bash shell, you can achieve the same result using expression syntax:

echo $((x / y))

Or:

z=$((x / y))
echo $z

How to get all files under a specific directory in MATLAB?

This answer does not directly answer the question but may be a good solution outside of the box.

I upvoted gnovice's solution, but want to offer another solution: Use the system dependent command of your operating system:

tic
asdfList = getAllFiles('../TIMIT_FULL/train');
toc
% Elapsed time is 19.066170 seconds.

tic
[status,cmdout] = system('find ../TIMIT_FULL/train/ -iname "*.wav"');
C = strsplit(strtrim(cmdout));
toc
% Elapsed time is 0.603163 seconds.

Positive:

  • Very fast (in my case for a database of 18000 files on linux).
  • You can use well tested solutions.
  • You do not need to learn or reinvent a new syntax to select i.e. *.wav files.

Negative:

  • You are not system independent.
  • You rely on a single string which may be hard to parse.

How to get the URL without any parameters in JavaScript?

Just one more alternative using URL

var theUrl = new URL(window.location.href);
theUrl.search = ""; //Remove any params
theUrl //as URL object
theUrl.href //as a string

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL

) 

Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

For everybody who uses Rider you have to select your project>Right Click>Properties>Configurations Then select Debug and Release and check "Allow unsafe code" for both.Screenshot

Android OnClickListener - identify a button

You will learn the way to do it, in an easy way, is:

public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler1);
    b2.setOnClickListener(myhandler2);
    ...
  }
  View.OnClickListener myhandler1 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 1st button
    }
  };
  View.OnClickListener myhandler2 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 2nd button
    }
  };
}

Or, if you are working with just one clicklistener, you can do:

View.OnClickListener myOnlyhandler = new View.OnClickListener() {
  public void onClick(View v) {
      switch(v.getId()) {
        case R.id.b1:
          // it was the first button
          break;
        case R.id.b2:
          // it was the second button
          break;
      }
  }
}

Though, I don't recommend doing it that way since you will have to add an if for each button you use. That's hard to maintain.

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

Inline styling would work in any case

  <p-column field="Quantity" header="Qté" [style]="{'width':'48px'}">

Websocket connections with Postman

You can use Socket.io tester, this app lets you connect to a socket.io server and subscribe to a certain topic and/or lets you send socket messages to the server

What LaTeX Editor do you suggest for Linux?

There is a pretty good list at linuxappfinder.com.

My personal preference for LaTeX on Linux has been the KDE-based editor Kile.

add new element in laravel collection object

If you want to add a product into the array you can use:

$item['product'] = $product;

Git push requires username and password

You basically have two options.

If you use the same user on both machines you need to copy the .pub key to your PC, so GitHub knows that you are the same user.

If you have created a new .pub file for your PC and want to treat the machines as different users, you need to register the new .pub file on the GitHub website.

If this still doesn't work it might be because ssh is not configured correctly and that ssh fail to find the location of your keys. Try

ssh -vv [email protected]

To get more information why SSH fails.

How to replace blank (null ) values with 0 for all records?

I would change the SQL statement above to be more generic. Using wildcards is never a bad idea when it comes to mass population to avoid nulls.

Try this:

Update Table Set * = 0 Where * Is Null; 

Handling null values in Freemarker

If you have a lot of variables to convert in optional, you can use SubimeText with this:

Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}

Be sure regex and case-sensitive options are enabled:

Sublime regex replace

Amazon AWS Filezilla transfer permission denied

In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

A great Spring MVC quickstart archetype is available on GitHub, courtesy of kolorobot. Good instructions are provided on how to install it to your local Maven repo and use it to create a new Spring MVC project. He’s even helpfully included the Tomcat 7 Maven plugin in the archetypical project so that the newly created Spring MVC can be run from the command line without having to manually deploy it to an application server.

Kolorobot’s example application includes the following:

  • No-xml Spring MVC 3.2 web application for Servlet 3.0 environment
  • Apache Tiles with configuration in place,
  • Bootstrap
  • JPA 2.0 (Hibernate/HSQLDB)
  • JUnit/Mockito
  • Spring Security 3.1

How do you set the title color for the new Toolbar?

Very simple, this worked for me (title and icon white):

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/PrimaryColor"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:elevation="4dp" />

Eloquent ->first() if ->exists()

Note: The first() method doesn't throw an exception as described in the original question. If you're getting this kind of exception, there is another error in your code.

The correct way to user first() and check for a result:

$user = User::where('mobile', Input::get('mobile'))->first(); // model or null
if (!$user) {
   // Do stuff if it doesn't exist.
}

Other techniques (not recommended, unnecessary overhead):

$user = User::where('mobile', Input::get('mobile'))->get();

if (!$user->isEmpty()){
    $firstUser = $user->first()
}

or

try {
    $user = User::where('mobile', Input::get('mobile'))->firstOrFail();
    // Do stuff when user exists.
} catch (ErrorException $e) {
    // Do stuff if it doesn't exist.
}

or

// Use either one of the below. 
$users = User::where('mobile', Input::get('mobile'))->get(); //Collection

if (count($users)){
    // Use the collection, to get the first item use $users->first().
    // Use the model if you used ->first();
}

Each one is a different way to get your required result.

Python requests library how to pass Authorization header with single token

In python:

('<MY_TOKEN>')

is equivalent to

'<MY_TOKEN>'

And requests interprets

('TOK', '<MY_TOKEN>')

As you wanting requests to use Basic Authentication and craft an authorization header like so:

'VE9LOjxNWV9UT0tFTj4K'

Which is the base64 representation of 'TOK:<MY_TOKEN>'

To pass your own header you pass in a dictionary like so:

r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})

Setting width and height

The below worked for me - but dont forget to put this in the "options" param.

var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
    maintainAspectRatio: false,
    responsive:true,
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}
});

How to get the id of the element clicked using jQuery

update as you loading contents dynamically so you use.

$(document).on('click', 'span', function () {
    alert(this.id);
});

old code

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

or you can use .on

$('span').on('click', function () {
    alert(this.id);
});

this refers to current span element clicked

this.id will give the id of the current span clicked

What is a Python egg?

Note: Egg packaging has been superseded by Wheel packaging.

Same concept as a .jar file in Java, it is a .zip file with some metadata files renamed .egg, for distributing code as bundles.

Specifically: The Internal Structure of Python Eggs

A "Python egg" is a logical structure embodying the release of a specific version of a Python project, comprising its code, resources, and metadata. There are multiple formats that can be used to physically encode a Python egg, and others can be developed. However, a key principle of Python eggs is that they should be discoverable and importable. That is, it should be possible for a Python application to easily and efficiently find out what eggs are present on a system, and to ensure that the desired eggs' contents are importable.

The .egg format is well-suited to distribution and the easy uninstallation or upgrades of code, since the project is essentially self-contained within a single directory or file, unmingled with any other projects' code or resources. It also makes it possible to have multiple versions of a project simultaneously installed, such that individual programs can select the versions they wish to use.

How to change FontSize By JavaScript?

JavaScript is case sensitive.

So, if you want to change the font size, you have to go:

span.style.fontSize = "25px";

Nested JSON objects - do I have to use arrays for everything?

Every object has to be named inside the parent object:

{ "data": {
    "stuff": {
        "onetype": [
            { "id": 1, "name": "" },
            { "id": 2, "name": "" }
        ],
        "othertype": [
            { "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
        ]
    },
    "otherstuff": {
        "thing":
            [[1, 42], [2, 2]]
    }
}
}

So you cant declare an object like this:

var obj = {property1, property2};

It has to be

var obj = {property1: 'value', property2: 'value'};

Prevent text selection after double click

or, on mozilla:

document.body.onselectstart = function() { return false; } // Or any html object

On IE,

document.body.onmousedown = function() { return false; } // valid for any html object as well

How to beautify JSON in Python?

I didn't like the output of json.dumps(...) -> For my taste way too much newlines. And I didn't want to use a command line tool or install something. I finally found Pythons pprint (= pretty print). Unfortunately it doesn't generate proper JSON but I think it is useful to have a user friendly glympse at the stored data.

Output of json.dumps(json_dict, indent=4)

{
    "hyperspace": {
        "constraints": [],
        "design": [
            [
                "windFarm.windparkSize.k",
                "continuous",
                [
                    0,
                    0,
                    5
                ]
            ],
            [
                "hydroPlant.primaryControlMax",
                "continuous",
                [
                    100,
                    300
                ]
            ]
        ],
        "kpis": [
            "frequency.y",
            "city.load.p[2]"
        ]
    },
    "lhc_size": 10,
    "number_of_runs": 10
}

Usage of pprint:

import pprint

json_dict = {"hyperspace": {"constraints": [], "design": [["windFarm.windparkSize.k", "continuous", [0, 0, 5]], ["hydroPlant.primaryControlMax", "continuous", [100, 300]]], "kpis": ["frequency.y", "city.load.p[2]"]}, "lhc_size": 10, "number_of_runs": 10}

formatted_json_str = pprint.pformat(json_dict)
print(formatted_json_str)
pprint.pprint(json_dict)

Result of pprint.pformat(...) or pprint.pprint(...):

{'hyperspace': {'constraints': [],
                'design': [['windFarm.windparkSize.k', 'continuous', [0, 0, 5]],
                           ['hydroPlant.primaryControlMax',
                            'continuous',
                            [100, 300]]],
                'kpis': ['frequency.y', 'city.load.p[2]']},
 'lhc_size': 10,
 'number_of_runs': 10}

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

Run cURL commands from Windows console

I have also found that if I put the cygwin bin on my windows path I can run curl from a windows command line. It also will give you access to things like ls and grep

How to check if an app is installed from a web-page on an iPhone?

I need to do something like this I ended up going with the following solution.

I have a specific website URL that will open a page with two buttons

1) Button One go to website

2) Button Two go to application (iphone / android phone / tablet) you can fall back to a default location from here if the app is not installed (like another url or an app store)

3) cookie to remember users choice

<head>
<title>Mobile Router Example </title>


<script type="text/javascript">
    function set_cookie(name,value)
    {
       // js code to write cookie
    }
    function read_cookie(name) {
       // jsCode to read cookie
    }

    function goToApp(appLocation) {
        setTimeout(function() {
            window.location = appLocation;
              //this is a fallback if the app is not installed. Could direct to an app store or a website telling user how to get app


        }, 25);
        window.location = "custom-uri://AppShouldListenForThis";
    }

    function goToWeb(webLocation) {
        window.location = webLocation;
    }

    if (readCookie('appLinkIgnoreWeb') == 'true' ) {
        goToWeb('http://somewebsite');

    }
    else if (readCookie('appLinkIgnoreApp') == 'true') {
        goToApp('http://fallbackLocation');
    }



</script>
</head>
<body>


<div class="iphone_table_padding">
<table border="0" cellspacing="0" cellpadding="0" style="width:100%;">
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <!-- INTRO -->
            <span class="iphone_copy_intro">Check out our new app or go to website</span>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_btn_padding">

                <!-- GET IPHONE APP BTN -->
                <table border="0" cellspacing="0" cellpadding="0" class="iphone_btn" onclick="set_cookie('appLinkIgnoreApp',document.getElementById('chkDontShow').checked);goToApp('http://getappfallback')">
                    <tr>
                        <td class="iphone_btn_on_left">&nbsp;</td>
                        <td class="iphone_btn_on_mid">
                            <span class="iphone_copy_btn">
                                Get The Mobile Applications
                            </span>
                        </td>
                        <td class="iphone_btn_on_right">&nbsp;</td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_btn_padding">

                <table border="0" cellspacing="0" cellpadding="0" class="iphone_btn"  onclick="set_cookie('appLinkIgnoreWeb',document.getElementById('chkDontShow').checked);goToWeb('http://www.website.com')">
                    <tr>
                        <td class="iphone_btn_left">&nbsp;</td>
                        <td class="iphone_btn_mid">
                            <span class="iphone_copy_btn">
                                Visit Website.com
                            </span>
                        </td>
                        <td class="iphone_btn_right">&nbsp;</td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_chk_padding">

                <!-- CHECK BOX -->
                <table border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td><input type="checkbox" id="chkDontShow" /></td>
                        <td>
                            <span class="iphone_copy_chk">
                                <label for="chkDontShow">&nbsp;Don&rsquo;t show this screen again.</label>
                            </span>
                        </td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
</table>

</div>

</body>
</html>

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

How to access PHP session variables from jQuery function in a .js file?

I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :

In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing : <p id="sessionOrigin"><?=$_SESSION['origin'];?></p>

In your js, using jQuery you can access it like so : $("#sessionOrigin").text();

EDIT: or even better, put it in a hidden input

<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>

How to force JS to do math instead of putting two strings together

I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value

example:

var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

dots = document.getElementById("txt").value;

could be changed to

dots = +(document.getElementById("txt").value);

to force it to a number

NOTE:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

How to get href value using jQuery?

You can get current href value by this code:

$(this).attr("href");

To get href value by ID

$("#mylink").attr("href");

Angular 4 default radio button checked by default

We can use [(ngModel)] in following way and have a value selection variable radioSelected

Example tutorial

Demo Link

app.component.html

  <div class="text-center mt-5">
  <h4>Selected value is {{radioSel.name}}</h4>

  <div>
    <ul class="list-group">
          <li class="list-group-item"  *ngFor="let item of itemsList">
            <input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/> 
            {{item.name}}

          </li>
    </ul>
  </div>


  <h5>{{radioSelectedString}}</h5>

  </div>

app.component.ts

  import {Item} from '../app/item';
  import {ITEMS} from '../app/mock-data';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent {
    title = 'app';
    radioSel:any;
    radioSelected:string;
    radioSelectedString:string;
    itemsList: Item[] = ITEMS;


      constructor() {
        this.itemsList = ITEMS;
        //Selecting Default Radio item here
        this.radioSelected = "item_3";
        this.getSelecteditem();
      }

      // Get row item from array  
      getSelecteditem(){
        this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
        this.radioSelectedString = JSON.stringify(this.radioSel);
      }
      // Radio Change Event
      onItemChange(item){
        this.getSelecteditem();
      }

  }

Sample Data for Listing

        export const ITEMS: Item[] = [
            {
                name:'Item 1',
                value:'item_1'
            },
            {
                name:'Item 2',
                value:'item_2'
            },
            {
                name:'Item 3',
                value:'item_3'
            },
            {
                name:'Item 4',
                value:'item_4'
                },
                {
                    name:'Item 5',
                    value:'item_5'
                }
        ];

Cannot import keras after installation

Ran to the same issue, Assuming your using anaconda3 and your using a venv with >= python=3.6:

python -m pip install keras
sudo python -m pip install --user tensorflow

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:

@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface

But regardless of which method you use, the annotations are not being processed (not even your @Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with @RunWith(MockitoJUnitRunner.class).

bootstrap jquery show.bs.modal event won't fire

Below are the granular details:

show.bs.modal works while model dialog loading shown.bs.modal worked to do any thing after loading. post rendering

How to SUM and SUBTRACT using SQL?

I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.

-- Loan Outstanding
    select  'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
    from
    (
        select 
            sum(laod.dr) as Unit,
            sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
            sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
            sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
        from loan_account_opening as lao
        inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
        where lao.organization = 3
        union
        select
            sum(lr.installment)*-1 as Unit,
            sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
            sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
            sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
        from loan_recovery as lr
        inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
        where lo.organization = 3
    ) as t3

Convert to binary and keep leading zeros in Python

You can use the string formatting mini language:

def binary(num, pre='0b', length=8, spacer=0):
    return '{0}{{:{1}>{2}}}'.format(pre, spacer, length).format(bin(num)[2:])

Demo:

print binary(1)

Output:

'0b00000001'

EDIT: based on @Martijn Pieters idea

def binary(num, length=8):
    return format(num, '#0{}b'.format(length + 2))

How to generate random positive and negative numbers in Java

([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))

example:

// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

Getting All Variables In Scope

No. "In scope" variables are determined by the "scope chain", which is not accessible programmatically.

For detail (quite a lot of it), check out the ECMAScript (JavaScript) specification. Here's a link to the official page where you can download the canonical spec (a PDF), and here's one to the official, linkable HTML version.

Update based on your comment to Camsoft

The variables in scope for your event function are determined by where you define your event function, not how they call it. But, you may find useful information about what's available to your function via this and arguments by doing something along the lines of what KennyTM pointed out (for (var propName in ____)) since that will tell you what's available on various objects provided to you (this and arguments; if you're not sure what arguments they give you, you can find out via the arguments variable that's implicitly defined for every function).

So in addition to whatever's in-scope because of where you define your function, you can find out what else is available by other means by doing:

var n, arg, name;
alert("typeof this = " + typeof this);
for (name in this) {
    alert("this[" + name + "]=" + this[name]);
}
for (n = 0; n < arguments.length; ++n) {
    arg = arguments[n];
    alert("typeof arguments[" + n + "] = " + typeof arg);
    for (name in arg) {
        alert("arguments[" + n + "][" + name + "]=" + arg[name]);
    }
}

(You can expand on that to get more useful information.)

Instead of that, though, I'd probably use a debugger like Chrome's dev tools (even if you don't normally use Chrome for development) or Firebug (even if you don't normally use Firefox for development), or Dragonfly on Opera, or "F12 Developer Tools" on IE. And read through whatever JavaScript files they provide you. And beat them over the head for proper docs. :-)

Multiple lines of text in UILabel

The best solution I have found (to an otherwise frustrating problem that should have been solved in the framework) is similar to vaychick's.

Just set number of lines to 0 in either IB or code

myLabel.numberOfLines = 0;

This will display the lines needed but will reposition the label so its centered horizontally (so that a 1 line and 3 line label are aligned in their horizontal position). To fix that add:

CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode]; 
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;

Is there a timeout for idle PostgreSQL connections?

It sounds like you have a connection leak in your application because it fails to close pooled connections. You aren't having issues just with <idle> in transaction sessions, but with too many connections overall.

Killing connections is not the right answer for that, but it's an OK-ish temporary workaround.

Rather than re-starting PostgreSQL to boot all other connections off a PostgreSQL database, see: How do I detach all other users from a postgres database? and How to drop a PostgreSQL database if there are active connections to it? . The latter shows a better query.

For setting timeouts, as @Doon suggested see How to close idle connections in PostgreSQL automatically?, which advises you to use PgBouncer to proxy for PostgreSQL and manage idle connections. This is a very good idea if you have a buggy application that leaks connections anyway; I very strongly recommend configuring PgBouncer.

A TCP keepalive won't do the job here, because the app is still connected and alive, it just shouldn't be.

In PostgreSQL 9.2 and above, you can use the new state_change timestamp column and the state field of pg_stat_activity to implement an idle connection reaper. Have a cron job run something like this:

SELECT pg_terminate_backend(pid)
    FROM pg_stat_activity
    WHERE datname = 'regress'
      AND pid <> pg_backend_pid()
      AND state = 'idle'
      AND state_change < current_timestamp - INTERVAL '5' MINUTE;

In older versions you need to implement complicated schemes that keep track of when the connection went idle. Do not bother; just use pgbouncer.

How to make a programme continue to run after log out from ssh?

Assuming that you have a program running in the foreground, press ctrl-Z, then:

[1]+  Stopped                 myprogram
$ disown -h %1
$ bg 1
[1]+ myprogram &
$ logout

If there is only one job, then you don't need to specify the job number. Just use disown -h and bg.

Explanation of the above steps:

You press ctrl-Z. The system suspends the running program, displays a job number and a "Stopped" message and returns you to a bash prompt.

You type the disown -h %1 command (here, I've used a 1, but you'd use the job number that was displayed in the Stopped message) which marks the job so it ignores the SIGHUP signal (it will not be stopped by logging out).

Next, type the bg command using the same job number; this resumes the running of the program in the background and a message is displayed confirming that.

You can now log out and it will continue running..

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

Behaviour of increment and decrement operators in Python

When you want to increment or decrement, you typically want to do that on an integer. Like so:

b++

But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:

>>> b = 5
>>> a = 5
>>> id(a)
162334512
>>> id(b)
162334512
>>> a is b
True

a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:

b = b + 1

Or simpler:

b += 1

Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.

In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.

Python - How do you run a .py file?

Your command should include the url parameter as stated in the script usage comments. The main function has 2 parameters, url and out (which is set to a default value) C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"

Enable SQL Server Broker taking too long

USE master;
GO
ALTER DATABASE Database_Name
    SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
GO
USE Database_Name;
GO

UICollectionView current visible cell index

For Swift 3.0

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let visibleRect = CGRect(origin: colView.contentOffset, size: colView.bounds.size)
    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
    let indexPath = colView.indexPathForItem(at: visiblePoint)
}

How to check sbt version?

sbt about then enter to get SBT version

enter image description here

Removing special characters VBA Excel

Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

Python loop counter in a for loop

I'll sometimes do this:

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.

How to remove all MySQL tables from the command-line without DROP database permissions?

You can generate statement like this: DROP TABLE t1, t2, t3, ... and then use prepared statements to execute it:

SET FOREIGN_KEY_CHECKS = 0; 
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
  FROM information_schema.tables 
  WHERE table_schema = 'database_name'; -- specify DB name here.

SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1; 

Generate HTML table from 2D JavaScript array

Generate table and support HTML as input.

Inspired by @spiny-norman https://stackoverflow.com/a/15164796/2326672

And @bornd https://stackoverflow.com/a/6234804/2326672

function escapeHtml(unsafe) {
    return String(unsafe)
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

function makeTableHTML(myArray) {
    var result = "<table border=1>";
    for(var i=0; i<myArray.length; i++) {
        result += "<tr>";
        for(var j=0; j<myArray[i].length; j++){
            k = escapeHtml((myArray[i][j]));
            result += "<td>"+k+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";

    return result;
}

Test here with JSFIDDLE - Paste directly from Microsoft Excel to get table

Finding index of character in Swift String

If you only need the index of a character the most simple, quick solution (as already pointed out by Pascal) is:

let index = string.characters.index(of: ".")
let intIndex = string.distance(from: string.startIndex, to: index)

How to strip a specific word from a string?

Easiest way would be to simply replace it with an empty string.

s = s.replace('papa', '')

Two dimensional array list

for (Project project : listOfLists) {
    String nama_project = project.getNama_project();
    if (project.getModelproject().size() > 1) {
        for (int i = 1; i < project.getModelproject().size(); i++) {
            DataModel model = project.getModelproject().get(i);
            int id_laporan = model.getId();
            String detail_pekerjaan = model.getAlamat();
        }
    }
}

CSS Background image not loading

I had the same issue. The problem ended up being the path to the image file. Make sure the image path is relative to the location of the CSS file instead of the HTML.

How to implement a Map with multiple keys?

Another possile solution providing the possibility of more complicated keys can be found here: http://insidecoffe.blogspot.de/2013/04/indexable-hashmap-implementation.html

html form - make inputs appear on the same line

Try just putting a div around the first and last name inputs/labels like this:

<div class="name">
        <label for="First_Name">First Name:</label>
        <input name="first_name" id="First_Name" type="text" />

        <label for="Name">Last Name:</label>
        <input name="last_name" id="Last_Name" type="text" /> 
</div>

Look at the fiddle here: http://jsfiddle.net/XAkXg/

XAMPP on Windows - Apache not starting

I spent over 3 hours to find out solution. Actually port 80 was being used by "system" service so I tried to change port from 80 to 8080 in "httpd" file but same problem raised "port 80 is used by system". It had driven me mad for 3 hours as every thing was changed like port , localhost server etc pointing to 8080.

At last I found mistake that was server root. Basically "Server Root" in "httpd" should be pointing to apache foler of xampp. In my case that's was

ServerRoot "xampp/apache"

I just changed it as follows:

ServerRoot "C:/xampp/apache" 

It has worked successfully and now everything is running with OK status.

How can I send mail from an iPhone application

On iOS 3.0 and later you should use the MFMailComposeViewController class, and the MFMailComposeViewControllerDelegate protocol, that is tucked away in the MessageUI framework.

First add the framework and import:

#import <MessageUI/MFMailComposeViewController.h>

Then, to send a message:

MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"My Subject"];
[controller setMessageBody:@"Hello there." isHTML:NO]; 
if (controller) [self presentModalViewController:controller animated:YES];
[controller release];

Then the user does the work and you get the delegate callback in time:

- (void)mailComposeController:(MFMailComposeViewController*)controller  
          didFinishWithResult:(MFMailComposeResult)result 
                        error:(NSError*)error;
{
  if (result == MFMailComposeResultSent) {
    NSLog(@"It's away!");
  }
  [self dismissModalViewControllerAnimated:YES];
}

Remember to check if the device is configured for sending email:

if ([MFMailComposeViewController canSendMail]) {
  // Show the composer
} else {
  // Handle the error
}

Getting each individual digit from a whole integer

RGB values fall nicely on bit boundaries; decimal digits don't. I don't think there's an easy way to do this using bitwise operators at all. You'd need to use decimal operators like modulo 10 (% 10).

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

This is how I do it in FreeBSD:

#!/usr/local/bin/bash
for i in $(ipcs -a | grep "^s" | awk '{ print $2 }');
do
        echo "ipcrm -s $i"
        ipcrm -s $i
done

How to programmatically disable page scrolling with jQuery

you can use this code:

$("body").css("overflow", "hidden");

How to place a JButton at a desired location in a JFrame using Java

You should set layout first by syntax pnlButton.setLayout(), and then choose the most suitable layout which u want. Ex: pnlButton.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));. And then, take that JButton into JPanel.

How to detect if a browser is Chrome using jQuery?

User Endless is right,

$.browser.chrome = (typeof window.chrome === "object"); 

code is best to detect Chrome browser using jQuery.

If you using IE and added GoogleFrame as plugin then

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

code will treat as Chrome browser because GoogleFrame plugin modifying the navigator property and adding chromeframe inside it.

Truncating Text in PHP?

$text="abc1234567890";

// truncate to 4 chars

echo substr(str_pad($text,4),0,4);

This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)

html5 audio player - jquery toggle click play/pause?

Well, I'm not 100% sure, but I don't think jQuery extends/parses those functions and attributes (.paused, .pause(), .play()).

try to access those over the DOM element, like:

$('.player_audio').click(function() {
  if (this.paused == false) {
      this.pause();
      alert('music paused');
  } else {
      this.play();
      alert('music playing');
  }
});

How to deal with http status codes other than 200 in Angular 2

Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs for the same like this way

import {Observable} from 'rxjs/Rx';

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status === 500) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 400) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 409) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 406) {
                    return Observable.throw(new Error(error.status));
                }
            });
    }

also you can handel error (with err block) that is throw by catch block while .map function,

like this -

...
.subscribe(res=>{....}
           err => {//handel here});

Update

as required for any status without checking particluar one you can try this: -

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status < 400 ||  error.status ===500) {
                    return Observable.throw(new Error(error.status));
                }
            })
            .subscribe(res => {...},
                       err => {console.log(err)} );

How to serve up a JSON response using Go?

You can set your content-type header so clients know to expect json

w.Header().Set("Content-Type", "application/json")

Another way to marshal a struct to json is to build an encoder using the http.ResponseWriter

// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)

"End of script output before headers" error in Apache

Since no answer is accepted, I would like to provide one possible solution. If your script is written on Windows and uploaded to a Linux server(through FTP), then the problem will raise usually. The reason is that Windows uses CRLF to end each line while Linux uses LF. So you should convert it from CRLF to LF with the help of an editor, such Atom, as following enter image description here

How to host google web fonts on my own server?

I wrote a bash script that fetches the CSS file on Google's servers with different user agents, downloads the different font formats to a local directory and writes a CSS file including them. Note that the script needs Bash version 4.x.

See https://neverpanic.de/blog/2014/03/19/downloading-google-web-fonts-for-local-hosting/ for the script (I'm not reproducing it here so I only have to update it in one place when I need to).

Edit: Moved to https://github.com/neverpanic/google-font-download

Transpose list of lists

Three options to choose from:

1. Map with Zip

solution1 = map(list, zip(*l))

2. List Comprehension

solution2 = [list(i) for i in zip(*l)]

3. For Loop Appending

solution3 = []
for i in zip(*l):
    solution3.append((list(i)))

And to view the results:

print(*solution1)
print(*solution2)
print(*solution3)

# [1, 4, 7], [2, 5, 8], [3, 6, 9]

Insert current date/time using now() in a field using MySQL/PHP

NOW() normally works in SQL statements and returns the date and time. Check if your database field has the correct type (datetime). Otherwise, you can always use the PHP date() function and insert:

date('Y-m-d H:i:s')

But I wouldn't recommend this.

What's the canonical way to check for type in Python?

Here is an example why duck typing is evil without knowing when it is dangerous. For instance: Here is the Python code (possibly omitting proper indenting), note that this situation is avoidable by taking care of isinstance and issubclassof functions to make sure that when you really need a duck, you don't get a bomb.

class Bomb:
    def __init__(self):
        ""

    def talk(self):
        self.explode()

    def explode(self):
        print "BOOM!, The bomb explodes."

class Duck:
    def __init__(self):
        ""
    def talk(self):
        print "I am a duck, I will not blow up if you ask me to talk."    

class Kid:
    kids_duck = None

    def __init__(self):
        print "Kid comes around a corner and asks you for money so he could buy a duck."

    def takeDuck(self, duck):
        self.kids_duck = duck
        print "The kid accepts the duck, and happily skips along"

    def doYourThing(self):
        print "The kid tries to get the duck to talk"
        self.kids_duck.talk()

myKid = Kid()
myBomb = Bomb()
myKid.takeDuck(myBomb)
myKid.doYourThing()

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

Apply CSS to jQuery Dialog Buttons

I’m reposting my answer to a similar question because no-one seems to have given it here and it’s much cleaner and neater:

Use the alternative buttons property syntax:

$dialogDiv.dialog({
    autoOpen: false,
    modal: true,
    width: 600,
    resizable: false,
    buttons: [
        {
            text: "Cancel",
            "class": 'cancelButtonClass',
            click: function() {
                // Cancel code here
            }
        },
        {
            text: "Save",
            "class": 'saveButtonClass',
            click: function() {
                // Save code here
            }
        }
    ],
    close: function() {
        // Close code here (incidentally, same as Cancel code)
    }
});

C# version of java's synchronized keyword?

First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).

For the method-level stuff, there is [MethodImpl]:

[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}

This can also be used on accessors (properties and events):

private int i;
public int SomeProperty
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    get { return i; }
    [MethodImpl(MethodImplOptions.Synchronized)]
    set { i = value; }
}

Note that field-like events are synchronized by default, while auto-implemented properties are not:

public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized

Personally, I don't like the implementation of MethodImpl as it locks this or typeof(Foo) - which is against best practice. The preferred option is to use your own locks:

private readonly object syncLock = new object();
public void SomeMethod() {
    lock(syncLock) { /* code */ }
}

Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a lock(this) / lock(Type) - however, in more recent compilers it uses Interlocked updates - so thread-safe without the nasty parts.

This allows more granular usage, and allows use of Monitor.Wait/Monitor.Pulse etc to communicate between threads.

A related blog entry (later revisited).

Visual Studio 64 bit?

For numerous reasons, No.

Why is explained in this MSDN post.

First, from a performance perspective the pointers get larger, so data structures get larger, and the processor cache stays the same size. That basically results in a raw speed hit (your mileage may vary). So you start in a hole and you have to dig yourself out of that hole by using the extra memory above 4G to your advantage. In Visual Studio this can happen in some large solutions but I think a preferable thing to do is to just use less memory in the first place. Many of VS’s algorithms are amenable to this. Here’s an old article that discusses the performance issues at some length: https://docs.microsoft.com/archive/blogs/joshwil/should-i-choose-to-take-advantage-of-64-bit

Secondly, from a cost perspective, probably the shortest path to porting Visual Studio to 64 bit is to port most of it to managed code incrementally and then port the rest. The cost of a full port of that much native code is going to be quite high and of course all known extensions would break and we’d basically have to create a 64 bit ecosystem pretty much like you do for drivers. Ouch.

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I am getting this error because log4j2 file got deleted from my src folder

Simply add xml file under src folder

<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
    </Console>

    <RollingFile name="RollingFile" filename="logs/B2CATA-hybrid.log"
        filepattern="${logPath}/%d{yyyyMMddHHmmss}-fargo.log">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
        <Policies>
            <SizeBasedTriggeringPolicy size="100 MB" />
        </Policies>
        <DefaultRolloverStrategy max="20" />
    </RollingFile>

</Appenders>
<Loggers>
   <Logger name="com.pragiti." level="trace" />
    <Root level="info">
        <AppenderRef ref="Console" />
        <AppenderRef ref="RollingFile" />
    </Root>
</Loggers>

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

invalid types 'int[int]' for array subscript

Just for completeness, this error can happen also in a different situation: when you declare an array in an outer scope, but declare another variable with the same name in an inner scope, shadowing the array. Then, when you try to index the array, you are actually accessing the variable in the inner scope, which might not even be an array, or it might be an array with fewer dimensions.

Example:

int a[10];  // a global scope

void f(int a)   // a declared in local scope, overshadows a in global scope
{
  printf("%d", a[0]);  // you trying to access the array a, but actually addressing local argument a
}

'ssh-keygen' is not recognized as an internal or external command

If you previously installed Git, open a git-bash and try the command from there.

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The problem is in this line:

with pattern.findall(row) as f:

You are using the with statement. It requires an object with __enter__ and __exit__ methods. But pattern.findall returns a list, with tries to store the __exit__ method, but it can't find it, and raises an error. Just use

f = pattern.findall(row)

instead.

Dependency injection with Jersey 2.0

Dependency required for jersey restful service and Tomcat is the server. where ${jersey.version} is 2.29.1

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0.SP1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>${jersey.version}</version>
    </dependency>

The basic code will be as follows:

@RequestScoped
@Path("test")
public class RESTEndpoint {

   @GET
   public String getMessage() {

adb doesn't show nexus 5 device

Here is simple solution for Windows 7 and Nexus 5 on Android 5.

  1. Download the Nexus 5 Drivers from http://androidhost.org/jelry
  2. Extract the zip contents and place all files in a single folder on your desktop.
  3. Connect your device to your computer.
  4. Launch the Device Manager on your PC.
  5. Now you should see the Nexus 5 listed in the hardware list.
  6. Right-click the ‘Nexus 5' line and then click on Update Driver Software.
  7. Next, click the ‘browse my computer’ option.
  8. In the new window click on ‘Browse…’ button.
  9. Go to folder unzipped at step 2. Select the folder where you extract the USB Drivers. Click Next. – make sure to tick the subfolder box too.
  10. Now, the Windows installer will search for Nexus 5 drivers, click Install when asked for permission.
  11. Wait for the process to complete and then check the Device Manager list to confirm that the installation was successful.

Original: http://www.android.gs/download-and-install-google-nexus-5-usb-drivers-adb-fastboot/

Note: do not forget to enable USB debugging on your device :)

Get values from a listbox on a sheet

Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)

Dim StrSelection As String

Private Sub ListBox1_Change()
    If ListBox1.Selected(ListBox1.ListIndex) Then
        If StrSelection = "" Then
            StrSelection = ListBox1.List(ListBox1.ListIndex)
        Else
            StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
        End If
    Else
        StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
    End If
End Sub

Determine the size of an InputStream

    try {
        InputStream connInputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int size = connInputStream.available();

int available () Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

InputStream - Android SDK | Android Developers

Restart pods when configmap updates in Kubernetes?

Signalling a pod on config map update is a feature in the works (https://github.com/kubernetes/kubernetes/issues/22368).

You can always write a custom pid1 that notices the confimap has changed and restarts your app.

You can also eg: mount the same config map in 2 containers, expose a http health check in the second container that fails if the hash of config map contents changes, and shove that as the liveness probe of the first container (because containers in a pod share the same network namespace). The kubelet will restart your first container for you when the probe fails.

Of course if you don't care about which nodes the pods are on, you can simply delete them and the replication controller will "restart" them for you.

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

In Dart, if/else and switch are statements not expressions. They don't return a value so you can't pass them to constructor params. If you have a lot of conditional logic in your build method, then it is a good practice to try and simplify it. For example, you can move self-contained logic to methods, and use if/else statements to initialize local variables which you can later use.

Using a method and if/else

Widget _buildChild() {
  if (condition) {
    return ...
  }
  return ...
}

Widget build(BuildContext context) {
  return new Container(child: _buildChild());
}

Using an if/else

Widget build(BuildContext context) {
  Widget child;
  if (condition) {
    child = ...
  } else {
    child = ...
  }
  return new Container(child: child);
}

"Rate This App"-link in Google Play store app on the phone

In-App Review API is a long-awaited feature that Google has launched in August 2020 like Apple did in 2016 for iOS apps.

With this API users will review and rate an application without leaving it. Google suggestion to developers not to force users to rate or review all the time as this API allocate a quota to each user on the specific usage of the application in a time. Surely developers would not be able to interrupt users with an attractive pop-up in the middle of their task.

Java

In Application level (build.gradle)

       dependencies {
            // This dependency from the Google Maven repository.
            // include that repository in your project's build.gradle file.
            implementation 'com.google.android.play:core:1.9.0'
        }

 

boolean isGMSAvailable = false;
int result = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
isGMSAvailable = (com.google.android.gms.common.ConnectionResult.SUCCESS == result);
  if(isGMSAvailable)
  {
    ReviewManager manager = ReviewManagerFactory.create(this);
    Task<ReviewInfo> request = manager.requestReviewFlow();
    request.addOnCompleteListener(task -> {
      try {
        if (task.isSuccessful())
        {
           // getting ReviewInfo object
            ReviewInfo reviewInfo = task.getResult();
            Task<Void> flow = manager.launchReviewFlow(this, reviewInfo);
            flow.addOnCompleteListener(task2 -> {
                // The flow has finished. The API does not indicate whether the user
                // reviewed or not, or even whether the review dialog was shown. Thus,
                // no matter the result, we continue our app flow.
                   });
        } else 
        {
            // There was some problem, continue regardless of the result
           // call old method for rating and user will land in Play Store App page
           Utils.rateOnPlayStore(this);       
        }
        } catch (Exception ex)
        {
            Log.e("review Ex", "review & rate: "+ ex);
                 }
                });
    }
    else
    {
       // if user has not installed Google play services in his/her device you land them to 
       // specific store e.g. Huawei AppGallery or Samsung Galaxy Store 
       Utils.rateOnOtherStore(this);
    }   

Kotlin

val manager = ReviewManagerFactory.create(context)
val request = manager.requestReviewFlow()
request.addOnCompleteListener { request ->
    if (request.isSuccessful) {
        // We got the ReviewInfo object
        val reviewInfo = request.result
    } else {
        // There was some problem, continue regardless of the result.
    }
}

//Launch the in-app review flow

val flow = manager.launchReviewFlow(activity, reviewInfo)
flow.addOnCompleteListener { _ ->
    // The flow has finished. The API does not indicate whether the user
    // reviewed or not, or even whether the review dialog was shown. Thus, no
    // matter the result, we continue our app flow.
}

for Testing use FakeReviewManager

//java
ReviewManager manager = new FakeReviewManager(this);

//Kotlin
val manager = FakeReviewManager(context)

Grunt watch error - Waiting...Fatal error: watch ENOSPC

After trying grenade's answer you may use a temporary fix:

sudo bash -c 'echo 524288 > /proc/sys/fs/inotify/max_user_watches'

This does the same thing as kds's answer, but without persisting the changes. This is useful if the error just occurs after some uptime of your system.

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

Add a helper class:

public static class Redirector {
        public static void RedirectTo(this Controller ct, string action) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action));
        }

        public static void RedirectTo(this Controller ct, string action, string controller) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller));
        }

        public static void RedirectTo(this Controller ct, string action, string controller, object routeValues) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller, routeValues));
        }
    }

Then call in your action:

this.RedirectTo("Index", "Cement");

Add javascript code to any global javascript included file or layout file to intercept all ajax requests:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  $(function() {_x000D_
    $(document).ajaxComplete(function (event, xhr, settings) {_x000D_
            var urlHeader = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
_x000D_
            if (urlHeader != null && urlHeader !== undefined) {_x000D_
                window.location = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
            }_x000D_
        });_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Get class list for element with jQuery

var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){

     //do something

});

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

The consequence of this is that you may need a rather insane-looking query, e. g.,

SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
                 ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
                 ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
                 ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How can I insert data into Database Laravel?

First method you can try this

$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();

Another way to insert records into the database with create function

$department = new Department;           
// Another Way to insert records
$department->create($request->all());

return redirect('admin/departments');

You need to set the filledby in Department model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
    protected $fillable = ['department_name','status'];
} 

How can I compile a Java program in Eclipse without running it?

You will need to go to Project->Clean...,then build your project. This will work, even when your source code does not contain any main method to run as an executable program. The .class files will appear in the bin folder of your project, in your workspace.

In PHP with PDO, how to check the final SQL parametrized query?

I check Query Log to see the exact query that was executed as prepared statement.

EditText request focus

It has worked for me as follows.

ed1.requestFocus();

            return; //Faça um return para retornar o foco

Converting a String to a List of Words?

To do this properly is quite complex. For your research, it is known as word tokenization. You should look at NLTK if you want to see what others have done, rather than starting from scratch:

>>> import nltk
>>> paragraph = u"Hi, this is my first sentence. And this is my second."
>>> sentences = nltk.sent_tokenize(paragraph)
>>> for sentence in sentences:
...     nltk.word_tokenize(sentence)
[u'Hi', u',', u'this', u'is', u'my', u'first', u'sentence', u'.']
[u'And', u'this', u'is', u'my', u'second', u'.']

How to change text color of simple list item

I realize this question is a bit old but here's a really simple solution that was missing. You don't need to create a custom ListView or even a custom layout.

Just create an anonymous subclass of ArrayAdapter and override getView(). Let super.getView() handle all the heavy lifting. Since simple_list_item_1 is just a text view you can customize it (e.g. set textColor) and then return it.

Here's an example from one of my apps. I'm displaying a list of recent locations and I want all occurrences of "Current Location" to be blue and the rest white.

ListView listView = (ListView) this.findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MobileMuni.getBookmarkStore().getRecentLocations()) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = (TextView) super.getView(position, convertView, parent);

        String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
        int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
        textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));

        return textView;
    }
});

HTML: How to center align a form

Being form a block element, you can center-align it by setting its side margins to auto:

form { margin: 0 auto; }

EDIT:
As @moomoochoo correctly pointed out, this rule will only work if the block element (your form, in this case) has been assigned a specific width.
Also, this 'trick' will not work for floating elements.

Indirectly referenced from required .class file

Have you Googled for "weblogic ExpressionMap"? Do you know what it is and what it does?

Looks like you definitely need to be compiling alongside Weblogic and with Weblogic's jars included in your Eclipse classpath, if you're not already.

If you're not already working with Weblogic, then you need to find out what in the world is referencing it. You might need to do some heavy-duty grepping on your jars, classfiles, and/or source files looking for which ones include the string "weblogic".

If I had to include something that was relying on this Weblogic class, but couldn't use Weblogic, I'd be tempted to try to reverse-engineer a compatible class. Create your own weblogic.utils.expressions.ExpressionMap class; see if everything compiles; use any resultant errors or warnings at compile-time or runtime to give you clues as to what methods and other members need to be in this class. Make stub methods that do nothing or return null if possible.

How to open Atom editor from command line in OS X?

Make sure to put (move) the atom into Application directory.enter image description here

Drawable image on a canvas

Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

Dependencies

These are the packages that your package needs to run, so they will be installed when people run

 npm install PACKAGE-NAME

An example would be if you used jQuery in your project. If someone doesn't have jQuery installed, then it wouldn't work. To save as a dependency, use

 npm install --save

Dev-Dependencies

These are the dependencies that you use in development, but isn't needed when people are using it, so when people run npm install, it won't install them since the are not necessary. For example, if you use mocha to test, people don't need mocha to run, so npm install doesn't install it. To save as a dev dependency, use

npm install PACKAGE --save-dev

Peer Dependencies

These can be used if you want to create and publish your own library so that it can be used as a dependency. For example, if you want your package to be used as a dependency in another project, then these will also be installed when someone installs the project which has your project as a dependency. Most of the time you won't use peer dependencies.

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

 I achieve this by following method

   timeAgo = (date) => {
            var ms = (new Date()).getTime() - date.getTime();
            var seconds = Math.floor(ms / 1000);
            var minutes = Math.floor(seconds / 60);
        var hours = Math.floor(minutes / 60);
        var days = Math.floor(hours / 24);
        var months = Math.floor(days / 30);
        var years = Math.floor(months / 12);
    
        if (ms === 0) {
            return 'Just now';
        } if (seconds < 60) {
            return seconds + ' seconds Ago';
        } if (minutes < 60) {
            return minutes + ' minutes Ago';
        } if (hours < 24) {
            return hours + ' hours Ago';
        } if (days < 30) {
            return days + ' days Ago';
        } if (months < 12) {
            return months + ' months Ago';
        } else {
            return years + ' years Ago';
        }
    
    }
    
        console.log(timeAgo(new Date()));
        console.log(timeAgo(new Date('Jun 27 2020 10:12:19')));
        console.log(timeAgo(new Date('Jun 27 2020 00:12:19')));
        console.log(timeAgo(new Date('May 28 2020 13:12:19')));
        console.log(timeAgo(new Date('May 28 2017 13:12:19')));

Find row where values for column is maximal in a pandas DataFrame

The idmax of the DataFrame returns the label index of the row with the maximum value and the behavior of argmax depends on version of pandas (right now it returns a warning). If you want to use the positional index, you can do the following:

max_row = df['A'].values.argmax()

or

import numpy as np
max_row = np.argmax(df['A'].values)

Note that if you use np.argmax(df['A']) behaves the same as df['A'].argmax().

How can I lock a file using java (if possible)

This may not be what you are looking for, but in the interest of coming at a problem from another angle....

Are these two Java processes that might want to access the same file in the same application? Perhaps you can just filter all access to the file through a single, synchronized method (or, even better, using JSR-166)? That way, you can control access to the file, and perhaps even queue access requests.

Trusting all certificates using HttpClient over HTTPS

Simply use this -

public DefaultHttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[]{tm}, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));
    return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
    return null;
}
}

How to handle anchor hash linking in AngularJS

My solution with ng-route was this simple directive:

   app.directive('scrollto',
       function ($anchorScroll,$location) {
            return {
                link: function (scope, element, attrs) {
                    element.click(function (e) {
                        e.preventDefault();
                        $location.hash(attrs["scrollto"]);
                        $anchorScroll();
                    });
                }
            };
    })

The html is looking like:

<a href="" scrollTo="yourid">link</a>

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

If you have the to your project and the Copy Local flag is in true, the solution should be just the project. That copy the DLL to the bin folder.

Creating a Facebook share button with customized url, title and image

This is the code as 2017:

<i class="fa fa-facebook-square"></i>
<a href="#" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),'facebook-share-dialog','width=626,height=436');return false;">Share on Facebook</a>

Facebook now takes all data from OG metatags.

NOTE: This code assumes you have OG metatags on in site's code.

Source

using where and inner join in mysql

You can use as many joins as you want, however, the more you use the more it will impact performance

Manually raising (throwing) an exception in Python

DON'T DO THIS. Raising a bare Exception is absolutely not the right thing to do; see Aaron Hall's excellent answer instead.

Can't get much more pythonic than this:

raise Exception("I know python!")

See the raise statement docs for python if you'd like more info.

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.

Using MySQL as an example (if for no other reason because it's most popular), you have DATE, DATETIME, TIME and TIMESTAMP column data types; just as you have CHAR, VARCHAR, FLOAT and INTEGER.

So, you ask, what's the difference? Well, some of them are self-explanatory. DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes.

You can read more about the differences between time formats in MySQL here.

In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP. Do you only need to store a date? Use DATE. Do you only need to store a time? Use TIME.

Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, respectively.

This means that within Rails, you only have to decide whether you need to store date, time or both.

How do I check if an HTML element is empty using jQuery?

Another option that should require less "work" for the browser than html() or children():

function isEmpty( el ){
  return !el.has('*').length;
}

Which programming language for cloud computing?

Obviously there is no "better" -- or more worth learning -- language at all. Which language you use is is just a matter of what you like AND what your server supports. You should not learn a language that wouldn't be supported by any server or is said to be dying in the near future. On the other hand it is obvious too that there will be even better languages in the future and that those will be more useful. So learn one that is fast, convenient and that you like and where learning it wouldn't be a too big effort because, as said, you're likely to change in less than 3 years.

I, personally would be considering an "open-source" (not proprietary) one, because the web is open to everyone and open-source is more likely to be supported by every-one. (Which means PHP in this case)

Reversing a linked list in Java, recursively

What other guys done , in other post is a game of content, what i did is a game of linkedlist, it reverse the LinkedList's member not reverse of a Value of members.

Public LinkedList reverse(LinkedList List)
{
       if(List == null)
               return null;
       if(List.next() == null)
              return List;
       LinkedList temp = this.reverse( List.next() );
       return temp.setNext( List );
}

What's the difference between SHA and AES encryption?

SHA is a hash function and AES is an encryption standard. Given an input you can use SHA to produce an output which is very unlikely to be produced from any other input. Also, some information is lost while applying the function so even if you knew how to produce an input yielding the same output, that input wouldn't likely be the same one used in the first place. On the other hand AES is meant to protect from disclosure to third parties any data sent between two parties sharing the same encryption key. This means that once you know the encryption key and the output (and the IV...) you can seamlessly get back to the original input. Please notice that SHA doesn't require anything but an input to be applied, while AES requires at least 3 thins: what you're encrypting/decrypting, an encryption key and the initialization vector (IV).

git push says "everything up-to-date" even though I have local changes

I was working with Jupyter-Notebook when I encountered this deceptive error.

I wasn't able to resolve through the solutions provided above as I neither had a detached head nor did I have different names for my local and remote repo.

But what I did have was my file sizes were slightly greater than 1MB and the largest was almost ~2MB.

I reduced the file size of each of the file using https://stackoverflow.com/questions/37807308/[][1] technique.

It helped reduce my file size by clearing the outputs. I was able to push the code, henceforth as it brought my file size in KBs.

Output to the same line overwriting previous output?

I found that for a simple print statement in python 2.7, just put a comma at the end after your '\r'.

print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',

This is shorter than other non-python 3 solutions, but also more difficult to maintain.

Get public/external IP address?

I had almost the same as Jesper, only I reused the webclient and disposed it correctly. Also I cleaned up some responses by removing the extra \n at the end.


    private static IPAddress GetExternalIp () {
      using (WebClient client = new WebClient()) {
        List<String> hosts = new List<String>();
        hosts.Add("https://icanhazip.com");
        hosts.Add("https://api.ipify.org");
        hosts.Add("https://ipinfo.io/ip");
        hosts.Add("https://wtfismyip.com/text");
        hosts.Add("https://checkip.amazonaws.com/");
        hosts.Add("https://bot.whatismyipaddress.com/");
        hosts.Add("https://ipecho.net/plain");
        foreach (String host in hosts) {
          try {
            String ipAdressString = client.DownloadString(host);
            ipAdressString = ipAdressString.Replace("\n", "");
            return IPAddress.Parse(ipAdressString);
          } catch {
          }
        }
      }
      return null;
    }

assign value using linq

You can create a extension method:

public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
    foreach(var item in self) {
        action(item);
        yield return item;
    }
}

And then use it in code:

listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

See this http://blog.stevenlevithan.com/archives/date-time-format

you can do anything with date.

file : http://stevenlevithan.com/assets/misc/date.format.js

add this to your html code using script tag and to use you can use it as :

var now = new Date();

now.format("m/dd/yy");
// Returns, e.g., 6/09/07

How to Update a Component without refreshing full page - Angular

Angular will automatically update a component when it detects a variable change .

So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts or via an @Input variable...


an example...

main.html

<app-header [header-data]="headerData"></app-header>

main.component.ts

public headerData:int = 0;

ngOnInit(){
    setInterval(()=>{this.headerData++;}, 250);
}

header.html

<p>{{data}}</p>

header.ts

@Input('header-data') data;

In the above example, the header will recieve the new data every 250ms and thus update the component.


For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks

How to convert java.sql.timestamp to LocalDate (java8) java.time?

You can do:

timeStamp.toLocalDateTime().toLocalDate();

Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.

round() doesn't seem to be rounding properly

It's a big problem indeed. Try out this code:

print "%.2f" % (round((2*4.4+3*5.6+3*4.4)/8,2),)

It displays 4.85. Then you do:

print "Media = %.1f" % (round((2*4.4+3*5.6+3*4.4)/8,1),)

and it shows 4.8. Do you calculations by hand the exact answer is 4.85, but if you try:

print "Media = %.20f" % (round((2*4.4+3*5.6+3*4.4)/8,20),)

you can see the truth: the float point is stored as the nearest finite sum of fractions whose denominators are powers of two.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Import this in to app.module.ts

import {HttpClientModule} from '@angular/common/http';

and add this one in imports

HttpClientModule

wp_nav_menu change sub-menu class name?

To change the default "sub-menu" class name, there is simple way. You can just change it in wordpress file.

location : www/project_name/wp-includes/nav-menu-template.php.

open this file and at line number 49, change the name of sub-menu class with your custom class.

Or you can also add your custom class next to sub-menu.

Done.

It worked for me.I used wordpress-4.4.1.

list.clear() vs list = new ArrayList<Integer>();

List.clear would remove the elements without reducing the capacity of the list.

groovy:000> mylist = [1,2,3,4,5,6,7,8,9,10,11,12]
===> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
groovy:000> mylist.elementData.length
===> 12
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@19d6af
groovy:000> mylist.clear()
===> null
groovy:000> mylist.elementData.length
===> 12
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@19d6af
groovy:000> mylist = new ArrayList();
===> []
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@2bfdff
groovy:000> mylist.elementData.length
===> 10

Here mylist got cleared, the references to the elements held by it got nulled out, but it keeps the same backing array. Then mylist was reinitialized and got a new backing array, the old one got GCed. So one way holds onto memory, the other one throws out its memory and gets reallocated from scratch (with the default capacity). Which is better depends on whether you want to reduce garbage-collection churn or minimize the current amount of unused memory. Whether the list sticks around long enough to be moved out of Eden might be a factor in deciding which is faster (because that might make garbage-collecting it more expensive).

Set a cookie to never expire

Never and forever are two words that I avoid using due to the unpredictability of life.

The latest time since 1 January 1970 that can be stored using a signed 32-bit integer is 03:14:07 on Tuesday, 19 January 2038 (231-1 = 2,147,483,647 seconds after 1 January 1970). This limitation is known as the Year 2038 problem

setCookie("name", "value", strtotime("2038-01-19 03:14:07"));

How can I remove the outline around hyperlinks images?

Use Like This for HTML 4.01

<img src="image.gif" border="0">

What is the correct JSON content type?

If you're in a client-side environment, investigating about the cross-browser support is mandatory for a well supported web application.

The right HTTP Content-Type would be application/json, as others already highlighted too, but some clients do not handle it very well, that's why jQuery recommends the default text/html.

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

Two options:

libimobiledevice is installable via homebrew and works great. Its idevicesyslog tool works similarly to deviceconsole (below), and it supports wirelessly viewing your device's syslog (!)

I've written more about that on Tumblr tl;dr:

brew install libimobiledevice
idevice_id --list // list available device UDIDs
idevicesyslog -u <device udid>

with the device connected via USB or available on the local wireless network.


(Keeping for the historical record, from 2013:) deviceconsole from rpetrich is a much less wacked-out solution than ideviceconsole above. My fork of it builds and runs in Xcode 5 out of the box, and the Build action will install the binary to /usr/local/bin for ease of use.

As an additional helpful bit of info, I use it in the following style which makes it easy to find the device I want in my shell history and removes unnecessary > lines that deviceconsole prints out.

deviceconsole -d -u <device UDID> | uniq -u && echo "<device name>"

How do I base64 encode a string efficiently using Excel VBA?

You can use the MSXML Base64 encoding functionality as described at www.nonhostile.com/howto-encode-decode-base64-vb6.asp:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)      

  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument 
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.Text 

  Set objNode = Nothing
  Set objXML = Nothing
End Function

How do I filter date range in DataTables?

Using other posters code with some tweaks:

<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
        <tbody>
            <tr>
                <td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;
                </td>
                
                <td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;                        
                </td>
                
                <td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
            </tr>
        </tbody>
    </table>
    
    <script>
        $(document).ready(function() {
            $(function() {
                var oTable = $('#tbAD').DataTable({
                "oLanguage": {
                    "sSearch": "Filter Data"
                },
                "iDisplayLength": -1,
                "sPaginationType": "full_numbers",
                "pageLength": 50, 
                });

                $("#datepicker_from").datepicker();
                $("#datepicker_to").datepicker();

                $('#datepicker_from').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_to').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_clear_lnk').click(function (e) {
                    oTable.draw();
                });
            });   

            $.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
                var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
                var startDate = new Date(data[9]).setHours(0,0,0,0);
                if (min == null && max == null) { return true; }
                if (min == null && startDate <= max) { return true; }
                if (max == null && startDate >= min) { return true; }
                if (startDate <= max && startDate >= min) { return true; }                    
                return false;
                }
            );
        });
</script>

Xcode 'CodeSign error: code signing is required'

In file /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/SDKSettings.plist

change the CODE_SIGNING_REQUIRED YES

to

CODE_SIGNING_REQUIRED NO

Restart Xcode

Android Notification Sound

Button btn;

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

    btn= findViewById(R.id.btn); 

   btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            notification();
        }
    });
  }   



private void notification() {
    NotificationCompat.Builder builder= new 
    NotificationCompat.Builder(this);
    builder.setAutoCancel(true);
    builder.setContentTitle("Work Progress");
    builder.setContentText("Submit your today's work progress");
    builder.setSmallIcon(R.drawable.ic_email_black_24dp);
    Intent intent=new Intent(this, WorkStatus.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, 
    PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    builder.setDefaults(Notification.DEFAULT_VIBRATE);
    builder.setDefaults(Notification.DEFAULT_SOUND);

    NotificationManager notificationManager= (NotificationManager) 
    getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder.build());
}

It is complete notification with sound and vibrates

React - Component Full Screen (with height 100%)

#app {
  height: 100%;
  min-height: 100vh;
}

Always full height of view min

Bootstrap NavBar with left, center or right aligned items

I needed something similar (left, center and right aligned items), but with ability to mark centered items as active. What worked for me was:

http://www.bootply.com/CSI2KcCoEM

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
      <li class="navbar-left"><a href="#">Left 1</a></li>
      <li class="navbar-left"><a href="#">Left 2</a></li>
      <li class="active"><a href="#">Center 1</a></li>
      <li><a href="#">Center 2</a></li>
      <li><a href="#">Center 3</a></li>
      <li class="navbar-right"><a href="#">Right 1</a></li>
      <li class="navbar-right"><a href="#">Right 2</a></li>
    </ul>
  </div>
</nav>

CSS:

@media (min-width: 768px) {
  .navbar-nav {
    width: 100%;
    text-align: center;
  }
  .navbar-nav > li {
    float: none;
    display: inline-block;
  }
  .navbar-nav > li.navbar-right {
    float: right !important;
  }
}

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I ran into this issue after updating the Java JDK, but had not yet restarted my command prompt. After restarting the command prompt, everything worked fine. Presumably, because the PATH variable need to be reset after the JDK update.

bash: mkvirtualenv: command not found

On Windows 10, to create the virtual environment, I replace "pip mkvirtualenv myproject" by "mkvirtualenv myproject" and that works well.

How to check the multiple permission at single request in Android M?

I had the same issue and stumbled on this library.

Basically you can ask for multiple permissions sequentially, plus you can add listeners to popup a snackbar if the user denies your permission.

dexter_sample

Get URL of ASP.Net Page in code-behind

Using a js file you can capture the following, that can be used in the codebehind as well:

<script type="text/javascript">
    alert('Server: ' + window.location.hostname);
    alert('Full path: ' + window.location.href);
    alert('Virtual path: ' + window.location.pathname);
    alert('HTTP path: ' + 
        window.location.href.replace(window.location.pathname, ''));    
</script>

Pass an array of integers to ASP.NET Web API?

I recently came across this requirement myself, and I decided to implement an ActionFilter to handle this.

public class ArrayInputAttribute : ActionFilterAttribute
{
    private readonly string _parameterName;

    public ArrayInputAttribute(string parameterName)
    {
        _parameterName = parameterName;
        Separator = ',';
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ActionArguments.ContainsKey(_parameterName))
        {
            string parameters = string.Empty;
            if (actionContext.ControllerContext.RouteData.Values.ContainsKey(_parameterName))
                parameters = (string) actionContext.ControllerContext.RouteData.Values[_parameterName];
            else if (actionContext.ControllerContext.Request.RequestUri.ParseQueryString()[_parameterName] != null)
                parameters = actionContext.ControllerContext.Request.RequestUri.ParseQueryString()[_parameterName];

            actionContext.ActionArguments[_parameterName] = parameters.Split(Separator).Select(int.Parse).ToArray();
        }
    }

    public char Separator { get; set; }
}

I am applying it like so (note that I used 'id', not 'ids', as that is how it is specified in my route):

[ArrayInput("id", Separator = ';')]
public IEnumerable<Measure> Get(int[] id)
{
    return id.Select(i => GetData(i));
}

And the public url would be:

/api/Data/1;2;3;4

You may have to refactor this to meet your specific needs.

Is there a naming convention for git repositories?

lowercase-with-hyphens is the style I most often see on GitHub.*

lowercase_with_underscores is probably the second most popular style I see.

The former is my preference because it saves keystrokes.

* Anecdotal; I haven't collected any data.

Preloading images with JavaScript

I can confirm that the approach in the question is sufficient to trigger the images to be downloaded and cached (unless you have forbidden the browser from doing so via your response headers) in, at least:

  • Chrome 74
  • Safari 12
  • Firefox 66
  • Edge 17

To test this, I made a small webapp with several endpoints that each sleep for 10 seconds before serving a picture of a kitten. Then I added two webpages, one of which contained a <script> tag in which each of the kittens is preloaded using the preloadImage function from the question, and the other of which includes all the kittens on the page using <img> tags.

In all the browsers above, I found that if I visited the preloader page first, waited a while, and then went to the page with the <img> tags, my kittens rendered instantly. This demonstrates that the preloader successfully loaded the kittens into the cache in all browsers tested.

You can see or try out the application I used to test this at https://github.com/ExplodingCabbage/preloadImage-test.

Note in particular that this technique works in the browsers above even if the number of images being looped over exceeds the number of parallel requests that the browser is willing to make at a time, contrary to what Robin's answer suggests. The rate at which your images preload will of course be limited by how many parallel requests the browser is willing to send, but it will eventually request each image URL you call preloadImage() on.

generate model using user:references vs user_id:integer

how does rails know that user_id is a foreign key referencing user?

Rails itself does not know that user_id is a foreign key referencing user. In the first command rails generate model Micropost user_id:integer it only adds a column user_id however rails does not know the use of the col. You need to manually put the line in the Micropost model

class Micropost < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :microposts
end

the keywords belongs_to and has_many determine the relationship between these models and declare user_id as a foreign key to User model.

The later command rails generate model Micropost user:references adds the line belongs_to :user in the Micropost model and hereby declares as a foreign key.

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench you find that there is no relationship threads drawn between the models. Like in the following pic enter image description here

However, if you use the later method you find that you migration file looks like:

def change
    create_table :microposts do |t|
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :microposts, :users

Now the foreign key is set at the database level. and you can generate proper EER diagrams. enter image description here

Xampp Access Forbidden php

Did you change any thing on the virtual-host before it stop working ?

Add this line to xampp/apache/conf/extra/httpd-vhosts.conf

<VirtualHost localhost:80>
    DocumentRoot "C:/xampp/htdocs"
    ServerAdmin localhost
    <Directory "C:/xampp/htdocs">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

In my case the problem was that I used notifyDataSetChanged when amount of newly loaded data was less than initial data. This approach helped me:

adapter.notifyItemRangeChanged(0, newAmountOfData + 1);
adapter.notifyItemRangeRemoved(newAmountOfData + 1, previousAmountOfData);

Remove unused imports in Android Studio

Press Ctrl + Alt + O.

A dialog box will appear with a few options. You can choose to have the dialog box not appear again in the future if you wish, setting a default behavior.

enter image description here

How to extract base URL from a string in JavaScript?

I use a simple regex that extracts the host form the url:

function get_host(url){
    return url.replace(/^((\w+:)?\/\/[^\/]+\/?).*$/,'$1');
}

and use it like this

var url = 'http://www.sitename.com/article/2009/09/14/this-is-an-article/'
var host = get_host(url);

Note, if the url does not end with a / the host will not end in a /.

Here are some tests:

describe('get_host', function(){
    it('should return the host', function(){
        var url = 'http://www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://www.sitename.com/');
    });
    it('should not have a / if the url has no /', function(){
        var url = 'http://www.sitename.com';
        assert.equal(get_host(url),'http://www.sitename.com');
    });
    it('should deal with https', function(){
        var url = 'https://www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'https://www.sitename.com/');
    });
    it('should deal with no protocol urls', function(){
        var url = '//www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'//www.sitename.com/');
    });
    it('should deal with ports', function(){
        var url = 'http://www.sitename.com:8080/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://www.sitename.com:8080/');
    });
    it('should deal with localhost', function(){
        var url = 'http://localhost/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://localhost/');
    });
    it('should deal with numeric ip', function(){
        var url = 'http://192.168.18.1/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://192.168.18.1/');
    });
});

How to install plugin for Eclipse from .zip

It depends on what the zip contains. Take a look to see if it got content.jar and artifacts.jar. If it does, it is an archived updated site. Install from it the same way as you install from a remote site.

If the zip doesn't contain content.jar and artifacts.jar, go to your Eclipse install's dropins directory, create a subfolder (name doesn't matter) and expand your zip into that folder. Restart Eclipse.

How do I reverse a commit in git?

I think you need to push a revert commit. So pull from github again, including the commit you want to revert, then use git revert and push the result.

If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset: git push origin :master.

Find object in list that has attribute equal to some value (that meets any condition)

You could also implement rich comparison via __eq__ method for your Test class and use in operator. Not sure if this is the best stand-alone way, but in case if you need to compare Test instances based on value somewhere else, this could be useful.

class Test:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        """To implement 'in' operator"""
        # Comparing with int (assuming "value" is int)
        if isinstance(other, int):
            return self.value == other
        # Comparing with another Test object
        elif isinstance(other, Test):
            return self.value == other.value

import random

value = 5

test_list = [Test(random.randint(0,100)) for x in range(1000)]

if value in test_list:
    print "i found it"