Programs & Examples On #Declarative authorization

The declarative authorization plugin offers an authorization mechanism for Ruby inspired by RBAC.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I had the same problem. mysql -u root -p worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password, if you did not set one. More info here.

Jackson with JSON: Unrecognized field, not marked as ignorable

This works better than All please refer to this property.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    projectVO = objectMapper.readValue(yourjsonstring, Test.class);

Android - set TextView TextStyle programmatically?

As mentioned here, this feature is not currently supported.

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

I've created a pared-down demo project for you.

You can try the above API Link from your local Fiddler to see the headers. Here is an explanation.

Global.ascx

All this does is call the WebApiConfig. It's nothing but code organization.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        WebApiConfig.Register(GlobalConfiguration.Configuration);
    }
}

WebApiConfig.cs

The key method for your here is the EnableCrossSiteRequests method. This is all that you need to do. The EnableCorsAttribute is a globally scoped CORS attribute.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        AddRoutes(config);
    }

    private static void AddRoutes(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/"
        );
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(
            origins: "*", 
            headers: "*", 
            methods: "*");
        config.EnableCors(cors);
    }
}

Values Controller

The Get method receives the EnableCors attribute that we applied globally. The Another method overrides the global EnableCors.

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { 
            "This is a CORS response.", 
            "It works from any origin." 
        };
    }

    // GET api/values/another
    [HttpGet]
    [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
    public IEnumerable<string> Another()
    {
        return new string[] { 
            "This is a CORS response. ", 
            "It works only from two origins: ",
            "1. www.bigfont.ca ",
            "2. the same origin." 
        };
    }
}

Web.config

You do not need to add anything special into web.config. In fact, this is what the demo's web.config looks like - it's empty.

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

Demo

_x000D_
_x000D_
var url = "https://cors-webapi.azurewebsites.net/api/values"_x000D_
_x000D_
$.get(url, function(data) {_x000D_
  console.log("We expect this to succeed.");_x000D_
  console.log(data);_x000D_
});_x000D_
_x000D_
var url = "https://cors-webapi.azurewebsites.net/api/values/another"_x000D_
_x000D_
$.get(url, function(data) {_x000D_
  console.log(data);_x000D_
}).fail(function(xhr, status, text) {_x000D_
  console.log("We expect this to fail.");_x000D_
  console.log(status);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Generating Request/Response XML from a WSDL

I use SOAPUI 5.3.0, it has an option for creating requests/responses (also using WSDL), you can even create a mock service which will respond when you send request. Procedure is as follows:

  1. Right click on your project and select New Mock Service option which will create mock service.
  2. Right click on mock service and select New Mock Operation option which will create response which you can use as template.

EDIT #1:

Check out the SoapUI link for the latest version. There is a Pro version as well as the free open source version.

How to calculate mean, median, mode and range from a set of numbers

Yes, there does seem to be 3rd libraries (none in Java Math). Two that have come up are:

http://opsresearch.com/app/

http://www.iro.umontreal.ca/~simardr/ssj/indexe.html

but, it is actually not that difficult to write your own methods to calculate mean, median, mode and range.

MEAN

public static double mean(double[] m) {
    double sum = 0;
    for (int i = 0; i < m.length; i++) {
        sum += m[i];
    }
    return sum / m.length;
}

MEDIAN

// the array double[] m MUST BE SORTED
public static double median(double[] m) {
    int middle = m.length/2;
    if (m.length%2 == 1) {
        return m[middle];
    } else {
        return (m[middle-1] + m[middle]) / 2.0;
    }
}

MODE

public static int mode(int a[]) {
    int maxValue, maxCount;

    for (int i = 0; i < a.length; ++i) {
        int count = 0;
        for (int j = 0; j < a.length; ++j) {
            if (a[j] == a[i]) ++count;
        }
        if (count > maxCount) {
            maxCount = count;
            maxValue = a[i];
        }
    }

    return maxValue;
}

UPDATE

As has been pointed out by Neelesh Salpe, the above does not cater for multi-modal collections. We can fix this quite easily:

public static List<Integer> mode(final int[] numbers) {
    final List<Integer> modes = new ArrayList<Integer>();
    final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();

    int max = -1;

    for (final int n : numbers) {
        int count = 0;

        if (countMap.containsKey(n)) {
            count = countMap.get(n) + 1;
        } else {
            count = 1;
        }

        countMap.put(n, count);

        if (count > max) {
            max = count;
        }
    }

    for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) {
        if (tuple.getValue() == max) {
            modes.add(tuple.getKey());
        }
    }

    return modes;
}

ADDITION

If you are using Java 8 or higher, you can also determine the modes like this:

public static List<Integer> getModes(final List<Integer> numbers) {
    final Map<Integer, Long> countFrequencies = numbers.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    final long maxFrequency = countFrequencies.values().stream()
            .mapToLong(count -> count)
            .max().orElse(-1);

    return countFrequencies.entrySet().stream()
            .filter(tuple -> tuple.getValue() == maxFrequency)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
}

Generate a unique id

Why don't use GUID?

Guid guid = Guid.NewGuid();
string str = guid.ToString();

redirect COPY of stdout to log file from within bash script itself

Inside your script file, put all of the commands within parentheses, like this:

(
echo start
ls -l
echo end
) | tee foo.log

How to set javascript variables using MVC4 with Razor

I've been looking into this approach:

function getServerObject(serverObject) {
  if (typeof serverObject === "undefined") {
    return null;
  }
  return serverObject;
}

var itCameFromDotNet = getServerObject(@dotNetObject);

To me this seems to make it safer on the JS side... worst case you end up with a null variable.

How to handle onchange event on input type=file in jQuery?

Try to use this:

HTML:

<input ID="fileUpload1" runat="server" type="file">

JavaScript:

$("#fileUpload1").on('change',function() {
    alert('Works!!');
});

?

Notification not showing in Oreo

Here's how you do it

private fun sendNotification() {
    val notificationId = 100
    val chanelid = "chanelid"
    val intent = Intent(this, MainActivity::class.java)
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
    val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // you must create a notification channel for API 26 and Above
        val name = "my channel"
        val description = "channel description"
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(chanelid, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
    }

    val mBuilder = NotificationCompat.Builder(this, chanelid)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Want to Open My App?")
            .setContentText("Open my app and see good things")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true) // cancel the notification when clicked
            .addAction(R.drawable.ic_check, "YES", pendingIntent) //add a btn to the Notification with a corresponding intent

    val notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notificationId, mBuilder.build());
}

Read full tutorial at => https://developer.android.com/training/notify-user/build-notification

Is there a way to comment out markup in an .ASPX page?

Yes, there are special server side comments:

<%-- Text not sent to client  --%>

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Sadly none of the solutions worked for me! I solved my problem by uninstalling existing APK from my phone and it all started working perfectly!

This started happening after I've updated android studio to latest version.

How do I implement a callback in PHP?

With PHP 5.3, you can now do this:

function doIt($callback) { $callback(); }

doIt(function() {
    // this will be done
});

Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.

sqlalchemy filter multiple columns

There are number of ways to do it:

Using filter() (and operator)

query = meta.Session.query(User).filter(
    User.firstname.like(search_var1),
    User.lastname.like(search_var2)
    )

Using filter_by() (and operator)

query = meta.Session.query(User).filter_by(
    firstname.like(search_var1),
    lastname.like(search_var2)
    )

Chaining filter() or filter_by() (and operator)

query = meta.Session.query(User).\
    filter_by(firstname.like(search_var1)).\
    filter_by(lastname.like(search_var2))

Using or_(), and_(), and not()

from sqlalchemy import and_, or_, not_

query = meta.Session.query(User).filter(
    and_(
        User.firstname.like(search_var1),
        User.lastname.like(search_var2)
    )
)

File upload progress bar with jQuery

This solved my problem

var url = "http://localhost/tech1/index.php?route=app/upload/ajax"; 

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
          var $img = $link.find('i'); 
          $link.html('Uploading..('+percentComplete+'%)');
          $link.append($img);
      }
    }, false);

    return xhr;
  },
  url: url,
  type: "POST",
  data: JSON.stringify(uploaddata),
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    console.log(result);
  }
});

HTML Mobile -forcing the soft keyboard to hide

Those answers aren't bad, but they are limited in that they don't actually allow you to enter data. We had a similar problem where we were using barcode readers to enter data into a field, but we wanted to suppress the keyboard.

This is what I put together, it works pretty well:

https://codepen.io/bobjase/pen/QrQQvd/

<!-- must be a select box with no children to suppress the keyboard -->
input: <select id="hiddenField" /> 
<span id="fakecursor" />

<input type="text" readonly="readonly" id="visibleField" />
<div id="cursorMeasuringDiv" />

#hiddenField {
  height:17px; 
  width:1px;
  position:absolute;
  margin-left:3px;
  margin-top:2px;
  border:none;
  border-width:0px 0px 0px 1px;
}

#cursorMeasuringDiv {
  position:absolute;
  visibility:hidden;
  margin:0px;
  padding:0px;
}

#hiddenField:focus {
  border:1px solid gray;  
  border-width:0px 0px 0px 1px;
  outline:none;
  animation-name: cursor;
  animation-duration: 1s;
  animation-iteration-count: infinite;
}

@keyframes cursor {
    from {opacity:0;}
    to {opacity:1;}
}

// whenever the visible field gets focused
$("#visibleField").bind("focus", function(e) {
  // silently shift the focus to the hidden select box
  $("#hiddenField").focus();
  $("#cursorMeasuringDiv").css("font", $("#visibleField").css("font"));
});

// whenever the user types on his keyboard in the select box
// which is natively supported for jumping to an <option>
$("#hiddenField").bind("keypress",function(e) {
  // get the current value of the readonly field
  var currentValue = $("#visibleField").val();

  // and append the key the user pressed into that field
  $("#visibleField").val(currentValue + e.key);
  $("#cursorMeasuringDiv").text(currentValue + e.key);

  // measure the width of the cursor offset
  var offset = 3;
  var textWidth = $("#cursorMeasuringDiv").width();
  $("#hiddenField").css("marginLeft",Math.min(offset+textWidth,$("#visibleField").width()));

});

