Programs & Examples On #Protege4

Protégé 4 is the fourth version of a free, open-source platform that provides a growing user community with a suite of tools to construct domain models and knowledge-based applications with ontologies.

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

The get method of the HashMap is returning an Object, but the variable current is expected to take a ArrayList:

ArrayList current = new ArrayList();
// ...
current = dictMap.get(dictCode);

For the above code to work, the Object must be cast to an ArrayList:

ArrayList current = new ArrayList();
// ...
current = (ArrayList)dictMap.get(dictCode);

However, probably the better way would be to use generic collection objects in the first place:

HashMap<String, ArrayList<Object>> dictMap =
    new HashMap<String, ArrayList<Object>>();

// Populate the HashMap.

ArrayList<Object> current = new ArrayList<Object>();      
if(dictMap.containsKey(dictCode)) {
    current = dictMap.get(dictCode);   
}

The above code is assuming that the ArrayList has a list of Objects, and that should be changed as necessary.

For more information on generics, The Java Tutorials has a lesson on generics.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

Only changing the settings with the following command did not work in my environment:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

I had to also ran the Force Merge API command:

curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"

ref: Force Merge API

C# Help reading foreign characters using StreamReader

I solved my problem of reading portuguese characters, changing the source file on notepad++.

enter image description here

C#

    var url = System.Web.HttpContext.Current.Server.MapPath(@"~/Content/data.json");
    string s = string.Empty;
    using (System.IO.StreamReader sr = new System.IO.StreamReader(url, System.Text.Encoding.UTF8,true))
    {
          s = sr.ReadToEnd();
    }

How to set the width of a RaisedButton in Flutter?

My preferred way to make Raise button with match parent is that wrap it with Container. below is sample code.

Container(
          width: double.infinity,
          child: RaisedButton(
                 onPressed: () {},
                 color: Colors.deepPurpleAccent[100],
                 child: Text(
                        "Continue",
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  )

Hashing a string with Sha256

Encoding.Unicode is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx

If you inspect your bytes array, you'll see that every second byte is 0x00 (because of the double-wide encoding).

You should be using Encoding.UTF8.GetBytes instead.

But also, you will see different results depending on whether or not you consider the terminating '\0' byte to be part of the data you're hashing. Hashing the two bytes "Hi" will give a different result from hashing the three bytes "Hi". You'll have to decide which you want to do. (Presumably you want to do whichever one your friend's PHP code is doing.)

For ASCII text, Encoding.UTF8 will definitely be suitable. If you're aiming for perfect compatibility with your friend's code, even on non-ASCII inputs, you'd better try a few test cases with non-ASCII characters such as é and ? and see whether your results still match up. If not, you'll have to figure out what encoding your friend is really using; it might be one of the 8-bit "code pages" that used to be popular before the invention of Unicode. (Again, I think Windows is the main reason that anyone still needs to worry about "code pages".)

What is a monad?

Another attempt at explaining monads, using just Python lists and the map function. I fully accept this isn't a full explanation, but I hope it gets at the core concepts.

I got the basis of this from the funfunfunction video on Monads and the Learn You A Haskell chapter 'For a Few Monads More'. I highly recommend watching the funfunfunction video.

At it's very simplest, Monads are objects that have a map and flatMap functions (bind in Haskell). There are some extra required properties, but these are the core ones.

flatMap 'flattens' the output of map, for lists this just concatenates the values of the list e.g.

concat([[1], [4], [9]]) = [1, 4, 9]

So in Python we can very basically implement a Monad with just these two functions:

def flatMap(func, lst):
    return concat(map(func, lst))

def concat(lst):
    return sum(lst, [])

func is any function that takes a value and returns a list e.g.

lambda x: [x*x]

Explanation

For clarity I created the concat function in Python via a simple function, which sums the lists i.e. [] + [1] + [4] + [9] = [1, 4, 9] (Haskell has a native concat method).

I'm assuming you know what the map function is e.g.:

>>> list(map(lambda x: [x*x], [1,2,3]))
[[1], [4], [9]]

Flattening is the key concept of Monads and for each object which is a Monad this flattening allows you to get at the value that is wrapped in the Monad.

Now we can call:

>>> flatMap(lambda x: [x*x], [1,2,3])
[1, 4, 9]

This lambda is taking a value x and putting it into a list. A monad works with any function that goes from a value to a type of the monad, so a list in this case.

That's your monad defined.

I think the question of why they're useful has been answered in other questions.

More explanation

Other examples that aren't lists are JavaScript Promises, which have the then method and JavaScript Streams which have a flatMap method.

So Promises and Streams use a slightly different function which flattens out a Stream or a Promise and returns the value from within.

The Haskell list monad has the following definition:

instance Monad [] where  
    return x = [x]  
    xs >>= f = concat (map f xs)  
    fail _ = [] 

i.e. there are three functions return (not to be confused with return in most other languages), >>= (the flatMap) and fail.

Hopefully you can see the similarity between:

xs >>= f = concat (map f xs)

and:

def flatMap(f, xs):
    return concat(map(f, xs))

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

Thanks to Andrey-Egorov and this answer, I've managed to do it in C#

IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");

Passing null arguments to C# methods

You can use NullableValueTypes (like int?) for this. The code would be like this:

private void Example(int? arg1, int? arg2)
{
    if(!arg1.HasValue)
    {
        //do something
    }
    if(!arg2.HasValue)
    {
        //do something else
    }
}

Google Maps V3 marker with label

The way to do this without use of plugins is to make a subclass of google's OverlayView() method.

https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView

You make a custom function and apply it to the map.

function Label() { 
    this.setMap(g.map);
};

Now you prototype your subclass and add HTML nodes:

Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
        this.MySpecialDiv               = document.createElement('div');
        this.MySpecialDiv.className     = 'MyLabel';
        this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers

}

you also have to implement remove and draw functions as stated in the API docs, or this won't work.

Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
      var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
            $('.myLabel')
            .css({
                'top'   : position.y + 'px',
                'left'  : position.x + 'px'
            })
        ;
}

That's the gist of it, you'll have to do some more work in your specific implementation.

Listen to changes within a DIV and act accordingly

There is an excellent jquery plugin, LiveQuery, that does just this.

Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

For example you could use the following code to bind a click event to all A tags, even any A tags you might add via AJAX.

$('a').livequery('click', function(event) { 
    alert('clicked'); 
    return false; 
}); 

Once you add new A tags to your document, Live Query will bind the click event and there is nothing else that needs to be called or done.

Here is a working example of its magic...

enter image description here

Tomcat 8 is not able to handle get request with '|' in query parameters?

Issue: Tomcat (7.0.88) is throwing below exception which leads to 400 – Bad Request.

java.lang.IllegalArgumentException: Invalid character found in the request target. 
The valid characters are defined in RFC 7230 and RFC 3986.

This issue is occurring most of the tomcat versions from 7.0.88 onwards.

Solution: (Suggested by Apache team):

Tomcat increased their security and no longer allows raw square brackets in the query string. In the request we have [,] (Square brackets) so the request is not processed by the server.

Add relaxedQueryChars attribute under tag under server.xml (%TOMCAT_HOME%/conf):

<Connector port="80" 
           protocol="HTTP/1.1"
           maxThreads="150"
           connectionTimeout="20000"
           redirectPort="443"
           compression="on"
           compressionMinSize="2048"
           noCompressionUserAgents="gozilla, traviata"
           compressableMimeType="text/html,text/xml"
                                     relaxedQueryChars="[,]"
             />

If application needs more special characters that are not supported by tomcat by default, then add those special characters in relaxedQueryChars attribute, comma-separated as above.

How can I pass request headers with jQuery's getJSON() method?

I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $.ajax({
          url: 'service.svc/Request',
          type: 'GET',
          dataType: 'json',
          success: function() { alert('hello!'); },
          error: function() { alert('boo!'); },
          beforeSend: setHeader
        });
      });

      function setHeader(xhr) {
        xhr.setRequestHeader('securityCode', 'Foo');
        xhr.setRequestHeader('passkey', 'Bar');
      }
    </script>
  </head>
  <body>
    <h1>Some Text</h1>
  </body>
</html>

If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:

  • securityCode with a value of Foo
  • passkey with a value of Bar

The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.

Hope this helps!

Concatenate two JSON objects

Just try this, using underscore

var json1 = [{ value1: '1', value2: '2' },{ value1: '3', value2: '4' }];
var json2 = [{ value3: 'a', value4: 'b' },{ value3: 'c', value4: 'd' }];
var resultArray = [];
json1.forEach(function(obj, index){
  resultArray.push(_.extend(obj,  json2[index]));
});

console.log("Result Array", resultArray);

Result

How to sort 2 dimensional array by column value?

Using the arrow function, and sorting by the second string field

_x000D_
_x000D_
var a = [[12, 'CCC'], [58, 'AAA'], [57, 'DDD'], [28, 'CCC'],[18, 'BBB']];_x000D_
a.sort((a, b) => a[1].localeCompare(b[1]));_x000D_
console.log(a)
_x000D_
_x000D_
_x000D_

Difference between database and schema

Schema is a way of categorising the objects in a database. It can be useful if you have several applications share a single database and while there is some common set of data that all application accesses.

In Windows cmd, how do I prompt for user input and use the result in another command?

Just added the

set /p NetworkLocation= Enter name for network?

echo %NetworkLocation% >> netlist.txt

sequence to my netsh batch job. It now shows me the location I respond as the point for that sample. I continuously >> the output file so I know now "home", "work", "Starbucks", etc. Looking for clear air, I can eavulate the lowest use channels and whether there are 5 or just all 2.4 MHz WLANs around.

How to delete empty folders using windows command prompt?

from the command line: for /R /D %1 in (*) do rd "%1"

in a batch file for /R /D %%1 in (*) do rd "%%1"

I don't know if it's documented as such, but it works in W2K, XP, and Win 7. And I don't know if it will always work, but it won't ever delete files by accident.

How to improve a case statement that uses two columns

You could do it this way:

-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     ELSE '"DECLINED"'
END

The reason you can do an AND here is that you are not checking the CASE of STATE, but instead you are CASING Conditions.

The key part here is that the STATE condition is a part of the WHEN.

Getting rid of all the rounded corners in Twitter Bootstrap

The code posted above by @BrunoS did not work for me,

* {
  .border-radius(0) !important;
}

what i used was

* {
  border-radius: 0 !important;
}

I hope this helps someone

What does "TypeError 'xxx' object is not callable" means?

The action occurs when you attempt to call an object which is not a function, as with (). For instance, this will produce the error:

>>> a = 5
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Class instances can also be called if they define a method __call__

One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0) instead of [0]

How do I increase the scrollback buffer in a running screen session?

WARNING: setting this value too high may cause your system to experience a significant hiccup. The higher the value you set, the more virtual memory is allocated to the screen process when initiating the screen session. I set my ~/.screenrc to "defscrollback 123456789" and when I initiated a screen, my entire system froze up for a good 10 minutes before coming back to the point that I was able to kill the screen process (which was consuming 16.6GB of VIRT mem by then).

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

In your servlet context listener contextDestroyed() method, manually deregister the drivers:

// This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory leaks wrto this class
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
    Driver driver = drivers.nextElement();
    try {
        DriverManager.deregisterDriver(driver);
        LOG.log(Level.INFO, String.format("deregistering jdbc driver: %s", driver));
    } catch (SQLException e) {
        LOG.log(Level.SEVERE, String.format("Error deregistering driver %s", driver), e);
    }
}

How to retrieve absolute path given relative

I think this is the most portable:

abspath() {                                               
    cd "$(dirname "$1")"
    printf "%s/%s\n" "$(pwd)" "$(basename "$1")"
    cd "$OLDPWD"
}

It will fail if the path does not exist though.

Mysql: Select rows from a table that are not in another

If you have 300 columns as you mentioned in another comment, and you want to compare on all columns (assuming the columns are all the same name), you can use a NATURAL LEFT JOIN to implicitly join on all matching column names between the two tables so that you don't have to tediously type out all join conditions manually:

SELECT            a.*
FROM              tbl_1 a
NATURAL LEFT JOIN tbl_2 b
WHERE             b.FirstName IS NULL

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

Go to Project Properties and under Build Make sure that the "Optimize Code" checkbox is unchecked.

Also, set the "Debug Info" dropdown to "Full" in the Advanced Options (Under Build tab).

php_network_getaddresses: getaddrinfo failed: Name or service not known

In my case this error caused by wrong /etc/nsswitch.conf configuration on debian.

I've been replaced string

hosts:          files myhostname mdns4_minimal [NOTFOUND=return] dns

with

hosts:          files dns

and everything works right now.

What's the difference between ISO 8601 and RFC 3339 Date Formats?

Is one just an extension?

Pretty much, yes - RFC 3339 is listed as a profile of ISO 8601. Most notably RFC 3339 specifies a complete representation of date and time (only fractional seconds are optional). The RFC also has some small, subtle differences. For example truncated representations of years with only two digits are not allowed -- RFC 3339 requires 4-digit years, and the RFC only allows a period character to be used as the decimal point for fractional seconds. The RFC also allows the "T" to be replaced by a space (or other character), while the standard only allows it to be omitted (and only when there is agreement between all parties using the representation).

