Programs & Examples On #Using declaration

What is the difference between 'typedef' and 'using' in C++11?

They are largely the same, except that:

The alias declaration is compatible with templates, whereas the C style typedef is not.

PLS-00201 - identifier must be declared

When creating the TABLE under B2BOWNER, be sure to prefix the PL/SQL function with the Schema name; i.e. B2BOWNER.F_SSC_Page_Map_Insert.

I did not realize this until the DBAs pointed it out. I could have created the table under my root USER/SCHEMA and the PL/SQL function would have worked fine.

Installing MySQL-python

yum install mysql-devel

It worked for me.

Pass a string parameter in an onclick function

Not escaping double quotes is the cause of OP's problem. A readable approach to escape double quotes is using backticks (MDN). Here is a sample solution:

my_btn.setAttribute('onclick', `my_func("${onclick_var1}", "${onclick_var2}")`);

Error: Cannot find module 'ejs'

I have the same issue it resolve after installing the express in my project directory. previously i install it in global scope with -g option with npm install command.

Which command do I use to generate the build of a Vue app?

if you used vue-cli and webpack when you created your project.

you can use just

npm run build command in command line, and it will create dist folder in your project. Just upload content of this folder to your ftp and done.

How do I implement a callback in PHP?

One nifty trick that I've recently found is to use PHP's create_function() to create an anonymous/lambda function for one-shot use. It's useful for PHP functions like array_map(), preg_replace_callback(), or usort() that use callbacks for custom processing. It looks pretty much like it does an eval() under the covers, but it's still a nice functional-style way to use PHP.

PHP class: Global variable as property in class

class myClass { protected $foo;

public function __construct(&$var)
{
    $this->foo = &$var;
}

public function foo()
{
    return ++$this->foo;
}

}

How to get the concrete class name as a string?

you can also create a dict with the classes themselves as keys, not necessarily the classnames

typefunc={
    int:lambda x: x*2,
    str:lambda s:'(*(%s)*)'%s
}

def transform (param):
    print typefunc[type(param)](param)

transform (1)
>>> 2
transform ("hi")
>>> (*(hi)*)

here typefunc is a dict that maps a function for each type. transform gets that function and applies it to the parameter.

of course, it would be much better to use 'real' OOP

Firefox Add-on RESTclient - How to input POST parameters?

If you want to submit a POST request

  1. You have to set the “request header” section of the Firefox plugin to have a “name” = “Content-Type” and “value” = “application/x-www-form-urlencoded
  2. Now, you are able to submit parameter like “name=mynamehere&title=TA” in the “request body” text area field

How to enable curl in Wamp server

I got the same issue and this solved it for me. Perhaps this might be a fix for your problem too.

Here is the fix. Follow this link http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/

Go to "Fixed curl extensions" and download the extension that matches your PHP version.

Extract and copy "php_curl.dll" to the extension directory of your wamp installation. (i.e. C:\wamp\bin\php\php5.3.13\ext)

Restart Apache

Done!

Refer to: http://blog.nterms.com/2012/07/php-curl-issues-with-wamp-server-on.html

Cheers!

jump to line X in nano editor

According to section 2.2 of the manual, you can use the Escape key pressed twice in place of the CTRL key. This allowed me to use Nano's key combination for GO TO LINE when running Nano on a Jupyter/ JupyterHub and accessing through my browser. The normal key combination was getting 'swallowed' as the manual warns about can more often happen with the ALT key on some systems, and which can be replaced by one press of the ESCAPE key.
So for jump to line it was ESCAPE pressed twice, followed by shift key + dash key.

Automatically enter SSH password with script

This should help in most of the cases (you need to install sshpass first!):

#!/usr/bin/bash
read -p 'Enter Your Username: ' UserName;
read -p 'Enter Your Password: ' Password;
read -p 'Enter Your Domain Name: ' Domain;

sshpass -p "$Password" ssh -o StrictHostKeyChecking=no $UserName@$Domain

How can I remove the top and right axis in matplotlib?

Alternatively, this

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

seems to achieve the same effect on an axis without losing rotated label support.

(Matplotlib 1.0.1; solution inspired by this).

JavaScript .replace only replaces first Match

Try using a regex instead of a string for the first argument.

"this is a test".replace(/ /g,'%20') // #=> "this%20is%20a%20test"

HTML - Change\Update page contents without refreshing\reloading the page

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:

<script type="text/javascript">
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
</script>

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div id='myStyle'>
</div>

Then you put your PHP code into a separate file: (I've called it data.php in the above example)

<?php
  require ('myConnect.php');     
  $id = $_GET['id'];
  $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
  if( mysql_num_rows($results) > 0 )
  {
   $row = mysql_fetch_array( $results );
   echo $row['para'];
  }
?>

iOS 7 UIBarButton back button arrow color

You have to set the tintColor of the entire app.

self.window.tintColor = [UIColor redColor];

Or in Swift 3:

self.window?.tintColor = UIColor.blue

Source: iOS 7 UI Transition Guide

jQuery checkbox onChange

There is no need to use :checkbox, also replace #activelist with #inactivelist:

$('#inactivelist').change(function () {
    alert('changed');
 });

How to pass command-line arguments to a PowerShell ps1 file

After digging through the PowerShell documentation, I discovered some useful information about this issue. You can't use the $args if you used the param(...) at the beginning of your file; instead you will need to use $PSBoundParameters. I copy/pasted your code into a PowerShell script, and it worked as you'd expect in PowerShell version 2 (I am not sure what version you were on when you ran into this issue).

If you are using $PSBoundParameters (and this ONLY works if you are using param(...) at the beginning of your script), then it is not an array, it is a hash table, so you will need to reference it using the key / value pair.

param($p1, $p2, $p3, $p4)
$Script:args=""
write-host "Num Args: " $PSBoundParameters.Keys.Count
foreach ($key in $PSBoundParameters.keys) {
    $Script:args+= "`$$key=" + $PSBoundParameters["$key"] + "  "
}
write-host $Script:args

And when called with...

PS> ./foo.ps1 a b c d

The result is...

Num Args:  4
$p1=a  $p2=b  $p3=c  $p4=d

Open Facebook page from Android app?

I implemented in this form in webview using fragment- inside oncreate:

 webView.setWebViewClient(new WebViewClient()
{
    public boolean shouldOverrideUrlLoading(WebView viewx, String urlx)
                {
     if(Uri.parse(urlx).getHost().endsWith("facebook.com")) {
                        {
                            goToFacebook();
                        }
                        return false;
                    }
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlx));
                    viewx.getContext().startActivity(intent);
                    return true;
                }

});

