Programs & Examples On #Findancestor

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Pls, check if DataGridComboBoxColumn xaml below would work for you:

<DataGridComboBoxColumn 
    SelectedValueBinding="{Binding CompanyID}" 
    DisplayMemberPath="Name" 
    SelectedValuePath="ID">

    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

Here you can find another solution for the problem you're facing: Using combo boxes with the WPF DataGrid

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Convert special characters to HTML in Javascript

Yes, but if you need to insert the resulting string somewhere without it being converted back, you need to do:

str.replace(/'/g,"&amp;amp;#39;"); // and so on

How does += (plus equal) work?

  1. 1 += 2 won't throw an error but you still shouldn't do it. In this statement you are basically saying "set 1 equal to 1 + 2" but 1 is a constant number and not a variable of type :number or :string so it probably wouldn't do anything. Saying
    var myVariable = 1
    myVariable += 2
    console.log(myVariable)
    
    would log 3 to the console, as x += y is just short for x = x + y
  2. var data = [1,2,3,4,5]
    var sum
    data.forEach(function(value){
      sum += value
    })
    
    would make sum = 15 because:
    sum += 1 //sum = 1
    sum += 2 //sum = 3
    sum += 3 //sum = 6
    sum += 4 //sum = 10
    sum += 5 //sum = 15
    

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Reason : Old versions of Tomcat 6 JSP compiler don't seem to be aware of JDK 8 constant pool enhancements - eg. method handles. New code in JDK 8u is using a method handle instead of creating an anonymous class. This will cause the method handle to be listed in the constant pool and the eclipse compiler will choke on this - https://bz.apache.org/bugzilla/show_bug.cgi?id=56613

jQuery - Check if DOM element already exists

(()=> {
    var elem = document.querySelector('.elem');  
    (
        (elem) ? 
        console.log(elem+' was found.') :
        console.log('not found')
    )
})();

If it exists, it spits out the specified element as a DOM object. With JQuery $('.elem') it only tells you that it's an object if found but not which.

Get value from SimpleXMLElement Object

you can convert array with this function

function xml2array($xml){
$arr = array();

foreach ($xml->children() as $r)
{
    $t = array();
    if(count($r->children()) == 0)
    {
        $arr[$r->getName()] = strval($r);
    }
    else
    {
        $arr[$r->getName()][] = xml2array($r);
    }
}
return $arr;
}

How to list the files in current directory?

There is nothing wrong with your code. It should list all of the files and directories directly contained by the nominated directory.

The problem is most likely one of the following:

  • The "." directory is not what you expect it to be. The "." pathname actually means the "current directory" or "working directory" for the JVM. You can verify what directory "." actually is by printing out dir.getCanonicalPath().

  • You are misunderstanding what dir.listFiles() returns. It doesn't return all objects in the tree beneath dir. It only returns objects (files, directories, symlinks, etc) that are directly in dir.

The ".classpath" file suggests that you are looking at an Eclipse project directory, and Eclipse projects are normally configured with the Java files in a subdirectory such as "./src". I wouldn't expect to see any Java source code in the "." directory.


Can anyone explain to me why src isn't the current folder?"

Assuming that you are launching an application in Eclipse, then the current folder defaults to the project directory. You can change the default current directory via one of the panels in the Launcher configuration wizard.

EF Migrations: Rollback last applied migration?

I want to add some clarification to this thread:

Update-Database -TargetMigration:"name_of_migration"

What you are doing above is saying that you want to rollback all migrations UNTIL you're left with the migration specified. Thus, if you use GET-MIGRATIONS and you find that you have A, B, C, D, and E, then using this command will rollback E and D to get you to C:

Update-Database -TargetMigration:"C"

Also, unless anyone can comment to the contrary, I noticed that you can use an ordinal value and the short -Target switch (thus, -Target is the same as -TargetMigration). If you want to rollback all migrations and start over, you can use:

Update-Database -Target:0

0, above, would rollback even the FIRST migration (this is a destructive command--be sure you know what you're doing before you use it!)--something you cannot do if you use the syntax above that requires the name of the target migration (the name of the 0th migration doesn't exist before a migration is applied!). So in that case, you have to use the 0 (ordinal) value. Likewise, if you have applied migrations A, B, C, D, and E (in that order), then the ordinal 1 should refer to A, ordinal 2 should refer to B, and so on. So to rollback to B you could use either:

Update-Database -TargetMigration:"B"

or

Update-Database -TargetMigration:2

Edit October 2019:

According to this related answer on a similar question, correct command is -Target for EF Core 1.1 while it is -Migration for EF Core 2.0.

Is there a way to detect if a browser window is not currently active?

A slightly more complicated way would be to use setInterval() to check mouse position and compare to last check. If the mouse hasn't moved in a set amount of time, the user is probably idle.

This has the added advantage of telling if the user is idle, instead of just checking if the window is not active.

As many people have pointed out, this is not always a good way to check whether the user or browser window is idle, as the user might not even be using the mouse or is watching a video, or similar. I am just suggesting one possible way to check for idle-ness.

How to copy in bash all directory and files recursive?

code for a simple copy.

cp -r ./SourceFolder ./DestFolder

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder

for details help

cp --help

How to have multiple conditions for one if statement in python

Assuming you're passing in strings rather than integers, try casting the arguments to integers:

def example(arg1, arg2, arg3):
     if int(arg1) == 1 and int(arg2) == 2 and int(arg3) == 3:
          print("Example Text")

(Edited to emphasize I'm not asking for clarification; I was trying to be diplomatic in my answer. )

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

I had to change the js file, so to include "function()" at the beginning of it, and also "()" at the end line. That solved the problem

How to store a list in a column of a database table

Many SQL databases allow a table to contain a subtable as a component. The usual method is to allow the domain of one of the columns to be a table. This is in addition to using some convention like CSV to encode the substructure in ways unknown to the DBMS.

When Ed Codd was developing the relational model in 1969-1970, he specifically defined a normal form that would disallow this kind of nesting of tables. Normal form was later called First Normal Form. He then went on to show that for every database, there is a database in first normal form that expresses the same information.

Why bother with this? Well, databases in first normal form permit keyed access to all data. If you provide a table name, a key value into that table, and a column name, the database will contain at most one cell containing one item of data.

If you allow a cell to contain a list or a table or any other collection, now you can't provide keyed access to the sub items, without completely reworking the idea of a key.

Keyed access to all data is fundamental to the relational model. Without this concept, the model isn't relational. As to why the relational model is a good idea, and what might be the limitations of that good idea, you have to look at the 50 years worth of accumulated experience with the relational model.

How to resume Fragment from BackStack if exists

I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`

public void replaceFragment(BaseFragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    final FragmentManager fManager = getSupportFragmentManager();
    BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
    transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);

    if (fragm == null) {  //here fragment is not available in the stack
        transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
        transaction.addToBackStack(fragment.getFragmentTag());
    } else { 
        //fragment was found in the stack , now we can reuse the fragment
        // please do not add in back stack else it will add transaction in back stack
        transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
    }
    transaction.commit();
}

And in the onBackPressed()

 @Override
public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        super.onBackPressed();
    }else{
        finish();
    }
}

How to remove specific object from ArrayList in Java?

You can use Collections.binarySearch to find the element, then call remove on the returned index.

See the documentation for Collections.binarySearch here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29

This would require the ArrayTest object to have .equals implemented though. You would also need to call Collections.sort to sort the list. Finally, ArrayTest would have to implement the Comparable interface, so that binarySearch would run correctly.

This is the "proper" way to do it in Java. If you are just looking to solve the problem in a quick and dirty fashion, then you can just iterate over the elements and remove the one with the attribute you are looking for.

How to close an iframe within iframe itself

its kind of hacky but it works well-ish

 function close_frame(){
    if(!window.should_close){
        window.should_close=1;
    }else if(window.should_close==1){
        location.reload();
        //or iframe hide or whatever
    }
 }

 <iframe src="iframe_index.php" onload="close_frame()"></iframe>

then inside the frame

$('#close_modal_main').click(function(){
        window.location = 'iframe_index.php?close=1';
});

and if you want to get fancy through a

if(isset($_GET['close'])){
  die;
}

at the top of your frame page to make that reload unnoticeable

so basically the first time the frame loads it doesnt hide itself but the next time it loads itll call the onload function and the parent will have a the window var causing the frame to close

Using "super" in C++

Bjarne Stroustrup mentions in Design and Evolution of C++ that super as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized.

Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced.

After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem.

Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post.

So, no, this will probably never get standardized.

If you don't have a copy, Design and Evolution is well worth the cover price. Used copies can be had for about $10.

Adding elements to a collection during iteration

Given a list List<Object> which you want to iterate over, the easy-peasy way is:

while (!list.isEmpty()){
   Object obj = list.get(0);

   // do whatever you need to
   // possibly list.add(new Object obj1);

   list.remove(0);
}

So, you iterate through a list, always taking the first element and then removing it. This way you can append new elements to the list while iterating.

C - error: storage size of ‘a’ isn’t known

To anyone with who is having this problem, its a typo error. Check your spelling of your struct delcerations and your struct

Alternative to Intersect in MySQL

Your query would always return an empty recordset since cut_name= '?????' and cut_name='??' will never evaluate to true.

In general, INTERSECT in MySQL should be emulated like this:

SELECT  *
FROM    mytable m
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    othertable o
        WHERE   (o.col1 = m.col1 OR (m.col1 IS NULL AND o.col1 IS NULL))
                AND (o.col2 = m.col2 OR (m.col2 IS NULL AND o.col2 IS NULL))
                AND (o.col3 = m.col3 OR (m.col3 IS NULL AND o.col3 IS NULL))
        )

If both your tables have columns marked as NOT NULL, you can omit the IS NULL parts and rewrite the query with a slightly more efficient IN:

SELECT  *
FROM    mytable m
WHERE   (col1, col2, col3) IN
        (
        SELECT  col1, col2, col3
        FROM    othertable o
        )

Where does Anaconda Python install on Windows?

If you installed as admin ( and meant for all users )

C:\ProgramData\Anaconda3\Scripts\anaconda.exe

If you install as a normal user

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe

How to pass form input value to php function

You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

Make an exception handler like this,

private int ConvertIntoNumeric(String xVal)
{
 try
  { 
     return Integer.parseInt(xVal);
  }
 catch(Exception ex) 
  {
     return 0; 
  }
}

.
.
.
.

int xTest = ConvertIntoNumeric("N/A");  //Will return 0

How to swap String characters in Java?

'In' a string, you cant. Strings are immutable. You can easily create a second string with:

 String second = first.replaceFirst("(.)(.)", "$2$1");

Reading file using relative path in python project

I was thundered when the following code worked.

import os

for file in os.listdir("../FutureBookList"):
    if file.endswith(".adoc"):
        filename, file_extension = os.path.splitext(file)
        print(filename)
        print(file_extension)
        continue
    else:
        continue

So, I checked the documentation and it says:

Changed in version 3.6: Accepts a path-like object.

path-like object:

An object representing a file system path. A path-like object is either a str or...

I did a little more digging and the following also works:

with open("../FutureBookList/file.txt") as file:
   data = file.read()

Permission denied error on Github Push

I used to have the same error when i change my user email by git config --global user.email and found my solution here: Go to: Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials

Under Generic Credentials there are some credentials related to Github, Click on them and click "Remove".

and when you try to push something, you need to login again. hope this will be helpful for you

What is the best way to declare global variable in Vue.js?

As you need access to your hostname variable in every component, and to change it to localhost while in development mode, or to production hostname when in production mode, you can define this variable in the prototype.

Like this:

Vue.prototype.$hostname = 'http://localhost:3000'

And $hostname will be available in all Vue instances:

new Vue({
  beforeCreate: function () {
    console.log(this.$hostname)
  }
})

In my case, to automatically change from development to production, I've defined the $hostname prototype according to a Vue production tip variable in the file where I instantiated the Vue.

Like this:

Vue.config.productionTip = false
Vue.prototype.$hostname = (Vue.config.productionTip) ? 'https://hostname' : 'http://localhost:3000'

An example can be found in the docs: Documentation on Adding Instance Properties

More about production tip config can be found here:

Vue documentation for production tip

Apk location in New Android Studio

The .apk file is located at [your project]\out\production\[your project name]

What is the difference between an Instance and an Object?

An object is a construct, something static that has certain features and traits, such as properties and methods, it can be anything (a string, a usercontrol, etc)

An instance is a unique copy of that object that you can use and do things with.

Imagine a product like a computer.

THE xw6400 workstation is an object

YOUR xw6400 workstation, (or YOUR WIFE's xw6400 workstation) is an instance of the xw6400 workstation object

Get the current URL with JavaScript?

OK, getting the full URL of the current page is easy using pure JavaScript. For example, try this code on this page:

window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"

The window.location.href property returns the URL of the current page.

_x000D_
_x000D_
document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <h2>JavaScript</h2>_x000D_
  <h3>The window.location.href</h3>_x000D_
  <p id="root"></p>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Just not bad to mention these as well:

  • if you need a relative path, simply use window.location.pathname;

  • if you'd like to get the host name, you can use window.location.hostname;

  • and if you need to get the protocol separately, use window.location.protocol

    • also, if your page has hash tag, you can get it like: window.location.hash.

So window.location.href handles all in once... basically:

window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
    //true

Also using window is not needed if already in window scope...

So, in that case, you can use:

location.protocol

location.hostname

location.pathname

location.hash

location.href

Get the current URL with JavaScript

Java: Best way to iterate through a Collection (here ArrayList)

Here is an example

Query query = em.createQuery("from Student");
             java.util.List list = query.getResultList();
             for (int i = 0; i < list.size(); i++) 
             {

                 student = (Student) list.get(i);
                 System.out.println(student.id  + "  " + student.age + " " + student.name + " " + student.prenom);

             }

How to pass values across the pages in ASP.net without using Session

If it's just for passing values between pages and you only require it for the one request. Use Context.

Context

The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here:

// Add item to
Context Context.Items["myKey"] = myValue;

// Read an item from the
 Context Response.Write(Context["myKey"]);

http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6

Using the above. If you then do a Server.Transfer the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

how to set length of an column in hibernate with maximum length

if your column is varchar use annotation length

@Column(length = 255)

or use another column type

@Column(columnDefinition="TEXT")

How do I list / export private keys from a keystore?

First of all, be careful! All of your security depends on the… er… privacy of your private keys. Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys.

Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the -nocrypt option of its pkcs8 utility):

KeyStore keys = ...
char[] password = ...
Enumeration<String> aliases = keys.aliases();
while (aliases.hasMoreElements()) {
  String alias = aliases.nextElement();
  if (!keys.isKeyEntry(alias))
    continue;
  Key key = keys.getKey(alias, password);
  if ((key instanceof PrivateKey) && "PKCS#8".equals(key.getFormat())) {
    /* Most PrivateKeys use this format, but check for safety. */
    try (FileOutputStream os = new FileOutputStream(alias + ".key")) {
      os.write(key.getEncoded());
      os.flush();
    }
  }
}

If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question.

Insert Picture into SQL Server 2005 Image Field using only SQL

For updating a record:

 UPDATE Employees SET [Photo] = (SELECT
 MyImage.* from Openrowset(Bulk
 'C:\photo.bmp', Single_Blob) MyImage)
 where Id = 10

Notes:

  • Make sure to add the 'BULKADMIN' Role Permissions for the login you are using.
  • Paths are not pointing to your computer when using SQL Server Management Studio. If you start SSMS on your local machine and connect to a SQL Server instance on server X, the file C:\photo.bmp will point to hard drive C: on server X, not your machine!

How do you use MySQL's source command to import large files in windows

On my Xampp set-up I was able to use the following to import a database into MySQL:

C:\xampp\mysql\bin\mysql -u {username goes here} -p {leave password blank} {database name} < /path/to/file.sql [enter]

My personal experience on my local machine was as follows:
Username: Root
Database Name: testdatabase
SQL File Location: databasebackup.sql is located on my desktop

C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql 

That worked for me to import my 1GB+ file into my database.

Developing for Android in Eclipse: R.java not regenerating

Almost assuredly there is something wrong with the content that would be inserted into the genfile. Eclipse is not smart enough to show what the problems are or even indicate that there are problems!

Think about the last edit you made to any of the XML or image content - and try to 'rollback' your changes, manually if necessary.

I find that sometimes Eclipse does not like my file names for whatever reason, and I have to change them.

So add to the resources one by one assuring that it all 'works'. When something breaks, just try changing it a little bit until Eclipse accepts it.

You know it's working when the genfile appears - it will do so automatically if there are no problems.

Get the closest number out of an array

Another variant here we have circular range connecting head to toe and accepts only min value to given input. This had helped me get char code values for one of the encryption algorithm.

function closestNumberInCircularRange(codes, charCode) {
  return codes.reduce((p_code, c_code)=>{
    if(((Math.abs(p_code-charCode) > Math.abs(c_code-charCode)) || p_code > charCode) && c_code < charCode){
      return c_code;
    }else if(p_code < charCode){
      return p_code;
    }else if(p_code > charCode && c_code > charCode){
      return Math.max.apply(Math, [p_code, c_code]);
    }
    return p_code;
  });
}

Input mask for numeric and decimal

or also

<input type="text" onkeypress="handleNumber(event, '€ {-10,3} $')" placeholder="€  $" size=25>

with

function handleNumber(event, mask) {
    /* numeric mask with pre, post, minus sign, dots and comma as decimal separator
        {}: positive integer
        {10}: positive integer max 10 digit
        {,3}: positive float max 3 decimal
        {10,3}: positive float max 7 digit and 3 decimal
        {null,null}: positive integer
        {10,null}: positive integer max 10 digit
        {null,3}: positive float max 3 decimal
        {-}: positive or negative integer
        {-10}: positive or negative integer max 10 digit
        {-,3}: positive or negative float max 3 decimal
        {-10,3}: positive or negative float max 7 digit and 3 decimal
    */
    with (event) {
        stopPropagation()
        preventDefault()
        if (!charCode) return
        var c = String.fromCharCode(charCode)
        if (c.match(/[^-\d,]/)) return
        with (target) {
            var txt = value.substring(0, selectionStart) + c + value.substr(selectionEnd)
            var pos = selectionStart + 1
        }
    }
    var dot = count(txt, /\./, pos)
    txt = txt.replace(/[^-\d,]/g,'')

    var mask = mask.match(/^(\D*)\{(-)?(\d*|null)?(?:,(\d+|null))?\}(\D*)$/); if (!mask) return // meglio exception?
    var sign = !!mask[2], decimals = +mask[4], integers = Math.max(0, +mask[3] - (decimals || 0))
    if (!txt.match('^' + (!sign?'':'-?') + '\\d*' + (!decimals?'':'(,\\d*)?') + '$')) return

    txt = txt.split(',')
    if (integers && txt[0] && count(txt[0],/\d/) > integers) return
    if (decimals && txt[1] && txt[1].length > decimals) return
    txt[0] = txt[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.')

    with (event.target) {
        value = mask[1] + txt.join(',') + mask[5]
        selectionStart = selectionEnd = pos + (pos==1 ? mask[1].length : count(value, /\./, pos) - dot) 
    }

    function count(str, c, e) {
        e = e || str.length
        for (var n=0, i=0; i<e; i+=1) if (str.charAt(i).match(c)) n+=1
        return n
    }
}

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

Search text in stored procedure in SQL Server

This query is search text in stored procedure from all databases.

DECLARE @T_Find_Text VARCHAR(1000) = 'Foo'

IF OBJECT_ID('tempdb..#T_DBNAME') IS NOT NULL DROP TABLE #T_DBNAME
IF OBJECT_ID('tempdb..#T_PROCEDURE') IS NOT NULL DROP TABLE #T_PROCEDURE

CREATE TABLE #T_DBNAME
(
    IDX int IDENTITY(1,1) PRIMARY KEY 
    , DBName VARCHAR(255)
)

CREATE TABLE #T_PROCEDURE
(
    IDX int IDENTITY(1,1) PRIMARY KEY 
    , DBName VARCHAR(255)
    , Procedure_Name VARCHAR(MAX)
    , Procedure_Description VARCHAR(MAX)
)

INSERT INTO #T_DBNAME (DBName)
SELECT name FROM master.dbo.sysdatabases

DECLARE @T_C_IDX INT = 0
DECLARE @T_C_DBName VARCHAR(255)
DECLARE @T_SQL NVARCHAR(MAX)
DECLARE @T_SQL_PARAM NVARCHAR(MAX) 

SET @T_SQL_PARAM =   
    '   @T_C_DBName VARCHAR(255)
        , @T_Find_Text VARCHAR(255)
    '  


WHILE EXISTS(SELECT TOP 1 IDX FROM #T_DBNAME WHERE IDX > @T_C_IDX ORDER BY IDX ASC)
BEGIN

    SELECT TOP 1 
    @T_C_DBName = DBName 
    FROM #T_DBNAME WHERE IDX > @T_C_IDX ORDER BY IDX ASC

    SET @T_SQL = ''

    SET @T_SQL = @T_SQL + 'INSERT INTO #T_PROCEDURE(DBName, Procedure_Name, Procedure_Description)'
    SET @T_SQL = @T_SQL + 'SELECT SPECIFIC_CATALOG, ROUTINE_NAME, ROUTINE_DEFINITION '
    SET @T_SQL = @T_SQL + 'FROM ' + @T_C_DBName +  '.INFORMATION_SCHEMA.ROUTINES  '
    SET @T_SQL = @T_SQL + 'WHERE ROUTINE_DEFINITION LIKE ''%''+ @T_Find_Text + ''%'' '
    SET @T_SQL = @T_SQL + 'AND ROUTINE_TYPE = ''PROCEDURE'' '

    BEGIN TRY
        EXEC SP_EXECUTESQL  @T_SQL, @T_SQL_PARAM, @T_C_DBName, @T_Find_Text
    END TRY
    BEGIN CATCH
        SELECT @T_C_DBName + ' ERROR'
    END CATCH

    SET @T_C_IDX = @T_C_IDX + 1
END

SELECT IDX, DBName, Procedure_Name FROM #T_PROCEDURE ORDER BY DBName ASC

How to access component methods from “outside” in ReactJS?

Alternatively, if the method on Child is truly static (not a product of current props, state) you can define it on statics and then access it as you would a static class method. For example:

var Child = React.createClass({
  statics: {
    someMethod: function() {
      return 'bar';
    }
  },
  // ...
});

console.log(Child.someMethod()) // bar

Invalid URI: The format of the URI could not be determined

Better use Uri.IsWellFormedUriString(string uriString, UriKind uriKind). http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx

Example :-

 if(Uri.IsWellFormedUriString(slct.Text,UriKind.Absolute))
 {
        Uri uri = new Uri(slct.Text);
        if (DeleteFileOnServer(uri))
        {
          nn.BalloonTipText = slct.Text + " has been deleted.";
          nn.ShowBalloonTip(30);
        }
 }

Python: finding an element in a list

From Dive Into Python:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5

Check if input value is empty and display an alert

Also you can try this, if you want to focus on same text after error.

If you wants to show this error message in a paragraph then you can use this one:

 $(document).ready(function () {
    $("#submit").click(function () {
        if($('#selBooks').val() === '') {
            $("#Paragraph_id").text("Please select a book and then proceed.").show();
            $('#selBooks').focus();
            return false;
        }
    });
 });

Using Position Relative/Absolute within a TD?

This trick also suitable, but in this case align properties (middle, bottom etc.) won't be working.

<td style="display: block; position: relative;">
</td>

RedirectToAction with parameter

....

int parameter = Convert.ToInt32(Session["Id"].ToString());

....

return RedirectToAction("ActionName", new { Id = parameter });

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Do what the compiler tells you to do, i.e. recompile with -fPIC. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.

In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.

Finally, you can read about it on Wikipedia too.

Understanding SQL Server LOCKS on SELECT queries

At my work, we have a very big system that runs on many PCs at the same time, with very big tables with hundreds of thousands of rows, and sometimes many millions of rows.

When you make a SELECT on a very big table, let's say you want to know every transaction a user has made in the past 10 years, and the primary key of the table is not built in an efficient way, the query might take several minutes to run.

Then, our application might me running on many user's PCs at the same time, accessing the same database. So if someone tries to insert into the table that the other SELECT is reading (in pages that SQL is trying to read), then a LOCK can occur and the two transactions block each other.

We had to add a "NO LOCK" to our SELECT statement, because it was a huge SELECT on a table that is used a lot by a lot of users at the same time and we had LOCKS all the time.

I don't know if my example is clear enough? This is a real life example.

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

I can see you have accepted an answer which doesn't solve your problem entirely:

android:screenOrientation="portrait" 

This will force your app to be portrait on both phones and tablets.

You can have the app forced in the device's "preferred" orientation by using

android:screenOrientation="nosensor"

This will lead to forcing your app to portrait on most phones phones and landscape on tablets. There are many phones with keypads which were designed for landscape mode. Forcing your app to portrait can make it almost unusable on such devices. Android is recently migrating to other types of devices as well. It is best to just let the device choose the preferred orientation.

Node.js global variables

I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:

// Some global/configuration file that gets called in initialisation

global.MyError = [Function of MyError];

Yes, it is taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or at least somewhere to:

  1. Define the Error class in the first place
  2. In the script where you're throwing it
  3. In the script where you're catching it

Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.

How to secure RESTful web services?

HTTP Basic + HTTPS is one common method.

What is simplest way to read a file into String?

Yes, you can do this in one line (though for robust IOException handling you wouldn't want to).

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

This uses a java.util.Scanner, telling it to delimit the input with \Z, which is the end of the string anchor. This ultimately makes the input have one actual token, which is the entire file, so it can be read with one call to next().

There is a constructor that takes a File and a String charSetName (among many other overloads). These two constructor may throw FileNotFoundException, but like all Scanner methods, no IOException can be thrown beyond these constructors.

You can query the Scanner itself through the ioException() method if an IOException occurred or not. You may also want to explicitly close() the Scanner after you read the content, so perhaps storing the Scanner reference in a local variable is best.

See also

Related questions


Third-party library options

For completeness, these are some really good options if you have these very reputable and highly useful third party libraries:

Guava

com.google.common.io.Files contains many useful methods. The pertinent ones here are:

Apache Commons/IO

org.apache.commons.io.IOUtils also offer similar functionality:

  • String toString(InputStream, String encoding)
    • Using the specified character encoding, gets the contents of an InputStream as a String
  • List readLines(InputStream, String encoding)
    • ... as a (raw) List of String, one entry per line

Related questions

How to format a URL to get a file from Amazon S3?

Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:

https://<region>.amazonaws.com/<bucket-name>/<key>

Where <region> is something like s3-ap-southeast-2.

Click on the item in the S3 GUI to get the link for your bucket.

Merge or combine by rownames

Use match to return your desired vector, then cbind it to your matrix

cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])

             [,1]         [,2]         [,3]         [,4]   
GO.ID        "GO:0002009" "GO:0030334" "GO:0015674" NA     
LEVEL        "8"          "6"          "7"          NA     
Annotated    "342"        "343"        "350"        NA     
Significant  "1"          "1"          "1"          NA     
Expected     "0.07"       "0.07"       "0.07"       NA     
resultFisher "0.679"      "0.065"      "0.065"      NA     
ILMN_1652464 "0"          "0"          "1"          "PLAC8"
ILMN_1651838 "0"          "0"          "0"          "RND1" 
ILMN_1711311 "1"          "1"          "0"          NA     
ILMN_1653026 "0"          "0"          "0"          "GRA"  

PS. Be warned that t is base R function that is used to transpose matrices. By creating a variable called t, it can lead to confusion in your downstream code.

Split string in JavaScript and detect line break

You should try detect the first line.

Then the:

if(n == 0){
  line = words[n]+"\n";
}

I'm not sure, but maybe it helps.

String replacement in java, similar to a velocity template

Take a look at the java.text.MessageFormat class, MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

Object[] params = new Object[]{"hello", "!"};
String msg = MessageFormat.format("{0} world {1}", params);

How to add "active" class to Html.ActionLink in ASP.NET MVC

I modified dom's "not pretty" answer and made it uglier. Sometimes two controllers have the conflicting action names (i.e. Index) so I do this:

<ul class="nav navbar-nav">
  <li class="@(ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString() == "HomeIndex" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
  <li class="@(ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString() == "AboutIndex" ? "active" : "")">@Html.ActionLink("About", "Index", "About")</li>
  <li class="@(ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString() == "ContactHome" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>

Very Simple, Very Smooth, JavaScript Marquee

Responsive resist jQuery marquee simple plugin. Tutorial:

// start plugin
    (function($){
        $.fn.marque = function(options, callback){

            // check callback

            if(typeof callback == 'function'){
                callback.call(this);
            } else{
                console.log("second argument (callback) is not a function");
                // throw "callback must be a function"; //only if callback for some reason is required
                // return this; //only if callback for some reason is required
            }

            //set and overwrite default functions
            var defOptions = $.extend({
                speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
                select: $('.message div'),
                clickSelect: '', // selector that on click will redirect user ... (optional)
                clickUrl: '' //... to this url. (optional)
            }, options);

            //Run marque plugin
            var windowWidth = $(window).width();
            var textWidth = defOptions.select.outerWidth();
            var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
            var startingPosition = (windowWidth + textWidth);
            var curentPosition = (windowWidth + textWidth);
            var speedProportionToLocation = curentPosition / startingPosition;
            defOptions.select.css({'right': -(textWidth)});
            defOptions.select.show();
            var animation;


            function marquee(animation){
                curentPosition = (windowWidth + defOptions.select.outerWidth());
                speedProportionToLocation = curentPosition / startingPosition;
                animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
                     defOptions.select.css({'right': -(textWidth)});
                });
            }
            var play = setInterval(marquee, 200);

            //add onclick behaviour
            if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
                defOptions.clickSelect.click(function(){
                    window.location.href = defOptions.clickUrl;
                });
            }
            return this;
        };

    }(jQuery)); 
// end plugin 

Use this custom jQuery plugin as bellow:

//use example
$(window).marque({
    speedPixelsInOneSecound: 150, // spped pixels/secound
    select: $('.message div'), // select an object on which you want to apply marquee effects.
    clickSelect: $('.message'), // select clicable object (optional)
    clickUrl: 'services.php' // define redirection url (optional)
});

What causes signal 'SIGILL'?

Make sure that all functions with non-void return type have a return statement.

While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.

Routing with multiple Get methods in ASP.NET Web API

There are lots of good answers already for this question. However nowadays Route configuration is sort of "deprecated". The newer version of MVC (.NET Core) does not support it. So better to get use to it :)

So I agree with all the answers which uses Attribute style routing. But I keep noticing that everyone repeated the base part of the route (api/...). It is better to apply a [RoutePrefix] attribute on top of the Controller class and don't repeat the same string over and over again.

[RoutePrefix("api/customers")]
public class MyController : Controller
{
 [HttpGet]
 public List<Customer> Get()
 {
   //gets all customer logic
 }

 [HttpGet]
 [Route("currentMonth")]
 public List<Customer> GetCustomerByCurrentMonth()
 {
     //gets some customer 
 }

 [HttpGet]
 [Route("{id}")]
 public Customer GetCustomerById(string id)
 {
  //gets a single customer by specified id
 }
 [HttpGet]
 [Route("customerByUsername/{username}")]
 public Customer GetCustomerByUsername(string username)
 {
    //gets customer by its username
 }
}

Writelines writes lines without newline, Just fills the file

This is actually a pretty common problem for newcomers to Python—especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the log-related stuff) add them.

So, there's a lot of Python code out there that does things like:

fw.write('\n'.join(line_list) + '\n')

or

fw.write(line + '\n' for line in line_list)

Either one is correct, and of course you could even write your own writelinesWithNewlines function that wraps it up…

But you should only do this if you can't avoid it.

It's better if you can create/keep the newlines in the first place—as in Greg Hewgill's suggestions:

line_list.append(new_line + "\n")

And it's even better if you can work at a higher level than raw lines of text, e.g., by using the csv module in the standard library, as esuaro suggests.

For example, right after defining fw, you might do this:

cw = csv.writer(fw, delimiter='|')

Then, instead of this:

new_line = d[looking_for]+'|'+'|'.join(columns[1:])
line_list.append(new_line)

You do this:

row_list.append(d[looking_for] + columns[1:])

And at the end, instead of this:

fw.writelines(line_list)

You do this:

cw.writerows(row_list)

Finally, your design is "open a file, then build up a list of lines to add to the file, then write them all at once". If you're going to open the file up top, why not just write the lines one by one? Whether you're using simple writes or a csv.writer, it'll make your life simpler, and your code easier to read. (Sometimes there can be simplicity, efficiency, or correctness reasons to write a file all at once—but once you've moved the open all the way to the opposite end of the program from the write, you've pretty much lost any benefits of all-at-once.)

Regular Expression for alphanumeric and underscores

How about:

^([A-Za-z]|[0-9]|_)+$

...if you want to be explicit, or:

^\w+$

...if you prefer concise (Perl syntax).

How to disable auto-play for local video in iframe

You can set the source of the player as blank string on loading the page, in this way you don't have to switch to video tag.

var player = document.getElementById("video-player");
player.src = "";

When you want to play a video, just change its src attribute, for example:

function play(source){
   player.src = source;
}

Get week number (in the year) from a date PHP

<?php
$ddate = "2012-10-18";
$duedt = explode("-",$ddate);
$date = mktime(0, 0, 0, $duedt[1], $duedt[2],$duedt[0]);
$week = (int)date('W', $date);
echo "Weeknummer: ".$week;
?>

You had the params to mktime wrong - needs to be Month/Day/Year, not Day/Month/Year

How can I see an the output of my C programs using Dev-C++?

I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc

SQLite table constraint - unique on multiple columns

Well, your syntax doesn't match the link you included, which specifies:

 CREATE TABLE name (column defs) 
    CONSTRAINT constraint_name    -- This is new
    UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE

How to highlight cell if value duplicate in same column for google spreadsheet?

From the "Text Contains" dropdown menu select "Custom formula is:", and write: "=countif(A:A, A1) > 1" (without the quotes)

I did exactly as zolley proposed, but there should be done small correction: use "Custom formula is" instead of "Text Contains". And then conditional rendering will work.

Screenshot from menu

Updating PartialView mvc 4

You can also try this.

 $(document).ready(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        setInterval(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        }, 30000); //Refreshes every 30 seconds

        $.ajaxSetup({ cache: false });  //Turn off caching
    });

It makes an initial call to load the div, and then subsequent calls are on a 30 second interval.

In the controller section you can update the object and pass the object to the partial view.

public class ControllerName: Controller
{
    public ActionResult ActionName()
    {
        .
        .   // code for update object
        .
        return PartialView("PartialViewName", updatedObject);
    }
}

How to create a file in a directory in java?

To create a file and write some string there:

BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write("");         // for empty file
bufferedWriter.close();

This works for Mac and PC.

How to dynamically load a Python class

If you don't want to roll your own, there is a function available in the pydoc module that does exactly this:

from pydoc import locate
my_class = locate('my_package.my_module.MyClass')

The advantage of this approach over the others listed here is that locate will find any python object at the provided dotted path, not just an object directly within a module. e.g. my_package.my_module.MyClass.attr.

If you're curious what their recipe is, here's the function:

def locate(path, forceload=0):
    """Locate an object by name or dotted path, importing as necessary."""
    parts = [part for part in split(path, '.') if part]
    module, n = None, 0
    while n < len(parts):
        nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
        if nextmodule: module, n = nextmodule, n + 1
        else: break
    if module:
        object = module
    else:
        object = __builtin__
    for part in parts[n:]:
        try:
            object = getattr(object, part)
        except AttributeError:
            return None
    return object

It relies on pydoc.safeimport function. Here are the docs for that:

"""Import a module; handle errors; return None if the module isn't found.

If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised.  Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning.  If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""

Can I make a function available in every controller in angular?

You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.factory('myService', function() {
        return {
            foo: function() {
                alert("I'm foo!");
            }
        };
    });

    myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
        $scope.callFoo = function() {
            myService.foo();
        }
    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="callFoo()">Call foo</button>
</body>
</html>

If that's not an option for you, you can add it to the root scope like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.run(function($rootScope) {
        $rootScope.globalFoo = function() {
            alert("I'm global foo!");
        };
    });

    myApp.controller('MainCtrl', ['$scope', function($scope){

    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="globalFoo()">Call global foo</button>
</body>
</html>

That way, all of your templates can call globalFoo() without having to pass it to the template from the controller.

How to create a checkbox with a clickable label?

You could also use CSS pseudo elements to pick and display your labels from all your checkbox's value attributes (respectively).
Edit: This will only work with webkit and blink based browsers (Chrome(ium), Safari, Opera....) and thus most mobile browsers. No Firefox or IE support here.
This may only be useful when embedding webkit/blink onto your apps.

<input type="checkbox" value="My checkbox label value" />
<style>
[type=checkbox]:after {
    content: attr(value);
    margin: -3px 15px;
    vertical-align: top;
    white-space:nowrap;
    display: inline-block;
}
</style>

All pseudo element labels will be clickable.

Demo:http://codepen.io/mrmoje/pen/oteLl, + The gist of it

Python unittest passing arguments

This is my solution:

# your test class
class TestingClass(unittest.TestCase):
    
    # This will only run once for all the tests within this class
    @classmethod
    def setUpClass(cls) -> None:
       if len(sys.argv) > 1:
          cls.email = sys.argv[1]

    def testEmails(self):
        assertEqual(self.email, "[email protected]")


if __name__ == "__main__":
    unittest.main()

you could have a runner.py file with something like this:

# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests


with the above code, you should be to run your tests with runner.py [email protected]

Get width/height of SVG element

From Firefox 33 onwards you can call getBoundingClientRect() and it will work normally, i.e. in the question above it will return 300 x 100.

Firefox 33 will be released on 14th October 2014 but the fix is already in Firefox nightlies if you want to try it out.

How can I view a git log of just one user's commits?

cat | git log --author="authorName" > author_commits_details.txt

This gives your commits in text format.

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

Java - Best way to print 2D array?

Try this,

for (char[] temp : box) {
    System.err.println(Arrays.toString(temp).replaceAll(",", " ").replaceAll("\\[|\\]", ""));
}

Multiple modals overlay

I realize an answer has been accepted, but I strongly suggest not hacking bootstrap to fix this.

You can pretty easily achieve the same effect by hooking the shown.bs.modal and hidden.bs.modal event handlers and adjusting the z-index there.

Here's a working example

A bit more info is available here.

This solution works automatically with arbitrarily deeply stacks modals.

The script source code:

$(document).ready(function() {

    $('.modal').on('hidden.bs.modal', function(event) {
        $(this).removeClass( 'fv-modal-stack' );
        $('body').data( 'fv_open_modals', $('body').data( 'fv_open_modals' ) - 1 );
    });

    $('.modal').on('shown.bs.modal', function (event) {
        // keep track of the number of open modals
        if ( typeof( $('body').data( 'fv_open_modals' ) ) == 'undefined' ) {
            $('body').data( 'fv_open_modals', 0 );
        }

        // if the z-index of this modal has been set, ignore.
        if ($(this).hasClass('fv-modal-stack')) {
            return;
        }

        $(this).addClass('fv-modal-stack');
        $('body').data('fv_open_modals', $('body').data('fv_open_modals' ) + 1 );
        $(this).css('z-index', 1040 + (10 * $('body').data('fv_open_modals' )));
        $('.modal-backdrop').not('.fv-modal-stack').css('z-index', 1039 + (10 * $('body').data('fv_open_modals')));
        $('.modal-backdrop').not('fv-modal-stack').addClass('fv-modal-stack'); 

    });        
});

Define css class in django Forms

Simply add the classes to your form as follows.

class UserLoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={
        'class':'form-control',
        'placeholder':'Username'
        }
    ))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
        'class':'form-control',
        'placeholder':'Password'
        }
    ))

Why doesn't git recognize that my file has been changed, therefore git add not working

In general with this issue, first check that you're editing the file you think you are! I had this problem when I was editing a transpiled JavaScript file instead of the source file (the transpiled version wasn't under source control).

Simple Android RecyclerView example

Since I cant comment yet im gonna post as an answer the link.. I have found a simple, well organized tutorial on recyclerview http://www.androiddeft.com/2017/10/01/recyclerview-android/

Apart from that when you are going to add a recycler view into you activity what you want to do is as below and how you should do this has been described on the link

  • add RecyclerView component into your layout file
  • make a class which you are going to display as list rows
  • make a layout file which is the layout of a row of you list
  • now we need a custom adapter so create a custom adapter by extending from the parent class RecyclerView.Adapter
  • add recyclerview into your mainActivity oncreate
  • adding separators
  • adding Touch listeners

Spring Boot Adding Http Request Interceptors

Since all responses to this make use of the now long-deprecated abstract WebMvcConfigurer Adapter instead of the WebMvcInterface (as already noted by @sebdooe), here is a working minimal example for a SpringBoot (2.1.4) application with an Interceptor:

Minimal.java:

@SpringBootApplication
public class Minimal
{
    public static void main(String[] args)
    {
        SpringApplication.run(Minimal.class, args);
    }
}

MinimalController.java:

@RestController
@RequestMapping("/")
public class Controller
{
    @GetMapping("/")
    @ResponseBody
    public ResponseEntity<String> getMinimal()
    {
        System.out.println("MINIMAL: GETMINIMAL()");

        return new ResponseEntity<String>("returnstring", HttpStatus.OK);
    }
}

Config.java:

@Configuration
public class Config implements WebMvcConfigurer
{
    //@Autowired
    //MinimalInterceptor minimalInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(new MinimalInterceptor());
    }
}

MinimalInterceptor.java:

public class MinimalInterceptor extends HandlerInterceptorAdapter
{
    @Override
    public boolean preHandle(HttpServletRequest requestServlet, HttpServletResponse responseServlet, Object handler) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR PREHANDLE CALLED");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR POSTHANDLE CALLED");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception
    {
        System.out.println("MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED");
    }
}

works as advertised

The output will give you something like:

> Task :Minimal.main()

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-04-29 11:53:47.560  INFO 4593 --- [           main] io.minimal.Minimal                       : Starting Minimal on y with PID 4593 (/x/y/z/spring-minimal/build/classes/java/main started by x in /x/y/z/spring-minimal)
2019-04-29 11:53:47.563  INFO 4593 --- [           main] io.minimal.Minimal                       : No active profile set, falling back to default profiles: default
2019-04-29 11:53:48.745  INFO 4593 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-04-29 11:53:48.780  INFO 4593 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-04-29 11:53:48.781  INFO 4593 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-29 11:53:48.892  INFO 4593 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-04-29 11:53:48.893  INFO 4593 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1269 ms
2019-04-29 11:53:49.130  INFO 4593 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-29 11:53:49.375  INFO 4593 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-29 11:53:49.380  INFO 4593 --- [           main] io.minimal.Minimal                       : Started Minimal in 2.525 seconds (JVM running for 2.9)
2019-04-29 11:54:01.267  INFO 4593 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-04-29 11:54:01.267  INFO 4593 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-04-29 11:54:01.286  INFO 4593 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 19 ms
MINIMAL: INTERCEPTOR PREHANDLE CALLED
MINIMAL: GETMINIMAL()
MINIMAL: INTERCEPTOR POSTHANDLE CALLED
MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED

ASP.NET Core configuration for .NET Core console application

On .Net Core 3.1 we just need to do these:

static void Main(string[] args)
{
  var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}

Using SeriLog will look like:

using Microsoft.Extensions.Configuration;
using Serilog;
using System;


namespace yournamespace
{
    class Program
    {

        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();

            try
            {
                Log.Information("Starting Program.");
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Program terminated unexpectedly.");
                return;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}

And the Serilog appsetings.json section for generating one file daily will look like:

  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "C:\\Logs\\Program.json",
          "rollingInterval": "Day",
          "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
        }
      }
    ]
  }

How To Set Text In An EditText

You need to:

  1. Declare the EditText in the xml file
  2. Find the EditText in the activity
  3. Set the text in the EditText

Unix tail equivalent command in Windows Powershell

I took @hajamie's solution and wrapped it up into a slightly more convenient script wrapper.

I added an option to start from an offset before the end of the file, so you can use the tail-like functionality of reading a certain amount from the end of the file. Note the offset is in bytes, not lines.

There's also an option to continue waiting for more content.

Examples (assuming you save this as TailFile.ps1):

.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000 -Follow:$true
.\TailFile.ps1 -File .\path\to\myfile.log -Follow:$true

And here is the script itself...

param (
    [Parameter(Mandatory=$true,HelpMessage="Enter the path to a file to tail")][string]$File = "",
    [Parameter(Mandatory=$true,HelpMessage="Enter the number of bytes from the end of the file")][int]$InitialOffset = 10248,
    [Parameter(Mandatory=$false,HelpMessage="Continuing monitoring the file for new additions?")][boolean]$Follow = $false
)

$ci = get-childitem $File
$fullName = $ci.FullName

$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($fullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length - $InitialOffset

while ($true)
{
    #if the file size has not changed, idle
    if ($reader.BaseStream.Length -ge $lastMaxOffset) {
        #seek to the last max offset
        $reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null

        #read out of the file until the EOF
        $line = ""
        while (($line = $reader.ReadLine()) -ne $null) {
            write-output $line
        }

        #update the last max offset
        $lastMaxOffset = $reader.BaseStream.Position
    }

    if($Follow){
        Start-Sleep -m 100
    } else {
        break;
    }
}

How does HTTP file upload work?

Send file as binary content (upload without form or FormData)

In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data Content-Type header.

If you want to send the file as the only content then you can directly add it as the request body and you set the Content-Type header to the MIME type of the file you are sending. The file name can be added in the Content-Disposition header. You can upload like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

If you don't (want to) use forms and you are only interested in uploading one single file this is the easiest way to include your file in the request.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Umair R's answer is mostly the right move to solve the problem, as this error used to be caused by the missing links between opencv libs and the programme. so there is the need to specify the ld_libraty_path configuration. ps. the usual library path is suppose to be:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

I have tried this and it worked well.

How to convert string to boolean php

Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP (taken from the documentation for empty):

  1. "" (an empty string);
  2. "0" (0 as a string)

If you need to set a boolean based on the text value of a string, then you'll need to check for the presence or otherwise of that value.

$test_mode_mail = $string === 'true'? true: false;

EDIT: the above code is intended for clarity of understanding. In actual use the following code may be more appropriate:

$test_mode_mail = ($string === 'true');

or maybe use of the filter_var function may cover more boolean values:

filter_var($string, FILTER_VALIDATE_BOOLEAN);

filter_var covers a whole range of values, including the truthy values "true", "1", "yes" and "on". See here for more details.

How to find a hash key containing a matching value

You could use Enumerable#select:

clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]

Note that the result will be an array of all the matching values, where each is an array of the key and value.

Using custom std::set comparator

1. Modern C++20 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;

We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

Online demo

2. Modern C++11 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);

Before C++20 we need to pass lambda as argument to set constructor

Online demo

3. Similar to first solution, but with function instead of lambda

Make comparator as usual boolean function

bool cmp(int a, int b) {
    return ...;
}

Then use it, either this way:

std::set<int, decltype(cmp)*> s(cmp);

Online demo

or this way:

std::set<int, decltype(&cmp)> s(&cmp);

Online demo

4. Old solution using struct with () operator

struct cmp {
    bool operator() (int a, int b) const {
        return ...
    }
};

// ...
// later
std::set<int, cmp> s;

Online demo

5. Alternative solution: create struct from boolean function

Take boolean function

bool cmp(int a, int b) {
    return ...;
}

And make struct from it using std::integral_constant

#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;

Finally, use the struct as comparator

std::set<X, Cmp> set;

Online demo

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Angular JS break ForEach

Try this as break;

angular.forEach([0,1,2], function(count){
  if(count == 1){
    return true;
  }
});

SVN how to resolve new tree conflicts when file is added on two branches

I found a post suggesting a solution for that. It's about to run:

svn resolve --accept working <YourPath>

which will claim the local version files as OK.
You can run it for single file or entire project catalogues.

Java: recommended solution for deep cloning/copying an instance

For deep cloning (clones the entire object hierarchy):

  • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable.

  • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable.

For shallow cloning (clones only the first level properties):

I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn't preferred.

Add a UIView above all, even the navigation bar

[[UIApplication sharedApplication].windows.lastObject addSubview:myView];

Programmatically get own phone number in iOS

No, there's no legal and reliable way to do this.

If you find a way, it will be disabled in the future, as it has happened with every method before.

Git Bash: Could not open a connection to your authentication agent

Situation: MVS2017 App - Using 'Git Bash' on Windows 10 - Trying to connect to a BitBucket repository.

To be clear, when you install Git for Windows (https://git-scm.com/download/win), it comes with an utility called Git Bash.

enter image description here

So, I am in 'Git Bash', as follows:

Mike@DUBLIN MINGW64 ~/source/repos/DoubleIrish (master)
$ git remote add origin [email protected]:Guiness/DoubleIrish.git
$ git remote -v
origin  [email protected]:Guiness/DoubleIrish.git (fetch)
origin  [email protected]:Guiness/DoubleIrish.git (push)
Mike@DUBLIN MINGW64 ~/source/repos/DoubleIrish (master)
$ git push -u origin master
[...]
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Is the private key set up?

$ ssh -V
OpenSSH_7.7p1, OpenSSL 1.0.2p  14 Aug 2018
$ ls -a ~/.ssh
./  ../  known_hosts

I can see that, at this point, my private key file (id_rsa) is missing. So I add it: (note: generating a pair of private-public keys is out of scope of my reply, but I can say that in Linux, you can use ssh-keygen for that.)

$ ls -a ~/.ssh
./  ../  id_rsa  known_hosts

OK, let's proceed:

$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-KhQwFLAgWGYC/agent.18320; export SSH_AUTH_SOCK;
SSH_AGENT_PID=17996; export SSH_AGENT_PID;
echo Agent pid 17996;

$ ssh-add ~/.ssh/id_rsa
Could not open a connection to your authentication agent.

To solve this, I run:

$ ssh-agent bash

And then, again:

$ ssh-add ~/.ssh/id_rsa
Identity added: /c/Users/Mike.CORP/.ssh/id_rsa (/c/Users/Mike.CORP/.ssh/id_rsa)

It worked for me. Hope this helps

Convert varchar into datetime in SQL Server

use Try_Convert:Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

DECLARE @DateString VARCHAR(10) ='20160805'
SELECT TRY_CONVERT(DATETIME,@DateString)

SET @DateString ='Invalid Date'
SELECT TRY_CONVERT(DATETIME,@DateString)

Link:MSDN TRY_CONVERT (Transact-SQL)

How to read pickle file?

There is a read_pickle function as part of pandas 0.22+

import pandas as pd

object = pd.read_pickle(r'filepath')

How to manage a redirect request after a jQuery Ajax call

Finally, I solve the problem by adding a custom HTTP Header. Just before response for every request in server side, i add the current requested url to response's header.

My application type on server is Asp.Net MVC, and it has a good place to do it. in Global.asax i implemented the Application_EndRequest event so:

    public class MvcApplication : System.Web.HttpApplication
    {

    //  ...
    //  ...

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            app.Context.Response.Headers.Add("CurrentUrl",app.Context. Request.CurrentExecutionFilePath);
        }

    }

It works perfect for me! Now in every response of the JQuery $.post i have the requested url and also other response headers which comes as result of POST method by status 302, 303 ,... .

and other important thing is that there is no need to modify code on server side nor client side.

and the next is the ability to get access to the other information of post action such errors, messages, and ..., In this way.

I posted this, maybe help someone :)

QtCreator: No valid kits found

In my case the issue was that my default kit's Qt version was None.

Go to Tools -> Options... -> Build & Run -> Kits tab, click on the kit you want to make as default and you'll see a list of fields beneath, one of which is Qt version. If it's None, change it to one of the versions available to you in the Qt versions tab which is just next to the Kits tab.

How to define an optional field in protobuf 3

Another way to encode the message you intend is to add another field to track "set" fields:

syntax="proto3";

package qtprotobuf.examples;

message SparseMessage {
    repeated uint32 fieldsUsed = 1;
    bool   attendedParty = 2;
    uint32 numberOfKids  = 3;
    string nickName      = 4;
}

message ExplicitMessage {
    enum PARTY_STATUS {ATTENDED=0; DIDNT_ATTEND=1; DIDNT_ASK=2;};
    PARTY_STATUS attendedParty = 1;
    bool   indicatedKids = 2;
    uint32 numberOfKids  = 3;
    enum NO_NICK_STATUS {HAS_NO_NICKNAME=0; WOULD_NOT_ADMIT_TO_HAVING_HAD_NICKNAME=1;};
    NO_NICK_STATUS noNickStatus = 4;
    string nickName      = 5;
}

This is especially appropriate if there is a large number of fields and only a small number of them have been assigned.

In python, usage would look like this:

import field_enum_example_pb2
m = field_enum_example_pb2.SparseMessage()
m.attendedParty = True
m.fieldsUsed.append(field_enum_example_pb2.SparseMessages.ATTENDEDPARTY_FIELD_NUMBER)

Create whole path automatically when writing to a new file

Use File.mkdirs():

File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);

Upgrade Node.js to the latest version on Mac OS

sudo npm install -g n

and then

sudo n latest for linux/mac users

For Windows please reinstall node.

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

How can I delete using INNER JOIN with SQL Server?

It is possible this will be helpful for you -

DELETE FROM dbo.WorkRecord2
WHERE EmployeeRun IN (
    SELECT e.EmployeeNo
    FROM dbo.Employee e
    WHERE ...
)

Or try this -

DELETE FROM dbo.WorkRecord2
WHERE EXISTS(
    SELECT 1
    FROM dbo.Employee e
    WHERE EmployeeRun = e.EmployeeNo
        AND ....
)

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

If someone is using the new DataTables (which is awesome btw) and want to use array of objects then you can do so easily with the columns option. Refer to the following link for an excellent example on this.

DataTables with Array of Objects

I was struggling with this for the past 2 days and this solved it. I didn't wanted to switch to multi-dimensional arrays for other code reasons so was looking for a solution like this.

Why is a ConcurrentModificationException thrown and how to debug it

This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
   Entry item = it.next();
   map.remove(item.getKey());
}

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

The correct approach would be

   Iterator it = map.entrySet().iterator();
   while (it.hasNext())
   {
      Entry item = it.next();
      it.remove();
   }

Assuming this iterator supports the remove() operation.

When should I use Kruskal as opposed to Prim (and vice versa)?

Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Fibonacci Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high ,like E=O(V²).

Output PowerShell variables to a text file

You can concatenate an array of values together using PowerShell's `-join' operator. Here is an example:

$FilePath = '{0}\temp\scripts\pshell\dump.txt' -f $env:SystemDrive;

$Computer = 'pc1';
$Speed = 9001;
$RegCheck = $true;

$Computer,$Speed,$RegCheck -join ',' | Out-File -FilePath $FilePath -Append -Width 200;

Output

pc1,9001,True

Access Controller method from another controller in Laravel 5

Late reply, but I have been looking for this for sometime. This is now possible in a very simple way.

Without parameters

return redirect()->action('HomeController@index');

With Parameters

return redirect()->action('UserController@profile', ['id' => 1]);

Docs: https://laravel.com/docs/5.6/responses#redirecting-controller-actions

Back in 5.0 it required the entire path, now it's much simpler.

Twitter Bootstrap - how to center elements horizontally or vertically

You may directly write into your css file like this :

_x000D_
_x000D_
.content {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left:50%;_x000D_
  transform: translate(-50%,-50%);_x000D_
  }
_x000D_
<div class = "content" >_x000D_
  _x000D_
   <p> some text </p>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

package R does not exist

For anyone who ran into this, I refactored by renaming the namespace folders. I just forgot to also edit AndroidManifest and that's why I got this error.

Make sure you check this as well.

JSON response parsing in Javascript to get key/value pair

var yourobj={
"c":{
    "a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
    },
"o":{
    "v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
    "e":[{"name":"lens cleaner","value":1}]
},
"h":{
    "d":[{"name":"hdmi cable","value":1},
         {"name":"hdtv essentials (hdtv cable setup)","value":1},
         {"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
  • first of all it's a good idea to get organized
  • top level reference must be a more convenient name other that a..v... etc
  • in o.v,o.i.e no need for the array [] because it is one json entry

my solution

var obj = [];
for(n1 in yourjson)
    for(n1_1 in yourjson[n])
        for(n1_2 in yourjson[n][n1_1])
            obj[n1_2[name]] = n1_2[value];

Approved code

for(n1 in yourobj){
    for(n1_1 in yourobj[n1]){
    for(n1_2 in yourobj[n1][n1_1]){
            for(n1_3 in yourobj[n1][n1_1][n1_2]){
      obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
            }
    }
 }
}
console.log(obj);

result

*You should use distinguish accessorizes when using [] method or dot notation

proove

Swift convert unix time to date and time

To get the date to show as the current time zone I used the following.

if let timeResult = (jsonResult["dt"] as? Double) {
     let date = NSDate(timeIntervalSince1970: timeResult)
     let dateFormatter = NSDateFormatter()
     dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
     dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
     dateFormatter.timeZone = NSTimeZone()
     let localDate = dateFormatter.stringFromDate(date)
}

Swift 3.0 Version

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = self.timeZone
    let localDate = dateFormatter.string(from: date)                     
}

Swift 5

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = .current
    let localDate = dateFormatter.string(from: date)                                
}

How to open a txt file and read numbers in Java

Read file, parse each line into an integer and store into a list:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while ((text = reader.readLine()) != null) {
        list.add(Integer.parseInt(text));
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
    }
}

//print out the list
System.out.println(list);

How do I cancel form submission in submit button onclick event?

This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.

<script>
document.getElementById(id of the form).addEventListener(
    "submit",
    function(event)
    {
        if(validData() === false)
        {
            event.preventDefault();
        }
    },
    false
);

The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.

P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.

How to check if C string is empty

strlen(url)

Returns the length of the string. It counts all characters until a null-byte is found. In your case, check it against 0.

Or just check it manually with:

*url == '\0'

How to copy data from another workbook (excel)?

Would you be happy to make "my file.xls" active if it didn't affect the screen? Turning off screen updating is the way to achieve this, it also has performance improvements (significant if you are doing looping while switching around worksheets / workbooks).

The command to do this is:

    Application.ScreenUpdating = False

Don't forget to turn it back to True when your macros is finished.

Arduino error: does not name a type?

I got the does not name a type error when installing the NeoMatrix library.

Solution: the .cpp and .h files need to be in the top folder when you copy it, e.g:

myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp

When I used the default Windows unzip program, it nested the contents inside another folder:

myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp

I moved the files up, so it was:

myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp

This fixed the does not name a type problem.

Failed loading english.pickle with nltk.data.load

you just need to go to python console and type->

import nltk

press enter and retype->

nltk.download()

and then a interface will come. Just search for download button and press it. It will install all the required items and will take time. Give the time and just try it again. Your problem will get solved

NGinx Default public www location?

For CentOS, Ubuntu and Fedora, the default directory is /usr/share/nginx/html

Error in spring application context schema

I also faced this problem and fixed it by removing version part from the XSD name.

http://www.springframework.org/schema/beans/spring-beans-4.2.xsd to http://www.springframework.org/schema/beans/spring-beans.xsd

Versions less XSD's are mapped to the current version of the framework used in the application.

6 digits regular expression

You could try

^[0-9]{1,6}$

it should work.

How can I select all children of an element except the last child?

.nav-menu li:not(:last-child){
    // write some style here
}

this code should apply the style to all

  • except the last child

  • How to center an element horizontally and vertically

    You can achieve this using CSS (your element display:inline-grid + grid-auto-flow: row; ) Grid and Flex Box ( parent element display:flex;),

    See below snippet

    _x000D_
    _x000D_
    #leftFrame {_x000D_
      display: flex;_x000D_
      height: 100vh;_x000D_
      width: 100%;_x000D_
    }_x000D_
    _x000D_
    #tabs {_x000D_
      display: inline-grid;_x000D_
      grid-auto-flow: row;_x000D_
      grid-gap: 24px;_x000D_
      justify-items: center;_x000D_
      margin: auto;_x000D_
    }_x000D_
    _x000D_
    html,body {_x000D_
      margin:0;_x000D_
      padding:0;_x000D_
    }
    _x000D_
    <div>_x000D_
    <div id=leftFrame>_x000D_
      <div id=tabs>_x000D_
        <div>first</div>_x000D_
        <div>second</div>        _x000D_
      </div>_x000D_
    </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Where is svn.exe in my machine?

    TortoiseSVN 1.7 has an option for installing the command line tools.

    It isn't checked by default, but you can run the installer again and select it. It will also automatically update your PATH environment variable.

    What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

    You can set TextBox properties for setting negative number display and decimal places settings.

    1. Right-click the cell and then click Text Box Properties.
    2. Select Number, and in the Category field, click Currency.

    enter image description here

    CSS selector - element with a given child

    Is it possible to select an element if it contains a specific child element?

    Unfortunately not yet.

    The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.


    A Note About Specification Changes

    This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.


    An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.

    The subject was going to be the element in the selector chain that would have styles applied to it.

    Example HTML
    <p><span>lorem</span> ipsum dolor sit amet</p>
    <p>consecteture edipsing elit</p>
    

    This selector would style the span element

    p span {
        color: red;
    }
    

    This selector would style the p element

    !p span {
        color: red;
    }
    

    A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()"

    :has() would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has() pseudo-selector*.

    In any event, continuing the example from above, to select the p element that contains a span one could use:

    p:has(span) {
        color: red;
    }
    

    * This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.

    Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

    same problem.

    and I solved it by:

    1. add C:\Program Files\apache-maven-3.3.9\bin; to PATH
    2. run cmd as administrator

    and then mvn --version works.

    sudo: port: command not found

    there might be the situation your machine is managed by Puppet or so. Then changing root .profile or .bash_rc file does not work at all. Therefore you could add the following to your .profile file. After that you can use "mydo" instead of "sudo". It works perfectly for me.

    function mydo() {
        echo Executing sudo with: "$1" "${@:2}"
        sudo $(which $1) "${@:2}"
    }
    

    Visit my page: http://www.danielkoitzsch.de/blog/2016/03/16/sudo-returns-xyz-command-not-found/

    Query to convert from datetime to date mysql

    Use the DATE function:

    SELECT DATE(orders.date_purchased) AS date
    

    Python Pandas counting and summing specific conditions

    You can first make a conditional selection, and sum up the results of the selection using the sum function.

    >> df = pd.DataFrame({'a': [1, 2, 3]})
    >> df[df.a > 1].sum()   
    a    5
    dtype: int64
    

    Having more than one condition:

    >> df[(df.a > 1) & (df.a < 3)].sum()
    a    2
    dtype: int64
    

    CSS: background image on background color

    The next syntax can be used as well.

    background: <background-color> 
                url('../assets/icons/my-icon.svg')
                <background-position-x background-position-y>
                <background-repeat>;
    

    It allows you combining background-color, background-image, background-position and background-repeat properties.

    Example

    background: #696969 url('../assets/icons/my-icon.svg') center center no-repeat;
    

    How to apply style classes to td classes?

    table.classname td {
        font-size: 90%;
    }
    

    worked for me. thanks.

    Using 24 hour time in bootstrap timepicker

    This will surely help on bootstrap timepicker

    format :"DD:MM:YYYY HH:mm"
    

    Styling Form with Label above Inputs

    You could try something like

    <form name="message" method="post">
        <section>
        <div>
          <label for="name">Name</label>
          <input id="name" type="text" value="" name="name">
        </div>
        <div>
          <label for="email">Email</label>
          <input id="email" type="text" value="" name="email">
        </div>
        </section>
        <section>
        <div>
          <label for="subject">Subject</label>
          <input id="subject" type="text" value="" name="subject">
        </div>
        <div class="full">
          <label for="message">Message</label>
          <input id="message" type="text" value="" name="message">
        </div>
        </section>
    </form>
    

    and then css it like

    form { width: 400px; }
    form section div { float: left; }
    form section div.full { clear: both; }
    form section div label { display: block; }
    

    Reloading/refreshing Kendo Grid

    The easiest way out to refresh is using the refresh() function. Which goes like:

    $('#gridName').data('kendoGrid').refresh();
    

    while you can also refresh the data source using this command:

    $('#gridName').data('kendoGrid').dataSource.read();
    

    The latter actually reloads the data source of the grid. The use of both can be done according to your need and requirement.

    No increment operator (++) in Ruby?

    Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.

    Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)

    That explains it better than I ever could.

    EDIT: and the reason from the language author himself (source):

    1. ++ and -- are NOT reserved operator in Ruby.
    2. C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
    3. self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

    Run a shell script with an html button

    This is how it look like in pure bash

    cat /usr/lib/cgi-bin/index.cgi

    #!/bin/bash
    echo Content-type: text/html
    echo ""
    ## make POST and GET stings
    ## as bash variables available
    if [ ! -z $CONTENT_LENGTH ] && [ "$CONTENT_LENGTH" -gt 0 ] && [ $CONTENT_TYPE != "multipart/form-data" ]; then
    read -n $CONTENT_LENGTH POST_STRING <&0
    eval `echo "${POST_STRING//;}"|tr '&' ';'`
    fi
    eval `echo "${QUERY_STRING//;}"|tr '&' ';'`
    
    echo  "<!DOCTYPE html>"
    echo  "<html>"
    echo  "<head>"
    echo  "</head>"
    
    if [[ "$vote" = "a" ]];then
    echo "you pressed A"
      sudo /usr/local/bin/run_a.sh
    elif [[ "$vote" = "b" ]];then
    echo "you pressed B"
      sudo /usr/local/bin/run_b.sh
    fi
    
    echo  "<body>"
    echo  "<div id=\"content-container\">"
    echo  "<div id=\"content-container-center\">"
    echo  "<form id=\"choice\" name='form' method=\"POST\" action=\"/\">"
    echo  "<button id=\"a\" type=\"submit\" name=\"vote\" class=\"a\" value=\"a\">A</button>"
    echo  "<button id=\"b\" type=\"submit\" name=\"vote\" class=\"b\" value=\"b\">B</button>"
    echo  "</form>"
    echo  "<div id=\"tip\">"
    echo  "</div>"
    echo  "</div>"
    echo  "</div>"
    echo  "</div>"
    echo  "</body>"
    echo  "</html>"
    

    Build with https://github.com/tinoschroeter/bash_on_steroids

    why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

    Pass CultureInfo.InvariantCulture as the second parameter of DateTime, it will return the string as what you want, even a very special format:

    DateTime.Now.ToString("dd|MM|yyyy", CultureInfo.InvariantCulture)
    

    will return: 28|02|2014

    What are the differences between 'call-template' and 'apply-templates' in XSL?

    To add to the good answer by @Tomalak:

    Here are some unmentioned and important differences:

    1. xsl:apply-templates is much richer and deeper than xsl:call-templates and even from xsl:for-each, simply because we don't know what code will be applied on the nodes of the selection -- in the general case this code will be different for different nodes of the node-list.

    2. The code that will be applied can be written way after the xsl:apply templates was written and by people that do not know the original author.

    The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates> instruction.

    Summary: Templates and the <xsl:apply-templates> instruction is how XSLT implements and deals with polymorphism.

    Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html

    How to strip a specific word from a string?

    If want to remove the word from only the start of the string, then you could do:

      string[string.startswith(prefix) and len(prefix):]  
    

    Where string is your string variable and prefix is the prefix you want to remove from your string variable.

    For example:

      >>> papa = "papa is a good man. papa is the best."  
      >>> prefix = 'papa'
      >>> papa[papa.startswith(prefix) and len(prefix):]
      ' is a good man. papa is the best.'
    

    How can I convert a .py to .exe for Python?

    There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.

    GUI:

    Auto Py to Exe

    Output:

    Output

    No plot window in matplotlib

    If you encounter an issue in which pylab.show() freezes the IPython window (this may be Mac OS X specific; not sure), you can cmd-c in the IPython window, switch to the plot window, and it will break out.

    Apparently, future calls to pylab.show() will not freeze the IPython window, only the first call. Unfortunately, I've found that the behavior of the plot window / interactions with show() changes every time I reinstall matplotlib, so this solution may not always hold.

    best way to get the key of a key/value javascript object

    Object.keys() The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

    var arr1 = Object.keys(obj);
    

    Object.values() The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

    var arr2 = Object.values(obj);
    

    For more please go here

    How to check currently internet connection is available or not in android

    Also, be aware that sometimes the user will be connected to a Wi-Fi network, but that network might require browser-based authentication. Most airport and hotel hotspots are like that, so you application might be fooled into thinking you have connectivity, and then any URL fetches will actually retrieve the hotspot's login page instead of the page you are looking for.

    Depending on the importance of performing this check, in addition to checking the connection with ConnectivityManager, I'd suggest including code to check that it's a working Internet connection and not just an illusion. You can do that by trying to fetch a known address/resource from your site, like a 1x1 PNG image or 1-byte text file.

    How to change option menu icon in the action bar?

    this work for me, just set your xml menu like this:

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
        <item
            android:icon="@drawable/your_icon"
            android:title="menu"
            app:showAsAction="always">
            <menu>
    
                <item
                    android:id="@+id/action_menu1"
                    android:orderInCategory="1"
                    android:title="menu 1" />
    
                <item
                    android:id="@+id/action_menu2"
                    android:orderInCategory="2"
                    android:title="menu 2" />
    
            </menu>
        </item>
    </menu>
    

    Python code to remove HTML tags from a string

    Note that this isn't perfect, since if you had something like, say, <a title=">"> it would break. However, it's about the closest you'd get in non-library Python without a really complex function:

    import re
    
    TAG_RE = re.compile(r'<[^>]+>')
    
    def remove_tags(text):
        return TAG_RE.sub('', text)
    

    However, as lvc mentions xml.etree is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml version:

    def remove_tags(text):
        return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
    

    _csv.Error: field larger than field limit (131072)

    You can use read_csv from pandas to skip these lines.

    import pandas as pd
    
    data_df = pd.read_csv('data.csv', error_bad_lines=False)
    

    How to remove unused imports in Intellij IDEA on commit?

    File/Settings/Inpsections/Imports and change "Unused import" to Error. This marks them more clearly in the Inspections gutter and the Inspection Results panel.

    How to pass object from one component to another in Angular 2?

    For one-way data binding from parent to child, use the @Input decorator (as recommended by the style guide) to specify an input property on the child component

    @Input() model: any;   // instead of any, specify your type
    

    and use template property binding in the parent template

    <child [model]="parentModel"></child>
    

    Since you are passing an object (a JavaScript reference type) any changes you make to object properties in the parent or the child component will be reflected in the other component, since both components have a reference to the same object. I show this in the Plunker.

    If you reassign the object in the parent component

    this.model = someNewModel;
    

    Angular will propagate the new object reference to the child component (automatically, as part of change detection).

    The only thing you shouldn't do is reassign the object in the child component. If you do this, the parent will still reference the original object. (If you do need two-way data binding, see https://stackoverflow.com/a/34616530/215945).

    @Component({
      selector: 'child',
      template: `<h3>child</h3> 
        <div>{{model.prop1}}</div>
        <button (click)="updateModel()">update model</button>`
    })
    class Child {
      @Input() model: any;   // instead of any, specify your type
      updateModel() {
        this.model.prop1 += ' child';
      }
    }
    
    @Component({
      selector: 'my-app',
      directives: [Child],
      template: `
        <h3>Parent</h3>
        <div>{{parentModel.prop1}}</div>
        <button (click)="updateModel()">update model</button>
        <child [model]="parentModel"></child>`
    })
    export class AppComponent {
      parentModel = { prop1: '1st prop', prop2: '2nd prop' };
      constructor() {}
      updateModel() { this.parentModel.prop1 += ' parent'; }
    }
    

    Plunker - Angular RC.2

    PHP check if date between two dates

    Simple solution:

    function betweenDates($cmpDate,$startDate,$endDate){ 
       return (date($cmpDate) > date($startDate)) && (date($cmpDate) < date($endDate));
    }
    

    Comparing two NumPy arrays for equality, element-wise

    The (A==B).all() solution is very neat, but there are some built-in functions for this task. Namely array_equal, allclose and array_equiv.

    (Although, some quick testing with timeit seems to indicate that the (A==B).all() method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)

    Does MS SQL Server's "between" include the range boundaries?

    Yes, but be careful when using between for dates.

    BETWEEN '20090101' AND '20090131'
    

    is really interpreted as 12am, or

    BETWEEN '20090101 00:00:00' AND '20090131 00:00:00'
    

    so will miss anything that occurred during the day of Jan 31st. In this case, you will have to use:

    myDate >= '20090101 00:00:00' AND myDate < '20090201 00:00:00'  --CORRECT!
    

    or

    BETWEEN '20090101 00:00:00' AND '20090131 23:59:59' --WRONG! (see update!)
    

    UPDATE: It is entirely possible to have records created within that last second of the day, with a datetime as late as 20090101 23:59:59.997!!

    For this reason, the BETWEEN (firstday) AND (lastday 23:59:59) approach is not recommended.

    Use the myDate >= (firstday) AND myDate < (Lastday+1) approach instead.

    Good article on this issue here.

    Delete data with foreign key in SQL Server table

    Usefull script which you can delete all data in all tables of a database , replace tt with you databse name :

    declare @tablename nvarchar(100)
    declare c1 cursor for
    SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG='tt' AND TABLE_TYPE='BASE TABLE'
    
    open  c1
    fetch next from c1 into @tablename
    
    while @@FETCH_STATUS = 0
        begin
        print @t1
            exec('alter table ' + @tablename + ' nocheck constraint all')
            exec('delete from ' + @tablename)
            exec ('alter table ' + @tablename + ' check constraint all')
            fetch next from c1 into @tablename
        end
    close c1
    DEALLOCATE c1
    

    How can I display a list view in an Android Alert Dialog?

    You can actually create a simple Array with Alert Dialog like this.

     val sexArray = arrayOf("Male", "Female")
     val selectedPosition = 0
    
     AlertDialog.Builder(requireContext())
        .setSingleChoiceItems(sexArray, 0) { dialog, position ->
            val selectedSex = sexArray[position]
        }.show()
    

    How do I convert from a string to an integer in Visual Basic?

    You can try it:

    Dim Price As Integer 
    Int32.TryParse(txtPrice.Text, Price) 
    

    MVC3 DropDownListFor - a simple example?

    I think this will help : In Controller get the list items and selected value

    public ActionResult Edit(int id)
    {
        ItemsStore item = itemStoreRepository.FindById(id);
        ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
                                            "Id", "Name",item.CategoryId);
    
        // ViewBag to pass values to View and SelectList
        //(get list of items,valuefield,textfield,selectedValue)
    
        return View(item);
    }
    

    and in View

    @Html.DropDownList("CategoryId",String.Empty)
    

    What is the format specifier for unsigned short int?

    From the Linux manual page:

    h      A  following  integer conversion corresponds to a short int or unsigned short int argument, or a fol-
           lowing n conversion corresponds to a pointer to a short int argument.
    

    So to print an unsigned short integer, the format string should be "%hu".

    How do I check that multiple keys are in a dict in a single pass?

    In the case of determining whether only some keys match, this works:

    any_keys_i_seek = ["key1", "key2", "key3"]
    
    if set(my_dict).intersection(any_keys_i_seek):
        # code_here
        pass
    

    Yet another option to find if only some keys match:

    any_keys_i_seek = ["key1", "key2", "key3"]
    
    if any_keys_i_seek & my_dict.keys():
        # code_here
        pass
    

    Wildcards in a Windows hosts file

    Acrylic DNS Proxy (free, open source) does the job. It creates a proxy DNS server (on your own computer) with its own hosts file. The hosts file accepts wildcards.

    Download from the offical website

    http://mayakron.altervista.org/support/browse.php?path=Acrylic&name=Home

    Configuring Acrylic DNS Proxy

    To configure Acrylic DNS Proxy, install it from the above link then go to:

    1. Start
    2. Programs
    3. Acrylic DNS Proxy
    4. Config
    5. Edit Custom Hosts File (AcrylicHosts.txt)

    Add the folowing lines on the end of the file:

    127.0.0.1   *.localhost
    127.0.0.1   *.local
    127.0.0.1   *.lc
    

    Restart the Acrylic DNS Proxy service:

    1. Start
    2. Programs
    3. Acrilic DNS Proxy
    4. Config
    5. Restart Acrylic Service

    You will also need to adjust your DNS setting in you network interface settings:

    1. Start
    2. Control Panel
    3. Network and Internet
    4. Network Connections
    5. Local Area Connection Properties
    6. TCP/IPv4

    Set "Use the following DNS server address":

    Preferred DNS Server: 127.0.0.1
    

    If you then combine this answer with jeremyasnyder's answer (using VirtualDocumentRoot) you can then automatically setup domains/virtual hosts by simply creating a directory.

    Binding a generic list to a repeater - ASP.NET

    You should use ToList() method. (Don't forget about System.Linq namespace)

    ex.:

    IList<Model> models = Builder<Model>.CreateListOfSize(10).Build();
    List<Model> lstMOdels = models.ToList();
    

    Create a GUID in Java

    Have a look at the UUID class bundled with Java 5 and later.

    For example:

    fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

    In Visual Studio 2012 +/-, the property page for "Configuration Properties'.Linker."Command Line" contains a box labeled "Additional Options". If you're building x64, make sure that box doesn't contain /MACHINE:I386. My projects did and it generated the error in question.

    How do I install Eclipse Marketplace in Eclipse Classic?

    first Help then Install new Software then Switch to the Kepler Repository then General Purpose Tools finally Marketplace Client

    Ansible date variable

    The command ansible localhost -m setup basically says "run the setup module against localhost", and the setup module gathers the facts that you see in the output.

    When you run the echo command these facts don't exist since the setup module wasn't run. A better method to testing things like this would be to use ansible-playbook to run a playbook that looks something like this:

    - hosts: localhost
      tasks:
          - debug: var=ansible_date_time
    
          - debug: msg="the current date is {{ ansible_date_time.date }}"
    

    Because this runs as a playbook facts for localhost are gathered before the tasks are run. The output of the above playbook will be something like this:

    PLAY [localhost] **************************************************
    
    GATHERING FACTS ***************************************************************
    ok: [localhost]
    
    TASK: [debug var=ansible_date_time] *******************************************
    ok: [localhost] => {
        "ansible_date_time": {
            "date": "2015-07-09",
            "day": "09",
            "epoch": "1436461166",
            "hour": "16",
            "iso8601": "2015-07-09T16:59:26Z",
            "iso8601_micro": "2015-07-09T16:59:26.896629Z",
            "minute": "59",
            "month": "07",
            "second": "26",
            "time": "16:59:26",
            "tz": "UTC",
            "tz_offset": "+0000",
            "weekday": "Thursday",
            "year": "2015"
        }
    }
    
    TASK: [debug msg="the current date is {{ ansible_date_time.date }}"] **********
    ok: [localhost] => {
        "msg": "the current date is 2015-07-09"
    }
    
    PLAY RECAP ********************************************************************
    localhost      : ok=3    changed=0    unreachable=0    failed=0
    

    How do I hide the bullets on my list for the sidebar?

    its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

    add this to your css

    ul{
         list-style:none;
    }

    lodash multi-column sortBy descending

    As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

    var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);
    

    Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):

    var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);
    

    In version 4 of lodash this method has been renamed orderBy:

    var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);
    

    Simple 'if' or logic statement in Python

    Here's a Boolean thing:

    if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
        print  filename + ' is not a flac or cue file'
    

    but

    if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
           print  filename + ' is not a flac or cue file'
    

    (not a) or (not b) == not ( a and b ) , is false only if a and b are both true

    not (a or b) is true only if a and be are both false.

    How to set some xlim and ylim in Seaborn lmplot facetgrid

    You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

    lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)
    

    Then you can get hold of the axes objects (an array of axes):

    axes = lm.axes
    

    After that you can tweak the axes properties

    axes[0,0].set_ylim(0,)
    axes[0,1].set_ylim(0,)
    

    creates:

    enter image description here

    Vector of structs initialization

    Create vector, push_back element, then modify it as so:

    struct subject {
        string name;
        int marks;
        int credits;
    };
    
    
    int main() {
        vector<subject> sub;
    
        //Push back new subject created with default constructor.
        sub.push_back(subject());
    
        //Vector now has 1 element @ index 0, so modify it.
        sub[0].name = "english";
    
        //Add a new element if you want another:
        sub.push_back(subject());
    
        //Modify its name and marks.
        sub[1].name = "math";
        sub[1].marks = 90;
    }
    

    You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.

    How do you create a UIImage View Programmatically - Swift

    First you create a UIImage from your image file, then create a UIImageView from that:

    let imageName = "yourImage.png"
    let image = UIImage(named: imageName)
    let imageView = UIImageView(image: image!)
    

    Finally you'll need to give imageView a frame and add it your view for it to be visible:

    imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
    view.addSubview(imageView)
    

    What does the restrict keyword mean in C++?

    Nothing. It was added to the C99 standard.

    Rendering JSON in controller

    For the instance of

    render :json => @projects, :include => :tasks
    

    You are stating that you want to render @projects as JSON, and include the association tasks on the Project model in the exported data.

    For the instance of

    render :json => @projects, :callback => 'updateRecordDisplay'
    

    You are stating that you want to render @projects as JSON, and wrap that data in a javascript call that will render somewhat like:

    updateRecordDisplay({'projects' => []})
    

    This allows the data to be sent to the parent window and bypass cross-site forgery issues.

    Sharepoint: How do I filter a document library view to show the contents of a subfolder?

    What kind of document library information do you want in the view? How do you want the user to filter the view?

    In general the most powerful way of creating views in sharepoint is with the data view web part. http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx

    You will need Microsoft Office SharePoint Designer.

    You can present different views of you folders using the data view filter and sorting controls.

    You can use web part connections to filter a dataview. You can use any datasource linked to say a drop down to filter a dataview. How to tie a dropdown list to a gridview in Sharepoint 2007?

    How do I lock the orientation to portrait mode in a iPhone Web Application?

    I have a similar issue, but to make landscape... I believe the code below should do the trick:

    _x000D_
    _x000D_
    //This code consider you are using the fullscreen portrait mode_x000D_
    function processOrientation(forceOrientation) {_x000D_
      var orientation = window.orientation;_x000D_
      if (forceOrientation != undefined)_x000D_
        orientation = forceOrientation;_x000D_
      var domElement = document.getElementById('fullscreen-element-div');_x000D_
      switch(orientation) {_x000D_
        case 90:_x000D_
          var width = window.innerHeight;_x000D_
          var height = window.innerWidth;_x000D_
          domElement.style.width = "100vh";_x000D_
          domElement.style.height = "100vw";_x000D_
          domElement.style.transformOrigin="50% 50%";_x000D_
          domElement.style.transform="translate("+(window.innerWidth/2-width/2)+"px, "+(window.innerHeight/2-height/2)+"px) rotate(-90deg)";_x000D_
          break;_x000D_
        case -90:_x000D_
          var width = window.innerHeight;_x000D_
          var height = window.innerWidth;_x000D_
          domElement.style.width = "100vh";_x000D_
          domElement.style.height = "100vw";_x000D_
          domElement.style.transformOrigin="50% 50%";_x000D_
          domElement.style.transform="translate("+(window.innerWidth/2-width/2)+"px, "+(window.innerHeight/2-height/2)+"px) rotate(90deg)";_x000D_
          break;_x000D_
        default:_x000D_
          domElement.style.width = "100vw";_x000D_
          domElement.style.height = "100vh";_x000D_
          domElement.style.transformOrigin="";_x000D_
          domElement.style.transform="";_x000D_
          break;_x000D_
      }_x000D_
    }_x000D_
    window.addEventListener('orientationchange', processOrientation);_x000D_
    processOrientation();
    _x000D_
    <html>_x000D_
    <head></head>_x000D_
    <body style="margin:0;padding:0;overflow: hidden;">_x000D_
      <div id="fullscreen-element-div" style="background-color:#00ff00;width:100vw;height:100vh;margin:0;padding:0"> Test_x000D_
      <br>_x000D_
      <input type="button" value="force 90" onclick="processOrientation(90);" /><br>_x000D_
      <input type="button" value="force -90" onclick="processOrientation(-90);" /><br>_x000D_
      <input type="button" value="back to normal" onclick="processOrientation();" />_x000D_
      </div>_x000D_
    </body>_x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Getting file size in Python?

    os.path.getsize(path)
    

    Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.

    This version of the application is not configured for billing through Google Play

    The problem also occurs, when you have added an in-app purchase after you uploaded the apk, but you have not published the application in the play store (alpha, beta and production).

    Which basically means, that you have to add the In-App purchase AFTER you have published the apk in the Play store (alpha, beta and production). Otherwise you wont be able to purchase or query for the In-App purchase.

    Find all files in a directory with extension .txt in Python

    Try this this will find all your files recursively:

    import glob, os
    os.chdir("H:\\wallpaper")# use whatever directory you want
    
    #double\\ no single \
    
    for file in glob.glob("**/*.txt", recursive = True):
        print(file)
    

    Conda command is not recognized on Windows 10

    In Windows, you will have to set the path to the location where you installed Anaconda3 to.

    For me, I installed anaconda3 into C:\Anaconda3. Therefore you need to add C:\Anaconda3 as well as C:\Anaconda3\Scripts\ to your path variable, e.g. set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\.

    You can do this via powershell (see above, https://msdn.microsoft.com/en-us/library/windows/desktop/bb776899(v=vs.85).aspx ), or hit the windows key ? enter environment ? choose from settings ? edit environment variables for your account ? select Path variable ? Edit ? New.

    To test it, open a new dos shell, and you should be able to use conda commands now. E.g., try conda --version.

    How to increase the vertical split window size in Vim

    I am using numbers to resize by mapping the following in .vimrc

    nmap 7 :res +2<CR> " increase pane by 2 
    nmap 8 :res -2<CR> " decrease pane by 2
    nmap 9 :vertical res +2<CR> " vertical increase pane by 2
    nmap 0 :vertical res -2<CR> " vertical decrease pane by 2
    

    How to use Typescript with native ES6 Promises

    As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json

    "compilerOptions": {
        "lib": ["es5", "es2015.promise"]
    }
    

    This will include the promise declarations that comes with TypeScript without having to set the target to ES6.

    How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

    it's well documented here:

    https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6

    How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:

    http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

    Standard Implementation -> address

    "For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."

    Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

    Starting with Kotlin 1.1.2, the dependencies with group org.jetbrains.kotlin are by default resolved with the version taken from the applied plugin. You can provide the version manually using the full dependency notation like:

    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    

    If you're targeting JDK 7 or JDK 8, you can use extended versions of the Kotlin standard library which contain additional extension functions for APIs added in new JDK versions. Instead of kotlin-stdlib, use one of the following dependencies:

    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    

    How to determine a Python variable's type?

    The question is somewhat ambiguous -- I'm not sure what you mean by "view". If you are trying to query the type of a native Python object, @atzz's answer will steer you in the right direction.

    However, if you are trying to generate Python objects that have the semantics of primitive C-types, (such as uint32_t, int16_t), use the struct module. You can determine the number of bits in a given C-type primitive thusly:

    >>> struct.calcsize('c') # char
    1
    >>> struct.calcsize('h') # short
    2
    >>> struct.calcsize('i') # int
    4
    >>> struct.calcsize('l') # long
    4
    

    This is also reflected in the array module, which can make arrays of these lower-level types:

    >>> array.array('c').itemsize # char
    1
    

    The maximum integer supported (Python 2's int) is given by sys.maxint.

    >>> import sys, math
    >>> math.ceil(math.log(sys.maxint, 2)) + 1 # Signedness
    32.0
    

    There is also sys.getsizeof, which returns the actual size of the Python object in residual memory:

    >>> a = 5
    >>> sys.getsizeof(a) # Residual memory.
    12
    

    For float data and precision data, use sys.float_info:

    >>> sys.float_info
    sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)
    

    How to get URL parameters with Javascript?

    function getURLParameter(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
    }
    

    So you can use:

    myvar = getURLParameter('myvar');
    

    "OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

    Restart Mac -> hold down "Command + R" after the startup chime -> Opens OS X Utilities -> Open Terminal and type "csrutil disable" -> Reboot OS X -> Open Terminal and check "csrutil status"

    Create SQLite Database and table

    The next link will bring you to a great tutorial, that helped me a lot!

    How to SQLITE in C#

    I nearly used everything in that article to create the SQLite database for my own C# Application.

    Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

    After you added the reference, refer to the dll from your code using the following line on top of your class:

    using System.Data.SQLite;

    You can find the dll's here:

    SQLite DLL's

    You can find the NuGet way here:

    NuGet

    Up next is the create script. Creating a database file:

    SQLiteConnection.CreateFile("MyDatabase.sqlite");
    
    SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
    m_dbConnection.Open();
    
    string sql = "create table highscores (name varchar(20), score int)";
    
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    command.ExecuteNonQuery();
    
    sql = "insert into highscores (name, score) values ('Me', 9001)";
    
    command = new SQLiteCommand(sql, m_dbConnection);
    command.ExecuteNonQuery();
    
    m_dbConnection.Close();
    

    After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

    Example on how to use transactions:

     using (TransactionScope tran = new TransactionScope())
     {
         //Insert create script here.
    
         //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
         tran.Complete();
     }
    

    jQuery hide and show toggle div with plus and minus icon

    Here is a quick edit of Enve's answer. I do like roXor's solution, but background images are not necessary. And everbody seems to forgot a preventDefault as well.

    _x000D_
    _x000D_
    $(document).ready(function() {_x000D_
      $(".slidingDiv").hide();_x000D_
    _x000D_
      $('.show_hide').click(function(e) {_x000D_
        $(".slidingDiv").slideToggle("fast");_x000D_
        var val = $(this).text() == "-" ? "+" : "-";_x000D_
        $(this).hide().text(val).fadeIn("fast");_x000D_
        e.preventDefault();_x000D_
      });_x000D_
    });
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <a href="#" class="show_hide">+</a>_x000D_
    _x000D_
    <div class="slidingDiv">_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta._x000D_
        Mauris massa. Vestibulum lacinia arcu eget nulla. </p>_x000D_
    _x000D_
      <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis._x000D_
        Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. </p>_x000D_
    _x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    What are all possible pos tags of NLTK?

    Just run this verbatim.

    import nltk
    nltk.download('tagsets')
    nltk.help.upenn_tagset()
    

    nltk.tag._POS_TAGGER won't work. It will give AttributeError: module 'nltk.tag' has no attribute '_POS_TAGGER'. It's not available in NLTK 3 anymore.

    Show animated GIF

    public class aiubMain {
    public static void main(String args[]) throws MalformedURLException{
        //home frame = new home();
        java.net.URL imgUrl2 = home.class.getResource("Campus.gif");
    
    Icon icon = new ImageIcon(imgUrl2);
    JLabel label = new JLabel(icon);
    
    JFrame f = new JFrame("Animation");
    f.getContentPane().add(label);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }
    }
    

    Proper use of errors

    Simple solution to emit and show message by Exception.

    try {
      throw new TypeError("Error message");
    }
    catch (e){
      console.log((<Error>e).message);//conversion to Error type
    }
    

    Caution

    Above is not a solution if we don't know what kind of error can be emitted from the block. In such cases type guards should be used and proper handling for proper error should be done - take a look on @Moriarty answer.

    Calculate MD5 checksum for a file

    And if you need to calculate the MD5 to see whether it matches the MD5 of an Azure blob, then this SO question and answer might be helpful: MD5 hash of blob uploaded on Azure doesnt match with same file on local machine