I wouldn't worry too much about the differences between the two, but on the off-chance your use case runs in to them, it'd be worth your while taking a glance at:

What is the optimal algorithm for the game 2048?

This is not a direct answer to OP's question, this is more of the stuffs (experiments) I tried so far to solve the same problem and obtained some results and have some observations that I want to share, I am curious if we can have some further insights from this.

I just tried my minimax implementation with alpha-beta pruning with search-tree depth cutoff at 3 and 5. I was trying to solve the same problem for a 4x4 grid as a project assignment for the edX course ColumbiaX: CSMM.101x Artificial Intelligence (AI).

I applied convex combination (tried different heuristic weights) of couple of heuristic evaluation functions, mainly from intuition and from the ones discussed above:

  1. Monotonicity
  2. Free Space Available

In my case, the computer player is completely random, but still i assumed adversarial settings and implemented the AI player agent as the max player.

I have 4x4 grid for playing the game.

Observation:

If I assign too much weights to the first heuristic function or the second heuristic function, both the cases the scores the AI player gets are low. I played with many possible weight assignments to the heuristic functions and take a convex combination, but very rarely the AI player is able to score 2048. Most of the times it either stops at 1024 or 512.

I also tried the corner heuristic, but for some reason it makes the results worse, any intuition why?

Also, I tried to increase the search depth cut-off from 3 to 5 (I can't increase it more since searching that space exceeds allowed time even with pruning) and added one more heuristic that looks at the values of adjacent tiles and gives more points if they are merge-able, but still I am not able to get 2048.

I think it will be better to use Expectimax instead of minimax, but still I want to solve this problem with minimax only and obtain high scores such as 2048 or 4096. I am not sure whether I am missing anything.

Below animation shows the last few steps of the game played by the AI agent with the computer player:

enter image description here

Any insights will be really very helpful, thanks in advance. (This is the link of my blog post for the article: https://sandipanweb.wordpress.com/2017/03/06/using-minimax-with-alpha-beta-pruning-and-heuristic-evaluation-to-solve-2048-game-with-computer/ and the youtube video: https://www.youtube.com/watch?v=VnVFilfZ0r4)

The following animation shows the last few steps of the game played where the AI player agent could get 2048 scores, this time adding the absolute value heuristic too:

enter image description here

The following figures show the game tree explored by the player AI agent assuming the computer as adversary for just a single step:

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

C# List<> Sort by x then y

I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).

I went with a list.Sort solution something like this.

    var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
    OrderId = o.id,
    OrderDate = o.orderDate,
    OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
    });

    data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
    o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));

When using SASS how can I import a file from a different directory?

Importing a .scss file that has a nested import with a different relative position won't work. the top proposed answer (using a lot of ../) is just a dirty hack that will work as long as you added enough ../ to reach the root of your project's deployment OS.

  1. Add the target SCSS path as a search target for SCSS compiler. This can be achieved by adding the stylesheets folder into the scss config file, this is function of the framework you are using,

use :load_paths at config.rd for compass-based frameworks (Ex. rails)

use the following code at scss-config.json for fourseven/meteor-scss

{
  "includePaths": [
    "{}/node_modules/ionicons/dist/scss/"
  ]
}
  1. Use absolute paths (vs. relative paths).

Example, with fourseven/meteor-scss, you can use {} to highlight top level of your project as per the following examplI

@import "{}/node_modules/module-name/stylesheet";

CSS: Position loading indicator in the center of the screen

Worked for me in angular 4

by adding style="margin:0 auto;"

<mat-progress-spinner
  style="margin:0 auto;"
  *ngIf="isLoading"
  mode="indeterminate">
  </mat-progress-spinner>

CreateProcess error=2, The system cannot find the file specified

My recomendation is to keep the getRuntime().exec because exec uses the ProcessBuilder.

Try

 p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);

Maven command to determine which settings.xml file Maven is using

Your comment to cletus' (correct) answer implies that there are multiple Maven settings files involved.

Maven always uses either one or two settings files. The global settings defined in (${M2_HOME}/conf/settings.xml) is always required. The user settings file (defined in ${user.home}/.m2/settings.xml) is optional. Any settings defined in the user settings take precedence over the corresponding global settings.

You can override the location of the global and user settings from the command line, the following example will set the global settings to c:\global\settings.xml and the user settings to c:\user\settings.xml:

mvn install --settings c:\user\settings.xml 
    --global-settings c:\global\settings.xml

Currently there is no property or means to establish what user and global settings files were used from with Maven. To access these values, you would have to modify MavenCli and/or DefaultMavenSettingsBuilder to inject the file locations into the resolved Settings object.

delete_all vs destroy_all?

delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.

If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.

How do I get bit-by-bit data from an integer value in C?

If you want the k-th bit of n, then do

(n & ( 1 << k )) >> k

Here we create a mask, apply the mask to n, and then right shift the masked value to get just the bit we want. We could write it out more fully as:

    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;

You can read more about bit-masking here.

Here is a program:

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

int *get_bits(int n, int bitswanted){
  int *bits = malloc(sizeof(int) * bitswanted);

  int k;
  for(k=0; k<bitswanted; k++){
    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;
    bits[k] = thebit;
  }

  return bits;
}

int main(){
  int n=7;

  int  bitswanted = 5;

  int *bits = get_bits(n, bitswanted);

  printf("%d = ", n);

  int i;
  for(i=bitswanted-1; i>=0;i--){
    printf("%d ", bits[i]);
  }

  printf("\n");
}

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

if you are using ASP.NET MVC

Open the layout file "_Layout.cshtml" or your custom one

At the part of the code you see, as below:

@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/jquery")

Remove the line "@Scripts.Render("~/bundles/jquery")"

(at the part of the code you see) past as the latest line, as below:

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")

This help me and hope helps you as well.

Convert UTC dates to local time in PHP

Date arithmetic is not needed if you just want to display the same timestamp in different timezones:

$format = "M d, Y h:ia";
$timestamp = gmdate($format);

date_default_timezone_set("UTC");
$utc_datetime = date($format, $timestamp);

date_default_timezone_set("America/Guayaquil");
$local_datetime = date($format, $timestamp);

How to clear jQuery validation error messages?

validator.resetForm() method clear error text. But if you want to remove the RED border from fields you have to remove the class has-error

$('#[FORM_ID] .form-group').removeClass('has-error');

Include .so library in apk in android studio

I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.

Basically what you need to do is put your .so files inside a a folder named lib (Note: it is not libs and this is not a mistake). It should be in the same structure it should be in the APK file.

In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.

So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip (the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip file into armeabi.jar and added the line compile fileTree(dir: 'libs', include: '*.jar') into dependencies {} in the gradle's build file.

This solved my problem in a rather clean way.

Set default syntax to different filetype in Sublime Text 2

You can turn on syntax highlighting based on the contents of the file.

For example, my Makefiles regardless of their extension the first line as follows:

#-*-Makefile-*- vim:syntax=make

This is typical practice for other editors such as vim.

However, for this to work you need to modify the Makefile.tmLanguage file.

  1. Find the file (for Sublime Text 3 in Ubuntu) at:

    /opt/sublime_text/Packages/Makefile.sublime-package
    

Note, that is really a zip file. Copy it, rename with .zip at the end, and extract the Makefile.tmLanguage file from it.

  1. Edit the new Makefile.tmLanguage by adding the "firstLineMatch" key and string after the "fileTypes" section. In the example below, the last two lines are new (should be added by you). The <string> section holds the regular expression, that will enable syntax highlighting for the files that match the first line. This expression recognizes two patterns: "-*-Makefile-*-" and "vim:syntax=make".

    ...
    <key>fileTypes</key>
    <array>
        <string>GNUmakefile</string>
        <string>makefile</string>
        <string>Makefile</string>
        <string>OCamlMakefile</string>
        <string>make</string>
    </array>
    
    <key>firstLineMatch</key>
    <string>^#\s*-\*-Makefile-\*-|^#.*\s*vim:syntax=make</string>
    
  2. Place the modified Makefile.tmLanguage in the User settings directory:

    ~/.config/sublime-text-3/Packages/User/Makefile.tmLanguage
    

All the files matching the first line rule should turn the syntax highlighting on when opened.

Spring - applicationContext.xml cannot be opened because it does not exist

just change the containing package of your applicationContext.xml file.
 applicationContext.xml must be in src package not in your project package.
 e.g. 
     src(main package)
         com.yourPackageName(package within src)
         classes etc.
     applicationContext.xml(within src but outside of yourPackage or we can say 
                            parallel to yourPackage name)

How create a new deep copy (clone) of a List<T>?

Straight forward simple way to copy any generic list :

List<whatever> originalCopy=new List<whatever>();//create new list
originalCopy.AddRange(original);//perform copy of original list

sql query to return differences between two tables

To get all the differences between two tables, you can use like me this SQL request :

SELECT 'TABLE1-ONLY' AS SRC, T1.*
FROM (
      SELECT * FROM Table1
      EXCEPT
      SELECT * FROM Table2
      ) AS T1
UNION ALL
SELECT 'TABLE2-ONLY' AS SRC, T2.*
FROM (
      SELECT * FROM Table2
      EXCEPT
      SELECT * FROM Table1
      ) AS T2
;

Ignore Duplicates and Create New List of Unique Values in Excel

To remove duplicates from a column

  1. Sort the values in column A A->Z
  2. Select column B
  3. While column B is still selected, in the formula input box, enter

    =IF(TRIM(A1)=TRIM(A2),"",TRIM(A1))
    
  4. While Column B is still selected, select Edit -> Fill -> Down (in newer versions, simply select cell B1 and pull down the outer box to expand all the way down in the column)

Note: if column B is on another sheet, you may do Sheet1!A1 and Sheet1!A2.

Elastic Search: how to see the indexed data

A tool that helps me a lot to debug ElasticSearch is ElasticHQ. Basically, it is an HTML file with some JavaScript. No need to install anywhere, let alone in ES itself: just download it, unzip int and open the HTML file with a browser.

Not sure it is the best tool for ES heavy users. Yet, it is really practical to whoever is in a hurry to see the entries.

Table variable error: Must declare the scalar variable "@temp"

You could stil use @TEMP if you quote the identifier "@TEMP":

declare @TEMP table (ID int, Name varchar(max));
insert into @temp SELECT 1 AS ID, 'a' Name;

SELECT * FROM @TEMP WHERE "@TEMP".ID  = 1 ;   

db<>fiddle demo

jQuery deferreds and promises - .then() vs .done()

In addition to the answers above:

The real power of .then is the possibility to chain ajax calls in a fluent way, and thus avoiding callback hell.

For example:

$.getJSON( 'dataservice/General', {action:'getSessionUser'} )
    .then( function( user ) {
        console.log( user );
        return $.getJSON( 'dataservice/Address', {action:'getFirstAddress'} );
    })
    .then( function( address ) {
        console.log( address );
    })

Here the second .then follows the returned $.getJSON

Changing image sizes proportionally using CSS?

If you don't want to stretch the image, fit it into div container without overflow and center it by adjusting it's margin if needed.

  1. The image will not get cropped
  2. The aspect ratio will also remain the same.

HTML:

<div id="app">
    <div id="container">
      <img src="#" alt="something">
    </div>
    <div id="container">
      <img src="#" alt="something">
    </div>
    <div id="container">
      <img src="#" alt="something">
    </div>
</div>

CSS:

div#container {
    height: 200px;
    width: 200px;
    border: 1px solid black;
    margin: 4px;
}
img {
    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: 0 auto;
}