When you click in the <input> box, it simulates a cursor in that box but really puts the focus on an empty <select> box. Select boxes naturally allow for keypresses to support jumping to an element in the list so it was only a matter of rerouting the keypress to the original input and offsetting the simulated cursor.

This won't work for backspace, delete, etc... but we didn't need those. You could probably use jQuery's trigger to send the keyboard event directly to another input box somewhere but we didn't need to bother with that so I didn't do it.

Check which element has been clicked with jQuery

Hope this useful for you.

$(document).click(function(e){
    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');
    }  
});

Spring default behavior for lazy-init

For those coming here and are using Java config you can set the Bean to lazy-init using annotations like this:

In the configuration class:

@Configuration
// @Lazy - For all Beans to load lazily
public class AppConf {

    @Bean
    @Lazy
    public Demo demo() {
        return new Demo();
    }
}

For component scanning and auto-wiring:

@Component
@Lazy
public class Demo {
    ....
    ....
}

@Component
public class B {

    @Autowired
    @Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
    private Demo demo;

    .......
 }

How to show PIL Image in ipython notebook

You can use IPython's Module: display to load the image. You can read more from the Doc.

from IPython.display import Image 
pil_img = Image(filename='data/empire.jpg')
display(pil_img)

updated

As OP's requirement is to use PIL, if you want to show inline image, you can use matplotlib.pyplot.imshow with numpy.asarray like this too:

from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image

%matplotlib inline
pil_im = Image.open('data/empire.jpg', 'r')
imshow(np.asarray(pil_im))

If you only require a preview rather than an inline, you may just use show like this:

pil_im = Image.open('data/empire.jpg', 'r')
pil_im.show()

Check if an image is loaded (no errors) with jQuery

I had a lot of problems with the complete load of a image and the EventListener.

Whatever I tried, the results was not reliable.

But then I found the solution. It is technically not a nice one, but now I never had a failed image load.

What I did:

                    document.getElementById(currentImgID).addEventListener("load", loadListener1);
                    document.getElementById(currentImgID).addEventListener("load", loadListener2);

                function loadListener1()
                    {
                    // Load again
                    }

                function loadListener2()
                {
                    var btn = document.getElementById("addForm_WithImage"); btn.disabled = false;
                    alert("Image loaded");
                }

Instead of loading the image one time, I just load it a second time direct after the first time and both run trough the eventhandler.

All my headaches are gone!


By the way: You guys from stackoverflow helped me already more then hundred times. For this a very big Thank you!

MySQL DELETE FROM with subquery as condition

You cannot specify target table for delete.

A workaround

create table term_hierarchy_backup (tid int(10)); <- check data type

insert into term_hierarchy_backup 
SELECT DISTINCT(th1.tid)
FROM term_hierarchy AS th1
INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
WHERE th1.parent = 1015;

DELETE FROM term_hierarchy AS th
WHERE th.parent = 1015 AND th.tid IN (select tid from term_hierarchy_backup);

JPA & Criteria API - Select only specific columns

First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):

List<T> results = session.createCriteria(entityClazz)
    .setProjection( Projections.projectionList()
        .add( Property.forName("ID") )
        .add( Property.forName("VERSION") )
    )
    .setResultTransformer(Transformers.aliasToBean(entityClazz); 
    .list();

This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.

Detect when input has a 'readonly' attribute

You can just use the attribute selector and then test the length:

$('input[readonly]').length == 0 // --> ok
$('input[readonly]').length > 0  // --> not ok

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

Get names of all keys in the collection

I was trying to write in nodejs and finally came up with this:

db.collection('collectionName').mapReduce(
function() {
    for (var key in this) {
        emit(key, null);
    }
},
function(key, stuff) {
    return null;
}, {
    "out": "allFieldNames"
},
function(err, results) {
    var fields = db.collection('allFieldNames').distinct('_id');
    fields
        .then(function(data) {
            var finalData = {
                "status": "success",
                "fields": data
            };
            res.send(finalData);
            delteCollection(db, 'allFieldNames');
        })
        .catch(function(err) {
            res.send(err);
            delteCollection(db, 'allFieldNames');
        });
 });

After reading the newly created collection "allFieldNames", delete it.

db.collection("allFieldNames").remove({}, function (err,result) {
     db.close();
     return; 
});

How to get the separate digits of an int number?

This uses the modulo 10 method to figure out each digit in a number greater than 0, then this will reverse the order of the array. This is assuming you are not using "0" as a starting digit.

This is modified to take in user input. This array is originally inserted backwards, so I had to use the Collections.reverse() call to put it back into the user's order.

    Scanner scanNumber = new Scanner(System.in);
    int userNum = scanNumber.nextInt(); // user's number

    // divides each digit into its own element within an array
    List<Integer> checkUserNum = new ArrayList<Integer>();
    while(userNum > 0) {
        checkUserNum.add(userNum % 10);
        userNum /= 10;
    }

    Collections.reverse(checkUserNum); // reverses the order of the array

    System.out.print(checkUserNum);

How to remove a package from Laravel using composer?

**

use "composer remove vendor/package"

** This is Example: Install / Add Pakage

composer require firebear/importexportfree

Uninsall / Remove

composer remove firebear/importexportfree

Finaly after removing:

php -f bin/magento setup:upgrade

php bin/magento setup:static-content:deploy –f

php bin/magento indexer:reindex 

php -f bin/magento cache:clean

Is calling destructor manually always a sign of bad design?

No, Depends on the situation, sometimes it is legitimate and good design.

To understand why and when you need to call destructors explicitly, let's look at what happening with "new" and "delete".

To created an object dynamically, T* t = new T; under the hood: 1. sizeof(T) memory is allocated. 2. T's constructor is called to initialize the allocated memory. The operator new does two things: allocation and initialization.

To destroy the object delete t; under the hood: 1. T's destructor is called. 2. memory allocated for that object is released. the operator delete also does two things: destruction and deallocation.

One writes the constructor to do initialization, and destructor to do destruction. When you explicitly call the destructor, only the destruction is done, but not the deallocation.

A legitimate use of explicitly calling destructor, therefore, could be, "I only want to destruct the object, but I don't (or can't) release the memory allocation (yet)."

A common example of this, is pre-allocating memory for a pool of certain objects which otherwise have to be allocated dynamically.

When creating a new object, you get the chunk of memory from the pre-allocated pool and do a "placement new". After done with the object, you may want to explicitly call the destructor to finish the cleanup work, if any. But you won't actually deallocate the memory, as the operator delete would have done. Instead, you return the chunk to the pool for reuse.

Finding rows containing a value (or values) in any column

Here's a dplyr option:

library(dplyr)

# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))

# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))                                                                                                     

How to get request url in a jQuery $.get/ajax request

I can't get it to work on $.get() because it has no complete event.

I suggest to use $.ajax() like this,

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

craz demo

identifier "string" undefined?

You must use std namespace. If this code in main.cpp you should write

using namespace std;

If this declaration is in header, then you shouldn't include namespace and just write

std::string level;

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Swift Method, and supply a demo.

func topMostController() -> UIViewController {
    var topController: UIViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
    while (topController.presentedViewController != nil) {
        topController = topController.presentedViewController!
    }
    return topController
}

func demo() {
    let vc = ViewController()
    let nav = UINavigationController.init(rootViewController: vc)
    topMostController().present(nav, animated: true, completion: nil)
}

Use Toast inside Fragment

        public void onClick(View v) {
            Context context = v.getContext();
            CharSequence text = "Message";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 6.1: in the home window click on the server instance(connection)/ or create a new one. In the thus opened 'connection' tab click on 'server' -> 'data import'. The rest of the steps remain as in Vishy's answer.

How to delete only the content of file in python

You can do this:

def deleteContent(pfile):
    fn=pfile.name 
    pfile.close()
    return open(fn,'w')

How to modify a specified commit?

If for some reason you don't like interactive editors, you can use git rebase --onto.

Say you want to modify Commit1. First, branch from before Commit1:

git checkout -b amending [commit before Commit1]

Second, grab Commit1 with cherry-pick:

git cherry-pick Commit1

Now, amend your changes, creating Commit1':

git add ...
git commit --amend -m "new message for Commit1"

And finally, after having stashed any other changes, transplant the rest of your commits up to master on top of your new commit:

git rebase --onto amending Commit1 master

Read: "rebase, onto the branch amending, all commits between Commit1 (non-inclusive) and master (inclusive)". That is, Commit2 and Commit3, cutting the old Commit1 out entirely. You could just cherry-pick them, but this way is easier.

Remember to clean up your branches!

git branch -d amending

Android: How to open a specific folder via Intent and show its content in a file browser?

I finally got it working. This way only a few apps are shown by the chooser (Google Drive, Dropbox, Root Explorer, and Solid Explorer). It's working fine with the two explorers but not with Google Drive and Dropbox (I guess because they cannot access the external storage). The other MIME type like "*/*" is also possible.

public void openFolder(){
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
         +  File.separator + "myFolder" + File.separator);
    intent.setDataAndType(uri, "text/csv");
    startActivity(Intent.createChooser(intent, "Open folder"));
}

Eclipse HotKey: how to switch between tabs?

Hold CTRL and press F6 until you reached the editor you want, then release. The UI is not as pretty as the window selection, but the functionality is the same.

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //MUST CALL THIS
    setMeasuredDimension(width, height);
}

Hope that Helps.

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

React: Expected an assignment or function call and instead saw an expression

The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.

example:

return posts.map((post, index) =>
    <div key={index}>
      <h3>{post.title}</h3>
      <p>{post.body}</p>
    </div>
);

CSS3 Fade Effect

You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:

span {
    background: url(button.png) no-repeat 0 0;
}
a {
    width: 32px;
    height: 32px;
    text-align: left;
    background: rgb(255,255,255);

    -webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
    -moz-transition: background 300ms ease-in 200ms;
    -o-transition: background 300ms ease-in 200ms;
    transition: background 300ms ease-in 200ms;
    }
a:hover {
    background: rgba(255,255,255,0);
}

Maintain model of scope when changing between views in AngularJS

I had the same problem, This is what I did: I have a SPA with multiple views in the same page (without ajax), so this is the code of the module:

var app = angular.module('otisApp', ['chieffancypants.loadingBar', 'ngRoute']);

app.config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/:page', {
        templateUrl: function(page){return page.page + '.html';},
        controller:'otisCtrl'
    })
    .otherwise({redirectTo:'/otis'});
}]);

I have only one controller for all views, but, the problem is the same as the question, the controller always refresh data, in order to avoid this behavior I did what people suggest above and I created a service for that purpose, then pass it to the controller as follows:

app.factory('otisService', function($http){
    var service = {            
        answers:[],
        ...

    }        
    return service;
});

app.controller('otisCtrl', ['$scope', '$window', 'otisService', '$routeParams',  
function($scope, $window, otisService, $routeParams){        
    $scope.message = "Hello from page: " + $routeParams.page;
    $scope.update = function(answer){
        otisService.answers.push(answers);
    };
    ...
}]);

Now I can call the update function from any of my views, pass values and update my model, I haven't no needed to use html5 apis for persistence data (this is in my case, maybe in other cases would be necessary to use html5 apis like localstorage and other stuff).

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

I fixed mine I added to my project > app > libs android volley.jar and my problem was solved

Find all zero-byte files in directory and subdirectories

Bash 4+ tested - This is the correct way to search for size 0:

find /path/to/dir -size 0 -type f -name "*.xml"

Search for multiple file extensions of size 0:

find /path/to/dir -size 0 -type f \( -iname \*.css -o -iname \*.js \)

Note: If you removed the \( ... \) the results would be all of the files that meet this requirement hence ignoring the size 0.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

How do I loop through children objects in javascript?

The backwards compatible version (IE9+) is

var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
  // Do stuff
});

The es6 way is

const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
  // Do stuff
});

SQL get the last date time record

If you want one row for each filename, reflecting a specific states and listing the most recent date then this is your friend:

select filename ,
       status   ,
       max_date = max( dates )
from some_table t
group by filename , status
having status = '<your-desired-status-here>'

Easy!

Javascript replace with reference to matched group?

For the replacement string and the replacement pattern as specified by $. here a resume:

enter image description here

link to doc : here

"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")



Note:

If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.

How to remove outliers from a dataset

Adding to @sefarkas' suggestion and using quantile as cut-offs, one could explore the following option:

newdata <- subset(mydata,!(mydata$var > quantile(mydata$var, probs=c(.01, .99))[2] | mydata$var < quantile(mydata$var, probs=c(.01, .99))[1]) ) 

This will remove the points points beyond the 99th quantile. Care should be taken like what aL3Xa was saying about keeping outliers. It should be removed only for getting an alternative conservative view of the data.

How to make HTML input tag only accept numerical values?

if you can use HTML5 you can do <input type="number" /> If not you will have to either do it through javascript as you said it doesnt get submited to do it from codebehind.

<input id="numbersOnly" onkeypress='validate()' />

function validate(){
  var returnString;
  var text = document.getElementByID('numbersOnly').value;
  var regex = /[0-9]|\./;
  var anArray = text.split('');
  for(var i=0; i<anArray.length; i++){
   if(!regex.test(anArray[i]))
   {
     anArray[i] = '';
   }
  }
  for(var i=0; i<anArray.length; i++) {
    returnString += anArray[i];
  }
  document.getElementByID('numbersOnly').value = returnString;
}

P.S didnt test the code but it should be more or less correct if not check for typos :D You might wanna add a few more things like what to do if the string is null or empty etc. Also you could make this quicker :D

Why am I getting error for apple-touch-icon-precomposed.png

Try to change link from

/apple-touch-icon-precomposed.png 

to:

<%=asset_path "apple-touch-icon-precomposed.png" %>

Updating version numbers of modules in a multi-module Maven project

The solution given above worked for us as well for a long time:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT

However it stopped working yesterday, and we found it due to a recent bug in a the versions-maven-plugin

Our (temporary) workaround was to change the parent/pom.xml file as follows:

--- jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 13:43:11 1880829
+++ jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 15:17:59 1880830
@@ -329,6 +329,13 @@
           <artifactId>spotbugs-maven-plugin</artifactId>
           <version>3.1.11</version>
         </plugin>
+        
+        <plugin>
+          <groupId>org.codehaus.mojo</groupId>
+          <artifactId>versions-maven-plugin</artifactId>
+          <version>2.7</version>
+        </plugin>
+        

shift a std_logic_vector of n bit to right or left

add_Pbl <= to_stdlogicvector(to_bitvector(dato_cu(25 downto 2)) sll 1);
add_Pbl is a std_logic_vector of 24 bit
dato_cu is a std_logic_vector of 32 bit

First, you need to convert the std_logic_vector with to_bitvector() function because sll statement works with logic 1 and 0 bits.

How to display (print) vector in Matlab?

You might try this way:

fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)

I hope this helps.

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

How to get an object's property's value by property name?

Try this :

$obj = @{
    SomeProp = "Hello"
}

Write-Host "Property Value is $($obj."SomeProp")"

Simple way to read single record from MySQL

Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:

$sql = "SELECT id FROM games LIMIT 1";  // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];

This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.

Illegal mix of collations error in MySql

Check the collation type of each table, and make sure that they have the same collation.

After that check also the collation type of each table field that you have use in operation.

I had encountered the same error, and that tricks works on me.

Java generics - get class?

Short answer: You can't.

Long answer:

Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:

public class Foo<T> 
{
    private Class<T> type;

    public Foo(Class<T> type) { this.type = type; } 
}

Usage example:

Foo<Integer> test = new Foo<Integer>(Integer.class);

iReport not starting using JRE 8

There's another way if you don't want to have older Java versions installed you can do the following:

1) Download the iReport-5.6.0.zip from https://sourceforge.net/projects/ireport/files/iReport/iReport-5.6.0/

2) Download jre-7u67-windows-x64.tar.gz (the one packed in a tar) from https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

3) Extract the iReport and in the extracted folder that contains the bin and etc folders throw in the jre. For example if you unpack twice the jre-7u67-windows-x64.tar.gz you end up with a folder named jre1.7.0_67. Put that folder in the iReport-5.6.0 directory:

enter image description here

and then go into the etc folder and edit the file ireport.conf and add the following line into it:

For Windows jdkhome=".\jre1.7.0_67"

For Linux jdkhome="./jre1.7.0_67"

Note : jre version may change! according to your download of 1.7

enter image description here

now if you run the ireport_w.exe from the bin folder in the iReport directory it should load just fine.

What's the simplest way to print a Java array?

Using regular for loop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

It gives output as yours 1, 2, 3, 4, 5

How to Exit a Method without Exiting the Program?

There are two ways to exit a method early (without quitting the program):

  • Use the return keyword.
  • Throw an exception.

Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

If your method returns void then you can write return without a value:

return;

Specifically about your code:

  • There is no need to write the same test three times. All those conditions are equivalent.
  • You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:

    if (textBox1.Text == String.Empty)
    {
        textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    }
    return; // Are you sure you want the return to be here??
    
  • If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.

  • You might want to use Environment.Newline instead of "\r\n".
  • You might want to consider another way to display invalid input other than writing messages to a text box.

Find object by id in an array of JavaScript objects

myArray.filter(function(a){ return a.id == some_id_you_want })[0]

How do I output text without a newline in PowerShell?

You simply cannot get PowerShell to omit those pesky newlines... There is no script or cmdlet that does. Of course, Write-Host is absolute nonsense, because you can't redirect/pipe from it!

Nevertheless, you can write your own EXE file to do it which is what I explained how to do in Stack Overflow question How to output something in PowerShell.

Tensorflow installation error: not a supported wheel on this platform

Seems that tensorflow only work on python 3.5 at the moment, try to run this command before running the pip install

conda create --name tensorflow python=3.5

After this running the following lines :

For cpu :

pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.1.0-cp35-cp35m-win_amd64.whl

For gpu :

pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl

Should work like a charm,

Cheers

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

How does one extract each folder name from a path?

Or, if you need to do something with each folder, have a look at the System.IO.DirectoryInfo class. It also has a Parent property that allows you to navigate to the parent directory.

Populate one dropdown based on selection in another