and outside onCreateView :

 private void goToFacebook() {
        try {
            String facebookUrl = getFacebookPageURL();
            Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
            facebookIntent.setData(Uri.parse(facebookUrl));
            startActivity(facebookIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //facebook url load
    private String getFacebookPageURL() {
        String FACEBOOK_URL = "https://www.facebook.com/pg/XXpagenameXX/";
        String facebookurl = null;

        try {
            PackageManager packageManager = getActivity().getPackageManager();

            if (packageManager != null) {
                Intent activated = packageManager.getLaunchIntentForPackage("com.facebook.katana");

                if (activated != null) {
                    int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

                    if (versionCode >= 3002850) {
                        facebookurl = "fb://page/XXXXXXpage_id";
                    }
                } else {
                    facebookurl = FACEBOOK_URL;
                }
            } else {
                facebookurl = FACEBOOK_URL;
            }
        } catch (Exception e) {
            facebookurl = FACEBOOK_URL;
        }
        return facebookurl;
    }

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How to get the number of columns from a JDBC ResultSet?

After establising the connection and executing the query try this:

 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

How do I seed a random class to avoid getting duplicate random values

public static Random rand = new Random(); // this happens once, and will be great at preventing duplicates

Note, this is not to be used for cryptographic purposes.

Permanently adding a file path to sys.path in Python

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can't "add a file to sys.path". You always add its directory and then you can import the file.

iOS: present view controller programmatically

Here is how you can do it in Swift:

let vc = UIViewController()
self.presentViewController(vc, animated: true, completion: nil)

Have a fixed position div that needs to scroll if content overflows

Generally speaking, fixed section should be set with width, height and top, bottom properties, otherwise it won't recognise its size and position.

If the used box is direct child for body and has neighbours, then it makes sense to check z-index and top, left properties, since they could overlap each other, which might affect your mouse hover while scrolling the content.

Here is the solution for a content box (a direct child of body tag) which is commonly used along with mobile navigation.

.fixed-content {
    position: fixed;
    top: 0;
    bottom:0;

    width: 100vw; /* viewport width */
    height: 100vh; /* viewport height */
    overflow-y: scroll;
    overflow-x: hidden;
}

Hope it helps anybody. Thank you!

access key and value of object using *ngFor

Have Object.keys accessible in the template and use it in *ngFor.

@Component({
  selector: 'app-myview',
  template: `<div *ngFor="let key of objectKeys(items)">{{key + ' : ' + items[key]}}</div>`
})

export class MyComponent {
  objectKeys = Object.keys;
  items = { keyOne: 'value 1', keyTwo: 'value 2', keyThree: 'value 3' };
  constructor(){}
}

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Just look in file /var/log/auth.log on the server. Setting additional verbosity with -vv on the client side won't help, because the server is unlikely to offer too much information to a possible attacker.

How can I create an array/list of dictionaries in python?

Minor variation to user1850980's answer (for the question "How to initialize a list of empty dictionaries") using list constructor:

dictlistGOOD = list( {} for i in xrange(listsize) )

I found out to my chagrin, this does NOT work:

dictlistFAIL = [{}] * listsize  # FAIL!

as it creates a list of references to the same empty dictionary, so that if you update one dictionary in the list, all the other references get updated too.

Try these updates to see the difference:

dictlistGOOD[0]["key"] = "value"
dictlistFAIL[0]["key"] = "value"

(I was actually looking for user1850980's answer to the question asked, so his/her answer was helpful.)

Is there a "previous sibling" selector?

You could use double negation

SELECTOR:not([SELECTOR]FILTER):not([SELECTOR]FILTER + SELECTOR) { ... }

Replace SELECTOR with either the TAG or .CLASS ( Using #ID is probably too specific ). Replace FILTER with some other :PSUEDO-SELECTOR (I've only tried :hover) or .CLASS (More for toggling through Javascript).

Since the typical usage will probably rely upon hovering (See example that follows)

/* Effect only limited when hovering */
TAG.CLASS:not(TAG.CLASS:hover):not(TAG.CLASS:hover + TAG.CLASS) {}
/* Effect only applied when hovering */
PARENT.CLASS:hover > CHILD.CLASS:not(CHILD.CLASS:hover):not(CHILD.CLASS:hover + CHILD.CLASS) {}

_x000D_
_x000D_
/* Solution */
div.parent:hover > div.child:not(:hover):not(:hover ~ .child)  {
    background-color:red;
    border-radius:1.5em;
}
div.parent:hover > div.child:not(:hover):not(:hover ~ .child) > div {
    background-color:yellow;
}

/* Make pretty (kinda) */
div.parent {
  width:9em;
  height:9em;
  /* Layout */
  display:grid;
  grid-template-columns : auto auto auto;
  grid-template-rows : auto auto auto;
}
div.child {
  /* Dimensions */
  height:3em;
  width:3em;
  /* Layout */
  position:relative;
  /* Cursor */
  cursor: pointer;
  /* Presentation */
  border: 1px black solid;
  border-radius:1.5em;
}
.star {
  /* Dimensions */
  width: 2.5em;
  height: 2.5em;
  /* Placement */
  position:absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
  /* Geometry */
  -webkit-clip-path: polygon(
    50% 0%,
    63% 38%,
    100% 38%,
    69% 59%,
    82% 100%,
    50% 75%,
    18% 100%,
    31% 59%,
    0% 38%,
    37% 38%
  );
  clip-path: polygon(
    50% 0%,
    63% 38%,
    100% 38%,
    69% 59%,
    82% 100%,
    50% 75%,
    18% 100%,
    31% 59%,
    0% 38%,
    37% 38%
  );
  /* Presentation */
  background-color: lightgrey;
}
div.child:hover {
    /* Presentation */
    background-color:yellow;
    border-radius:1.5em;
}
div.child:hover > div.star {
    /* Presentation */
    background-color:red;
}
_x000D_
<div class="parent">
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
 </div>
_x000D_
_x000D_
_x000D_

How to redirect 404 errors to a page in ExpressJS?

If you use express-generator package:

next(err);

This code send you to the 404 middleware.

How to use a dot "." to access members of dictionary?

Using namedtuple allows dot access.

It is like a lightweight object which also has the properties of a tuple.

It allows to define properties and access them using the dot operator.

from collections import namedtuple
Data = namedtuple('Data', ['key1', 'key2'])

dataObj = Data(val1, key2=val2) # can instantiate using keyword arguments and positional arguments

Access using dot operator

dataObj.key1 # Gives val1
datObj.key2 # Gives val2

Access using tuple indices

dataObj[0] # Gives val1
dataObj[1] # Gives val2

But remember this is a tuple; not a dict. So the below code will give error

dataObj['key1'] # Gives TypeError: tuple indices must be integers or slices, not str

Refer: namedtuple

What is the difference between Serializable and Externalizable in Java?

Serialization provides default functionality to store and later recreate the object. It uses verbose format to define the whole graph of objects to be stored e.g. suppose you have a linkedList and you code like below, then the default serialization will discover all the objects which are linked and will serialize. In default serialization the object is constructed entirely from its stored bits, with no constructor calls.

  ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream("/Users/Desktop/files/temp.txt"));
        oos.writeObject(linkedListHead); //writing head of linked list
        oos.close();

But if you want restricted serialization or don't want some portion of your object to be serialized then use Externalizable. The Externalizable interface extends the Serializable interface and adds two methods, writeExternal() and readExternal(). These are automatically called while serialization or deserialization. While working with Externalizable we should remember that the default constructer should be public else the code will throw exception. Please follow the below code:

public class MyExternalizable implements Externalizable
{

private String userName;
private String passWord;
private Integer roll;

public MyExternalizable()
{

}

public MyExternalizable(String userName, String passWord, Integer roll)
{
    this.userName = userName;
    this.passWord = passWord;
    this.roll = roll;
}

@Override
public void writeExternal(ObjectOutput oo) throws IOException 
{
    oo.writeObject(userName);
    oo.writeObject(roll);
}

@Override
public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException 
{
    userName = (String)oi.readObject();
    roll = (Integer)oi.readObject();
}

public String toString()
{
    StringBuilder b = new StringBuilder();
    b.append("userName: ");
    b.append(userName);
    b.append("  passWord: ");
    b.append(passWord);
    b.append("  roll: ");
    b.append(roll);

    return b.toString();
}
public static void main(String[] args)
{
    try
    {
        MyExternalizable m  = new MyExternalizable("nikki", "student001", 20);
        System.out.println(m.toString());
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/Desktop/files/temp1.txt"));
        oos.writeObject(m);
        oos.close();

        System.out.println("***********************************************************************");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/Desktop/files/temp1.txt"));
        MyExternalizable mm = (MyExternalizable)ois.readObject();
        mm.toString();
        System.out.println(mm.toString());
    } 
    catch (ClassNotFoundException ex) 
    {
        Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch(IOException ex)
    {
        Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

Here if you comment the default constructer then the code will throw below exception:

 java.io.InvalidClassException: javaserialization.MyExternalizable;     
 javaserialization.MyExternalizable; no valid constructor.

We can observe that as password is sensitive information, so i am not serializing it in writeExternal(ObjectOutput oo) method and not setting the value of same in readExternal(ObjectInput oi). That's the flexibility that is provided by Externalizable.

The output of the above code is as per below:

userName: nikki  passWord: student001  roll: 20
***********************************************************************
userName: nikki  passWord: null  roll: 20

We can observe as we are not setting the value of passWord so it's null.

The same can also be achieved by declaring the password field as transient.

private transient String passWord;

Hope it helps. I apologize if i made any mistakes. Thanks.

Limit results in jQuery UI Autocomplete

Here is the proper documentation for the jQueryUI widget. There isn't a built-in parameter for limiting max results, but you can accomplish it easily:

$("#auto").autocomplete({
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(myarray, request.term);

        response(results.slice(0, 10));
    }
});

You can supply a function to the source parameter and then call slice on the filtered array.

Here's a working example: http://jsfiddle.net/andrewwhitaker/vqwBP/

Can a relative sitemap url be used in a robots.txt?

Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.

It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"

In the above URL after the colon gives space. I also like to support Deepak.

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

Enable/disable buttons with Angular

export class ClassComponent implements OnInit {
  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]


checkCurrentLession(current){

 this.classes.forEach((obj)=>{
    if(obj.currentLession == current){
      return true;
    }

  });
  return false;
}


<ul class="table lessonOverview">
        <li>
          <p>Lesson 1</p>
          <button [routerLink]="['/lesson1']" 
             [disabled]="checkCurrentLession(1)" class="primair">
               Start lesson</button>
        </li>
        <li>
          <p>Lesson 2</p>
          <button [routerLink]="['/lesson2']" 
             [disabled]="!checkCurrentLession(2)" class="primair">
               Start lesson</button>
        </li>
     </ul>

MVC Razor Radio Button

<p>@Html.RadioButtonFor(x => x.type, "Item1")Item1</p>
<p>@Html.RadioButtonFor(x => x.type, "Item2")Item2</p>
<p>@Html.RadioButtonFor(x => x.type, "Item3")Item3</p>

Align two divs horizontally side by side center to the page using bootstrap css

The response provided by Ranveer (second answer above) absolutely does NOT work.

He says to use col-xx-offset-#, but that is not how offsets are used.

If you wasted your time trying to use col-xx-offset-#, as I did based on his answer, the solution is to use offset-xx-#.

Application_Start not firing?

Try switching the managed pipeline mode for the app pool to "Classic" instead of "Integrated". That solved the problem for me. Looking into the reason now...

(Props for this answer belong to Flores (see his comment on his own answer), I just wanted to provide this as a separate answer to draw more attention to it)

how to make UITextView height dynamic according to text length?

In my project, the view controller is involved with lots of Constraints and StackView, and I set the TextView height as a constraint, and it varies based on the textView.contentSize.height value.

step1: get a IB outlet

@IBOutlet weak var textViewHeight: NSLayoutConstraint!

step2: use the delegation method below.

extension NewPostViewController: UITextViewDelegate {
     func textViewDidChange(_ textView: UITextView) {
          textViewHeight.constant = self.textView.contentSize.height + 10
     }
}

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

How do I check if a cookie exists?

There are several good answers here. I however prefer [1] not using a regular expression, and [2] using logic that is simple to read, and [3] to have a short function that [4] does not return true if the name is a substring of another cookie name . Lastly [5] we can't use a for each loop since a return doesn't break it.

function cookieExists(name) {
  var cks = document.cookie.split(';');
  for(i = 0; i < cks.length; i++)
    if (cks[i].split('=')[0].trim() == name) return true;
}

How to disable the parent form when a child form is active?

@Melodia

Sorry for this is not C# code but this is what you would want, besides translating this should be easy.

FORM1

Private Sub Form1_MouseEnter(sender As Object, e As EventArgs) Handles MyBase.MouseEnter
    Me.Focus()
    Me.Enabled = True
    Form2.Enabled = False
End Sub

Private Sub Form1_MouseLeave(sender As Object, e As EventArgs) Handles MyBase.MouseLeave
    Form2.Enabled = True
    Form2.Focus()
End Sub

FORM2

Private Sub Form2_MouseEnter(sender As Object, e As EventArgs) Handles MyBase.MouseEnter
    Me.Focus()
    Me.Enabled = True
    Form1.Enabled = False
End Sub

Private Sub Form2_MouseLeave(sender As Object, e As EventArgs) Handles MyBase.MouseLeave
    Form1.Enabled = True
    Form1.Focus()
End Sub

Hope this helps

How do I create a URL shortener?

Why not just generate a random string and append it to the base URL? This is a very simplified version of doing this in C#.

static string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
static string baseUrl = "https://google.com/";

private static string RandomString(int length)
{
    char[] s = new char[length];
    Random rnd = new Random();
    for (int x = 0; x < length; x++)
    {
        s[x] = chars[rnd.Next(chars.Length)];
    }
    Thread.Sleep(10);

    return new String(s);
}

Then just add the append the random string to the baseURL:

string tinyURL = baseUrl + RandomString(5);

Remember this is a very simplified version of doing this and it's possible the RandomString method could create duplicate strings. In production you would want to take in account for duplicate strings to ensure you will always have a unique URL. I have some code that takes account for duplicate strings by querying a database table I could share if anyone is interested.

What does DIM stand for in Visual Basic and BASIC?

Back in the day DIM reserved memory for the array and when memory was limited you had to be careful how you used it. I once wrote (in 1981) a BASIC program on TRS-80 Model III with 48Kb RAM. It wouldn't run on a similar machine with 16Kb RAM until I decreased the array size by changing the DIM statement

Refresh Page C# ASP.NET

You can just do a regular postback to refresh the page if you don't want to redirect. Posting back from any control will run the page lifecycle and refresh the page.

To do it from javascript, you can just call the __doPostBack() function.

Adding a collaborator to my free GitHub account?

It is pretty easy to add a collaborator to a free plan.

  1. Navigate to the repository on Github you wish to share with your collaborator.
  2. Click on the "Settings" tab on the right side of the menu at the top of the screen.
  3. On the new page, click the "Collaborators" menu item on the left side of the page.
  4. Start typing the new collaborator's GitHub username into the text box.
  5. Select the GitHub user from the list that appears below the text box.
  6. Click the "Add" button.

The added user should now be able to push to your repository on GitHub.

how to write value into cell with vba code without auto type conversion?

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

Stash just a single file

You can interactively stash single lines with git stash -p (analogous to git add -p).

It doesn't take a filename, but you could just skip other files with d until you reached the file you want stashed and the stash all changes in there with a.

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

How to set image button backgroundimage for different state?

i think you problem is not the selector file.

you have to add

<imagebutton ..
    android:clickable="true"
/>

to your image buttons.

by default the onClick is handled at the listitem level (parent). and the imageButtons dont recieve the onClick.

when you add the above attribute the image button will receive the event and the selector will be used.

check this POST which explains the same for checkbox.

How do I check/uncheck all checkboxes with a button using jQuery?

Below code will work if user select all checkboxs then check all-checkbox will be checked and if user unselect any one checkbox then check all-checkbox will be unchecked.

_x000D_
_x000D_
$("#checkall").change(function () {_x000D_
    $("input:checkbox").prop('checked', $(this).prop("checked"));_x000D_
});_x000D_
_x000D_
$(".cb-element").change(function () {_x000D_
  if($(".cb-element").length==$(".cb-element:checked").length)_x000D_
    $("#checkall").prop('checked', true);_x000D_
  else_x000D_
    $("#checkall").prop('checked', false);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="all" id="checkall" />Check All</br>_x000D_
_x000D_
<input type="checkbox" class="cb-element" /> Checkbox  1</br>_x000D_
<input type="checkbox" class="cb-element" /> Checkbox  2</br>_x000D_
<input type="checkbox" class="cb-element" /> Checkbox  3
_x000D_
_x000D_
_x000D_

Store output of sed into a variable

To store the third line into a variable, use below syntax:

variable=`echo "$1" | sed '3q;d' urfile`

To store the changed line into a variable, use below syntax: variable=echo 'overflow' | sed -e "s/over/"OVER"/g" output:OVERflow

What is the difference between <p> and <div>?

The only difference between the two elements is semantics. Both elements, by default, have the CSS rule display: block (hence block-level) applied to them; nothing more (except somewhat extra margin in some instances). However, as aforementioned, they both different greatly in terms of semantics.

The <p> element, as its name somewhat implies, is for paragraphs. Thus, <p> should be used when you want to create blocks of paragraph text.

The <div> element, however, has little to no meaning semantically and therefore can be used as a generic block-level element — most commonly, people use it within layouts because it is meaningless semantically and can be used for generally anything you might require a block-level element for.

Link for more detail

Refresh/reload the content in Div using jquery/ajax

$("#mydiv").load(location.href + " #mydiv");

Always take note of the space just before the second # sign, otherwise the above code will return the whole page nested inside you intended DIV. Always put space.

Deep copy of a dict in python

dict.copy() is a shallow copy function for dictionary
id is built-in function that gives you the address of variable

First you need to understand "why is this particular problem is happening?"

In [1]: my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}

In [2]: my_copy = my_dict.copy()

In [3]: id(my_dict)
Out[3]: 140190444167808

In [4]: id(my_copy)
Out[4]: 140190444170328

In [5]: id(my_copy['a'])
Out[5]: 140190444024104

In [6]: id(my_dict['a'])
Out[6]: 140190444024104

The address of the list present in both the dicts for key 'a' is pointing to same location.
Therefore when you change value of the list in my_dict, the list in my_copy changes as well.


Solution for data structure mentioned in the question:

In [7]: my_copy = {key: value[:] for key, value in my_dict.items()}

In [8]: id(my_copy['a'])
Out[8]: 140190444024176

Or you can use deepcopy as mentioned above.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

This will work to both load and save a file into TXT from a HTML page with a save as choice

<html>
<body>

<table>
    <tr><td>Text to Save:</td></tr>
    <tr>
        <td colspan="3">
            <textarea id="inputTextToSave" cols="80" rows="25"></textarea>
        </td>
    </tr>
    <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
    <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad"></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </tr>
</table>

<script type="text/javascript">

function saveTextAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

function loadFileAsText()
{
    var fileToLoad = document.getElementById("fileToLoad").files[0];

    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}

</script>

</body>
</html>

Differences between JDK and Java SDK

My initial guess would be that the Java SDK is for building the JVM while the JDK is for building apps for the JVM.

Edit: Although this looks to be incorrect at the moment. Sun are in the process of opensourcing the JVM (perhaps they've even finished, now) so I wouldn't be too surprised if my answer does become correct... But at the moment, the SDK and JDK are the same thing.

Regex remove all special characters except numbers?

If you don't mind including the underscore as an allowed character, you could try simply:

result = subject.replace(/\W+/g, "");

If the underscore must be excluded also, then

result = subject.replace(/[^A-Z0-9]+/ig, "");

(Note the case insensitive flag)

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

Python: Tuples/dictionaries as keys, select, sort

A dictionary probably isn't what you should be using in this case. A more full featured library would be a better alternative. Probably a real database. The easiest would be sqlite. You can keep the whole thing in memory by passing in the string ':memory:' instead of a filename.

If you do want to continue down this path, you can do it with the extra attributes in the key or the value. However a dictionary can't be the key to a another dictionary, but a tuple can. The docs explain what's allowable. It must be an immutable object, which includes strings, numbers and tuples that contain only strings and numbers (and more tuples containing only those types recursively...).

You could do your first example with d = {('apple', 'red') : 4}, but it'll be very hard to query for what you want. You'd need to do something like this:

#find all apples
apples = [d[key] for key in d.keys() if key[0] == 'apple']

#find all red items
red = [d[key] for key in d.keys() if key[1] == 'red']

#the red apple
redapples = d[('apple', 'red')]

How to work with progress indicator in flutter?

This is my solution with stack

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

final themeColor = new Color(0xfff5a623);
final primaryColor = new Color(0xff203152);
final greyColor = new Color(0xffaeaeae);
final greyColor2 = new Color(0xffE8E8E8);

class LoadindScreen extends StatefulWidget {
  LoadindScreen({Key key, this.title}) : super(key: key);
  final String title;
  @override
  LoginScreenState createState() => new LoginScreenState();
}

class LoginScreenState extends State<LoadindScreen> {
  SharedPreferences prefs;

  bool isLoading = false;

  Future<Null> handleSignIn() async {
    setState(() {
      isLoading = true;
    });
    prefs = await SharedPreferences.getInstance();
    var isLoadingFuture = Future.delayed(const Duration(seconds: 3), () {
      return false;
    });
    isLoadingFuture.then((response) {
      setState(() {
        isLoading = response;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            widget.title,
            style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
          ),
          centerTitle: true,
        ),
        body: Stack(
          children: <Widget>[
            Center(
              child: FlatButton(
                  onPressed: handleSignIn,
                  child: Text(
                    'SIGN IN WITH GOOGLE',
                    style: TextStyle(fontSize: 16.0),
                  ),
                  color: Color(0xffdd4b39),
                  highlightColor: Color(0xffff7f7f),
                  splashColor: Colors.transparent,
                  textColor: Colors.white,
                  padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0)),
            ),

            // Loading
            Positioned(
              child: isLoading
                  ? Container(
                      child: Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(themeColor),
                        ),
                      ),
                      color: Colors.white.withOpacity(0.8),
                    )
                  : Container(),
            ),
          ],
        ));
  }
}

Multiple glibc libraries on a single host

I am not sure that the question is still relevant, but there is another way of fixing the problem: Docker. One can install an almost empty container of the Source Distribution (The Distribution used for development) and copy the files into the Container. That way You do not need to create the filesystem needed for chroot.

Angular checkbox and ng-click

The order of execution of ng-click and ng-model is ambiguous since they do not define clear priorities. Instead you should use ng-change or a $watch on the $scope to ensure that you obtain the correct values of the model variable.

In your case, this should work:

<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">

windows batch file rename

Use REN Command

Ren is for rename

ren ( where the file is located ) ( the new name )

example

ren C:\Users\&username%\Desktop\aaa.txt bbb.txt

it will change aaa.txt to bbb.txt

Your code will be :

ren (file located)AAA_a001.jpg a001.AAA.jpg

ren (file located)BBB_a002.jpg a002.BBB.jpg

ren (file located)CCC_a003.jpg a003.CCC.jpg

and so on

IT WILL NOT WORK IF THERE IS SPACES!

Hope it helps :D

how to show calendar on text box click in html

HTML Date Picker You can refer this.

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

My problem was that I had other libraries that my project referenced and those libraries had another version of appcompat referenced. This is what I did to resolve the issue:

(You should back up your project before doing this)

1) I deleted all the appcompat layout folders (ex: /res/layout-v11).

2) Solved the problems that arose from that, usually an error in menu.xml

3) Back to main project and add appcompat library, clean, and everything works!

What's the equivalent of Java's Thread.sleep() in JavaScript?

Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:

async function sleep(msec) {
    return new Promise(resolve => setTimeout(resolve, msec));
}

You can then use the sleep function in any other async function like this:

async function testSleep() {
    console.log("Waiting for 1 second...");
    await sleep(1000);
    console.log("Waiting done."); // Called 1 second after the first console.log
}

This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.

From MDN:

The await expression causes async function execution to pause until a Promise is fulfilled or rejected, and to resume execution of the async function after fulfillment.

For a full explanation see:

Validating with an XML schema in Python

I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check Validation with lxml. The page also lists how to use lxml to validate with other schema types.

How to add an extra source directory for maven to compile and include in the build jar?

You can add the directories for your build process like:

    ...
   <resources>
     <resource>
       <directory>src/bootstrap</directory>
     </resource>
   </resources>
   ...

The src/main/java is the default path which is not needed to be mentioned in the pom.xml

Excel 2013 VBA Clear All Filters macro

That is brilliant, the only answer I found that met my particular need, thanks SO much for putting it up!

I made just a minor addition to it so that the screen didn't flash and it removes and subsequently reapplies the password on each sheet as it cycles through [I have the same password for all sheets in the workbook]. In the spirit of your submission, I add this to assist anyone else....

Sub ClearFilters()
    Application.ScreenUpdating = False

    On Error Resume Next
    For Each wrksheet In ActiveWorkbook.Worksheets
        'Change the password to whatever is required
        wrksheet.Unprotect Password:="Albuterol1"
        wrksheet.ShowAllData 'This works for filtered data not in a table

        For Each lstobj In wrksheet.ListObjects
            If lstobj.ShowAutoFilter Then
                lstobj.Range.AutoFilter 'Clear filters from a table
                lstobj.Range.AutoFilter 'Add the filters back to the table
            End If

        'Change the password to whatever is required
        wrksheet.Protect Password:="Albuterol1", _
              DrawingObjects:=True, _
              Contents:=True, _
              Scenarios:=True, _
              AllowFiltering:=True
        Next 'Check next worksheet in the workbook
    Next

    Application.ScreenUpdating = True
End Sub

I know this is a relatively old post and don't really like being a necromancer... But since I had the same issue and tried a few of the options in this thread without success I combined some of the answers to get a working macro..

Hopefully this helps someone out there :)

Sub ResetFilters()
    On Error Resume Next
    For Each wrksheet In ActiveWorkbook.Worksheets
        wrksheet.ShowAllData 'This works for filtered data not in a table
        For Each lstobj In wrksheet.ListObjects
            If lstobj.ShowAutoFilter Then
                lstobj.Range.AutoFilter 'Clear filters from a table
                lstobj.Range.AutoFilter 'Add the filters back to the table
            End If
        Next 'Check next worksheet in the workbook
    Next
End Sub

Get element of JS object with an index

var myobj = {"A":["Abe"], "B":["Bob"]};

var keysArray = Object.keys(myobj);

var valuesArray = Object.keys(myobj).map(function(k) {

   return String(myobj[k]);

});

var mydata = valuesArray[keysArray.indexOf("A")]; // Abe

How to detect a loop in a linked list?

boolean hasCycle(Node head) {

    boolean dec = false;
    Node first = head;
    Node sec = head;
    while(first != null && sec != null)
    {
        first = first.next;
        sec = sec.next.next;
        if(first == sec )
        {
            dec = true;
            break;
        }

    }
        return dec;
}

Use above function to detect a loop in linkedlist in java.

jQuery select option elements by value

Here's the simplest solution with a clear selector:

function select_option(i) {
  return $('span#span_id select option[value="' + i + '"]').html();
}

Float a DIV on top of another DIV

Just add position, right and top to your class .close-image

.close-image {
    cursor: pointer;
    display: block;
    float: right;  
    z-index: 3;
    position: absolute; /*newly added*/
    right: 5px; /*newly added*/
    top: 5px;/*newly added*/
}

Error: " 'dict' object has no attribute 'iteritems' "

In Python2, dictionary.iteritems() is more efficient than dictionary.items() so in Python3, the functionality of dictionary.iteritems() has been migrated to dictionary.items() and iteritems() is removed. So you are getting this error.

Use dict.items() in Python3 which is same as dict.iteritems() of Python2.

Using Gradle to build a jar with dependencies

If you want the jar task to behave normally and also have an additional fatJar task, use the following:

task fatJar(type: Jar) {
    classifier = 'all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

The important part is with jar. Without it, the classes of this project are not included.

How to specify table's height such that a vertical scroll bar appears?

to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link

How to extract duration time from ffmpeg output?

I recommend using json format, it's easier for parsing

ffprobe -i your-input-file.mp4 -v quiet -print_format json -show_format -show_streams -hide_banner

{
    "streams": [
        {
            "index": 0,
            "codec_name": "aac",
            "codec_long_name": "AAC (Advanced Audio Coding)",
            "profile": "HE-AACv2",
            "codec_type": "audio",
            "codec_time_base": "1/44100",
            "codec_tag_string": "[0][0][0][0]",
            "codec_tag": "0x0000",
            "sample_fmt": "fltp",
            "sample_rate": "44100",
            "channels": 2,
            "channel_layout": "stereo",
            "bits_per_sample": 0,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/28224000",
            "duration_ts": 305349201,
            "duration": "10.818778",
            "bit_rate": "27734",
            "disposition": {
                "default": 0,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0
            }
        }
    ],
    "format": {
        "filename": "your-input-file.mp4",
        "nb_streams": 1,
        "nb_programs": 0,
        "format_name": "aac",
        "format_long_name": "raw ADTS AAC (Advanced Audio Coding)",
        "duration": "10.818778",
        "size": "37506",
        "bit_rate": "27734",
        "probe_score": 51
    }
}

you can find the duration information in format section, works both for video and audio

Adding Table rows Dynamically in Android

Activity
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableLayout
            android:id="@+id/mytable"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </TableLayout>
    </HorizontalScrollView>

Your Class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testtable);
    table = (TableLayout)findViewById(R.id.mytable);
    showTableLayout();
}


public  void showTableLayout(){
    Date date = new Date();
    int rows = 80;
    int colums  = 10;
    table.setStretchAllColumns(true);
    table.bringToFront();

    for(int i = 0; i < rows; i++){

        TableRow tr =  new TableRow(this);
        for(int j = 0; j < colums; j++)
        {
            TextView txtGeneric = new TextView(this);
            txtGeneric.setTextSize(18);
            txtGeneric.setText( dateFormat.format(date) + "\t\t\t\t" );
            tr.addView(txtGeneric);
            /*txtGeneric.setHeight(30); txtGeneric.setWidth(50);   txtGeneric.setTextColor(Color.BLUE);*/
        }
        table.addView(tr);
    }
}

Looping over arrays, printing both index and value

You would find the array keys with "${!foo[@]}" (reference), so:

for i in "${!foo[@]}"; do 
  printf "%s\t%s\n" "$i" "${foo[$i]}"
done

Which means that indices will be in $i while the elements themselves have to be accessed via ${foo[$i]}

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

How to get/generate the create statement for an existing hive table?

As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE which "shows the CREATE TABLE statement that creates a given table, or the CREATE VIEW statement that creates a given view."

Usage:

SHOW CREATE TABLE myTable;

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

HTTP Request in Kotlin

For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

However, you can also use standard Java libraries like java.net.HttpURLConnection which is part of the Java SDK:

fun sendGet() {
    val url = URL("http://www.google.com/")

    with(url.openConnection() as HttpURLConnection) {
        requestMethod = "GET"  // optional default is GET

        println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }
    }
}

Or simpler:

URL("https://google.com").readText()

After submitting a POST form open a new window showing the result

Add

<form target="_blank" ...></form>

or

form.setAttribute("target", "_blank");

to your form's definition.

Insert a background image in CSS (Twitter Bootstrap)

If you add the following you can set the background colour or image (your css)

 html { 
     background-image: url('http://yoursite/i/tile.jpg');
     background-repeat: repeat; 
 }

 .body {
     background-color: transparent; 
 }

This is because BS applies a css rule for background colour and also for the .container class.

How do you keep parents of floated elements from collapsing?

Although the code isn't perfectly semantic, I think it's more straightforward to have what I call a "clearing div" at the bottom of every container with floats in it. In fact, I've included the following style rule in my reset block for every project:

.clear 
{
   clear: both;
}

If you're styling for IE6 (god help you), you might want to give this rule a 0px line-height and height as well.

Laravel Eloquent update just if changes have been made

You can use getChanges() on Eloquent model even after persisting.

React - Preventing Form Submission

Make sure you put the onSubmit attribute on the form not the button in case you have a from.

<form onSubmit={e => e.preventDefault()}>
    <button onClick={this.handleClick}>Click Me</button>
</form>

Make sure to change the button onClick attribute to your custom function.

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Create a .c file containing just the line:

_MSC_VER

or

CompilerVersion=_MSC_VER

then pre-process with

cl /nologo /EP <filename>.c

It is easy to parse the output.

What's the difference between returning value or Promise.resolve from then()

In simple terms, inside a then handler function:

A) When x is a value (number, string, etc):

  1. return x is equivalent to return Promise.resolve(x)
  2. throw x is equivalent to return Promise.reject(x)