(.text+0x20): undefined reference to `main' and undefined reference to function

This error means that, while linking, compiler is not able to find the definition of main() function anywhere.

In your makefile, the main rule will expand to something like this.

main: producer.o consumer.o AddRemove.o
   gcc -pthread -Wall -o producer.o consumer.o AddRemove.o

As per the gcc manual page, the use of -o switch is as below

-o file     Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out.

It means, gcc will put the output in the filename provided immediate next to -o switch. So, here instead of linking all the .o files together and creating the binary [main, in your case], its creating the binary as producer.o, linking the other .o files. Please correct that.

Server.Transfer Vs. Response.Redirect

Response.Redirect involves an extra round trip and updates the address bar.

Server.Transfer does not cause the address bar to change, the server responds to the request with content from another page

e.g.

Response.Redirect:-

  1. On the client the browser requests a page http://InitiallyRequestedPage.aspx
  2. On the server responds to the request with 302 passing the redirect address http://AnotherPage.aspx.
  3. On the client the browser makes a second request to the address http://AnotherPage.aspx.
  4. On the server responds with content from http://AnotherPage.aspx

Server.Transfer:-

  1. On the client browser requests a page http://InitiallyRequestedPage.aspx
  2. On the server Server.Transfer to http://AnotherPage.aspx
  3. On the server the response is made to the request for http://InitiallyRequestedPage.aspx passing back content from http://AnotherPage.aspx

Response.Redirect

Pros:- RESTful - It changes the address bar, the address can be used to record changes of state inbetween requests.

Cons:- Slow - There is an extra round-trip between the client and server. This can be expensive when there is substantial latency between the client and the server.

Server.Transfer

Pros:- Quick.

Cons:- State lost - If you're using Server.Transfer to change the state of the application in response to post backs, if the page is then reloaded that state will be lost, as the address bar will be the same as it was on the first request.

What is "loose coupling?" Please provide examples

You can read more about the generic concept of "loose coupling".

In short, it's a description of a relationship between two classes, where each class knows the very least about the other and each class could potentially continue to work just fine whether the other is present or not and without dependency on the particular implementation of the other class.

How to install mysql-connector via pip

First install setuptools

sudo pip install setuptools

Then install mysql-connector

sudo pip install mysql-connector

If using Python3, then replace pip by pip3

Using OR in SQLAlchemy

SQLAlchemy overloads the bitwise operators &, | and ~ so instead of the ugly and hard-to-read prefix syntax with or_() and and_() (like in Bastien's answer) you can use these operators:

.filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))

Note that the parentheses are not optional due to the precedence of the bitwise operators.

So your whole query could look like this:

addr = session.query(AddressBook) \
    .filter(AddressBook.city == "boston") \
    .filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];

openCV video saving in python

jveitchmichaelis at https://github.com/ContinuumIO/anaconda-issues/issues/223 provided a thorough answer. Here I copied his answer:

The documentation in OpenCV says (hidden away) that you can only write to avi using OpenCV3. Whether that's true or not I've not been able to determine, but I've been unable to write to anything else.

However, OpenCV is mainly a computer vision library, not a video stream, codec and write one. Therefore, the developers tried to keep this part as simple as possible. Due to this OpenCV for video containers supports only the avi extension, its first version.

From: http://docs.opencv.org/3.1.0/d7/d9e/tutorial_video_write.html

My setup: I built OpenCV 3 from source using MSVC 2015, including ffmpeg. I've also downloaded and installed XVID and openh264 from Cisco, which I added to my PATH. I'm running Anaconda Python 3. I also downloaded a recent build of ffmpeg and added the bin folder to my path, though that shouldn't make a difference as its baked into OpenCV.

I'm running in Win 10 64-bit.

This code seems to work fine on my computer. It will generate a video containing random static:

writer = cv2.VideoWriter("output.avi",
cv2.VideoWriter_fourcc(*"MJPG"), 30,(640,480))

for frame in range(1000):
    writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8'))

writer.release()

Some things I've learned through trial and error:

  • Only use '.avi', it's just a container, the codec is the important thing.
  • Be careful with specifying frame sizes. In the constructor you need to pass the frame size as (column, row) e.g. 640x480. However the array you pass in, is indexed as (row, column). See in the above example how it's switched?

  • If your input image has a different size to the VideoWriter, it will fail (often silently)

  • Only pass in 8 bit images, manually cast your arrays if you have to (.astype('uint8'))
  • In fact, never mind, just always cast. Even if you load in images using cv2.imread, you need to cast to uint8...
  • MJPG will fail if you don't pass in a 3 channel, 8-bit image. I get an assertion failure for this at least.
  • XVID also requires a 3 channel image but fails silently if you don't do this.
  • H264 seems to be fine with a single channel image
  • If you need raw output, say from a machine vision camera, you can use 'DIB '. 'RAW ' or an empty codec sometimes works. Oddly if I use DIB, I get an ffmpeg error, but the video is saved fine. If I use RAW, there isn't an error, but Windows Video player won't open it. All are fine in VLC.

In the end I think the key point is that OpenCV is not designed to be a video capture library - it doesn't even support sound. VideoWriter is useful, but 99% of the time you're better off saving all your images into a folder and using ffmpeg to turn them into a useful video.

using scp in terminal

I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.

scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop

The username@remotecomputer is the same string you used with ssh initially.

C# DropDownList with a Dictionary as DataSource

When a dictionary is enumerated, it will yield KeyValuePair<TKey,TValue> objects... so you just need to specify "Value" and "Key" for DataTextField and DataValueField respectively, to select the Value/Key properties.

Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as:

list.Add(cul.DisplayName, cod);

(And then changing the binding to use "Key" for DataTextField and "Value" for DataValueField, of course.)

In fact, I'd suggest that as it seems you really do want a list rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a List<KeyValuePair<string, string>>:

string[] languageCodsList = service.LanguagesAvailable();
var list = new List<KeyValuePair<string, string>>();

foreach (string cod in languageCodsList)
{
    CultureInfo cul = new CultureInfo(cod);
    list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod));
}

Alternatively, use a list of plain CultureInfo values. LINQ makes this really easy:

var cultures = service.LanguagesAvailable()
                      .Select(language => new CultureInfo(language));
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

If you're not using LINQ, you can still use a normal foreach loop:

List<CultureInfo> cultures = new List<CultureInfo>();
foreach (string cod in service.LanguagesAvailable())
{
    cultures.Add(new CultureInfo(cod));
}
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

no suitable HttpMessageConverter found for response type

This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.

In Spring 4.0.9, we were able to send this

    JSONObject jsonCredential = new JSONObject();
    jsonCredential.put(APPLICATION_CREDENTIALS, data);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);

In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.

The way Convertors work is that if you have it in your classpath, they get registered.

Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.

Once we added I could see the converter being registered.

enter image description here

Change bundle identifier in Xcode when submitting my first app in IOS

This solve my problem.

Just change the Bundle identifier from Build Setting.

 Navigate to Project >> Build Setting >> Product Bundle Identifier 

How to programmatically disable page scrolling with jQuery

This is what I ended up doing:

CoffeeScript:

    $("input").focus ->
        $("html, body").css "overflow-y","hidden"
        $(document).on "scroll.stopped touchmove.stopped mousewheel.stopped", (event) ->
            event.preventDefault()

    $("input").blur ->
        $("html, body").css "overflow-y","auto"
        $(document).off "scroll.stopped touchmove.stopped mousewheel.stopped"

Javascript:

$("input").focus(function() {
 $("html, body").css("overflow-y", "hidden");
 $(document).on("scroll.stopped touchmove.stopped mousewheel.stopped", function(event) {
   return event.preventDefault();
 });
});

$("input").blur(function() {
 $("html, body").css("overflow-y", "auto");
 $(document).off("scroll.stopped touchmove.stopped mousewheel.stopped");
});

Git log to get commits only for a specific branch

Here I present an alias based on Richard Hansen's answer (and Ben C's suggestion), but that I adapted to exclude tags. The alias should be fairly robust.

# For Git 1.22+
git config --global alias.only '!b=${1:-$(git branch --show-current)}; git log --oneline --graph "heads/$b" --not --exclude="$b" --branches --remotes #'
# For older Git:
git config --global alias.only '!b=${1:-$(git symbolic-ref -q --short HEAD)}; b=${b##heads/}; git log --oneline --graph "heads/$b" --not --exclude="$b" --branches --remotes #'

Example of use:

git only mybranch  # Show commits that are in mybranch ONLY
git only           # Show commits that are ONLY in current branch

Note that ONLY means commits that would be LOST (after garbage collection) if the given branch was deleted (excluding the effect of tags). The alias should work even if there is unfortunately a tag named mybranch (thanks to prefix heads/). Note also that no commits are shown if they are part of any remote branch (including upstream if any), in compliance with the definition of ONLY.

The alias shows the one-line history as a graph of the selected commits.

  a --- b --- c --- master
   \           \
    \           d
     \           \
      e --- f --- g --- mybranch (HEAD)
       \
        h --- origin/other

With example above, git only would show:

  * (mybranch,HEAD)
  * g
  |\
  | * d
  * f 

In order to include tags (but still excluding HEAD), the alias becomes (adapt as above for older Git):

git config --global alias.only '!b=${1:-$(git branch --show-current)};  git log --oneline --graph --all --not --exclude="refs/heads/$b" --exclude=HEAD --all #'

Or the variant that includes all the tags including HEAD (and removing current branch as default since it won't output anything):

git config --global alias.only '!git log --oneline --graph --all --not --exclude=\"refs/heads/$1\" --all #'

This last version is the only one that really satisfies the criteria commits-that-are-lost-if-given-branch-is-deleted, since a branch cannot be deleted if it is checked out, and no commit pointed by HEAD or any other tag will be lost. However the first two variants are more useful.

Finally, the alias does not work with remote branches (eg. git only origin/master). The alias must be modified, for instance:

git config --global alias.remote-only '!git log --oneline --graph "$1" --not --exclude="$1" --remotes --branches #'

How to print variables in Perl

You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.

print $ids should be a fairly hard statement to mess up, but it is possible. Possible reasons:

  1. $ids is undefined. Gives the warning undefined value in print
  2. $ids is out of scope. With use strict, gives fatal warning Global variable $ids needs explicit package name, and otherwise the undefined warning from above.
  3. You forgot a semi-colon at the end of the line.
  4. You tried to do print $ids $nIds, in which case perl thinks that $ids is supposed to be a filehandle, and you get an error such as print to unopened filehandle.

Explanations

1: Should not happen. It might happen if you do something like this (assuming you are not using strict):

my $var;
while (<>) {
    $Var .= $_;
}
print $var;

Gives the warning for undefined value, because $Var and $var are two different variables.

2: Might happen, if you do something like this:

if ($something) {
    my $var = "something happened!";
}
print $var;

my declares the variable inside the current block. Outside the block, it is out of scope.

3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings.

4: Also a common mistake. There are a number of ways to correctly print two variables in the same print statement:

print "$var1 $var2";  # concatenation inside a double quoted string
print $var1 . $var2;  # concatenation
print $var1, $var2;   # supplying print with a list of args

Lastly, some perl magic tips for you:

use strict;
use warnings;

# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;

# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;

my $ids  = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";

Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.

Variations:

  • print "@file" is equivalent to $ids = join(' ',@file); print $ids;
  • $#file will return the last index in @file. Since arrays usually start at 0, $#file + 1 is equivalent to scalar @file.

You can also do:

my $ids;
do {
    local $/;
    $ids = <$fh>;
}

By temporarily "turning off" $/, the input record separator, i.e. newline, you will make <$fh> return the entire file. What <$fh> really does is read until it finds $/, then return that string. Note that this will preserve the newlines in $ids.

Line-by-line solution:

open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
    chomp;
    $ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.

How to remove rows with any zero value

I would probably go with Joran's suggestion of replacing 0's with NAs and then using the built in functions you mentioned. If you can't/don't want to do that, one approach is to use any() to find rows that contain 0's and subset those out:

set.seed(42)
#Fake data
x <- data.frame(a = sample(0:2, 5, TRUE), b = sample(0:2, 5, TRUE))
> x
  a b
1 2 1
2 2 2
3 0 0
4 2 1
5 1 2
#Subset out any rows with a 0 in them
#Note the negation with ! around the apply function
x[!(apply(x, 1, function(y) any(y == 0))),]
  a b
1 2 1
2 2 2
4 2 1
5 1 2

To implement Joran's method, something like this should get you started:

x[x==0] <- NA

How to check Oracle database for long running queries

v$session_longops

If you look for sofar != totalwork you'll see ones that haven't completed, but the entries aren't removed when the operation completes so you can see a lot of history there too.

ArrayList initialization equivalent to array initialization

Here is the closest you can get:

ArrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));

You can go even simpler with:

List<String> list = Arrays.asList("Ryan", "Julie", "Bob")

Looking at the source for Arrays.asList, it constructs an ArrayList, but by default is cast to List. So you could do this (but not reliably for new JDKs):

ArrayList<String> list = (ArrayList<String>)Arrays.asList("Ryan", "Julie", "Bob")

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

How do I get the domain originating the request in express.js?

You have to retrieve it from the HOST header.

var host = req.get('host');

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.


If this is for supporting cross-origin requests, you would instead use the Origin header.

var origin = req.get('origin');

Note that some cross-origin requests require validation through a "preflight" request:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});

If you're looking for the client's IP, you can retrieve that with:

var userIP = req.socket.remoteAddress;

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

Testing pointers for validity (C/C++)

Technically you can override operator new (and delete) and collect information about all allocated memory, so you can have a method to check if heap memory is valid. but:

  1. you still need a way to check if pointer is allocated on stack ()

  2. you will need to define what is 'valid' pointer:

a) memory on that address is allocated

b) memory at that address is start address of object (e.g. address not in the middle of huge array)

c) memory at that address is start address of object of expected type

Bottom line: approach in question is not C++ way, you need to define some rules which ensure that function receives valid pointers.

Declare a constant array

There is no such thing as array constant in Go.

Quoting from the Go Language Specification: Constants:

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

A Constant expression (which is used to initialize a constant) may contain only constant operands and are evaluated at compile time.

The specification lists the different types of constants. Note that you can create and initialize constants with constant expressions of types having one of the allowed types as the underlying type. For example this is valid:

func main() {
    type Myint int
    const i1 Myint = 1
    const i2 = Myint(2)
    fmt.Printf("%T %v\n", i1, i1)
    fmt.Printf("%T %v\n", i2, i2)
}

Output (try it on the Go Playground):

main.Myint 1
main.Myint 2

If you need an array, it can only be a variable, but not a constant.

I recommend this great blog article about constants: Constants

Spark DataFrame groupBy and sort in the descending order (pyspark)

In PySpark 1.3 sort method doesn't take ascending parameter. You can use desc method instead:

from pyspark.sql.functions import col

(group_by_dataframe
    .count()
    .filter("`count` >= 10")
    .sort(col("count").desc()))

or desc function:

from pyspark.sql.functions import desc

(group_by_dataframe
    .count()
    .filter("`count` >= 10")
    .sort(desc("count"))

Both methods can be used with with Spark >= 1.3 (including Spark 2.x).

Modify tick label text

This also works in matplotlib 3:

x1 = [0,1,2,3]
squad = ['Fultz','Embiid','Dario','Simmons']

plt.xticks(x1, squad, rotation=45)

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

If you use .net core try this:

client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
        new X509ServiceCertificateAuthentication()
        {
            CertificateValidationMode = X509CertificateValidationMode.None,
            RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck
        };

Where to change the value of lower_case_table_names=2 on windows xampp

I have same problem while importing database from linux to Windows. It lowercases Database name aswell as Tables' name. Use following steps for same problem:

  1. Open c:\xampp\mysql\bin\my.ini in editor.
  2. look for

# The MySQL server

[mysqld]

3 . Find

lower_case_table_names

and change value to 2


if not avail copy this at the end of this [mysqld] portion.

lower_case_table_names = 2

This will surely work.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

I got the same error

Could not connect to the Magento WebService API: SOAP-ERROR: Parsing WSDL: Couldn't load from 'example.com/api/soap/?wsdl' : failed to load external entity "example.com/api/soap/?wsdl"

and my issue resolved once I update my Magento Root URL to

example.com/index.php/api/soap/?wsdl

Yes, I was missing index.php that causes the error.

How to insert a character in a string at a certain position?

String.format("%0d.%02d", d / 100, d % 100);

How do you run a .exe with parameters using vba's shell()?

The below code will help you to auto open the .exe file from excel...

Sub Auto_Open()


    Dim x As Variant
    Dim Path As String

    ' Set the Path variable equal to the path of your program's installation
    Path = "C:\Program Files\GameTop.com\Alien Shooter\game.exe"
    x = Shell(Path, vbNormalFocus)

End Sub

Simpler way to create dictionary of separate variables?

This is a hack. It will not work on all Python implementations distributions (in particular, those that do not have traceback.extract_stack.)

import traceback

def make_dict(*expr):
    (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
    begin=text.find('make_dict(')+len('make_dict(')
    end=text.find(')',begin)
    text=[name.strip() for name in text[begin:end].split(',')]
    return dict(zip(text,expr))

bar=True
foo=False
print(make_dict(bar,foo))
# {'foo': False, 'bar': True}

Note that this hack is fragile:

make_dict(bar,
          foo)

(calling make_dict on 2 lines) will not work.

Instead of trying to generate the dict out of the values foo and bar, it would be much more Pythonic to generate the dict out of the string variable names 'foo' and 'bar':

dict([(name,locals()[name]) for name in ('foo','bar')])

How to find the width of a div using vanilla JavaScript?

You can also search the DOM using ClassName. For example:

document.getElementsByClassName("myDiv")

This will return an array. If there is one particular property you are interested in. For example:

var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;

divWidth will now be equal to the the width of the first element in your div array.

add an onclick event to a div

Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this http://reference.sitepoint.com/javascript/Element/setAttribute . You should read documentations first before you start giving "-".

What is the purpose of using WHERE 1=1 in SQL statements?

As you said:

if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.

Class file for com.google.android.gms.internal.zzaja not found

play services, firebase, gradle plugin latest version combination that worked for me.
try app module build.gradle

android {
        compileSdkVersion 27
        buildToolsVersion '27.0.3'
        defaultConfig {
            applicationId "my package name"
            minSdkVersion 16
            targetSdkVersion 27
            versionCode 1
            versionName "1.0"
            multiDexEnabled true
            publishNonDefault true
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        } }

    dependencies {
        implementation 'com.google.android.gms:play-services-location:15.0.1'
        implementation 'com.google.android.gms:play-services-maps:15.0.1'
        implementation 'com.google.android.gms:play-services-vision:15.0.2'
        implementation 'com.google.android.gms:play-services-analytics:16.0.1'
        implementation 'com.google.firebase:firebase-core:16.0.1'
        implementation 'com.google.firebase:firebase-iid:17.0.0'
        implementation 'com.google.firebase:firebase-messaging:17.3.0'
        implementation 'com.google.firebase:firebase-crash:16.0.1'
    }

    apply plugin: 'com.google.gms.google-services'

And project level build.gradle like this

buildscript {
    repositories {

        maven { url 'https://maven.google.com' }
        google()
        jcenter()

    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
        classpath 'com.google.gms:google-services:4.1.0'
    }
}

Proper way to make HTML nested list?

I prefer option two because it clearly shows the list item as the possessor of that nested list. I would always lean towards semantically sound HTML.

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

Address already in use: JVM_Bind java

I was having this problem too. For me, I couldn't start/stop openfire (it said it was stopped, but everything was still running)

sudo /etc/init.d/openfire stop
sudo /etc/init.d/openfire start

Also, restarting apache did not help either

sudo /etc/init.d/apache2 restart

The errors were inside:

/opt/openfire/logs/stderror.log
Error creating server listener on port 5269: Address already in use
Error creating server listener on port 5222: Address already in use

The way I fixed this, I had to actually turn off the server inside the admin area for my host.

class << self idiom in Ruby

Usually, instance methods are global methods. That means they are available in all instances of the class on which they were defined. In contrast, a singleton method is implemented on a single object.

Ruby stores methods in classes and all methods must be associated with a class. The object on which a singleton method is defined is not a class (it is an instance of a class). If only classes can store methods, how can an object store a singleton method? When a singleton method is created, Ruby automatically creates an anonymous class to store that method. These anonymous classes are called metaclasses, also known as singleton classes or eigenclasses. The singleton method is associated with the metaclass which, in turn, is associated with the object on which the singleton method was defined.

If multiple singleton methods are defined within a single object, they are all stored in the same metaclass.

class Zen
end

z1 = Zen.new
z2 = Zen.new

class << z1
  def say_hello
    puts "Hello!"
  end
end

z1.say_hello    # Output: Hello!
z2.say_hello    # Output: NoMethodError: undefined method `say_hello'…