_x000D_
_x000D_
function configureDropDownLists(ddl1, ddl2) {_x000D_
  var colours = ['Black', 'White', 'Blue'];_x000D_
  var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
  var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
  switch (ddl1.value) {_x000D_
    case 'Colours':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < colours.length; i++) {_x000D_
        createOption(ddl2, colours[i], colours[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Shapes':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < shapes.length; i++) {_x000D_
        createOption(ddl2, shapes[i], shapes[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Names':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < names.length; i++) {_x000D_
        createOption(ddl2, names[i], names[i]);_x000D_
      }_x000D_
      break;_x000D_
    default:_x000D_
      ddl2.options.length = 0;_x000D_
      break;_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
  var opt = document.createElement('option');_x000D_
  opt.value = value;_x000D_
  opt.text = text;_x000D_
  ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
  <option value=""></option>_x000D_
  <option value="Colours">Colours</option>_x000D_
  <option value="Shapes">Shapes</option>_x000D_
  <option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
_x000D_
_x000D_

Removing object from array in Swift 3

This is what I've used (Swift 5)...

    extension Array where Element:Equatable
    {
        @discardableResult
        mutating func removeFirst(_ item:Any ) -> Any? {
            for index in 0..<self.count {
                if(item as? Element == self[index]) {
                    return self.remove(at: index)
                }
            }
            return nil
        }
        @discardableResult
        mutating func removeLast(_ item:Any ) -> Any? {
            var index = self.count-1
            while index >= 0 {
                if(item as? Element == self[index]) {
                    return self.remove(at: index)
                }
                index -= 1
            }
            return nil
        }
    }

    var arrContacts:[String] = ["A","B","D","C","B","D"]
    var contacts: [Any] = ["B","D"]
    print(arrContacts)
    var index = 1
    arrContacts.removeFirst(contacts[index])
    print(arrContacts)
    index = 0
    arrContacts.removeLast(contacts[index])
    print(arrContacts)

Results:

   ["A", "B", "D", "C", "B", "D"]
   ["A", "B", "C", "B", "D"]
   ["A", "B", "C", "D"]

Important: The array from which you remove items must contain Equatable elements (such as objects, strings, number, etc.)

Constants in Objective-C

If you like namespace constant, you can leverage struct, Friday Q&A 2011-08-19: Namespaced Constants and Functions

// in the header
extern const struct MANotifyingArrayNotificationsStruct
{
    NSString *didAddObject;
    NSString *didChangeObject;
    NSString *didRemoveObject;
} MANotifyingArrayNotifications;

// in the implementation
const struct MANotifyingArrayNotificationsStruct MANotifyingArrayNotifications = {
    .didAddObject = @"didAddObject",
    .didChangeObject = @"didChangeObject",
    .didRemoveObject = @"didRemoveObject"
};

File.Move Does Not Work - File Already Exists

Personally I prefer this method. This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.

string source = @"c:\test\SomeFile.txt";
string destination = @"c:\test\test\SomeFile.txt";

try
{
    File.Copy(source, destination, true);
    File.Delete(source);
}
catch
{
    //some error handling
}

Java count occurrence of each item in an array

I would use a hashtable with in key takes the element of the array (here string) and in value an Integer.

then go through the list doing something like this :

for(String s:array){
if(hash.containsKey(s)){
  Integer i = hash.get(s);
  i++;
}else{
  hash.put(s, new Interger(1));
}

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

How do I restart nginx only after the configuration test was successful on Ubuntu?

You can use signals to control nginx.

According to documentation, you need to send HUP signal to nginx master process.

HUP - changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes

Check the documentation here: http://nginx.org/en/docs/control.html

You can send the HUP signal to nginx master process PID like this:

kill -HUP $( cat /var/run/nginx.pid )

The command above reads the nginx PID from /var/run/nginx.pid. By default nginx pid is written to /usr/local/nginx/logs/nginx.pid but that can be overridden in config. Check your nginx.config to see where it saves the PID.

How to initialize a variable of date type in java?

Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:

Date firstDate = new Date(ConstructorArgsHere);

Now you have a bit of a choice. If you don't pass in any arguments, and just do this,

Date firstDate = new Date();

it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:

Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);

How do I make a redirect in PHP?

Use:

<?php
    $url = "targetpage"
    function redirect$url(){
        if (headers_sent()) == false{
            echo '<script>window.location.href="' . $url . '";</script>';
        }
    }
?>

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

Why are my CSS3 media queries not working on mobile devices?

Well, in my case, the px after the width value was missing ... Interestingly, the W3C validator did not even notice this error, just silently ignored the definition.

What uses are there for "placement new"?

Generally, placement new is used to get rid of allocation cost of a 'normal new'.

Another scenario where I used it is a place where I wanted to have access to the pointer to an object that was still to be constructed, to implement a per-document singleton.

How can I remove the last character of a string in python?

You could use String.rstrip.

result = string.rstrip('/')

Fixed Table Cell Width

for FULLSCREEN width table:

  • table width MUST be 100%

  • if need N colunms, then THs MUST be N+1

example for 3 columns:

_x000D_
_x000D_
table.fixed {_x000D_
      table-layout: fixed;_x000D_
      width: 100%;_x000D_
    }_x000D_
    table.fixed td {_x000D_
      overflow: hidden;_x000D_
    }
_x000D_
  <table class="fixed">_x000D_
      <col width=20 />_x000D_
      <col width=20 />_x000D_
      <col width=20 />_x000D_
    <tr>_x000D_
      <th>1</th>_x000D_
      <th>2</th>_x000D_
      <th>3</th>_x000D_
      <th>FREE</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>text111111111</td>_x000D_
      <td>text222222222</td>_x000D_
      <td>text3333333</td>_x000D_
    </tr>_x000D_
  </table>
_x000D_
_x000D_
_x000D_

VueJS conditionally add an attribute for an element

You can pass boolean by coercing it, put !! before the variable.

let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean 

But I would like to pull your attention for the following case where the receiving component has defined type for props. In that case, if isRequired has defined type to be string then passing boolean make it type check fails and you will get Vue warning. To fix that you may want to avoid passing that prop, so just put undefined fallback and the prop will not sent to component

let isValue = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>

Explanation

I have been through the same problem, and tried above solutions !! Yes, I don't see the prop but that actually does not fulfils what required here.

My problem -

let isValid = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist': false"
/>

In the above case, what I expected is not having my-prop get passed to the child component - <any-conponent/> I don't see the prop in DOM but In my <any-component/> component, an error pops out of prop type check failure. As in the child component, I am expecting my-prop to be a String but it is boolean.

myProp : {
 type: String,
 required: false,
 default: ''
}

Which means that child component did receive the prop even if it is false. Tweak here is to let the child component to take the default-value and also skip the check. Passed undefined works though!

<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
 

This works and my child prop is having the default value.

Node.js: socket.io close client connection

socket.disconnect()

Only reboots the connection firing disconnect event on client side. But gets connected again.

socket.close()

Disconnect the connection from client. The client will keep trying to connect.

How to make script execution wait until jquery is loaded

the easiest and safest way is to use something like this:

var waitForJQuery = setInterval(function () {
    if (typeof $ != 'undefined') {

        // place your code here.

        clearInterval(waitForJQuery);
    }
}, 10);

Round up value to nearest whole number in SQL UPDATE

Combine round and ceiling to get a proper round up.

select ceiling(round(984.375000), 0)) => 984

while

select round(984.375000, 0) => 984.000000

and

select ceil (984.375000) => 985

jQuery UI tabs. How to select a tab based on its id not based on index

Active 1st tab

$("#workflowTab").tabs({ active: 0 });

Active last tab

$("#workflowTab").tabs({ active: -1 });

Active 2nd tab

$("#workflowTab").tabs({ active: 1 });

Its work like an array

Quick way to create a list of values in C#?

You can drop the new string[] part:

List<string> values = new List<string> { "one", "two", "three" };

How to disable Hyper-V in command line?

Open command prompt as admin and write :

bcdedit /set hypervisorlaunchtype off

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

I love jQuery's method chaining. Simply do...

    var value = $("#text").val().replace('.',':');

    //Or if you want to return the value:
    return $("#text").val().replace('.',':');

How to make an AlertDialog in Flutter?

Here is a shorter, but complete code.

If you need a dialog with only one button:

await showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('Message'),
        content: Text(
                'Your file is saved.'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () {
              Navigator.of(context, rootNavigator: true)
                  .pop(); // dismisses only the dialog and returns nothing
            },
            child: new Text('OK'),
          ),
        ],
      ),
    );

If you need a dialog with Yes/No buttons:

onPressed: () async {
bool result = await showDialog(
  context: context,
  builder: (context) {
    return AlertDialog(
      title: Text('Confirmation'),
      content: Text('Do you want to save?'),
      actions: <Widget>[
        new FlatButton(
          onPressed: () {
            Navigator.of(context, rootNavigator: true)
                .pop(false); // dismisses only the dialog and returns false
          },
          child: Text('No'),
        ),
        FlatButton(
          onPressed: () {
            Navigator.of(context, rootNavigator: true)
                .pop(true); // dismisses only the dialog and returns true
          },
          child: Text('Yes'),
        ),
      ],
    );
  },
);

if (result) {
  if (missingvalue) {
    Scaffold.of(context).showSnackBar(new SnackBar(
      content: new Text('Missing Value'),
    ));
  } else {
    saveObject();
    Navigator.of(context).pop(_myObject); // dismisses the entire widget
  }
} else {
  Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
}

Sql Query to list all views in an SQL Server 2005 database

Some time you need to access with schema name,as an example you are using AdventureWorks Database you need to access with schemas.

 SELECT s.name +'.'+v.name FROM sys.views v inner join sys.schemas s on s.schema_id = v.schema_id 

In PHP, what is a closure and why does it use the "use" identifier?

This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.

Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, $tax and a reference to $total) outside of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.

Java properties UTF-8 encoding in Eclipse

Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");         
props.load(new InputStreamReader(resource.openStream(), "UTF8"));

this works well in java 1.6. How can i do this in 1.5, Since Properties class does not have a method to pars InputStreamReader.

How to check if a variable is empty in python?

Just use not:

if not your_variable:
    print("your_variable is empty")

and for your 0 as string use:

if your_variable == "0":
    print("your_variable is 0 (string)")

combine them:

if not your_variable or your_variable == "0":
    print("your_variable is empty")

Python is about simplicity, so is this answer :)

How to declare and use 1D and 2D byte arrays in Verilog?

In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:

module tb;

byte b [4];

initial begin
    foreach (b[i]) b[i] = 1 << i;
    foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
    $finish;
end

endmodule

This prints out:

Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000

This is similar in concept to Marty's reg [7:0] a [0:3];. However, byte is a 2-state data type (0 and 1), but reg is 4-state (01xz). Using byte also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i]) loop syntax.

The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.

pull out p-values and r-squared from a linear regression

x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
> names(summary(fit))
[1] "call"          "terms"        
 [3] "residuals"     "coefficients" 
 [5] "aliased"       "sigma"        
 [7] "df"            "r.squared"    
 [9] "adj.r.squared" "fstatistic"   
[11] "cov.unscaled" 
    summary(fit)$r.squared