B) When x is a Promise that is already settled (not pending anymore):

  1. return x is equivalent to return Promise.resolve(x), if the Promise was already resolved.
  2. return x is equivalent to return Promise.reject(x), if the Promise was already rejected.

C) When x is a Promise that is pending:

  1. return x will return a pending Promise, and it will be evaluated on the subsequent then.

Read more on this topic on the Promise.prototype.then() docs.

What is perm space?

What exists under PremGen : Class Area comes under PremGen area. Static fields are also developed at class loading time, so they also exist in PremGen. Constant Pool area having all immutable fields that are pooled like String are kept here. In addition to that, class data loaded by class loaders, Object arrays, internal objects used by jvm are also located.

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

How to get selenium to wait for ajax response?

This works like a charm for me :

public void waitForAjax() {

    try {
        WebDriverWait driverWait = new WebDriverWait(driver, 10);

        ExpectedCondition<Boolean> expectation;   
        expectation = new ExpectedCondition<Boolean>() {

            public Boolean apply(WebDriver driverjs) {

                JavascriptExecutor js = (JavascriptExecutor) driverjs;
                return js.executeScript("return((window.jQuery != null) && (jQuery.active === 0))").equals("true");
            }
        };
        driverWait.until(expectation);
    }       
    catch (TimeoutException exTimeout) {

       // fail code
    }
    catch (WebDriverException exWebDriverException) {

       // fail code
    }
    return this;
}