In the above example, class << z1 changes the current self to point to the metaclass of the z1 object; then, it defines the say_hello method within the metaclass.

Classes are also objects (instances of the built-in class called Class). Class methods are nothing more than singleton methods associated with a class object.

class Zabuton
  class << self
    def stuff
      puts "Stuffing zabuton…"
    end
  end
end

All objects may have metaclasses. That means classes can also have metaclasses. In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self. Hence, the stuff method is defined within the metaclass of the Zabuton class. The above example is just another way to define a class method. IMHO, it's better to use the def self.my_new_clas_method syntax to define class methods, as it makes the code easier to understand. The above example was included so we understand what's happening when we come across the class << self syntax.

Additional info can be found at this post about Ruby Classes.

Wait till a Function with animations is finished until running another Function

You can use jQuery's $.Deferred

var FunctionOne = function () {
  // create a deferred object
  var r = $.Deferred();

  // do whatever you want (e.g. ajax/animations other asyc tasks)

  setTimeout(function () {
    // and call `resolve` on the deferred object, once you're done
    r.resolve();
  }, 2500);

  // return the deferred object
  return r;
};

// define FunctionTwo as needed
var FunctionTwo = function () {
  console.log('FunctionTwo');
};

// call FunctionOne and use the `done` method
// with `FunctionTwo` as it's parameter
FunctionOne().done(FunctionTwo);

you could also pack multiple deferreds together:

var FunctionOne = function () {
  var
    a = $.Deferred(),
    b = $.Deferred();

  // some fake asyc task
  setTimeout(function () {
    console.log('a done');
    a.resolve();
  }, Math.random() * 4000);

  // some other fake asyc task
  setTimeout(function () {
    console.log('b done');
    b.resolve();
  }, Math.random() * 4000);

  return $.Deferred(function (def) {
    $.when(a, b).done(function () {
      def.resolve();
    });
  });
};

http://jsfiddle.net/p22dK/

Specifying maxlength for multiline textbox

Roll your own:

function Count(text) 
{
    //asp.net textarea maxlength doesnt work; do it by hand
    var maxlength = 2000; //set your value here (or add a parm and pass it in)
    var object = document.getElementById(text.id)  //get your object
    if (object.value.length > maxlength) 
    {
        object.focus(); //set focus to prevent jumping
        object.value = text.value.substring(0, maxlength); //truncate the value
        object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
        return false;
    }
    return true;
}

Call like this:

<asp:TextBox ID="foo" runat="server" Rows="3" TextMode="MultiLine" onKeyUp="javascript:Count(this);" onChange="javascript:Count(this);" ></asp:TextBox>

How to disable EditText in Android

You can write edittext.setInputType(0) if you want to show the edittext but not input any values

Error 'tunneling socket' while executing npm install

I lost a day trying to make this work. Worked with this steps.

I opened Fiddler and checked the option Rules > Automatically Autenticate.

After, search for file .npmrc, usually in c:\users\ and used it as configuration:

registry=https://registry.npmjs.org/
proxy=http://username:[email protected]:8888
https-proxy=http://username:[email protected]:8888
http-proxy=http://username:[email protected]:8888
strict-ssl=false
ca=null

Hope help someone!

zsh compinit: insecure directories

On macOS Sierra you need to run: sudo chown -R $(whoami):staff /usr/local

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Forget trying to decipher the example .ts - as others have said it is often incomplete.

Instead just click on the 'pop-out' icon circled here and you'll get a fully working StackBlitz example.

enter image description here

You can quickly confirm the required modules:

enter image description here

Comment out any instances of ReactiveFormsModule, and sure enough you'll get the error:

Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. 

How to join on multiple columns in Pyspark?

An alternative approach would be:

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))

df = df1.join(df2, ['x1','x2'])
df.show()

which outputs:

+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
|  2|  b|3.0|0.0|
+---+---+---+---+

With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.


Whenever the columns in the two tables have different names, (let's say in the example above, df2 has the columns y1, y2 and y4), you could use the following syntax:

df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])

AndroidStudio SDK directory does not exists

Right click your project and select 'Open Module Settings' under SDK Location put your location for your SDK.

paste in /Users/AhmadMusa/Library/Android/sdk

Clean and rebuild your project

Update

Try to delete your local.properties file and create a new one, but do not check it into version control.

Right click top level of project and Create new file 'local.properties' then add: sdk.dir=/Users/AhmadMusa/Library/Android/sdk

Clean and build

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out as an attribute:

<c:set var="test" value="test1"/>
<%
  String resp = "abc";
  String test = pageContext.getAttribute("test");
  resp = resp + test;
  pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>

If you look at the docs for <c:set>, you'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

How to set a primary key in MongoDB?

If you thinking like RDBMS, you can't create primary key. Default primary key is _id. But you can create Unique Index. Example is bellow.

db.members.createIndex( { "user_id": 1 }, { unique: true } )

db.members.insert({'user_id':1,'name':'nanhe'})

db.members.insert({'name':'kumar'})

db.members.find();

Output is bellow.

{ "_id" : ObjectId("577f9cecd71d71fa1fb6f43a"), "user_id" : 1, "name" : "nanhe" }

{ "_id" : ObjectId("577f9d02d71d71fa1fb6f43b"), "name" : "kumar" }

When you try to insert same user_id mongodb throws a write error.

db.members.insert({'user_id':1,'name':'aarush'})

WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: student.members index: user_id_1 dup key: { : 1.0 }" } })

How to get the process ID to kill a nohup process?

suppose i am running ruby script in the background with below command

nohup ruby script.rb &

then i can get the pid of above background process by specifying command name. In my case command is ruby.

ps -ef | grep ruby

output

ubuntu   25938 25742  0 05:16 pts/0    00:00:00 ruby test.rb

Now you can easily kill the process by using kill command

kill 25938

Login credentials not working with Gmail SMTP

I had same issue. And I fix it with creating an app-password for Email application on Mac. You can find it at my account -> Security -> Signing in to Google -> App passwords. below is the link for it. https://myaccount.google.com/apppasswords?utm_source=google-account&utm_medium=web

Add/remove HTML inside div using JavaScript

<!DOCTYPE html>
<html>
<head>
    <title>Dynamical Add/Remove Text Box</title>
    <script language="javascript">

        localStorage.i = Number(1);

        function myevent(action)
        {
            var i = Number(localStorage.i);
            var div = document.createElement('div');

            if(action.id == "add")
            {
                localStorage.i = Number(localStorage.i) + Number(1);
                var id = i;
                div.id = id;
                div.innerHTML = 'TextBox_'+id+': <input type="text" name="tbox_'+id+'"/>' + ' <input type="button" id='+id+' onclick="myevent(this)" value="Delete" />';

                document.getElementById('AddDel').appendChild(div);
            }
            else
            {
                var element = document.getElementById(action.id);
                element.parentNode.removeChild(element);
            }
        }
    </script>
</head>
<body>
    <fieldset>
    <legend>Dynamical Add / Remove Text Box</legend>
    <form>
        <div id="AddDel">
            Default TextBox:
            <input type="text" name="default_tb">
            <input type="button" id="add" onclick="myevent(this)" value="Add" />
        </div>
            <input type="button" type="submit" value="Submit Data" />
    </form>
    </fieldset>