How do you create a Swift Date object?

According to Apple documentation

Example :

var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow

How do I perform a JAVA callback between classes?

I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.

first define a generic callback:

public interface ITypedCallback<T> {
    void execute(T type);
}

create a new ITypedCallback instance on ServerConnections instantiation:

public Server(int _address) {
    serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
        @Override
        public void execute(Socket socket) {
            // do something with your socket here
        }
    });
}

call the execute methode on the callback object.

public class ServerConnections implements Runnable {

    private ITypedCallback<Socket> callback;

    public ServerConnections(ITypedCallback<Socket> _callback) {
        callback = _callback;
    }

    @Override
    public void run() {   
        try {
            mainSocket = new ServerSocket(serverPort);
            while (true) {
                callback.execute(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

btw: I didn't check if it's 100% correct, directly coded it here.

How do I position one image on top of another in HTML?

Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.

Plotting a list of (x, y) coordinates in python matplotlib

If you have a numpy array you can do this:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()

Hide element by class in pure Javascript

var appBanners = document.getElementsByClassName('appBanner');

for (var i = 0; i < appBanners.length; i ++) {
    appBanners[i].style.display = 'none';
}

JSFiddle.

How to start automatic download of a file in Internet Explorer?

<meta http-equiv="Refresh" content="n;url">

That's It. Easy, Right?

_x000D_
_x000D_
<meta http-equiv="Refresh" content="n;url">
_x000D_
_x000D_
_x000D_

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

How to use ImageBackground to set background image for screen in react-native

I faced same problem with background image and its child components including logo images. After wasting few hours, I found the correct way to solve this problem. This is surely helped to you.

var {View, Text, Image, ImageBackground} = require('react-native');
import Images from '@assets';

export default class Welcome extends Component {
    render() {
        return (
            <ImageBackground source={Images.main_bg} style={styles.container}>
                <View style={styles.markWrap}>
                    <Image source={Images.main_logo} 
                    style={styles.mark} resizeMode="contain" />
                </View>
                <View style={[styles.wrapper]}>
                    {//Here put your other components}
                </View>              
                
            </ImageBackground>
        );
    }
}

var styles = StyleSheet.create({
    container:{
        flex: 1,
    },
    markWrap: {
        flex: 1,
        marginTop: 83,
        borderWidth:1, borderColor: "green"
      },
    mark: {
        width: null,
        height: null,
        flex: 1,
    },
    wrapper:{
        borderWidth:1, borderColor: "green",///for debug
        flex: 1,
        position:"relative",
    },
}

Logo on background Image

(PS: I put on the dummy image on this screen instead of real company logo.)

Passing base64 encoded strings in URL

In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.

In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".

Select columns in PySpark dataframe

The method select accepts a list of column names (string) or expressions (Column) as a parameter. To select columns you can use:

-- column names (strings):

df.select('col_1','col_2','col_3')

-- column objects:

import pyspark.sql.functions as F

df.select(F.col('col_1'), F.col('col_2'), F.col('col_3'))

# or

df.select(df.col_1, df.col_2, df.col_3)

# or

df.select(df['col_1'], df['col_2'], df['col_3'])

-- a list of column names or column objects:

df.select(*['col_1','col_2','col_3'])

#or

df.select(*[F.col('col_1'), F.col('col_2'), F.col('col_3')])

#or 

df.select(*[df.col_1, df.col_2, df.col_3])

The star operator * can be omitted as it's used to keep it consistent with other functions like drop that don't accept a list as a parameter.

Vba macro to copy row from table if value in table meets condition

you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.

You should always consider a non-vba solution first.

Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):

http://www.youtube.com/watch?v=RCLUM0UMLXo

http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx


If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.

If it has to be the latter, then there is need for more details on your specification, regarding performance questions.

You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.

This would look something like that:

Public Sub CopyFilter()

  Dim wks As Worksheet
  Dim avarTemp() As Variant
  'go through each worksheet
  For Each wks In ThisWorkbook.Worksheets
        avarTemp = wks.UsedRange
        For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
          'check in the first column in each row
          If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
            'copy cell
             targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
          End If
        Next i
  Next wks
End Sub

Ok, now i have something nice which could come in handy for myself:

Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
  Dim avarTemp() As Variant
  Dim avarResult() As Variant
  Dim i As Long
  avarTemp = rng

  ReDim avarResult(0)

  For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
      If avarTemp(i, 1) = "active" Then
        avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
        'expand our result array
        ReDim Preserve avarResult(UBound(avarResult) + 1)
      End If
  Next i

  FILTER = avarResult
End Function

You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)

How do you get an iPhone's device name

For Swift 4+ versions, please use the below code:

UIDevice.current.name

Convert Select Columns in Pandas Dataframe to Numpy Array

The fastest and easiest way is to use .as_matrix(). One short line:

df.iloc[:,[1,2,3]].as_matrix()

Gives:

array([[3, 2, 0.816497],
   [0, 'NaN', 'NaN'],
   [2, 51, 50.0]], dtype=object)

By using indices of the columns, you can use this code for any dataframe with different column names.

Here are the steps for your example:

import pandas as pd
columns = ['viz', 'a1_count', 'a1_mean', 'a1_std']
index = [0,1,2]
vals = {'viz': ['n','n','n'], 'a1_count': [3,0,2], 'a1_mean': [2,'NaN', 51], 'a1_std': [0.816497, 'NaN', 50.000000]}
df = pd.DataFrame(vals, columns=columns, index=index)

Gives:

   viz  a1_count a1_mean    a1_std
0   n         3       2  0.816497
1   n         0     NaN       NaN
2   n         2      51        50

Then:

x1 = df.iloc[:,[1,2,3]].as_matrix()

Gives:

array([[3, 2, 0.816497],
   [0, 'NaN', 'NaN'],
   [2, 51, 50.0]], dtype=object)

Where x1 is numpy.ndarray.

How to choose multiple files using File Upload Control?

here is the complete example of how you can select and upload multiple files in asp.net using file upload control....

write this code in .aspx file..

<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div>
    <input type="file" id="myfile" multiple="multiple" name="myfile" runat="server" size="100" />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <br />
    <asp:Label ID="Span1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

after that write this code in .aspx.cs file..

   protected void Button1_Click(object sender,EventArgs e) {
          string filepath = Server.MapPath("\\Upload");
          HttpFileCollection uploadedFiles = Request.Files;
          Span1.Text = string.Empty;

          for(int i = 0;i < uploadedFiles.Count;i++) {
              HttpPostedFile userPostedFile = uploadedFiles[i];

              try {
                  if (userPostedFile.ContentLength > 0) {
                     Span1.Text += "<u>File #" + (i + 1) +  "</u><br>";
                     Span1.Text += "File Content Type: " +  userPostedFile.ContentType      + "<br>";
                     Span1.Text += "File Size: " + userPostedFile.ContentLength           + "kb<br>";
                     Span1.Text += "File Name: " + userPostedFile.FileName + "<br>";

                     userPostedFile.SaveAs(filepath + "\\" +    Path.GetFileName(userPostedFile.FileName));                  
                     Span1.Text += "Location where saved: " +   filepath + "\\" +   Path.GetFileName(userPostedFile.FileName) + "<p>";
                  }
              } catch(Exception Ex) {
                  Span1.Text += "Error: <br>" + Ex.Message;
              }
           }
        }
    }

and here you go...your multiple file upload control is ready..have a happy day.

Installing SciPy with pip

On Fedora, this works:

sudo yum install -y python-pip
sudo yum install -y lapack lapack-devel blas blas-devel 
sudo yum install -y blas-static lapack-static
sudo pip install numpy
sudo pip install scipy

If you get any public key errors while downloading, add --nogpgcheck as parameter to yum, for example: yum --nogpgcheck install blas-devel

On Fedora 23 onwards, use dnf instead of yum.

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

Selecting all text in HTML text input when clicked

input autofocus, with onfocus event:

<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>

This lets you open a form with the desired element selected. It works by using autofocus to hit the input, which then sends itself an onfocus event, which in turn selects the text.

Eclipse, regular expression search and replace

Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2

...replaces ...

from checks import checklist(_list):

...with...

from checks import checklist



Blocks in regex are delineated by parenthesis (which are not preceded by a "\")

(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)

(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)

(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"

Then in the replace, just put the $1$2 to replace all three blocks with just the first two.



Screenshot

Using str_replace so that it only acts on the first match?

Can be done with preg_replace:

function str_replace_first($from, $to, $content)
{
    $from = '/'.preg_quote($from, '/').'/';

    return preg_replace($from, $to, $content, 1);
}

echo str_replace_first('abc', '123', 'abcdef abcdef abcdef'); 
// outputs '123def abcdef abcdef'

The magic is in the optional fourth parameter [Limit]. From the documentation:

[Limit] - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).


Though, see zombat's answer for a more efficient method (roughly, 3-4x faster).

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.

same example

...  ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
...  div collapse="isCollapsed"> ...

with

@media screen and (min-width: 768px) {
    .collapse{
        display: block !important;
    }
}

CSS / HTML Navigation and Logo on same line

1) you can float the image to the left:

<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">

2)You can use an HTML table to place elements on one line.

Code below

  <div class="navigation-bar">
    <div id="navigation-container">
      <table>
        <tr>
          <td><img src="http://i.imgur.com/hCrQkJi.png"></td>
          <td><ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Get in Touch</a></li>
        </ul>
          </td></tr></table>
    </div>

How do I use System.getProperty("line.separator").toString()?

The problem

You must NOT assume that an arbitrary input text file uses the "correct" platform-specific newline separator. This seems to be the source of your problem; it has little to do with regex.

To illustrate, on the Windows platform, System.getProperty("line.separator") is "\r\n" (CR+LF). However, when you run your Java code on this platform, you may very well have to deal with an input file whose line separator is simply "\n" (LF). Maybe this file was originally created in Unix platform, and then transferred in binary (instead of text) mode to Windows. There could be many scenarios where you may run into these kinds of situations, where you must parse a text file as input which does not use the current platform's newline separator.

(Coincidentally, when a Windows text file is transferred to Unix in binary mode, many editors would display ^M which confused some people who didn't understand what was going on).

When you are producing a text file as output, you should probably prefer the platform-specific newline separator, but when you are consuming a text file as input, it's probably not safe to make the assumption that it correctly uses the platform specific newline separator.


The solution

One way to solve the problem is to use e.g. java.util.Scanner. It has a nextLine() method that can return the next line (if one exists), correctly handling any inconsistency between the platform's newline separator and the input text file.

You can also combine 2 Scanner, one to scan the file line by line, and another to scan the tokens of each line. Here's a simple usage example that breaks each line into a List<String>. The entire file therefore becomes a List<List<String>>.

This is probably a better approach than reading the entire file into one huge String and then split into lines (which are then split into parts).

    String text
        = "row1\tblah\tblah\tblah\n"
        + "row2\t1\t2\t3\t4\r\n"
        + "row3\tA\tB\tC\r"
        + "row4";

    System.out.println(text);
    //  row1    blah    blah    blah
    //  row2    1   2   3   4
    //  row3    A   B   C
    //  row4

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

    Scanner sc = new Scanner(text);
    while (sc.hasNextLine()) {
        Scanner lineSc = new Scanner(sc.nextLine()).useDelimiter("\t");
        List<String> line = new ArrayList<String>();
        while (lineSc.hasNext()) {
            line.add(lineSc.next());
        }
        input.add(line);
    }
    System.out.println(input);
    // [[row1, blah, blah, blah], [row2, 1, 2, 3, 4], [row3, A, B, C], [row4]]

See also

  • Effective Java 2nd Edition, Item 25: Prefer lists to arrays

Related questions

Jest spyOn function called

In your test code your are trying to pass App to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:

1) Where the click handler calls a function passed as a prop, e.g.

class App extends Component {

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.props.someCallback();
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now pass in a spy function as a prop to the component, and assert that it is called:

describe('my sweet test', () => {
 it('clicks it', () => {
    const spy = jest.fn();
    const app = shallow(<App someCallback={spy} />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

2) Where the click handler sets some state on the component, e.g.

class App extends Component {
  state = {
      aProperty: 'first'
  }

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.setState({
          aProperty: 'second'
      });
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now make assertions about the state of the component, i.e.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(app.state('aProperty')).toEqual('second');
 })
})

Linux bash script to extract IP address

A slight modification to one of the previous ip route ... solutions, which eliminates the need for a grep:

ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'

React - How to get parameter value from query string?

React Router v3

With React Router v3, you can get query-string from this.props.location.search (?qs1=naisarg&qs2=parmar). For example, with let params = queryString.parse(this.props.location.search), would give { qs1 : 'naisarg', qs2 : 'parmar'}

React Router v4

With React Router v4, the this.props.location.query does not exist anymore. You need to use this.props.location.search instead and parse the query parameters either by yourself or using an existing package such as query-string.

Example

Here is a minimal example using React Router v4 and the query-string library.

import { withRouter } from 'react-router-dom';
import queryString from 'query-string';
    
class ActivateAccount extends Component{
    someFunction(){
        let params = queryString.parse(this.props.location.search)
        ...
    }
    ...
}
export default withRouter(ActivateAccount);

Rational

The React Router's team rational for removing the query property is:

There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".

[...]

The approach being taken for 4.0 is to strip out all the "batteries included" kind of features and get back to just basic routing. If you need query string parsing or async loading or Redux integration or something else very specific, then you can add that in with a library specifically for your use case. Less cruft is packed in that you don't need and you can customize things to your specific preferences and needs.

You can find the full discussion on GitHub.

IntelliJ IDEA JDK configuration on Mac OS

The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.

/Library/Java/JavaVirtualMachines/

Next, say JDK version that you find is jdk1.8.0_151.jdk, the path to home directory within it is the JDK home path.

In my case it was :

/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

You can configure it by going to File -> Project Structure -> SDKs.

enter image description here enter image description here

trying to animate a constraint in swift

You need to first change the constraint and then animate the update.
This should be in the superview.

self.nameInputConstraint.constant = 8

Swift 2

UIView.animateWithDuration(0.5) {
    self.view.layoutIfNeeded()
}

Swift 3, 4, 5

UIView.animate(withDuration: 0.5) {
    self.view.layoutIfNeeded()
}

How to convert an object to JSON correctly in Angular 2 with TypeScript

Because you're encapsulating the product again. Try to convert it like so:

let body = JSON.stringify(product); 

NullPointerException in Java with no StackTrace

This will output the Exception, use only to debug you should handle you exceptions better.

import java.io.PrintWriter;
import java.io.StringWriter;
    public static String getStackTrace(Throwable t)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        t.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Follow these steps to run your application on the device connected. 1. Change directories to the root of your Android project and execute: ant debug 2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute: adb install bin/<*your app name*>-debug.apk On your device, locate <*your app name*> and open it.

Refer Running App

How do I escape double and single quotes in sed?

My problem was that I needed to have the "" outside the expression since I have a dynamic variable inside the sed expression itself. So than the actual solution is that one from lenn jackman that you replace the " inside the sed regex with [\"].

So my complete bash is:

RELEASE_VERSION="0.6.6"

sed -i -e "s#value=[\"]trunk[\"]#value=\"tags/$RELEASE_VERSION\"#g" myfile.xml

Here is:

# is the sed separator

[\"] = " in regex

value = \"tags/$RELEASE_VERSION\" = my replacement string, important it has just the \" for the quotes

Predefined type 'System.ValueTuple´2´ is not defined or imported

We were seeing this same issue in one of our old projects that was targeting Framework 4.5.2. I tried several scenarios including all of the ones listed above: target 4.6.1, add System.ValueTuple package, delete bin, obj, and .vs folders. No dice. Repeat the same process for 4.7.2. Then tried removing the System.ValueTuple package since I was targeting 4.7.2 as one commenter suggested. Still nothing. Checked csproj file reference path. Looks right. Even dropped back down to 4.5.2 and installing the package again. All this with several VS restarts and deleting the same folders several times. Literally nothing worked.

I had to refactor to use a struct instead. I hope others don't continue to run into this issue in the future but thought this might be helpful if you end up as stumped up as we were.

How do you handle a form change in jQuery?

var formStr = JSON.stringify($("#form").serializeArray());
...
function Submit(){
   var newformStr = JSON.stringify($("#form").serializeArray());
   if (formStr != newformStr){
      ...
         formChangedfunct();
      ...
   }
   else {
      ...
         formUnchangedfunct();
      ...
   }
}

Creating a system overlay window (always on top)

I'm one of the developers of the Tooleap SDK. We also provide a way for developers to display always on top windows and buttons, and and we have dealt with a similar situation.

One problem the answers here haven't addressed is that of the Android "Secured Buttons".

Secured buttons have the filterTouchesWhenObscured property which means they can't be interacted with, if placed under a window, even if that window does not receive any touches. Quoting the Android documentation:

Specifies whether to filter touches when the view's window is obscured by another visible window. When set to true, the view will not receive touches whenever a toast, dialog or other window appears above the view's window. Refer to the {@link android.view.View} security documentation for more details.

An example of such a button is the install button when you try to install third party apks. Any app can display such a button if adding to the view layout the following line:

android:filterTouchesWhenObscured="true"

If you display an always-on-top window over a "Secured Button", so all the secured button parts that are covered by an overlay will not handle any touches, even if that overlay is not clickable. So if you are planing to display such a window, you should provide a way for the user to move it or dismiss it. And if a part of your overlay is transparent, take into account that your user might be confused why is a certain button in the underlying app is not working for him suddenly.

using jQuery .animate to animate a div from right to left?

so the .animate method works only if you have given a position attribute to an element, if not it didn't move?

for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;

How to check if any flags of a flag combination are set?

You could just check if the value is not zero.

if ((Int32)(letter & Letters.AB) != 0) { }

But I would consider it a better solution to introduce a new enumeration value with value zero and compare agains this enumeration value (if possible because you must be able to modify the enumeration).

[Flags]
enum Letters
{
    None = 0,
    A    = 1,
    B    = 2,
    C    = 4,
    AB   =  A | B,
    All  = AB | C
}

if (letter != Letters.None) { }

UPDATE

Missread the question - fixed the first suggestion and just ignore the second suggestion.

Interpreting "condition has length > 1" warning from `if` function

if statement is not vectorized. For vectorized if statements you should use ifelse. In your case it is sufficient to write

w <- function(a){
if (any(a>0)){
  a/sum(a)
}
  else 1
}

or a short vectorised version

ifelse(a > 0, a/sum(a), 1)

It depends on which do you want to use, because first function gives output vector of length 1 (in else part) and ifelse gives output vector of length equal to length of a.

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

As simple as this...

setSize(220, 400);
setLocationRelativeTo(null);  

or if you are using a frame then set the frame to

frame.setSize(220, 400);
frame.setLocationRelativeTo(null);  

For clarification, from the docs:

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

Trying to start a service on boot on Android

Before mounting external storage BOOT_COMPLETE is sent execute.if your app is installed to external storage it won't receive BOOT_COMPLETE broadcast message. To prevent this you can install your application in internal storage. you can do this just adding this line in menifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="internalOnly"
... >

Some HTC devices can enable a "fast boot" feature that is more like a deep hibernation and not a real reboot and therefore should not give the BOOT_COMPLETE intent. To recover this you can add this intent filter inside your receiver:

            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>

What is it exactly a BLOB in a DBMS context

any large single block of data stored in a database, such as a picture or sound file, which does not include record fields, and cannot be directly searched by the database's search engine.

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I have checked and fixed the following and got it resolved -

  1. httpd.conf file at /etc/httpd/conf/
  2. Checked the listening IP and port e.g. 10.12.13.4:80
  3. Removed extra listening port(s)
  4. Restarted the httpd service to take

Xcopy Command excluding files and folders

It is same as above answers, but is simple in steps

c:\SRC\folder1

c:\SRC\folder2

c:\SRC\folder3

c:\SRC\folder4

to copy all above folders to c:\DST\ except folder1 and folder2.

Step1: create a file c:\list.txt with below content, one folder name per one line

folder1\

folder2\

Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt

Unable to open a file with fopen()

Your executable's working directory is probably set to something other than the directory where it is saved. Check your IDE settings.

LPCSTR, LPCTSTR and LPTSTR

To answer the first part of your question:

LPCSTR is a pointer to a const string (LP means Long Pointer)

LPCTSTR is a pointer to a const TCHAR string, (TCHAR being either a wide char or char depending on whether UNICODE is defined in your project)

LPTSTR is a pointer to a (non-const) TCHAR string

In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.

This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Solution to this problem is simple

Go to build.gradle (module.app) file

Change the Build Version for app as shown in the photo link

It will help us to rebuild gradle for the project, to make it sync again.

Parse RSS with jQuery

The jQuery-rss project is pretty lightweight and doesn't impose any particular styling.

The syntax can be as simple as

$("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")

See a working example at http://jsfiddle.net/jhfrench/AFHfn/

Where does npm install packages?

Expanding upon other answers.

npm list -g

will show you the location of globally installed packages.

If you want to output that list to a file that you can then easily search in your text editor:

npm list -g > ~/Desktop/npmfiles.txt

Converting string to number in javascript/jQuery

You can adding a + before the string without using parseInt and parseFloat and radix, Simply

sample:

var votevalue = +$('button').data('votevalue');

alert(typeof(votevalue));

How to make a DIV not wrap?

Try using white-space: nowrap; in the container style (instead of overflow: hidden;)

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

If you don't want to change your table structure, you can run the following query:

ALTER TABLE [UserStore] 
NOCHECK CONSTRAINT FK_UserStore_User_UserId

ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT  FK_UserIdentity_User_UserId

BEGIN TRAN

UPDATE  [user] 
SET Id = 10
WHERE Id = 9

UPDATE  [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9

UPDATE  [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9

COMMIT TRAN

ALTER TABLE [UserStore] 
CHECK CONSTRAINT FK_UserStore_User_UserId

ALTER TABLE UserIdentity 
CHECK CONSTRAINT FK_UserIdentity_User_UserId

Django - Static file not found

There could be following things in your settings.py:

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': ["templates"],

'APP_DIRS': True,

'OPTIONS': {
# ... some options here ...
},
}, ]

OR

STATIC_URL = '/static/'

OR

STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )

Adding new column to existing DataFrame in Python pandas

x=pd.DataFrame([1,2,3,4,5])

y=pd.DataFrame([5,4,3,2,1])

z=pd.concat([x,y],axis=1)

enter image description here

How can I specify a local gem in my Gemfile?

You can also reference a local gem with git if you happen to be working on it.

gem 'foo',
  :git => '/Path/to/local/git/repo',
  :branch => 'my-feature-branch'

Then, if it changes I run

bundle exec gem uninstall foo
bundle update foo

But I am not sure everyone needs to run these two steps.

A child container failed during start java.util.concurrent.ExecutionException

Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.

Remove them all.

The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.

If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.

How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat

Im Maven Project:-

add follwing line in pom.xml file

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${default.javax.servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${default.javax.servlet.jsp.version}</version>
            <scope>provided</scope>
        </dependency>

Handle ModelState Validation in ASP.NET Web API

Maybe not what you were looking for, but perhaps nice for someone to know:

If you are using .net Web Api 2 you could just do the following:

if (!ModelState.IsValid)
     return BadRequest(ModelState);

Depending on the model errors, you get this result:

{
   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       ],
       model.PropertyB: [
             "The PropertyB field is required."
       ]
   }
}

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

Alternate Bootstrap 4 solution (this way you can use divs which are smaller than col-6):

Horizontal Align Center

<div class="container">
  <div class="row justify-content-center">
    <div class="col-4">
      One of two columns
    </div>
    <div class="col-4">
      One of two columns
    </div>
  </div>
</div>

More

php & mysql query not echoing in html with tags?

<td class="first"> <?php echo $proxy ?> </td> is inside a literal string that you are echoing. End the string, or concatenate it correctly:

<td class="first">' . $proxy . '</td>

Preview an image before it is uploaded

This is size improvement of cmlevy answer - try

_x000D_
_x000D_
<input type=file oninput="pic.src=window.URL.createObjectURL(this.files[0])">
<img id="pic" />
_x000D_
_x000D_
_x000D_

Bootstrap 3 unable to display glyphicon properly

I ended up switching to Font-Awesome Icons. They are just as good if not better, and all you need to do is link in the font, happy days.

Rails: How can I set default values in ActiveRecord?

Some simple cases can be handled by defining a default in the database schema but that doesn't handle a number of trickier cases including calculated values and keys of other models. For these cases I do this:

after_initialize :defaults

def defaults
   unless persisted?
    self.extras||={}
    self.other_stuff||="This stuff"
    self.assoc = [OtherModel.find_by_name('special')]
  end
end

I've decided to use the after_initialize but I don't want it to be applied to objects that are found only those new or created. I think it is almost shocking that an after_new callback isn't provided for this obvious use case but I've made do by confirming whether the object is already persisted indicating that it isn't new.

Having seen Brad Murray's answer this is even cleaner if the condition is moved to callback request:

after_initialize :defaults, unless: :persisted?
              # ":if => :new_record?" is equivalent in this context

def defaults
  self.extras||={}
  self.other_stuff||="This stuff"
  self.assoc = [OtherModel.find_by_name('special')]
end

jQuery.animate() with css class only, without explicit styles

The jQueryUI provides a extension to animate function that allows you to animate css class.

edit: Example here

There are also methods to add/remove/toggle class which you might also be interested in.

Viewing unpushed Git commits

You can show all commits that you have locally but not upstream with

git log @{u}..

@{u} or @{upstream} means the upstream branch of the current branch (see git rev-parse --help or git help revisions for details).

fast way to copy formatting in excel

Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.

TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat

AngularJS ng-class if-else expression

This is the best and reliable way to do this. Here is a simple example and after that you can develop your custom logic:

//In .ts
public showUploadButton:boolean = false;

if(some logic)
{
    //your logic
    showUploadButton = true;
}

//In template
<button [class]="showUploadButton ? 'btn btn-default': 'btn btn-info'">Upload</button>

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

The compiler doesn't know that spe_context_ptr_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file.

AttributeError: 'module' object has no attribute 'urlretrieve'

Suppose you have following lines of code

MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)

If you are receiving following error message

AttributeError: module 'urllib' has no attribute 'urlretrieve'

Then you should try following code to fix the issue:

import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)

How to get the ActionBar height?

Java:

    int actionBarHeight;
    int[] abSzAttr;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        abSzAttr = new int[] { android.R.attr.actionBarSize };
    } else {
        abSzAttr = new int[] { R.attr.actionBarSize };
    }
    TypedArray a = obtainStyledAttributes(abSzAttr);
    actionBarHeight = a.getDimensionPixelSize(0, -1);

xml:

    ?attr/actionBarSize

Fixing Segmentation faults in C++

On Unix you can use valgrind to find issues. It's free and powerful. If you'd rather do it yourself you can overload the new and delete operators to set up a configuration where you have 1 byte with 0xDEADBEEF before and after each new object. Then track what happens at each iteration. This can fail to catch everything (you aren't guaranteed to even touch those bytes) but it has worked for me in the past on a Windows platform.

Git keeps prompting me for a password

##Configuring credential.helper

On OS X (now macOS), run this in Terminal:

git config --global credential.helper osxkeychain

It enables Git to use file Keychain.app to store username and password and to retrieve the passphrase to your private SSH key from the keychain.

For Windows use:

git config --global credential.helper wincred

For Linux use:

git config --global credential.helper cache // If you want to cache the credentials for some time (default 15 minutes)

OR

git config --global credential.helper store // if you want to store the credentials for ever (considered unsafe)

Note : The first method will cache the credentials in memory, whereas the second will store them in ~/.git-credentials in plain text format.

Check here for more info about Linux method.
Check here for more info about all three.

##Troubleshooting

If the Git credential helper is configured correctly macOS saves the passphrase in the keychain. Sometimes the connection between SSH and the passphrases stored in the keychain can break. Run ssh-add -K or ssh-add ~/.ssh/id_rsa to add the key to keychain again.

macOS v10.12 (Sierra) changes to ssh

For macOS v10.12 (Sierra), ssh-add -K needs to be run after every reboot. To avoid this, create ~/.ssh/config with this content.

Host *
   AddKeysToAgent yes
   UseKeychain yes
   IdentityFile ~/.ssh/id_rsa

From the ssh_config man page on 10.12.2:

UseKeychain

On macOS, specifies whether the system should search for passphrases in the user's keychain when attempting to use a particular key. When the passphrase is provided by the user, this option also specifies whether the passphrase should be stored into the keychain once it has been verified to be correct. The argument must be 'yes' or 'no'. The default is 'no'.

Apple has added Technote 2449 which explains what happened.

Prior to macOS Sierra, ssh would present a dialog asking for your passphrase and would offer the option to store it into the keychain. This UI was deprecated some time ago and has been removed.

Mockito How to mock and assert a thrown exception?

Updated answer for 06/19/2015 (if you're using java 8)

Just use assertj

Using assertj-core-3.0.0 + Java 8 Lambdas

@Test
public void shouldThrowIllegalArgumentExceptionWhenPassingBadArg() {
assertThatThrownBy(() -> myService.sumTingWong("badArg"))
                                  .isInstanceOf(IllegalArgumentException.class);
}

Reference: http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html

Difference between Static and final?

Static and final have some big differences:

Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:

public class Test{    
   public final int first = 10;
   public static int second = 20;

   public Test(){
     second = second + 1
     first = first + 1;
   }
}

The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.

How to implement swipe gestures for mobile devices?

Shameless plug I know, but you might want to consider a jQuery plugin that I wrote:

https://github.com/benmajor/jQuery-Mobile-Events

It does not require jQuery Mobile, only jQuery.

How do I flush the PRINT buffer in TSQL?

Use the RAISERROR function:

RAISERROR( 'This message will show up right away...',0,1) WITH NOWAIT

You shouldn't completely replace all your prints with raiserror. If you have a loop or large cursor somewhere just do it once or twice per iteration or even just every several iterations.

Also: I first learned about RAISERROR at this link, which I now consider the definitive source on SQL Server Error handling and definitely worth a read:
http://www.sommarskog.se/error-handling-I.html

How to create image slideshow in html?

Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.

Here is the one I most liked.

http://www.zurb.com/playground/orbit-jquery-image-slider

Get the value for a listbox item by index

simply try this 'listBox' is your list and 'yu' is a veriable to which the value on index 0 will be assigned

string yu = listBox1.Items[0].ToString();
MessageBox.Show(yu);

Convert serial.read() into a useable string using Arduino?

I could get away with this:

void setup() {
  Serial.begin(9600);
}

void loop() {
  String message = "";
  while (Serial.available())
    message.concat((char) Serial.read());
  if (message != "")
    Serial.println(message);
}

SPAN vs DIV (inline-block)

As others have answered… div is a “block element” (now redefined as Flow Content) and span is an “inline element” (Phrasing Content). Yes, you may change the default presentation of these elements, but there is a difference between “flow” versus “block”, and “phrasing” versus “inline”.

An element classified as flow content can only be used where flow content is expected, and an element classified as phrasing content can be used where phrasing content is expected. Since all phrasing content is flow content, a phrasing element can also be used anywhere flow content is expected. The specs provide more detailed info.

All phrasing elements, such as strong and em, can only contain other phrasing elements: you can’t put a table inside a cite for instance. Most flow content such as div and li can contain all types of flow content (as well as phrasing content), but there are a few exceptions: p, pre, and th are examples of non-phrasing flow content (“block elements”) that can only contain phrasing content (“inline elements”). And of course there are the normal element restrictions such as dl and table only being allowed to contain certain elements.

While both div and p are non-phrasing flow content, the div can contain other flow content children (including more divs and ps). On the other hand, p may only contain phrasing content children. That means you can’t put a div inside a p, even though both are non-phrasing flow elements.

Now here’s the kicker. These semantic specifications are unrelated to how the element is displayed. Thus, if you have a div inside a span, you will get a validation error even if you have span {display: block;} and div {display: inline;} in your CSS.

How to convert java.lang.Object to ArrayList?

Rather Cast It to an Object Array.

Object obj2 = from some source . . ;
Object[] objects=(Object[])obj2;

How to hide Bootstrap modal with javascript?

I use Bootstrap 3.4 For me this does not work

$('#myModal').modal('hide')

In desperation,I did this:

$('#myModal').hide();
$('.modal-backdrop').hide();

Maybe it's not elegant, but it works

cin and getline skipping input

I faced this issue, and resolved this issue using getchar() to catch the ('\n') new char

Can I find events bound on an element with jQuery?

I'm adding this for posterity; There's an easier way that doesn't involve writing more JS. Using the amazing firebug addon for firefox,

  1. Right click on the element and select 'Inspect element with Firebug'
  2. In the sidebar panels (shown in the screenshot), navigate to the events tab using the tiny > arrow
  3. The events tab shows the events and corresponding functions for each event
  4. The text next to it shows the function location

enter image description here

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I know its a bit late for answer but this is the first link appearing in google, and none of the above solutions were working for me.

I was having the same problem i.e after uploading build from application loader it stuck in processing. This happened many times, after hours of head banging I found that as soon as I close the application loader on my Mac, build status was changed :)

I hope this answer will help many.

Remove Item from ArrayList

 public void DeleteUserIMP(UserIMP useriamp) {
       synchronized (ListUserIMP) {
            if (ListUserIMP.isEmpty()) {
            System.out.println("user is empty");
        }  else {
            Iterator<UserIMP> it = ListUserIMP.iterator();
            while (it.hasNext()) {
                UserIMP user = it.next();
                if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
                    it.remove();
                    System.out.println("remove it");
                }
            }
            // ListUserIMP.remove(useriamp);

            System.out.println(" this user removed");
        }
        Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
        // System.out.println("This user Deleted " + Constants.MESSAGE_OK);

    }
}

Collections.emptyList() vs. new instance

Be carefully though. If you return Collections.emptyList() and then try to do some changes with it like add() or smth like that, u will have an UnsupportedOperationException() because Collections.emptyList() returns an immutable object.

How do you get the Git repository's name in some Git repository?

A little bit late for this question, but if you:

cat /path/to/repo/.git/config

You will see the url of the repository which will include the reponame:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/your_git_user_name/your_git_repo_name.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

How do I concatenate strings and variables in PowerShell?

Just for the fun. You can also access the values of the PSObject directly like below:

$assoc.psobject.Properties.value -join " - "

But if you do not specify that the object should be ordered, PowerShell will display the values in a random order. So you should add the flag [ordered]:

$assoc = [pscustomobject] [ordered] @{
    Id = 42
    Name = "Slim Shady"
    Owner = "Eminem"
}

Git merge without auto commit

If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too

$ git merge --squash v1.0
$ git commit

How to fix the "508 Resource Limit is reached" error in WordPress?

I faced to this problem a lot when developing my company's website using WordPress. Finally I found that it happened because me and my colleague update the website at the same time as well as we installed and activated many plugins that we did not use them. The solution for me was we update the website in different time and deactivated and uninstalled those plugins.

How to check list A contains any value from list B?

Sorry, if this is irelevant, but will return list with matches using FindAll() in case you need this:

        private bool IsContain(string cont)
    {
        List<string> ListToMatch= new List<string>() {"string1","string2"};

        if (ListToMatch.ToArray().Any(cont.Contains))
        {
            return false;
        }
        else
            return true;
    }

And usage:

List<string> ListToCheck = new List<string>() {"string1","string2","string3","string4"};
List<string> FinalList = ListToCheck.FindAll(IsContain);

The final list contains only the matched elements string1 and string2 from list to check. Can easy be switched to int List.

WRONGTYPE Operation against a key holding the wrong kind of value php

I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like

$redis->set('persons', $persons)

Later I decided to change to "hSet" method, and I tried it this way

foreach($persons as $person){
    $redis->hSet('persons', $person->id, $person);
}

Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with

del persons

It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.

IIS7: Setup Integrated Windows Authentication like in IIS6

Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.

You can either:

  1. Change the app domain to be in IIS6 classic mode...
  2. Follow this example (old link) of how to fake two-stage authentication with IIS7 integrated mode.
  3. Use Helicon Ape and mod_auth to provide basic authentication

Scale an equation to fit exact page width

The graphicx package provides the command \resizebox{width}{height}{object}:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
 A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}

How do I deserialize a complex JSON object in C# .NET?

Should just be this:

var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);

You can paste the json string to here: http://json2csharp.com/ to check your classes are correct.

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 

or

static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);
}

Cannot get OpenCV to compile because of undefined references?

follow this tutorial. i ran the install-opencv.sh file in bash. its in the tutorial

read the example from openCV

CMakeLists.txt

cmake_minimum_required(VERSION 3.7)
project(openCVTest)
# cmake needs this line
cmake_minimum_required(VERSION 2.8)

# Define project name
project(opencv_example_project)

# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)

# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")

if(CMAKE_VERSION VERSION_LESS "2.8.11")
    # Add OpenCV headers location to your include paths
    include_directories(${OpenCV_INCLUDE_DIRS})
endif()

# Declare the executable target built from your sources
add_executable(main main.cpp)

# Link your application with OpenCV libraries
target_link_libraries(main ${OpenCV_LIBS})

main.cpp

/**
 * @file LinearBlend.cpp
 * @brief Simple linear blender ( dst = alpha*src1 + beta*src2 )
 * @author OpenCV team
 */

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

using namespace cv;

/** Global Variables */
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;

/** Matrices to store images */
Mat src1;
Mat src2;
Mat dst;

//![on_trackbar]
/**
 * @function on_trackbar
 * @brief Callback for trackbar
 */
static void on_trackbar( int, void* )
{
    alpha = (double) alpha_slider/alpha_slider_max ;

    beta = ( 1.0 - alpha );

    addWeighted( src1, alpha, src2, beta, 0.0, dst);

    imshow( "Linear Blend", dst );
}
//![on_trackbar]

/**
 * @function main
 * @brief Main function
 */
int main( void )
{
    //![load]
    /// Read images ( both have to be of the same size and type )
    src1 = imread("../data/LinuxLogo.jpg");
    src2 = imread("../data/WindowsLogo.jpg");
    //![load]

    if( src1.empty() ) { printf("Error loading src1 \n"); return -1; }
    if( src2.empty() ) { printf("Error loading src2 \n"); return -1; }

    /// Initialize values
    alpha_slider = 0;

    //![window]
    namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
    //![window]

    //![create_trackbar]
    char TrackbarName[50];
    sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
    createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
    //![create_trackbar]

    /// Show some stuff
    on_trackbar( alpha_slider, 0 );

    /// Wait until user press some key
    waitKey(0);
    return 0;
}

Tested in linux mint 17

How do you update a DateTime field in T-SQL?

Using a DateTime parameter is the best way. However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.

e.g.

Given a table created like :

create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())

The following should always work :

update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic

The following will work :

SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1

However, this won't :

SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1  

This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .

The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.

More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

The target principal name is incorrect. Cannot generate SSPI context

In my Case since I was working in my development environment, someone had shut down the Domain Controller and Windows Credentials couldn't be authenticated. After turning on the Domain Controller, the error disappeared and everything worked just fine.