Get div height with plain JavaScript

try

myDiv.offsetHeight 

_x000D_
_x000D_
console.log("Height:", myDiv.offsetHeight );
_x000D_
#myDiv { width: 100px; height: 666px; background: red}
_x000D_
<div id="myDiv"></div>
_x000D_
_x000D_
_x000D_

Shortcut to create properties in Visual Studio?

In addition to Amra's answer, you can find other snippets by typing

Ctrl + K, Ctrl + X

Which is mapped to Edit.InsertSnippet in my Visual Studio and shows you the full list of snippets available.

Also remember that you can configure your own snippets by using the Snippets Manager, which is available in the Tools menu, Code Snippets Manager.... Basically you create a file *.snippet and use the Import button in the Code Snippets Manager to add it to Visual Studio. For a full tutorial you can go to the docs; Walkthrough: Create a code snippet.


In Visual Studio Code snippets are handled slightly different than in Visual Studio. You can access all snippets by typing Ctrl + Shift + P and type in snippet. Two options should be available, Insert Snippet and Preferences: Configure User Snippets.

The former inserts a snippet from your list of snippets (using the Language Mode which you can see in the status bar), and with the latter you can create your own snippets for any Language Mode.

If you know the shortname you can just type that and use Tab to expand the snippet. For inserting a C# property you have three snippets available, prop, propfull, and propg, for different purposes.