</body>
</html>

Using async/await with a forEach loop

Just adding to the original answer

  • The parallel reading syntax in the original answer is sometimes confusing and difficult to read, maybe we can write it in a different approach
async function printFiles() {
  const files = await getFilePaths();
  const fileReadPromises = [];

  const readAndLogFile = async filePath => {
    const contents = await fs.readFile(file, "utf8");
    console.log(contents);
    return contents;
  };

  files.forEach(file => {
    fileReadPromises.push(readAndLogFile(file));
  });

  await Promise.all(fileReadPromises);
}

  • For sequential operation, not just for...of, normal for loop will also work
async function printFiles() {
  const files = await getFilePaths();

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const contents = await fs.readFile(file, "utf8");
    console.log(contents);
  }
}

jQuery to remove an option from drop down list, given option's text/value

Many people had difficulty in using this keyword when we have iteration of Drop-downs with same elements but different values or say as Multi line data in USER INTERFACE. : Here is the code snippet : $(this).find('option[value=yourvalue]');

Hope you got this.

Anonymous method in Invoke call

I had problems with the other suggestions because I want to sometimes return values from my methods. If you try to use MethodInvoker with return values it doesn't seem to like it. So the solution I use is like this (very happy to hear a way to make this more succinct - I'm using c#.net 2.0):

    // Create delegates for the different return types needed.
    private delegate void VoidDelegate();
    private delegate Boolean ReturnBooleanDelegate();
    private delegate Hashtable ReturnHashtableDelegate();

    // Now use the delegates and the delegate() keyword to create 
    // an anonymous method as required

    // Here a case where there's no value returned:
    public void SetTitle(string title)
    {
        myWindow.Invoke(new VoidDelegate(delegate()
        {
            myWindow.Text = title;
        }));
    }

    // Here's an example of a value being returned
    public Hashtable CurrentlyLoadedDocs()
    {
        return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()
        {
            return myWindow.CurrentlyLoadedDocs;
        }));
    }

xls to csv converter

Maybe someone find this ready-to-use piece of code useful. It allows to create CSVs from all spreadsheets in Excel's workbook.

enter image description here

# -*- coding: utf-8 -*-
import xlrd
import csv
from os import sys

def csv_from_excel(excel_file):
    workbook = xlrd.open_workbook(excel_file)
    all_worksheets = workbook.sheet_names()
    for worksheet_name in all_worksheets:
        worksheet = workbook.sheet_by_name(worksheet_name)
        with open(u'{}.csv'.format(worksheet_name), 'wb') as your_csv_file:
            wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
            for rownum in xrange(worksheet.nrows):
                wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])

if __name__ == "__main__":
    csv_from_excel(sys.argv[1])

Onclick javascript to make browser go back to previous page?

You just need to call the following:

history.go(-1);

extract date only from given timestamp in oracle sql

If you want the value from your timestamp column to come back as a date datatype, use something like this:

select trunc(my_timestamp_column,'dd') as my_date_column from my_table;

How to run a class from Jar which is not the Main-Class in its Manifest file

First of all jar creates a jar, and does not run it. Try java -jar instead.

Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2) and as file (com/mycomp/myproj/dir2/MainClass2.class)?

Edit:

It seems as if java -jar requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ... instead. -cp sets the jar on the classpath and enables java to look up the main class there.

HTML5 video won't play in Chrome only

Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?

Browsers might use the canPlayType method internally to check if a <source> is candidate to playback.

In Chrome, I have these results:

document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"

What does 'public static void' mean in Java?

The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.)

In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started.

The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made.

The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values.

MVC 4 - how do I pass model data to a partial view?

You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>(). Try this:

@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
    </div>
</div>

How to properly export an ES6 class in Node 4?

With ECMAScript 2015 you can export and import multiple classes like this

class Person
{
    constructor()
    {
        this.type = "Person";
    }
}

class Animal{
    constructor()
    {
        this.type = "Animal";
    }
}

module.exports = {
    Person,
    Animal
};

then where you use them:

const { Animal, Person } = require("classes");

const animal = new Animal();
const person = new Person();

In case of name collisions, or you prefer other names you can rename them like this:

const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");

const animal = new OtherAnimal();
const person = new OtherPerson();

Checking if a website is up via Python

I think the easiest way to do it is by using Requests module.

import requests

def url_ok(url):
    r = requests.head(url)
    return r.status_code == 200

How to specify preference of library path?

This is an old question, but no one seems to have mentioned this.

You were getting lucky that the thing was linking at all.

You needed to change

g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp

to this:

g++ -g -Wall -o my_binary -L/my/dir bar.cpp -lfoo

Your linker keeps track of symbols it needs to resolve. If it reads the library first, it doesn't have any needed symbols, so it ignores the symbols in it. Specify the libraries after the things that need to link to them so that your linker has symbols to find in them.

Also, -lfoo makes it search specifically for a file named libfoo.a or libfoo.so as needed. Not libfoo.so.0. So either ln the name or rename the library as appopriate.

To quote the gcc man page:

-l library
   ...
   It makes a difference where in the command you 
   write this option; the linker searches and processes 
   libraries and object files in the order they are 
   specified.  Thus, foo.o -lz bar.o searches library z 
   after file foo.o but before bar.o.  If bar.o refers 
   to functions in z, those functions may not be loaded.

Adding the file directly to g++'s command line should have worked, unless of course, you put it prior to bar.cpp, causing the linker to ignore it for lacking any needed symbols, because no symbols were needed yet.

What's the easiest way to call a function every 5 seconds in jQuery?

A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

function myTimer() {
    console.log(' each 1 second...');
}

var myVar = setInterval(myTimer, 1000);

call this line to stop the loop:

 clearInterval(myVar);

Android getting value from selected radiobutton

int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();

Hope this works. You can convert your output to string in the above manner. gender.getCheckedRadioButtonId(); - gender is the id of RadioGroup.

How do I block or restrict special characters from input fields with jquery?

this is an example that prevent the user from typing the character "a"

$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
    return false;

});
});

key codes refrence here:
http://www.expandinghead.net/keycode.html

Can one class extend two classes?

In Groovy, you can use trait instead of class. As they act similar to abstract classes (in the way that you can specify abstract methods, but you can still implement others), you can do something like:

trait EmployeeTrait {
    int getId() {
         return 1000 //Default value
    }
    abstract String getName() //Required
}

trait CustomerTrait {
    String getCompany() {
        return "Internal" // Default value
    }
    abstract String getAddress()
}

class InternalCustomer implements EmployeeTrait, CustomerTrait {
    String getName() { ... }
    String getAddress() { ... }
}

def internalCustomer = new InternalCustomer()
println internalCustomer.id // 1000
println internalCustomer.company //Internal

Just to point out, its not exactly the same as extending two classes, but in some cases (like the above example), it can solve the situation. I strongly suggest to analyze your design before jumping into using traits, usually they are not required and you won't be able to nicely implement inheritance (for example, you can't use protected methods in traits). Follow the accepted answer's recommendation if possible.

Regular expression to find two strings anywhere in input

(.* word1.* word2.* )|(.* word2.* word1.*)

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

Be careful, that you do not use more than one constraint in the same direction and type.

For example: Vertical constraint for trailing = 15 and another one is >= 10.

Sometimes, Xcode creates some constraints you don't notice. You have to get rid of redundant constraints and the log warning will surely disappear.

enter image description here

Additionaly, you can read and detect some certain reasons, directly from the log:

NSLayoutConstraint:0xa338390 V:|-(15)-[UILabel:0xa331260] (Names: '|':UILabel:0xa330270 )>

This we can read as problem in UILabel constraint, it is leading vertical constraint being 15pt long.

NSLayoutConstraint:0x859ab20 H:-(13)-|[UIView:0x85a8fb0]...

This would be trailing horizontal constraint etc.

Android: How to change CheckBox size?

I use

android:scaleX="0.70" android:scaleY="0.70"

to ajust the size of checkbox

then I set margins like this

android:layout_marginLeft="-10dp"

to adjust ths location of the checkbox.

Extract Month and Year From Date in R

The zoo package has the function of as.yearmon can help to convert.

require(zoo)

df$ym<-as.yearmon(df$date, "%Y %m")

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

Yes strings must be quoted and in some cases like in applescript, quotes must be escaped

do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

How to get a table creation script in MySQL Workbench?

I cannot find such an option either, at least in the Community edition.

I suppose this corresponds to the Reverse Engineering feature, which, unfortunately, is only available in the commercial edition (quoting) :

reverse engineering a database directly from a MySQL server applies to commercial versions of MySQL Workbench only.


Still, you can use plain-SQL to get the create table instruction that will allow you to create a table.

For instance, the following query :

show create table url_alias;

when executed on a drupal database, would give, when using right click > copy field content on the result :