Transferring files over SSH

If copying to/from your desktop machine, use WinSCP, or if on Linux, Nautilus supports SCP via the Connect To Server option.

scp can only copy files to a machine running sshd, hence you need to run the client software on the remote machine from the one you are running scp on.

If copying on the command line, use:

# copy from local machine to remote machine
scp localfile user@host:/path/to/whereyouwant/thefile

or

# copy from remote machine to local machine
scp user@host:/path/to/remotefile localfile

URL Encode a string in jQuery for an AJAX request

I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)

Hardcoded URL i.e.>

 var encodedName = encodeURIComponent(name);
 var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;

Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method

 var url = "ControllerName/ActionName/";   
 $.post(url,
        { name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
 function (data) {.......});

How to represent matrices in python

((1,2,3,4),
 (5,6,7,8),
 (9,0,1,2))

Using tuples instead of lists makes it marginally harder to change the data structure in unwanted ways.

If you are going to do extensive use of those, you are best off wrapping a true number array in a class, so you can define methods and properties on them. (Or, you could NumPy, SciPy, ... if you are going to do your processing with those libraries.)

Any good, visual HTML5 Editor or IDE?

for online solution try maqetta and aloha editor

for offline solution (download-able) try blue griffon

they are free :) oh yeah, one more, my favorite editor :) and game editor also: construct2

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

Hidden Columns in jqGrid

I just want to expand on queen3's suggestion, applying the following does the trick:

editoptions: { 
              dataInit: function(element) { 
                          $(element).attr("readonly", "readonly"); 
                        } 
             }

Scenario #1:

  • Field must be visible in the grid
  • Field must be visible in the form
  • Field must be read-only

Solution:

colModel:[
        {  name:'providerUserId',
               index:'providerUserId', 
               width:100,editable:true, 
               editrules:{required:true}, 
               editoptions:{ 
                            dataInit: function(element) { 
                                  jq(element).attr("readonly", "readonly"); 
                             } 
                           }
            },
],

The providerUserId is visible in the grid and visible when editing the form. But you cannot edit the contents.


Scenario #2:

  • Field must not be visible in the grid
  • Field must be visible in the form
  • Field must be read-only

Solution:

colModel:[
           {name:'providerUserId',
            index:'providerUserId', 
            width:100,editable:true, 
            editrules:{
                         required:true, 
                         edithidden:true
                      },
            hidden:true, 
            editoptions:{ 
                  dataInit: function(element) {                     
                             jq(element).attr("readonly", "readonly"); 
                          } 
                     }
         },
        ]

Notice in both instances I'm using jq to reference jquery, instead of the usual $. In my HTML I have the following script to modify the variable used by jQuery:

<script type="text/javascript">
    var jq = jQuery.noConflict();
</script>

Unable to ping vmware guest from another vmware guest

On both Operation Systems, must turnoff firewall. I using MS SERVER 2012 R2 & MS WIN-7 as a client. First of all call "RUN BOX" window logo button+ R, once RUN box appeared type "firewall.cpl" at Window Firewall setting you will see "Turn Window Firewall On or Off" like this you click it & chose "turn off window firewall" on both Private and Public Setting then OK. Ping again on guests OS. GOOD-LUCK Aungkokokhant

Intercept and override HTTP requests from WebView

Try this, I've used it in a personal wiki-like app:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("foo://")) {
            // magic
            return true;
        }
        return false;
    }
});

Why does Lua have no "continue" statement?

In Lua 5.2 the best workaround is to use goto:

-- prints odd numbers in [|1,10|]
for i=1,10 do
  if i % 2 == 0 then goto continue end
  print(i)
  ::continue::
end

This is supported in LuaJIT since version 2.0.1

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

I disagree with the most voted answer. Use screen and not window

    if(screen.innerHeight > screen.innerWidth){
    alert("Please use Landscape!");
}

Is the proper way to do it. If you calculate with window.height, you ll have trouble on Android. When keyboard is open, window shrinks. So use screen instead of window.

The screen.orientation.type is a good answer but with IE. https://caniuse.com/#search=screen.orientation

How enable auto-format code for Intellij IDEA?

None of the solutions in Intellij is as elegant (or useful) as in Eclipse. What we need is feature request to the intellij so that we can add a hook (what actions to perform) when the IDE autosaves.

In Eclipse we can add "post-save" actions, such as organize imports and format the class. Yes you have to do a "save" or ctrl-s but the hook is very convenient.

Rounding up to next power of 2

I'm trying to get nearest lower power of 2 and made this function. May it help you.Just multiplied nearest lower number times 2 to get nearest upper power of 2

int nearest_upper_power(int number){
    int temp=number;
    while((number&(number-1))!=0){
        temp<<=1;
        number&=temp;
    }
    //Here number is closest lower power 
    number*=2;
    return number;
}

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

I got solution. For pre-8.0 devices, you have to just use startService(), but for post-7.0 devices, you have to use startForgroundService(). Here is sample for code to start service.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, ServedService.class));
    } else {
        context.startService(new Intent(context, ServedService.class));
    }

And in service class, please add the code below for notification:

@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}

Where O is Android version 26.

If you don't want your service to run in Foreground and want it to run in background instead, post Android O you must bind the service to a connection like below:

Intent serviceIntent = new Intent(context, ServedService.class);
context.startService(serviceIntent);
context.bindService(serviceIntent, new ServiceConnection() {
     @Override
     public void onServiceConnected(ComponentName name, IBinder service) {
         //retrieve an instance of the service here from the IBinder returned 
         //from the onBind method to communicate with 
     }

     @Override
     public void onServiceDisconnected(ComponentName name) {
     }
}, Context.BIND_AUTO_CREATE);

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

How to set JFrame to appear centered, regardless of monitor resolution?

Use setLocationRelativeTo(null)

This method has a special effect when you pass it a null. According to the Javadoc:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

This should be done after setting the size or calling pack(), but before setting it visible, like this:

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Go to first line in a file in vim?

If you are using gvim, you could just hit Ctrl + Home to go the first line. Similarly, Ctrl + End goes to the last line.

ctypes - Beginner

Firstly: The >>> code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:

>>> 4+5
9

Here we see that the line that starts with >>> is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.

You never enter the >>> part into a .py file.

That takes care of your syntax error.

Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.

They all have benefits and drawbacks.

SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.

Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.

ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.

Where is the .NET Framework 4.5 directory?

The webpage is incorrect and I have pointed this out to MS and they will get it changed.

As already stated above .NET 4.5 is an in-place upgrade of 4.0 so you will only have Microsoft.NET\Framework\v4.0.30319.

The ToolVersion for MSBuild remains at "4.0".

Only allow Numbers in input Tag without Javascript

Though it's probably suggested to get some heavier validation via JS or on the server, HTML5 does support this via the pattern attribute.

<input type= "text" name= "name" pattern= "[0-9]"  title= "Title"/>

Using IS NULL or IS NOT NULL on join conditions - Theory question

Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.

What does "atomic" mean in programming?

It's something that "appears to the rest of the system to occur instantaneously", and falls under categorisation of Linearizability in computing processes. To quote that linked article further:

Atomicity is a guarantee of isolation from concurrent processes. Additionally, atomic operations commonly have a succeed-or-fail definition — they either successfully change the state of the system, or have no apparent effect.

So, for instance, in the context of a database system, one can have 'atomic commits', meaning that you can push a changeset of updates to a relational database and those changes will either all be submitted, or none of them at all in the event of failure, in this way data does not become corrupt, and consequential of locks and/or queues, the next operation will be a different write or a read, but only after the fact. In the context of variables and threading this is much the same, applied to memory.

Your quote highlights that this need not be expected behaviour in all instances.

iPhone hide Navigation Bar only on first page

The nicest solution I have found is to do the following in the first view controller.

Objective-C

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillDisappear:animated];
}

Swift

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(true, animated: animated)
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(false, animated: animated)
    super.viewWillDisappear(animated)
} 

This will cause the navigation bar to animate in from the left (together with the next view) when you push the next UIViewController on the stack, and animate away to the left (together with the old view), when you press the back button on the UINavigationBar.

Please note also that these are not delegate methods, you are overriding UIViewController's implementation of these methods, and according to the documentation you must call the super's implementation somewhere in your implementation.

How to show an alert box in PHP?

echo '<script language="javascript>';

Seems like a simple typo. You're missing a double-quote.

echo '<script language="javascript">';

This should do.

Convert International String to \u Codes in java

Apache commons StringEscapeUtils.escapeEcmaScript(String) returns a string with unicode characters escaped using the \u notation.

"Art of Beer  " -> "Art of Beer \u1F3A8 \u1F37A"

Why are hexadecimal numbers prefixed with 0x?

Short story: The 0 tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x is an arbitrary choice.

Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).

The BCPL language used the syntax 8 1234 for octal numbers. When Ken Thompson created B from BCPL, he used the 0 prefix instead. This is great because

  1. an integer constant now always consists of a single token,
  2. the parser can still tell right away it's got a constant,
  3. the parser can immediately tell the base (0 is the same in both bases),
  4. it's mathematically sane (00005 == 05), and
  5. no precious special characters are needed (as in #123).

When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x was arbitrarily chosen (00 was probably ruled out as awkward).

C# is a descendant of C, so it inherits the syntax.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

You seems to be missing implementation for interface UserDao. If you look at the exception closely it says

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency:

The way @Autowired works is that it would automatically look for implementation of a dependency you inject via an interface. In this case since there is no valid implementation of interface UserDao you get the error.Ensure you have a valid implementation for this class and your error should go.

Hope that helps.

how to define variable in jquery

var name = 'john';
document.write(name);

it will write the variable you have declared upper

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

Print time in a batch file (milliseconds)

If you're doing something like

for /l %%i in (1,1,500) do @echo %time%

or

if foo (
    echo %time%
    do_something
    echo %time%
)

then you could simply put a setlocal enabledelayedexpansion at the beginning of your batch file and use !time! instead of %time% which gets evaluated on execution, not on parsing the line (which includes complete blocks enclosed in parentheses).

How to prevent line-break in a column of a table cell (not a single cell)?

Just add

style="white-space:nowrap;"

Example:

<table class="blueTable" style="white-space:nowrap;">
   <tr>
      <td>My name is good</td>
    </tr>
 </table>

How to find encoding of a file via script on Linux?

uchardet - An encoding detector library ported from Mozilla.

Usage:

~> uchardet file.java 
UTF-8

Various Linux distributions (Debian/Ubuntu, OpenSuse-packman, ...) provide binaries.

Push origin master error on new repository

Initital add & commit worked like a charm. I guess it's just a matter of understanding Git's methodology of managing a project within the repository.

After that I've managed to push my data straight-away with no hassle.

Java: Add elements to arraylist with FOR loop where element name has increasing number

There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).

public class TheClass {

    private int theField= 42;

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

        TheClass c= new TheClass();

        System.out.println(c.getClass().getDeclaredField("theField").get(c));
    }
}

If else on WHERE clause

Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2 if email is NULL. Mine assumes you want to use email2 if email is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE `email` LIKE  '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE  '%[email protected]%')

How to check if a registry value exists using C#?

string keyName=@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\services\pcmcia";
string valueName="Start";
if (Registry.GetValue(keyName, valueName, null) == null)
{
     //code if key Not Exist
}
else
{
     //code if key Exist
}

error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords: http://en.cppreference.com/w/cpp/keyword

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

How to change border color of textarea on :focus

you need just in scss varible

$input-btn-focus-width:       .05rem !default;

How to change mysql to mysqli?

Here is a complete tutorial how to make it quickly if you need to make worgking again a website after PHP upgrade. I used it after upgrading hosting for my customers from 5.4 (OMG!!!) to 7.x PHP version.

This is a workaround and it is better to rewrite all code using PDO or mysqli Class.

1. Connection definition

First of all, you need to put the connection to a new variable $link or $con, or whatever you want.

Example

Change the connection from :

@mysql_connect($host, $username, $password) or die("Error message...");
@mysql_select_db($db);

or

@mysql_connect($host, $username, $password, $db) or die("Error message...");

to:

$con = mysqli_connect($host, $username, $password, $db) or die("Error message...");

2. mysql_* modification

With Notepad++ I use "Find in files" (Ctrl + Shift + f) :

Search and replace notepad++ box

in the following order I choose "Replace in Files" :

  1. mysql_query( -> mysqli_query($con,

  2. mysql_error() -> mysqli_error($con)

  3. mysql_close() -> mysqli_close($con)

  4. mysql_insert_id() -> mysqli_insert_id($con)

  5. mysql_real_escape_string( -> mysqli_real_escape_string($con,

  6. mysql_ -> mysqli_

3. adjustments

if you get errors it is maybe because your $con is not accessible from your functions.

You need to add a global $con; in all your functions, for example :

function my_function(...) {
    global $con;
    ...
}

In SQL class, you will put connection to $this->con instead of $con. and replace it in each functions call (for example : mysqli_query($con, $query);)

Downloading all maven dependencies to a directory NOT in repository?

Based on @Raghuram answer, I find a tutorial on Copying project dependencies, Just:

  1. Open your project pom.xml file and find this:

    <project>
      [...]
      <build>
        <plugins>
          ...
        </plugins>
      </build>
      [...]
    </project>
    
  2. Than replace the <plugins> ... </plugins> with:

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
              <overWriteReleases>false</overWriteReleases>
              <overWriteSnapshots>false</overWriteSnapshots>
              <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
    
  3. And call maven within the command line mvn dependency:copy-dependencies

After it finishes, it will create the folder target/dependency within all the jar's dependencies on the current directory where the pom.xml lives.

Perform commands over ssh with Python

First: I'm surprised that no one has mentioned fabric yet.

Second: For exactly those requirements you describe I've implemented an own python module named jk_simpleexec. It's purpose: Making running commands easy.

Let me explain a little bit about it for you.

The 'executing a command locally' problem

My python module jk_simpleexec provides a function named runCmd(..) that can execute a shell (!) command locally or remotely. This is very simple. Here is an example for local execution of a command:

import jk_simpleexec

cmdResult = jk_simpleexec.runCmd(None, "cd / ; ls -la")

NOTE: Be aware that the returned data is trimmed automatically by default to remove excessive empty lines from STDOUT and STDERR. (Of course this behavior can be deactivated, but for the purpose you've in mind exactly that behavior is what you will want.)

The 'processing the result' problem

What you will receive is an object that contains the return code, STDOUT and STDERR. Therefore it's very easy to process the result.

And this is what you want to do as the command you execute might exist and is launched but might fail in doing what it is intended to do. In the most simple case where you're not interested in STDOUT and STDERR your code will likely look something like this:

cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)

For debugging purposes you want to output the result to STDOUT at some time, so for this you can do just this:

cmdResult.dump()

If you would want to process STDOUT it's simple as well. Example:

for line in cmdResult.stdOutLines:
    print(line)

The 'executing a command remotely' problem

Now of course we might want to execute this command remotely on another system. For this we can use the same function runCmd(..) in exactly the same way but we need to specify a fabric connection object first. This can be done like this:

from fabric import Connection

REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = "mypwd"
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})

cmdResult = jk_simpleexec.runCmd(c, "cd / ; ls -la")

# ... process the result stored in cmdResult ...

c.close()

Everything remains exactly the same, but this time we run this command on another host. This is intended: I wanted to have a uniform API where there are no modifications required in the software if you at some time decide to move from the local host to another host.

The password input problem

Now of course there is the password problem. This has been mentioned above by some users: We might want to ask the user executing this python code for a password.

For this problem I have created an own module quite some time ago. jk_pwdinput. The difference to regular password input is that jk_pwdinput will output some stars instead of just printing nothing. So for every password character you type you will see a star. This way it's more easy for you to enter a password.

Here is the code:

import jk_pwdinput

# ... define other 'constants' such as REMOTE_LOGIN, REMOTE_HOST ...

REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")

(For completeness: If readpwd(..) returned None the user canceled the password input with Ctrl+C. In a real world scenario you might want to act on this appropriately.)

Full example

Here is a full example:

import jk_simpleexec
import jk_pwdinput
from fabric import Connection

REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})