'CREATE TABLE `url_alias` (
  `pid` int(10) unsigned NOT NULL auto_increment,
  `src` varchar(128) NOT NULL default '''',
  `dst` varchar(128) NOT NULL default '''',
  `language` varchar(12) NOT NULL default '''',
  PRIMARY KEY  (`pid`),
  UNIQUE KEY `dst_language` (`dst`,`language`),
  KEY `src_language` (`src`,`language`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8'

Unfortunately (again), MySQL Workbench adds some quotes everywhere when copying this way :-(


EDIT: Using MySQL 8.0, there is an option to right click > copy field (unquoted) on the result to get the desired result without quotes.


In the end, the simplest solution, except from staying with MySQL Query Browser, will most likely be to connect to the database, using the command-line client, and execute the show create table query from there :

mysql> show create table url_alias\G
*************************** 1. row ***************************
       Table: url_alias
Create Table: CREATE TABLE `url_alias` (
  `pid` int(10) unsigned NOT NULL auto_increment,
  `src` varchar(128) NOT NULL default '',
  `dst` varchar(128) NOT NULL default '',
  `language` varchar(12) NOT NULL default '',
  PRIMARY KEY  (`pid`),
  UNIQUE KEY `dst_language` (`dst`,`language`),
  KEY `src_language` (`src`,`language`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

Getting "the right portion" of the output is easier, there : no quote to remove.



And, just for the sake of completness, you could also use mysqldump to get your table's structure :

mysqldump --no-data --user=USERNAME --password=PASSWORD --host=HOST DATABASE_NAME TABLE_NAME

Using the --no-data switch, you'll only get the structure -- in the middle of some mode settings and all that.

How to use UTF-8 in resource properties with ResourceBundle

I tried to use the approach provided by Rod, but taking into consideration BalusC concern about not repeating the same work-around in all the application and came with this class:

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;

public class MyResourceBundle {

    // feature variables
    private ResourceBundle bundle;
    private String fileEncoding;

    public MyResourceBundle(Locale locale, String fileEncoding){
        this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
        this.fileEncoding = fileEncoding;
    }

    public MyResourceBundle(Locale locale){
        this(locale, "UTF-8");
    }

    public String getString(String key){
        String value = bundle.getString(key); 
        try {
            return new String(value.getBytes("ISO-8859-1"), fileEncoding);
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    }
}

The way to use this would be very similar than the regular ResourceBundle usage:

private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)

Or you can use the alternate constructor which uses UTF-8 by default:

private MyResourceBundle labels = new MyResourceBundle("es");

Are nested try/except blocks in Python a good programming practice?

try:
    #if it gone wrong then it will go to except
except:
    try:
        #if it also go wrong then it will go to except
    except:
        try:
            #if it also go wrong then  it will go to except
        except:
             print('write what is your need')

code for above content:

def():
    try:
        A = 5
        raise SyntaxError
    except:
        try:
           A = 5
           raise SyntaxError
       except:
           try:
               A = 5
               raise SyntaxError
           except:
               print('None')
   finally:
      return A
    

VSCode regex find & replace submatch math?

Given a regular expression of (foobar) you can reference the first group using $1 and so on if you have more groups in the replace input field.

Command line .cmd/.bat script, how to get directory of running script

This is equivalent to the path of the script:

%~dp0

This uses the batch parameter extension syntax. Parameter 0 is always the script itself.

If your script is stored at C:\example\script.bat, then %~dp0 evaluates to C:\example\.

ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:

You can get the value of any parameter using a % followed by it's numerical position on the command line.

[...]

When a parameter is used to supply a filename then the following extended syntax can be applied:

[...]

%~d1 Expand %1 to a Drive letter only - C:

[...]

%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.

[...]

The modifiers above can be combined:

%~dp1 Expand %1 to a drive letter and path only

[...]

You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\

Best way to update an element in a generic List

AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }

JavaScript split String with white space

For split string by space like in Python lang, can be used:

   var w = "hello    my brothers    ;";
   w.split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );

output:

   ["hello", "my", "brothers", ";"]

or similar:

   w.split(/(\s+)/).filter( e => e.trim().length > 0)

(output some)

VBA Excel sort range by specific column

Or this:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
    Order1:=xlAscending, Header:=xlYes

What does this GCC error "... relocation truncated to fit..." mean?

Minimal example that generates the error

main.S moves an address into %eax (32-bit).

main.S

_start:
    mov $_start, %eax

linker.ld

SECTIONS
{
    /* This says where `.text` will go in the executable. */
    . = 0x100000000;
    .text :
    {
        *(*)
    }
}

Compile on x86-64:

as -o main.o main.S
ld -o main.out -T linker.ld main.o

Outcome of ld:

(.text+0x1): relocation truncated to fit: R_X86_64_32 against `.text'

Keep in mind that:

  • as puts everything on the .text if no other section is specified
  • ld uses the .text as the default entry point if ENTRY. Thus _start is the very first byte of .text.

How to fix it: use this linker.ld instead, and subtract 1 from the start:

SECTIONS
{
    . = 0xFFFFFFFF;
    .text :
    {
        *(*)
    }
}

Notes:

  • we cannot make _start global in this example with .global _start, otherwise it still fails. I think this happens because global symbols have alignment constraints (0xFFFFFFF0 works). TODO where is that documented in the ELF standard?

  • the .text segment also has an alignment constraint of p_align == 2M. But our linker is smart enough to place the segment at 0xFFE00000, fill with zeros until 0xFFFFFFFF and set e_entry == 0xFFFFFFFF. This works, but generates an oversized executable.

Tested on Ubuntu 14.04 AMD64, Binutils 2.24.

Explanation

First you must understand what relocation is with a minimal example: https://stackoverflow.com/a/30507725/895245

Next, take a look at objdump -Sr main.o:

0000000000000000 <_start>:
   0:   b8 00 00 00 00          mov    $0x0,%eax
                        1: R_X86_64_32  .text

If we look into how instructions are encoded in the Intel manual, we see that:

  • b8 says that this is a mov to %eax
  • 0 is an immediate value to be moved to %eax. Relocation will then modify it to contain the address of _start.

When moving to 32-bit registers, the immediate must also be 32-bit.

But here, the relocation has to modify those 32-bit to put the address of _start into them after linking happens.

0x100000000 does not fit into 32-bit, but 0xFFFFFFFF does. Thus the error.

This error can only happen on relocations that generate truncation, e.g. R_X86_64_32 (8 bytes to 4 bytes), but never on R_X86_64_64.

And there are some types of relocation that require sign extension instead of zero extension as shown here, e.g. R_X86_64_32S. See also: https://stackoverflow.com/a/33289761/895245

R_AARCH64_PREL32

Asked at: How to prevent "main.o:(.eh_frame+0x1c): relocation truncated to fit: R_AARCH64_PREL32 against `.text'" when creating an aarch64 baremetal program?

Properly embedding Youtube video into bootstrap 3.0 page

I use bootstrap 3.x as well and the following code fore responsive youtube video embedding works like charm for me:

.videoWrapperOuter {
  max-width:640px; 
  margin-left:auto;
  margin-right:auto;
}
.videoWrapperInner {
  float: none;
  clear: both;
  width: 100%;
  position: relative;
  padding-bottom: 50%;
  padding-top: 25px;
  height: 0;
}
.videoWrapperInner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="videoWrapperOuter">
  <div class="videoWrapperInner">
    <iframe src="//www.youtube.com/embed/C6-TWRn0k4I" 
      frameborder="0" allowfullscreen></iframe>
  </div>
</div>

I gave a similiar answer on another thread (Shrink a YouTube video to responsive width), but I guess my answers can help here as well.

Converting EditText to int? (Android)

You can use like this

 EditText dollar=(EditText) findViewById(R.id.money);
 int rupees=Integer.parseInt( dollar.getText().toString());

Get DOM content of cross-domain iframe

If you have access to the iframed page you could use something like easyXDM to make function calls in the iframe and return the data.

If you don't have access to the iframed page you will have to use a server side solution. With PHP you could do something quick and dirty like:

    <?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?> 

Load a bitmap image into Windows Forms using open file dialog

It's simple. Just add:

PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;

Convert Xml to DataTable

I would first create a DataTable with the columns that you require, then populate it via Linq-to-XML.

You could use a Select query to create an object that represents each row, then use the standard approach for creating DataRows for each item ...

class Quest
{
    public string Answer1;
    public string Answer2;
    public string Answer3;
    public string Answer4;
}

public static void Main()
{
    var doc = XDocument.Load("filename.xml");

    var rows = doc.Descendants("QuestId").Select(el => new Quest
    {
        Answer1 = el.Element("Answer1").Value,
        Answer2 = el.Element("Answer2").Value,
        Answer3 = el.Element("Answer3").Value,
        Answer4 = el.Element("Answer4").Value,
    });

    // iterate over the rows and add to DataTable ...

}

Generic List - moving an item within the list

I created an extension method for moving items in a list.

An index should not shift if we are moving an existing item since we are moving an item to an existing index position in the list.

The edge case that @Oliver refers to below (moving an item to the end of the list) would actually cause the tests to fail, but this is by design. To insert a new item at the end of the list we would just call List<T>.Add. list.Move(predicate, list.Count) should fail since this index position does not exist before the move.

In any case, I've created two additional extension methods, MoveToEnd and MoveToBeginning, the source of which can be found here.

/// <summary>
/// Extension methods for <see cref="System.Collections.Generic.List{T}"/>
/// </summary>
public static class ListExtensions
{
    /// <summary>
    /// Moves the item matching the <paramref name="itemSelector"/> to the <paramref name="newIndex"/> in a list.
    /// </summary>
    public static void Move<T>(this List<T> list, Predicate<T> itemSelector, int newIndex)
    {
        Ensure.Argument.NotNull(list, "list");
        Ensure.Argument.NotNull(itemSelector, "itemSelector");
        Ensure.Argument.Is(newIndex >= 0, "New index must be greater than or equal to zero.");

        var currentIndex = list.FindIndex(itemSelector);
        Ensure.That<ArgumentException>(currentIndex >= 0, "No item was found that matches the specified selector.");

        // Copy the current item
        var item = list[currentIndex];

        // Remove the item
        list.RemoveAt(currentIndex);

        // Finally add the item at the new index
        list.Insert(newIndex, item);
    }
}

[Subject(typeof(ListExtensions), "Move")]
public class List_Move
{
    static List<int> list;

    public class When_no_matching_item_is_found
    {
        static Exception exception;

        Establish ctx = () => {
            list = new List<int>();
        };

        Because of = ()
            => exception = Catch.Exception(() => list.Move(x => x == 10, 10));

        It Should_throw_an_exception = ()
            => exception.ShouldBeOfType<ArgumentException>();
    }

    public class When_new_index_is_higher
    {
        Establish ctx = () => {
            list = new List<int> { 1, 2, 3, 4, 5 };
        };

        Because of = ()
            => list.Move(x => x == 3, 4); // move 3 to end of list (index 4)

        It Should_be_moved_to_the_specified_index = () =>
            {
                list[0].ShouldEqual(1);
                list[1].ShouldEqual(2);
                list[2].ShouldEqual(4);
                list[3].ShouldEqual(5);
                list[4].ShouldEqual(3);
            };
    }

    public class When_new_index_is_lower
    {
        Establish ctx = () => {
            list = new List<int> { 1, 2, 3, 4, 5 };
        };

        Because of = ()
            => list.Move(x => x == 4, 0); // move 4 to beginning of list (index 0)

        It Should_be_moved_to_the_specified_index = () =>
        {
            list[0].ShouldEqual(4);
            list[1].ShouldEqual(1);
            list[2].ShouldEqual(2);
            list[3].ShouldEqual(3);
            list[4].ShouldEqual(5);
        };
    }
}

Bootstrap 4 File Input

For changing the language of the file browser:
As an alternate to what ZimSystem mentioned (override the CSS), a more elegant solution is suggested by the bootstrap docs: build your custom bootstrap styles by adding languages in SCSS
Read about it here: https://getbootstrap.com/docs/4.0/components/forms/#file-browser

Note: you need to have the lang attribute properly set in your document for this to work

For updating the value on file selection:
You could do it with inline js like this:

   <label class="custom-file">
      <input type="file" id="myfile" class="custom-file-input" onchange="$(this).next().after().text($(this).val().split('\\').slice(-1)[0])">
      <span class="custom-file-control"></span>
   </label>

Note: the .split('\\').slice(-1)[0] part removes the C:\fakepath\ prefix

Bootstrap dropdown not working

Copy-paste below jQuery <script> and stylesheet <link> into your <head> to make sure you're loading all necessary files.

It's important that your JQuery .js file is above .css stylesheet

Simply paste the following line to test

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

The problem occurs mostly with loading of jQuery script, make sure you add references correctly.

Now test

Still if it doesn't work, check bootstrap website they've a sample implementation.

https://getbootstrap.com/docs/4.3/components/navbar/#supported-content

The property 'Id' is part of the object's key information and cannot be modified

I am using EF 4.0 and WPF and I had similar problem, and .... found the issue that solved it (at least for me) in a very simple way.

Because, like you, I thought it must be simple to update a field in a table (i.e. in your case: Contact) that is referenced to by a foreignkey from another table (i.e. in your case: ContactType).

However, the Error Message: ".... is part of the object's key information and cannot be modified." only appears when you try to update a Primary Key (which wasn't my intention at all).

Had a closer look at the XML code of my EntityModel and found it:

<EntityType Name="Contact">
    <Key>
        <PropertyRef Name="ID" />
        <PropertyRef Name="contactTypeID" />   <!-- This second line caused my problem -->
    </Key>
    <Property Name="ID" Type="int" Nullable="false" />
    ...
    ...
</EntityType>

For some reason (maybe I made some foolish mistake within my database), when Visual Studio autogenerated for me the DataModel from my database, it added in that very table (Contact), where I wanted to update the field (ContactTypeID) a second PropertyRef (second line).

I just deleted that second PropertyRef:

<PropertyRef Name="contactTypeID" />

in both, the store model and the conceptual model and .... issue was solved :-)

Hence, remains like:

<EntityType Name="Contact">
    <Key>
        <PropertyRef Name="ID" />
    </Key>
    <Property Name="ID" Type="int" Nullable="false" />
    ...
    ...
</EntityType>

Updates and Inserts are now running smoothly like a baby .... :-)

Hence, good idea to check the XML of the datamodel to verify that only your PK is listed as PropertyRef. Worked for me ... :-)

No Such Element Exception?

It looks like you are calling next even if the scanner no longer has a next element to provide... throwing the exception.

while(!file.next().equals(treasure)){
        file.next();
        }

Should be something like

boolean foundTreasure = false;

while(file.hasNext()){
     if(file.next().equals(treasure)){
          foundTreasure = true;
          break; // found treasure, if you need to use it, assign to variable beforehand
     }
}
    // out here, either we never found treasure at all, or the last element we looked as was treasure... act accordingly

Add JVM options in Tomcat

After checking catalina.sh (for windows use the .bat versions of everything mentioned below)

#   Do not set the variables in this script. Instead put them into a script
#   setenv.sh in CATALINA_BASE/bin to keep your customizations separate.

Also this

#   CATALINA_OPTS   (Optional) Java runtime options used when the "start",
#                   "run" or "debug" command is executed.
#                   Include here and not in JAVA_OPTS all options, that should
#                   only be used by Tomcat itself, not by the stop process,
#                   the version command etc.
#                   Examples are heap size, GC logging, JMX ports etc

So create a setenv.sh under CATALINA_BASE/bin (same dir where the catalina.sh resides). Edit the file and set the arguments to CATALINA_OPTS

For e.g. the file would look like this if you wanted to change the heap size

CATALINA_OPTS=-Xmx512m

Or in your case since you're using windows setenv.bat would be

set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5

To clear the added options later just delete setenv.bat/sh

What is the difference between Python and IPython?

ipython is an interactive shell built with python.

From the project website:

IPython provides a rich toolkit to help you make the most out of using Python, with:

  • Powerful Python shells (terminal and Qt-based).
  • A web-based notebook with the same core features but support for code, text, mathematical expressions, inline plots and other rich media.
  • Support for interactive data visualization and use of GUI toolkits.
  • Flexible, embeddable interpreters to load into your own projects.
  • Easy to use, high performance tools for parallel computing.

Note that the first 2 lines tell you it helps you make the most of using Python. Thus, you don't need to alter your code, the IPython shell runs your python code just like the normal python shell does, only with more features.

I recommend reading the IPython tutorial to get a sense of what features you gain when using IPython.

What is MVC and what are the advantages of it?

Main advantage of MVC architecture is differentiating the layers of a project in Model,View and Controller for the Re-usability of code, easy to maintain code and maintenance. The best thing is the developer feels good to add some code in between the project maintenance.

Here you can see the some more points on Main Advantages of MVC Architecture.

What's a concise way to check that environment variables are set in a Unix shell script?

${MyVariable:=SomeDefault}

If MyVariable is set and not null, it will reset the variable value (= nothing happens).
Else, MyVariable is set to SomeDefault.

The above will attempt to execute ${MyVariable}, so if you just want to set the variable do:

MyVariable=${MyVariable:=SomeDefault}

Authentication failed because remote party has closed the transport stream

This happened to me when an web request endpoint was switched to another server that accepted TLS1.2 requests only. Tried so many attempts mostly found on Stackoverflow like

  1. Registry Keys ,
  2. Added :
    System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12; to Global.ASX OnStart,
  3. Added in Web.config.
  4. Updated .Net framework to 4.7.2 Still getting same Exception.

The exception received did no make justice to the actual problem I was facing and found no help from the service operator.

To solve this I have to add a new Cipher Suite TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 I have used IIS Crypto 2.0 Tool from here as shown below.

enter image description here

Disable ONLY_FULL_GROUP_BY

This is what I performed to fix on Mysql workbench:

Before I got the current value with the below command

SELECT @@sql_mode 

later I removed the ONLY_FULL_GROUP_BY key from the list and I pasted the below command

SET sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

Node Sass couldn't find a binding for your current environment

I had this issue when upgrading from VS 2017 Professional to Enterprise

  1. Close VS
  2. Delete node_modules
  3. Open VS
  4. Right click package.json and select 'restore packages'

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

How to give a delay in loop execution using Qt

So this question is nearly 10 years old, but it popped up on one of my searches, and I think that there are better solutions when programming in Qt: Signals & slots, timers, and finite state machines. The delays that are required can be implemented without sleeping the application in a way that interrupts other functions, and without concurrent programming and without spinning the processor - the Qt application will sleep when there are no events to process.

A hack for this is to have a sequence of timers with their timeout() signal connected to the slot for the event, which then kicks off the second timer. This is nice because it is simple. It's not so nice because it quickly becomes difficult to troubleshoot and maintain if there are logical branches, which there generally will be outside of any toy example.

QTimer

A better, more flexible option is the State Machine infrastructure within Qt. There you can configure an framework for an arbitrary sequence of events with multiple states and branches. An FSM is much easier to define, expand and maintain over time.

Qt State Machine

What does the "map" method do in Ruby?

#each

#each runs a function for each element in an array. The following two code excerpts are equivalent:

x = 10
["zero", "one", "two"].each{|element|
    x++
    puts element
}
x = 10
array = ["zero", "one", "two"]

for i in 0..2
    x++
    puts array[i]
end

#map

#map applies a function to each element of an array, returning the resulting array. The following are equivalent:

array = ["zero", "one", "two"]
newArray = array.map{|element| element.capitalize()}
array = ["zero", "one", "two"]

newArray = []
array.each{|element|
    newArray << element.capitalize()
}

#map!

#map! is like #map, but modifies the array in place. The following are equivalent:

array = ["zero", "one", "two"]
array.map!{|element| element.capitalize()}
array = ["zero", "one", "two"]
array = array.map{|element| element.capitalize()}

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

Why is document.write considered a "bad practice"?

I think the biggest problem is that any elements written via document.write are added to the end of the page's elements. That's rarely the desired effect with modern page layouts and AJAX. (you have to keep in mind that the elements in the DOM are temporal, and when the script runs may affect its behavior).

It's much better to set a placeholder element on the page, and then manipulate it's innerHTML.

Why is it important to override GetHashCode when Equals method is overridden?

It is because the framework requires that two objects that are the same must have the same hashcode. If you override the equals method to do a special comparison of two objects and the two objects are considered the same by the method, then the hash code of the two objects must also be the same. (Dictionaries and Hashtables rely on this principle).

ImportError: cannot import name NUMPY_MKL

If you look at the line which is causing the error, you'll see this:

from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl

This line comment states the dependency as numpy+mkl (numpy with Intel Math Kernel Library). This means that you've installed the numpy by pip, but the scipy was installed by precompiled archive, which expects numpy+mkl.

This problem can be easy solved by installation for numpy+mkl from whl file from here.

Adding Table rows Dynamically in Android

change code of init like following,

public void init(){
    menuDB = new MenuDBAdapter(this);
    ll = (TableLayout) findViewById(R.id.displayLinear);
    ll.removeAllViews()

    for (int i = 0; i <2; i++) {
        TableRow row=(TableRow)findViewById(R.id.display_row);
        checkBox = new CheckBox(this);
        tv = new TextView(this);
        addBtn = new ImageButton(this);
        addBtn.setImageResource(R.drawable.add);
        minusBtn = new ImageButton(this);
        minusBtn.setImageResource(R.drawable.minus);
        qty = new TextView(this);
        checkBox.setText("hello");
        qty.setText("10");
        row.addView(checkBox);
        row.addView(minusBtn);
        row.addView(qty);
        row.addView(addBtn);
        ll.addView(row,i);

    }

A process crashed in windows .. Crash dump location

Windows 7, 64 bit, no modifications to the Registry key, the location is:

C:\Users[Current User when app crashed]\AppData\Local\Microsoft\Windows\WER\ReportArchive

Custom method names in ASP.NET Web API

Just modify your WebAPIConfig.cs as bellow

Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}/{action}/{id}",
  defaults: new { action = "get", id = RouteParameter.Optional });

Then implement your API as bellow

    // GET: api/Controller_Name/Show/1
    [ActionName("Show")]
    [HttpGet]
    public EventPlanner Id(int id){}

Importing data from a JSON file into R

packages:

  • library(httr)
  • library(jsonlite)

I have had issues converting json to dataframe/csv. For my case I did:

Token <- "245432532532"
source <- "http://......."
header_type <- "applcation/json"
full_token <- paste0("Bearer ", Token)
response <- GET(n_source, add_headers(Authorization = full_token, Accept = h_type), timeout(120), verbose())
text_json <- content(response, type = 'text', encoding = "UTF-8")
jfile <- fromJSON(text_json)
df <- as.data.frame(jfile)

then from df to csv.

In this format it should be easy to convert it to multiple .csvs if needed.

The important part is content function should have type = 'text'.

HTTPS using Jersey Client

Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :

System.setProperty("jsse.enableSNIExtension", "false");

(Courtesy to many stackoverflow answers combined together to figure this out)

The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
    public static ClientConfig configureClient()
    {
        System.setProperty("jsse.enableSNIExtension", "false");
        TrustManager[] certs = new TrustManager[]
        {
            new X509TrustManager()
            {
                @Override
                public X509Certificate[] getAcceptedIssuers()
                {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }
            }
        };
        SSLContext ctx = null;
        try
        {
            ctx = SSLContext.getInstance("SSL");
            ctx.init(null, certs, new SecureRandom());
        }
        catch (java.security.GeneralSecurityException ex)
        {
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        ClientConfig config = new DefaultClientConfig();
        try
        {
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
                    new HostnameVerifier()
            {
                @Override
                public boolean verify(String hostname, SSLSession session)
                {
                    return true;
                }
            },
                    ctx));
        }
        catch (Exception e)
        {
        }
        return config;
    }

    public static Client createClient()
    {
        return Client.create(ClientHelper.configureClient());
    }

Selecting data frame rows based on partial string match in a column

I notice that you mention a function %like% in your current approach. I don't know if that's a reference to the %like% from "data.table", but if it is, you can definitely use it as follows.

Note that the object does not have to be a data.table (but also remember that subsetting approaches for data.frames and data.tables are not identical):

library(data.table)
mtcars[rownames(mtcars) %like% "Merc", ]
iris[iris$Species %like% "osa", ]

If that is what you had, then perhaps you had just mixed up row and column positions for subsetting data.


If you don't want to load a package, you can try using grep() to search for the string you're matching. Here's an example with the mtcars dataset, where we are matching all rows where the row names includes "Merc":

mtcars[grep("Merc", rownames(mtcars)), ]
             mpg cyl  disp  hp drat   wt qsec vs am gear carb
# Merc 240D   24.4   4 146.7  62 3.69 3.19 20.0  1  0    4    2
# Merc 230    22.8   4 140.8  95 3.92 3.15 22.9  1  0    4    2
# Merc 280    19.2   6 167.6 123 3.92 3.44 18.3  1  0    4    4
# Merc 280C   17.8   6 167.6 123 3.92 3.44 18.9  1  0    4    4
# Merc 450SE  16.4   8 275.8 180 3.07 4.07 17.4  0  0    3    3
# Merc 450SL  17.3   8 275.8 180 3.07 3.73 17.6  0  0    3    3
# Merc 450SLC 15.2   8 275.8 180 3.07 3.78 18.0  0  0    3    3

And, another example, using the iris dataset searching for the string osa:

irisSubset <- iris[grep("osa", iris$Species), ]
head(irisSubset)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

For your problem try:

selectedRows <- conservedData[grep("hsa-", conservedData$miRNA), ]

How does the 'binding' attribute work in JSF? When and how should it be used?

each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.

  • Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
  • The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
  • For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.

    http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123

The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

Can the :not() pseudo-class have multiple arguments?

If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:

@mixin not($ignorList...) {
    //if only a single value given
    @if (length($ignorList) == 1){
        //it is probably a list variable so set ignore list to the variable
        $ignorList: nth($ignorList,1);
    }
    //set up an empty $notOutput variable
    $notOutput: '';
    //for each item in the list
    @each $not in $ignorList {
        //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
        $notOutput: $notOutput + ':not(#{$not})';
    }
    //output the full :not() rule including all ignored items
    &#{$notOutput} {
        @content;
    }
}

it can be used in 2 ways:

Option 1: list the ignored items inline

input {
  /*non-ignored styling goes here*/
  @include not('[type="radio"]','[type="checkbox"]'){
    /*ignored styling goes here*/
  }
}

Option 2: list the ignored items in a variable first

$ignoredItems:
  '[type="radio"]',
  '[type="checkbox"]'
;

input {
  /*non-ignored styling goes here*/
  @include not($ignoredItems){
    /*ignored styling goes here*/
  }
}

Outputted CSS for either option

input {
    /*non-ignored styling goes here*/
}

input:not([type="radio"]):not([type="checkbox"]) {
    /*ignored styling goes here*/
}

adding directory to sys.path /PYTHONPATH

When running a Python script from Powershell under Windows, this should work:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

AngularJS ng-if with multiple conditions

HTML code

<div ng-app>
<div ng-controller='ctrl'>
    <div ng-class='whatClassIsIt(call.state[0])'>{{call.state[0]}}</div>
    <div ng-class='whatClassIsIt(call.state[1])'>{{call.state[1]}}</div>
    <div ng-class='whatClassIsIt(call.state[2])'>{{call.state[2]}}</div>
    <div ng-class='whatClassIsIt(call.state[3])'>{{call.state[3]}}</div>
    <div ng-class='whatClassIsIt(call.state[4])'>{{call.state[4]}}</div>
    <div ng-class='whatClassIsIt(call.state[5])'>{{call.state[5]}}</div>
    <div ng-class='whatClassIsIt(call.state[6])'>{{call.state[6]}}</div>
    <div ng-class='whatClassIsIt(call.state[7])'>{{call.state[7]}}</div>
</div>

JavaScript Code

function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}


$scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
    else
         return "ClassC";
}
}

How to save a figure in MATLAB from the command line?

try plot(var); saveFigure('title'); it will save as a jpeg automatically

JQuery Ajax Post results in 500 Internal Server Error

in case if someone using the codeigniter framework, the problem may be caused by the csrf protection config enabled.

Explode string by one or more spaces or tabs

@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.

$str = "A      B      C      D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){    
    if ( trim($b) ) {
     print "using $b\n";
    }
}

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Wrap your Container in SingleChildScrollView() widget. Then it will not come above when keyboard pops up.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

Please follow this guide: https://gist.github.com/feczo/7282a6e00181fde4281b with pictures.

In short:

Using Puttygen, click 'Generate' move the mouse around as instructed and wait

  • Enter your desired username

  • Enter your password

  • Save the private key

Copy the entire content of the 'Public key for pasting into OpenSSH authorized_keys file' window. Make sure to copy every single character from the beginning to the very end!

Go to the Create instances page in the Google Cloud Platform Console and in the advanced options link paste the contents of your public key.

Note the IP address of the instance once it is complete. Open putty, from the left hand menu go to Connection / SSH / Auth and define the key file location which was saved.

From the left hand menu go to Connection / Data and define the same username

  • Enter the IP address of your instance
  • name the connection below saved Sessions as 'GCE' click on 'Save'
  • double click the 'GCE' entry you just created
  • accept the identy of the host

Now login with the password you specified earlier and run sudo su - and you are all set.

How to create a HTML Cancel button that redirects to a URL

Thats what i am using try it.

<a href="index.php"><button style ="position:absolute;top:450px;left:1100px;height:30px;width:200px;"> Cancel </button></a>

String is immutable. What exactly is the meaning?

Only the reference is changing. First a was referencing to the string "a", and later you changed it to "ty". The string "a" remains the same.

Bootstrap 3 Collapse show state with Chevron icon

I'm using font awesome! and wanted a panel to be collapsible

        <div class="panel panel-default">
                <div class="panel-heading" data-toggle="collapse" data-target="#collapseOrderItems"><i class="fa fa-chevron fa-fw" ></i> products</div>

                <div class="collapse in" id="collapseOrderItems">
                            ....
                </div>
        </div>

and the css

.panel-heading .fa-chevron:after {
    content: "\f078";   
}
.panel-heading.collapsed .fa-chevron:after {
    content: "\f054";   
}

enter image description here

enter image description here

Laravel redirect back to original destination after login

For Laravel 5.2 (previous versions I did not use)

Paste the code into the file app\Http\Controllers\Auth\AurhController.php

   /**
 * Overrides method in class 'AuthenticatesUsers'
 *
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
public function showLoginForm()
{
    $view = property_exists($this, 'loginView')
        ? $this->loginView : 'auth.authenticate';
    if (view()->exists($view)) {
        return view($view);
    }
    /**
     * seve the previous page in the session
     */
    $previous_url = Session::get('_previous.url');
    $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    $ref = rtrim($ref, '/');
    if ($previous_url != url('login')) {
        Session::put('referrer', $ref);
        if ($previous_url == $ref) {
            Session::put('url.intended', $ref);
        }
    }
    /**
     * seve the previous page in the session
     * end
     */
    return view('auth.login');
}
/**
 * Overrides method in class 'AuthenticatesUsers'
 *
 * @param Request $request
 * @param $throttles
 *
 * @return \Illuminate\Http\RedirectResponse
 */
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
    if ($throttles) {
        $this->clearLoginAttempts($request);
    }
    if (method_exists($this, 'authenticated')) {
        return $this->authenticated($request, Auth::guard($this->getGuard())->user());
    }
    /*return to the previous page*/
    return redirect()->intended(Session::pull('referrer'));
    /*return redirect()->intended($this->redirectPath()); /*Larevel default*/
}

And import namespace: use Session;

If you have not made any changes to the file app\Http\Controllers\Auth\AurhController.php, you can just replace it with the file from the GitHub

NSNotificationCenter addObserver in Swift

Swift 5 & Xcode 10.2:

NotificationCenter.default.addObserver(
            self,
            selector: #selector(batteryLevelDidChangeNotification),
            name: UIDevice.batteryLevelDidChangeNotification,
            object: nil)

Using two CSS classes on one element

If you want to apply styles only to an element which is its parents' first child, is it better to use :first-child pseudo-class

.social:first-child{
    border-bottom: dotted 1px #6d6d6d;
    padding-top: 0;
}
.social{
    border: 0;
    width: 330px;
    height: 75px;
    float: right;
    text-align: left;
    padding: 10px 0;
}

Then, the rule .social has both common styles and the last element's styles.

And .social:first-child overrides them with first element's styles.

You could also use :last-child selector, but :first-childis more supported by old browsers: see https://developer.mozilla.org/en-US/docs/CSS/:first-child#Browser_compatibility and https://developer.mozilla.org/es/docs/CSS/:last-child#Browser_compatibility.

Access index of the parent ng-repeat from child ng-repeat

You can also get control of grand parent index by the following code

$parent.$parent.$index

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

Hover and Active only when not disabled

One way is to add a partcular class while disabling buttons and overriding the hover and active states for that class in css. Or removing a class when disabling and specifying the hover and active pseudo properties on that class only in css. Either way, it likely cannot be done purely with css, you'll need to use a bit of js.

How to open standard Google Map application from my application?

I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.

Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_refresh) {
        Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
        new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
        return true;
    } else if (id == R.id.action_map) {
        Log.d(APP_TAG, "onOptionsItemSelected Map selected");
        Intent intent = new Intent(this, MapsMarkerActivity.class);
        intent.putExtra("CITY_NAME", CITY);
        startActivity(intent);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public class MapsMarkerActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    private String cityName = "";

    private double longitude;

    private double latitude;

    static final int numberOptions = 10;

    String [] optionArray = new String[numberOptions];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_map);
        // Get the SupportMapFragment and request notification
        // when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // Test whether geocoder is present on platform
        if(Geocoder.isPresent()){
            cityName = getIntent().getStringExtra("CITY_NAME");
            geocodeLocation(cityName);
        } else {
            String noGoGeo = "FAILURE: No Geocoder on this platform.";
            Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
            return;
        }
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user receives a prompt to install
     * Play services inside the SupportMapFragment. The API invokes this method after the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(latitude, longitude);
        // If cityName is not available then use
        // Default Location.
        String markerDisplay = "Default Location";
        if (cityName != null
                && cityName.length() > 0) {
            markerDisplay = "Marker in " + cityName;
        }
        googleMap.addMarker(new MarkerOptions().position(sydney)
                .title(markerDisplay));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    /**
     * Method to geocode location passed as string (e.g., "Pentagon"), which
     * places the corresponding latitude and longitude in the variables lat and lon.
     *
     * @param placeName
     */
    private void geocodeLocation(String placeName){

        // Following adapted from Conder and Darcey, pp.321 ff.
        Geocoder gcoder = new Geocoder(this);

        // Note that the Geocoder uses synchronous network access, so in a serious application
        // it would be best to put it on a background thread to prevent blocking the main UI if network
        // access is slow. Here we are just giving an example of how to use it so, for simplicity, we
        // don't put it on a separate thread.  See the class RouteMapper in this package for an example
        // of making a network access on a background thread. Geocoding is implemented by a backend
        // that is not part of the core Android framework, so we use the static method
        // Geocoder.isPresent() to test for presence of the required backend on the given platform.

        try{
            List<Address> results = null;
            if(Geocoder.isPresent()){
                results = gcoder.getFromLocationName(placeName, numberOptions);
            } else {
                Log.i(MainActivity.APP_TAG, "No Geocoder found");
                return;
            }
            Iterator<Address> locations = results.iterator();
            String raw = "\nRaw String:\n";
            String country;
            int opCount = 0;
            while(locations.hasNext()){
                Address location = locations.next();
                if(opCount == 0 && location != null){
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
                country = location.getCountryName();
                if(country == null) {
                    country = "";
                } else {
                    country =  ", " + country;
                }
                raw += location+"\n";
                optionArray[opCount] = location.getAddressLine(0)+", "
                        +location.getAddressLine(1)+country+"\n";
                opCount ++;
            }
            // Log the returned data
            Log.d(MainActivity.APP_TAG, raw);
            Log.d(MainActivity.APP_TAG, "\nOptions:\n");
            for(int i=0; i<opCount; i++){
                Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
            }
            Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
        } catch (Exception e){
            Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
        }
    }
}

Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753

Hiding the scroll bar on an HTML page

To disable the vertical scroll bar, just add overflow-y:hidden;.

Find more about it: overflow.

How to prevent Browser cache for php site

You can try this:

    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Connection: close");

Hopefully it will help prevent Cache, if any!

Correct way to load a Nib for a UIView subclass

Answering my own question about 2 or something years later here but...

It uses a protocol extension so you can do it without any extra code for all classes.

/*

Prerequisites
-------------
- In IB set the view's class to the type hook up any IBOutlets
- In IB ensure the file's owner is blank

*/

public protocol CreatedFromNib {
    static func createFromNib() -> Self?
    static func nibName() -> String?
}

extension UIView: CreatedFromNib { }

public extension CreatedFromNib where Self: UIView {

    public static func createFromNib() -> Self? {
        guard let nibName = nibName() else { return nil }
        guard let view = NSBundle.mainBundle().loadNibNamed(nibName, owner: nil, options: nil).last as? Self else { return nil }
        return view
    }

    public static func nibName() -> String? {
        guard let n = NSStringFromClass(Self.self).componentsSeparatedByString(".").last else { return nil }
        return n
    }
}

// Usage:
let myView = MyView().createFromNib()

Format datetime in asp.net mvc 4

Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat] attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407


Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.

Model:

public class MyViewModel
{
    [DisplayName("date of birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Birth = DateTime.Now
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Birth)
    @Html.EditorFor(x => x.Birth)
    @Html.ValidationMessageFor(x => x.Birth)
    <button type="submit">OK</button>
}

Registration of the custom model binder in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());

And the custom model binder itself:

public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName,
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

Now, no matter what culture you have setup in your web.config (<globalization> element) or the current thread culture, the custom model binder will use the DisplayFormat attribute's date format when parsing nullable dates.

How does Python manage int and long?

Python 2.7.9 auto promotes numbers. For a case where one is unsure to use int() or long().

>>> a = int("123")
>>> type(a)
<type 'int'>
>>> a = int("111111111111111111111111111111111111111111111111111")
>>> type(a)
<type 'long'>

Handling NULL values in Hive

Firstly — I don't think column1 is not NULL or column1 <> '' makes very much sense. Maybe you meant to write column1 is not NULL and column1 <> '' (AND instead of OR)?

Secondly — because of Hive's "schema on read" approach to table definitions, invalid values will be converted to NULL when you read from them. So, for example, if table1.column1 is of type STRING and table2.column1 is of type INT, then I don't think that table1.column1 IS NOT NULL is enough to guarantee that table2.column1 IS NOT NULL. (I'm not sure about this, though.)

PHP: Count a stdClass object

The object doesn't have 30 properties. It has one, which is an array that has 30 elements. You need the number of elements in that array.

create a white rgba / CSS3

The code you have is a white with low opacity.

If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.

Here is a simple demo.

If you want it to look 'more white', make it less opaque:

background:rgba(255,255,255, 0.9);

Demo

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

Find Number of CPUs and Cores per CPU using Command Prompt

If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS% shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd:

@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f

And then execute like this:

GetNumberOfCores.cmd

echo %NumberOfCores%

The script will set a environment variable named %NumberOfCores% and it will contain the number of processors.

How to update parent's state in React?

I like the answer regarding passing functions around, its a very handy technique.

On the flip side you can also achieve this using pub/sub or using a variant, a dispatcher, as Flux does. The theory is super simple, have component 5 dispatch a message which component 3 is listening for. Component 3 then updates its state which triggers the re-render. This requires stateful components, which, depending on your viewpoint, may or may not be an anti-pattern. I'm against them personally and would rather that something else is listening for dispatches and changes state from the very top-down (Redux does this, but adds additional terminology).

import { Dispatcher } from flux
import { Component } from React

const dispatcher = new Dispatcher()

// Component 3
// Some methods, such as constructor, omitted for brevity
class StatefulParent extends Component {
  state = {
    text: 'foo'
  } 

  componentDidMount() {
    dispatcher.register( dispatch => {
      if ( dispatch.type === 'change' ) {
        this.setState({ text: 'bar' })
      }
    }
  }

  render() {
    return <h1>{ this.state.text }</h1>
  }
}

// Click handler
const onClick = event => {
  dispatcher.dispatch({
    type: 'change'
  })
}

// Component 5 in your example
const StatelessChild = props => {
  return <button onClick={ onClick }>Click me</button> 
}

The dispatcher bundles with Flux is very simple, it simply registers callbacks and invokes them when any dispatch occurs, passing through the contents on the dispatch (in the above terse example there is no payload with the dispatch, simply a message id). You could adapt this to traditional pub/sub (e.g. using the EventEmitter from events, or some other version) very easily if that makes more sense to you.

What are callee and caller saved registers?

Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.

In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.

If using maven, usually you put log4j.properties under java or resources?

The resources used for initializing the project are preferably put in src/main/resources folder. To enable loading of these resources during the build, one can simply add entries in the pom.xml in maven project as a build resource

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering> 
        </resource>
    </resources>
</build> 

Other .properties files can also be kept in this folder used for initialization. Filtering is set true if you want to have some variables in the properties files of resources folder and populate them from the profile filters properties files, which are kept in src/main/filters which is set as profiles but it is a different use case altogether. For now, you can ignore them.

This is a great resource maven resource plugins, it's useful, just browse through other sections too.

How do I compare a value to a backslash?

Escape the backslash:

if message.value[0] == "/" or message.value[0] == "\\":

From the documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

How to access site running apache server over lan without internet connection

Open httpd.conf of Apache server (backup first) Look for the the following : Listen

Change the line to

Listen *:80

Still in httpd.conf, look for the following (or similar):

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    Deny from all
</Directory>

Change this block to :

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    #Deny from all
</Directory>

Save httpd.conf and restart apache

Open port 80 of the server such that everyone can access your server.

Open Control Panel >> System and Security >> Windows Firewall then click on “Advance Setting” and then select “Inbound Rules” from the left panel and then click on “Add Rule…”. Select “PORT” as an option from the list and then in the next screen select “TCP” protocol and enter port number “80” under “Specific local port” then click on the ”Next” button and select “Allow the Connection” and then give the general name and description to this port and click Done.

Restart WAMP and access your machine in LAN or WAN.

postgresql - sql - count of `true` values

Simply convert boolean field to integer and do a sum. This will work on postgresql :

select sum(myCol::int) from <table name>

Hope that helps!

How to use an existing database with an Android application

If you already have a database, keep it in your asset folder and copy it in your application. For more detail, see Android database basics.

How to make an android app to always run in background?

You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.

Create a service:

public class YourService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your jobs here
        return super.onStartCommand(intent, flags, startId);
    }
}

Create an Application class and start your service:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this, YourService.class));
    }
}

Add "name" attribute into the "application" tag of your AndroidManifest.xml

android:name=".App"

Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml

<service android:name=".YourService"/>

And also this permission request in the "manifest" tag (if API level 28 or higher):

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

UPDATE

After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.

public class YourService extends Service {

    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){

        // do your jobs here

        startForeground();
        
        return super.onStartCommand(intent, flags, startId);
    }

    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
                NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Service is running background")
                .setContentIntent(pendingIntent)
                .build());         
    }
}

EDIT: RESTRICTED OEMS

Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from https://dontkillmyapp.com/.

If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library (https://github.com/judemanutd/AutoStarter) in order to redirect your users regarding permissions page easily from your app.

By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (https://developer.android.com/topic/libraries/architecture/workmanager)