cmdResult = jk_simpleexec.runCmd(
    c = c,
    command = "cd / ; ls -la"
)
cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)

c.close()

Final notes

So we have the full set:

  • Executing a command,
  • executing that command remotely via the same API,
  • creating the connection in an easy and secure way with password input.

The code above solves the problem quite well for me (and hopefully for you as well). And everything is open source: Fabric is BSD-2-Clause, and my own modules are provided under Apache-2.

Modules used:

Happy coding! ;-)

How to use "raise" keyword in Python

raise without any arguments is a special use of python syntax. It means get the exception and re-raise it. If this usage it could have been called reraise.

    raise

From The Python Language Reference:

If no expressions are present, raise re-raises the last exception that was active in the current scope.

If raise is used alone without any argument is strictly used for reraise-ing. If done in the situation that is not at a reraise of another exception, the following error is shown: RuntimeError: No active exception to reraise

How do I set the colour of a label (coloured text) in Java?

object.setForeground(Color.green);

*any colour you wish *object being declared earlier

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

Delete specific line from a text file?

  1. Read and remember each line

  2. Identify the one you want to get rid of

  3. Forget that one

  4. Write the rest back over the top of the file

Getting a count of objects in a queryset in django

Use related name to count votes for a specific contest

class Item(models.Model):
    name = models.CharField()

class Contest(models.Model);
    name = models.CharField()

class Votes(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)
    contest = models.ForeignKey(Contest, related_name="contest_votes")
    comment = models.TextField()

>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()

Writing File to Temp Folder

The Path class is very useful here.
You get two methods called

Path.GetTempFileName

Path.GetTempPath

that could solve your issue

So for example you could write: (if you don't mind the exact file name)

using(StreamWriter sw = new StreamWriter(Path.GetTempFileName()))
{
    sw.WriteLine("Your error message");
}

Or if you need to set your file name

string myTempFile = Path.Combine(Path.GetTempPath(), "SaveFile.txt");
using(StreamWriter sw = new StreamWriter(myTempFile))
{
     sw.WriteLine("Your error message");
}

java build path problems

  1. Right click on project, Properties, Java Build Path.
  2. Remove the current JRE library.
  3. Click Add library > JRE System Library > Workspace default JRE.

CSS Image size, how to fill, but not stretch?

Building off of @Dominic Green's answer using jQuery, here is a solution that should work for images that are either wider than they are high or higher than they are wide.

http://jsfiddle.net/grZLR/4/

There is probably a more elegant way of doing the JavaScript, but this does work.

function myTest() {
  var imgH = $("#my-img").height();
  var imgW = $("#my-img").width();
  if(imgW > imgH) {
    $(".container img").css("height", "100%");
    var conWidth = $(".container").width();
    var imgWidth = $(".container img").width();
    var gap = (imgWidth - conWidth)/2;
    $(".container img").css("margin-left", -gap);
  } else {
    $(".container img").css("width", "100%");
    var conHeight = $(".container").height();
    var imgHeight = $(".container img").height();
    var gap = (imgHeight - conHeight)/2;
    $(".container img").css("margin-top", -gap);
  }
}
myTest();

How to make a flat list out of list of lists?

Simple code for underscore.py package fan

from underscore import _
_.flatten([[1, 2, 3], [4, 5, 6], [7], [8, 9]])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

It solves all flatten problems (none list item or complex nesting)

from underscore import _
# 1 is none list item
# [2, [3]] is complex nesting
_.flatten([1, [2, [3]], [4, 5, 6], [7], [8, 9]])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

You can install underscore.py with pip

pip install underscore.py

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);

How to set environment variables in PyCharm?

You can set environmental variables in Pycharm's run configurations menu.

  1. Open the Run Configuration selector in the top-right and cick Edit Configurations...

    Edit Configurations...

  2. Find Environmental variables and click ...

    Environmental variables

  3. Add or change variables, then click OK

    Editing environmental variables

You can access your environmental variables with os.environ

import os
print(os.environ['SOME_VAR'])

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

How do I make a delay in Java?

Use Thread.sleep(1000);

1000 is the number of milliseconds that the program will pause.

try
{
    Thread.sleep(1000);
}
catch(InterruptedException ex)
{
    Thread.currentThread().interrupt();
}

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

If you are a Windows user you may uninstall Composer. Then install Composer. After that you install Laravel. Maybe it will work.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

python3x or higher

  1. load file in byte stream:
     body = ''
        for lines in open('website/index.html','rb'):
            decodedLine = lines.decode('utf-8')
            body = body+decodedLine.strip()
        return body
  1. use global setting:
    import io
    import sys
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

csv.Error: iterator should return strings, not bytes

You open the file in text mode.

More specifically:

ifile  = open('sample.csv', "rt", encoding=<theencodingofthefile>)

Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.

How to generate a number of most distinctive colors in R?

You can use the Polychrome package for this purpose. It just requires the number of colors and a few seedcolors. For example:

# install.packages("Polychrome")
library(Polychrome)

# create your own color palette based on `seedcolors`
P36 = createPalette(36,  c("#ff0000", "#00ff00", "#0000ff"))
swatch(P36)

You can learn more about this package at https://www.jstatsoft.org/article/view/v090c01.

what is this value means 1.845E-07 in excel?

Highlight the cells, format cells, select Custom then select zero.

What is the total amount of public IPv4 addresses?

According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.

And too many addresses in this post.

How do I remove a property from a JavaScript object?

_x000D_
_x000D_
var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};_x000D_
    _x000D_
delete myObject.regex;_x000D_
_x000D_
console.log ( myObject.regex); // logs: undefined
_x000D_
_x000D_
_x000D_

This works in Firefox and Internet Explorer, and I think it works in all others.

Flask-SQLalchemy update a row's information

Just assigning the value and committing them will work for all the data types but JSON and Pickled attributes. Since pickled type is explained above I'll note down a slightly different but easy way to update JSONs.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    data = db.Column(db.JSON)

def __init__(self, name, data):
    self.name = name
    self.data = data

Let's say the model is like above.

user = User("Jon Dove", {"country":"Sri Lanka"})
db.session.add(user)
db.session.flush()
db.session.commit()

This will add the user into the MySQL database with data {"country":"Sri Lanka"}

Modifying data will be ignored. My code that didn't work is as follows.

user = User.query().filter(User.name=='Jon Dove')
data = user.data
data["province"] = "south"
user.data = data
db.session.merge(user)
db.session.flush()
db.session.commit()

Instead of going through the painful work of copying the JSON to a new dict (not assigning it to a new variable as above), which should have worked I found a simple way to do that. There is a way to flag the system that JSONs have changed.

Following is the working code.

from sqlalchemy.orm.attributes import flag_modified
user = User.query().filter(User.name=='Jon Dove')
data = user.data
data["province"] = "south"
user.data = data
flag_modified(user, "data")
db.session.merge(user)
db.session.flush()
db.session.commit()

This worked like a charm. There is another method proposed along with this method here Hope I've helped some one.

System not declared in scope?

You need to add:

 #include <cstdlib>

in order for the compiler to see the prototype for system().

Maximum length of the textual representation of an IPv6 address?

Answered my own question:

IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).

So that's 39 characters max.

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}

How to jQuery clone() and change id?

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

To solve this issue you need to run your application by increasing the memory limit by using the option --max_old_space_size. By default the memory limit of Node.js is 512 mb.

node --max_old_space_size=2000  server.js 

Label on the left side instead above an input field

You must float left all elements like so:

.form-group,
.form-group label,
.form-group input { float:left; display:inline;   }

give some margin to the desired elements :

 .form-group { margin-right:5px }

and set the label the same line height as the height of the fields:

.form-group label { line-height:--px; }

Select top 1 result using JPA

Use a native SQL query by specifying a @NamedNativeQuery annotation on the entity class, or by using the EntityManager.createNativeQuery method. You will need to specify the type of the ResultSet using an appropriate class, or use a ResultSet mapping.

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

Android Design Support Library expandable Floating Action Button(FAB) menu

Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.

Just using animate().translationY() function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.

first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:

    <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab3"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_btn_speak_now" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab2"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_dialog_map" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

Now in your java class just define all your FAB and perform the click like shown below:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab1 = (FloatingActionButton) findViewById(R.id.fab1);
    fab2 = (FloatingActionButton) findViewById(R.id.fab2);
    fab3 = (FloatingActionButton) findViewById(R.id.fab3);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!isFABOpen){
                showFABMenu();
            }else{
                closeFABMenu();
            }
        }
    });

Use the animation().translationY() to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:

 private void showFABMenu(){
    isFABOpen=true;
    fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
    fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
    fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}

private void closeFABMenu(){
    isFABOpen=false;
    fab1.animate().translationY(0);
    fab2.animate().translationY(0);
    fab3.animate().translationY(0);
}

Now define the above mentioned dimension inside res->values->dimens.xml as shown below:

    <dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>

That's all hope this solution will help the people in future, who are searching for simple solution.

EDITED

If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github

to close the FAB on Backpress, override onBackPress() as showen below:

    @Override
public void onBackPressed() {
    if(!isFABOpen){
        this.super.onBackPressed();
    }else{
        closeFABMenu();
    }
}

The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub

enter image description here

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

Where to download visual studio express 2005?

Small tip for you. Microsoft frequently has 'launch parties' or 'launch events' in which they frequently distribute licensed, not for resale copies, of that product. I've gotten the last two versions of VS (2005 and 2008) by attending my local .NET user group chapter during those days.

Reload child component when variables on parent component changes. Angular2

In case, when we have no control over child component, like a 3rd party library component.

We can use *ngIf and setTimeout to reset the child component from parent without making any change in child component.

.template:

.ts:

show:boolean = true

resetChildForm(){
   this.show = false;

   setTimeout(() => {
      this.show = true
    }, 100);
}

event.preventDefault() function not working in IE

in IE, you can use

event.returnValue = false;

to achieve the same result.

And in order not to get an error, you can test for the existence of preventDefault:

if(event.preventDefault) event.preventDefault();

You can combine the two with:

event.preventDefault ? event.preventDefault() : (event.returnValue = false);

How to determine an interface{} value's "real" type?

There are multiple ways to get a string representation of a type. Switches can also be used with user types:

var user interface{}
user = User{name: "Eugene"}

// .(type) can only be used inside a switch
switch v := user.(type) {
case int:
    // Built-in types are possible (int, float64, string, etc.)
    fmt.Printf("Integer: %v", v)
case User:
    // User defined types work as well  
    fmt.Printf("It's a user: %s\n", user.(User).name)
}

// You can use reflection to get *reflect.rtype
userType := reflect.TypeOf(user)
fmt.Printf("%+v\n", userType)

// You can also use %T to get a string value
fmt.Printf("%T", user)

// You can even get it into a string
userTypeAsString := fmt.Sprintf("%T", user)

if userTypeAsString == "main.User" {
    fmt.Printf("\nIt's definitely a user")
}

Link to a playground: https://play.golang.org/p/VDeNDUd9uK6

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

I reached the point that I set, up to max_iter=1200000 on my LinearSVC classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False and leaving max_iter to its default.

With LogisticRegression(solver='lbfgs') classifier, you should increase max_iter. Mine have reached max_iter=7600 before the "ConvergenceWarning" disappears when training with large dataset's features.

How to send a POST request with BODY in swift

If you are using swift4 and Alamofire v4.0 then the accepted code would look like this :

            let parameters: Parameters = [ "username" : email.text!, "password" : password.text! ]
            let urlString = "https://api.harridev.com/api/v1/login"
            let url = URL.init(string: urlString)
            Alamofire.request(url!, method: .put, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
                 switch response.result
                {
                case .success(let json):
                    let jsonData = json as! Any
                    print(jsonData)
                case .failure(let error):
                    self.errorFailer(error: error)
                }
            }

Where to change default pdf page width and font size in jspdf.debug.js?

My case was to print horizontal (landscape) summary section - so:

}).then((canvas) => {
  const img = canvas.toDataURL('image/jpg');
  new jsPDF({
        orientation: 'l', // landscape
        unit: 'pt', // points, pixels won't work properly
        format: [canvas.width, canvas.height] // set needed dimensions for any element
  });
  pdf.addImage(img, 'JPEG', 0, 0, canvas.width, canvas.height);
  pdf.save('your-filename.pdf');
});

Storage permission error in Marshmallow

   Try this



int permission = ContextCompat.checkSelfPermission(MainActivity.this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

     if (permission != PackageManager.PERMISSION_GRANTED) {
                Log.i("grant", "Permission to record denied");

                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setMessage(getString(R.string.permsg))
                            .setTitle(getString(R.string.permtitle));

                    builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int id) {
                            Log.i("grant", "Clicked");
                            makeRequest();
                        }
                    });

                    AlertDialog dialog = builder.create();
                    dialog.show();

                } else {

                    //makeRequest1();
                    makeRequest();
                }
            }


     protected void makeRequest() {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    500);
        }



     @Override
        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case 500: {

                    if (grantResults.length == 0
                            || grantResults[0] !=
                            PackageManager.PERMISSION_GRANTED) {

                        Log.i("1", "Permission has been denied by user");

                    } else {

                        Log.i("1", "Permission has been granted by user");

                    }
                    return;
                }

            }
        }

How to delete columns that contain ONLY NAs?

Another option with Filter

Filter(function(x) !all(is.na(x)), df)

NOTE: Data from @Simon O'Hanlon's post.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

I had read yesterday that the issue was fixed for someone when that person cleared cookies. I had tried that but it did not work for me.

Checking the following section in DatabaseInterface.class.php,

        define(
            'PMA_MYSQL_INT_VERSION',
            PMA_Util::cacheGet('PMA_MYSQL_INT_VERSION', true)
        );

I figured that somehow cache is the problem. So, I remembered that I was restarting the service instead of doing a start and stop.

# restart the service
systemd restart php-fpm

# start and stop the service
systemd stop php-fpm
systemd start php-fpm

Doing a stop followed by a start fixed the issue for me.

Convert java.time.LocalDate into java.util.Date type

Kotlin Solution:

1) Paste this extension function somewhere.

fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())

2) Use it, and never google this again.

val myDate = myLocalDate.toDate()

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

As an alternative to everyone else's answers I've always done something like this:

List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
    if (someCondition) {
        toRemove.add(str);
    }
}
myArrayList.removeAll(toRemove);

This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.

How to switch activity without animation in Android?

The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying. So, if you want an instant transition - you could use this in the theme style:

<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>

Asp.net MVC ModelState.Clear

Well, this seemed to work on my Razor Page and never even did a round trip to the .cs file. This is old html way. It might be useful.

<input type="reset" value="Reset">

Floating point comparison functions for C#

static class FloatUtil {

    static bool IsEqual(float a, float b, float tolerance = 0.001f) {
      return Math.Abs(a - b) < tolerance;
    }

    static bool IsGreater(float a, float b) {
      return a > b;
    }

    static bool IsLess(float a, float b) {
      return a < b;
    }
}

The value of tolerance that is passed into IsEqual is something that the client could decide.

IsEqual(1.002, 1.001);          -->   False
IsEqual(1.002, 1.001, 0.01);    -->   True

How to set a default row for a query that returns no rows?

If your base query is expected to return only one row, then you could use this trick:

select NVL( MIN(rate), 0 ) AS rate 
from d_payment_index
where fy = 2007
  and payment_year = 2008
  and program_id = 18

(Oracle code, not sure if NVL is the right function for SQL Server.)

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I have exactly the same issue. I ran a couple of virtual hosts on my local machine for developing.

First, I changed /etc/apache2/conf-available/php5-fpm.conf. I replaced every

Order Deny,Allow
Deny from all

to

Require all granted

The configuration has to be enabled by a2enconf php5-fpm. I did the same with my virtual hosts configurations and made the replacements.

I think this is not advised for security reasons, but as long as I use my server for local purposes only I can live with it.

"X does not name a type" error in C++

You must declare the prototype it before using it:

class User;

class MyMessageBox
{
public:
 void sendMessage(Message *msg, User *recvr);
 Message receiveMessage();
 vector<Message> *dataMessageList;
};

class User
{
public:
 MyMessageBox dataMsgBox;
};

edit: Swapped the types

When to use StringBuilder in Java

Ralph's answer is fabulous. I would rather use StringBuilder class to build/decorate the String because the usage of it is more look like Builder pattern.

public String decorateTheString(String orgStr){
            StringBuilder builder = new StringBuilder();
            builder.append(orgStr);
            builder.deleteCharAt(orgStr.length()-1);
            builder.insert(0,builder.hashCode());
            return builder.toString();
}

It can be use as a helper/builder to build the String, not the String itself.

Is there a command like "watch" or "inotifywait" on the Mac?

I have a GIST for this and the usage is pretty simple

watchfiles <cmd> <paths...>

To illustrate, the following command will echo Hello World every time that file1 OR file2 change; and the default interval check is 1 second

watchfiles 'echo Hello World' /path/to/file1 /path/to/file2 

If I want to check every 5 seconds I can use the -t flag

watchfiles -t 'echo Hello World' /path/to/file1 /path/to/file2 
  • -v enables the verbose mode which shows debug information
  • -q makes watchfiles execute quietly (# will be shown so the user can see the program is executing)
  • -qq makes watchfiles execute completely quietly
  • -h shows the help and usage

https://gist.github.com/thiagoh/5d8f53bfb64985b94e5bc8b3844dba55

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

Method call if not null in C#

This article by Ian Griffiths gives two different solutions to the problem that he concludes are neat tricks that you should not use.

Powershell: Get FQDN Hostname

I have the following add.. I need to separate out the dns suffix from the hostname.. and I only "know" the servers alias shortname... and want to know what the dns suffix is

#example:
#serveralias:     MyAppServer.us.fred.com
#actualhostname:  server01.us.fred.com 
#I "know":        "MyAppServer" .. I pass this on as an env var called myjumpbox .. this could also be $env:computername


$forname                 = $env:myjumpbox
$fqdn                    = [System.Net.Dns]::GetHostByName($forname).Hostname
$shortname               = $fqdn.split('.')[0]
$domainname              = $fqdn -split $fqdn.split('.')[0]+"."
$dnssuf                  = $domainname[1]  
" name parts are- alias: " + $forname + " actual hostname: " + $shortname + " suffix: " + $dnssuf

#returns

name parts are- alias: MyAppServer actual hostname: server01 suffix: us.fred.com

Why rgb and not cmy?

The basic colours are RGB not RYB. Yes most of the softwares use the traditional RGB which can be used to mix together to form any other color i.e. RGB are the fundamental colours (as defined in Physics & Chemistry texts).

The printer user CMYK (cyan, magenta, yellow, and black) coloring as said by @jcomeau_ictx. You can view the following article to know about RGB vs CMYK: RGB Vs CMYK

A bit more information from the extract about them:

Red, Green, and Blue are "additive colors". If we combine red, green and blue light you will get white light. This is the principal behind the T.V. set in your living room and the monitor you are staring at now. Additive color, or RGB mode, is optimized for display on computer monitors and peripherals, most notably scanning devices.

Cyan, Magenta and Yellow are "subtractive colors". If we print cyan, magenta and yellow inks on white paper, they absorb the light shining on the page. Since our eyes receive no reflected light from the paper, we perceive black... in a perfect world! The printing world operates in subtractive color, or CMYK mode.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN