text:
Q: How to import `json` package in python3.6 I am using python3.6. Below code is to use json module to parse data:
import urllib.request
from pandas import *
from pandas import json
import numpy as np
import pandas as pd
import requests
import urllib
import time
def request_image_info(lat, lon):
    res = urllib.request.urlopen('https://biocache.ala.org.au/ws/explore/group/Plants.json?lat='+str(lat)+'&lon='+str(lon)+'&pageSize=1&radius=1')
    json_data = json.load(res)
    guid = json_data[0]['guid']
    name = json_data[0]['name']
    family = json_data[0]['family']
    common_name = json_data[0]['commonName']
    count = json_data[0]['count']
    rank = json_data[0]['rank']
    kingdom = json_data[0]['kingdom']
    image_id = time.time()

I got below error when run this code. The line19 is the code json_data = json.load(res)
Traceback (most recent call last):
  File "loadImages.py", line 57, in <module>
    request_image_info(row[2], row[3])
  File "loadImages.py", line 19, in request_image_info
    json_data = json.load(res)
  File "/Users/admin/tmp/p36/lib/python3.6/site-packages/pandas/util/_depr_module.py", line 61, in __getattr__
    obj = getattr(deprmodule, name)
AttributeError: module 'pandas.json' has no attribute 'load'

I have installed pandas module as below:
$ pip3 install pandas
Requirement already satisfied: pandas in /usr/local/lib/python3.6/site-packages
Requirement already satisfied: numpy>=1.7.0 in /usr/local/lib/python3.6/site-packages (from pandas)
Requirement already satisfied: pytz>=2011k in /usr/local/lib/python3.6/site-packages (from pandas)
Requirement already satisfied: python-dateutil>=2 in /usr/local/lib/python3.6/site-packages (from pandas)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/site-packages (from python-dateutil>=2->pandas)

how can I solve this issue?
Below is the python and pip version I am using:
$ python --version
Python 3.6.2
$ pip --version
pip 9.0.1 from /Users/admin/tmp/p36/lib/python3.6/site-packages (python 3.6)

A: You're importing wrong json. Remove
from pandas import json

and do
import json

instead.


text:
Q: Show Map Pins on a Custom Map Image I have on my site currently a map showing lots of pins in a google map. This is driven by a database of lat/long items.
The Google Map is overkill in my case, Ideally I would obtain a nice outline image of my country (UK) and plot the pins directly onto it. Its just to show "coverage".
Does anyone know of a good approach to this?

A: You could use canvas to plot points on an image, but that will probably be more trouble than using Google Maps.  You would have to find a way to convert the lat/lng data into x,y pixel coordinates.
What I would do is stitch the outline image to a Google Map, then you can use Google's  OverlayView methods to plot the points in the correct place.
Google has an example of this in the API reference here.
You could disable all of the navigation tools on the map and give the impression of a static image on your page while still being able to add new points later if needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Binding WPF Toolkit DataGrid ComboBox column to Linq-to-Sql collection after Window loads and connection changes? I am a beginner to MVVM. The main window uses a stock DataGrid from the WPF Toolkit. It has one View Model and relies only on DataContext_Changed event handler in the .xaml.cs file. The main window's DataContext is the View Model.
I am attempting to bind the ItemsSource property of a DataGridComboBoxColumn to a CLR property, "FieldTypes", on the View Model. "FieldTypes" is a List which derives from a Linq to Sql table of type FieldType.
The ItemsSource of the DataGrid is from one System.Data.Linq.Table and "FieldTypes" is from a separate Table, and these two tables have no relationship.
To bind the FieldTypes DataGridComboBoxColumn to the "FieldTypes" property on the View Model, I created a DataTemplate StaticResource to be used in a DataGridTemplateColumn:
    <DataTemplate x:Key='FieldTypeCombo' >
        <ComboBox DataContext='{Binding ElementName=window, Mode=OneWay, Path=DataContext, UpdateSourceTrigger=PropertyChanged}'
                  ItemsSource='{Binding FieldTypes}'
                  DisplayMemberPath='Name'
                  />
    </DataTemplate>

It turns out that this DataTemplate will work on a child element of the main window NOT in the DataGrid, such as in a HeaderedContentControl.ContentTemplate, but will not work in a DataGridTemplateColumn.CellTemplate.
If I try binding a DataGridComboBoxColumn to the ComboBox.ItemsSource property of a regular ComboBox not in the DataGrid,
                        <c:DataGridComboBoxColumn Header="FieldType"
                                      ItemsSource="{Binding ElementName=regularcombobox, Path=ItemsSource, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                      />

it works as expected, but not for a ComboBox inside the DataGrid.
I'd like to have as much data binding as possible on the View Model's properties, but this also looks like an opportunity for a StaticResource. This StaticResource would change however, after the window loads, since the connection string is not known until after. Even when binding the ItemsSource of the ComboBox column to the StaticResource, I've had no luck with this, or DynamicResource either.
Is there some way to accomplish this binding of a DataGrid ComboBox column to a collection separate from the ItemsSource of the DataGrid, using MVVM? Or is there a way to accomplish this with a StaticResource,even if the SQL connection changes after the window loads?

A: Try replacing the ElementName Binding with this:
{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Mode=OneWay, Path=DataContext, UpdateSourceTrigger=PropertyChanged}'

ElementName can only resolve names within a certain scope and it's generally not a good idea to use them inside a DataTemplate to refer to something external (although it will work in some cases).


text:
Q: Drag and drop a div in Drupal 7 I am trying to use drag and drop of a div (using jQuery) in Drupal 7.   I am using jQuery 1.4.4 and jQuery-ui 1.8.7.   The code works in a simple html file.   I see the inclusion of the 1.4.4 jQuery file in the standard Drupal 7 setup.   I am making a specific include of query-ui 1.8.7 because I am seeing no include of the jquery-ui.  When I embed the following code in a Drupal 7 basic page, it does not work ...

Why would this not work? Nothing drags. I am attempting to create a draggable div that constrains the drag to the horizontal direction.
Please, suggestions would be appreciated ...
Thank you
   Dave


text:
Q: Proof: Sum of the combination of the these numbers are not equal. You have a set (wallet) of 5 coins: $\{1, 5, 10, 50, 100\}$.
Now there are clearly $2^5$ subsets of this set since the decision needed to build a subset is whether to include each element or not (can be coded 0/1) and you make five such decisions $2^5$ by the multiplication rule.
What I want to show is that no combination of elements results in the same sum. Is there a neat way to proof that?

A: Let us assume there are two different subsets which have the same sum. Now, if there are two subsets which have the same sum, it also means that there are two disjoint subsets which have the same sum. (We get the disjoint subsets by deleting the common elements.)
Neither of these sets can contain $1$ or $5$, because if they did, the sum's last digit would be $1$, $5$ or $6$ which can't be reached by the remaining three numbers.
Now,we must divide the remaining three numbers into two subsets which have the same sum. Clearly, if $100$ is in either set, it's sum will be greater than the other set.
Now, we only have two unequal elements, $10$ and $50$ which to be put into two subsets of equal sums. This wold only be possible if $10=50$, but it isn't.

A: Since $1<5, 1+5<10, 1+5+10<50, 1+5+10+50<100$, you can prove that no two collections of coins can add up to the same value.
That's because if two collections add to the same value, then you can look at the largest coin in the two sets. If it is in both sets, then you can remove it from both sets, so assume the largest coin is only in one set.
But then the other set consists of smaller coins only, and those smaller coins can't add up to even that largest coin.

A: The number of partitions of $n$ such that each number in $\{1, 5, 10, 50, 100\} $ appears at most once  is given by the coefficient of $x^n$ in $(1+x)(1+x^5)(1+x^{10})(1+x^{50})(1+x^{100})$. When you developp you obtain :$$x^{166}+x^{165}+x^{161}+x^{160}+x^{156}+x^{155}+x^{151}+x^{150}+x^{116}+x^{115}+x^{111}+x^{110}+x^{106}+x^{105}+x^{101}+x^{100}+x^{66}+x^{65}+x^{61}+x^{60}+x^{56}+x^{55}+x^{51}+x^{50}+x^{16}+x^{15}+x^{11}+x^{10}+x^6+x^5+x+1$$
So all the reachable amounts are reachable only in one way.


text:
Q: React Material Table - New field when add row In the Material Table below taken from the example, how would I do to make the 'ahiddenfield' appear when adding a new row? I'm not really sure how to access the state when the new row is about to be added (Before onRowAdd). Is it possible without too much headache?
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        { title: 'Name', field: 'name' },
        { title: 'Hidden Field', field: 'hiddenfield', hidden: true }
      ],
      data: [
        { name: 'Mehmet' },
        { name: 'Zerya Betül'},
      ]
    }
  }

  render() {
    return (
      <MaterialTable
        title="Editable Preview"
        columns={this.state.columns}
        data={this.state.data}
        editable={{
          onRowAdd: newData =>
            new Promise((resolve, reject) => {
              setTimeout(() => {
                {
                  const data = this.state.data;
                  data.push(newData);
                  this.setState({ data }, () => resolve());
                }
                resolve()
              }, 1000)
            }),
          onRowUpdate: (newData, oldData) =>
            new Promise((resolve, reject) => {
              setTimeout(() => {
                {
                  const data = this.state.data;
                  const index = data.indexOf(oldData);
                  data[index] = newData;
                  this.setState({ data }, () => resolve());
                }
                resolve()
              }, 1000)
            }),
          onRowDelete: oldData =>
            new Promise((resolve, reject) => {
              setTimeout(() => {
                {
                  let data = this.state.data;
                  const index = data.indexOf(oldData);
                  data.splice(index, 1);
                  this.setState({ data }, () => resolve());
                }
                resolve()
              }, 1000)
            }),
        }}
      />
    )
  }
} ```

A: In your <MaterialTable /> component, you should replace the data prop like this:
data={Array.from(this.state.data)}.
This is not documented in the docs. More info here: https://github.com/mbrn/material-table/issues/1900


text:
Q: Divergent and Convergent sums Does sum convergence or divergence indicates anything for we can determine if the sum has an explicit formula?
i.e  $\sum_{k=1}^n \frac 1k$ is divergent, does this mean we can/can't devise an explicit formula for this sum?

A: No, it does not mean anything. In fact, we define the harmonic numbers as follows:
$$H_n=\sum_{k=1}^{n} \frac{1}{k}$$
Because it does not have a nice closed form. But some of them have, for example:
$$\sum_{i=1}^{n} i=\frac{n(n+1)}{2}$$
Or
$$\sum_{i=1}^{n} i^2=\frac{n(n+1)(2n+1)}{6}$$

A: There is an asymptotic estimate for this sum, usually denoted by $H_n$, namely
$$H_n=\ln n+\gamma+\frac1{2n}-\frac1{12n^2}+\frac1{120n^4}+O\left(\frac1{n^6}\right)
$$
Up to the Landau big Oh, this is an explicit formula.


text:
Q: Right to left support for MarkdownTextBlock in uwp I'm working on an Instagram unofficial client for UWP and using Microsoft.Toolkit.Uwp.UI.Controls.MarkdownTextBlock for captions and some other things.
Everything is going very well in English texts but when text is in an RTL language like Persian it uses LTR for them too.
Unfortunately, MarkdownTextBlock doesn't have a TextAlignment property and also I wasn't able to find a markdown to show text in Right to left.
Is there any way for it?
UWP Target Platform: Windows 10 Version 1803 (Build 17134)
Minimum version; Anniversary Update (Build 14393)
Microsoft.Toolkit.Uwp.UI.Controls: V4.0 (Because I want to support Windows 10 Mobile it's not possible to use V5.0)
Thank you

A: I have logged an issue on github as well as a fix for the issue. When all of the kinks are worked out it will be released in the next version.
UPDATE: Fix has been merged. Feel free to take the source and use in your app or wait until the next version is released.


text:
Q: How to generate excel file using node.js? Hi I am go for the generate excel file form the array but I am not getting successes. I am work using node.js and I am use npm package for generate excel file but I am not getting any data in excel file. excel is generate but not getting any type of data in my file. so any one know where is my mistake then please let me know how can fix it.
This is my array and query =>
            var XLSX = require('xlsx');
                   var Array = [];
                    Array.push({
                        username: 'Carakc',
                        fullName: 'Crack',
                        followingCount: 2655,
                        followerCount: 466,
                        biography: 'I am new man'
                    },
                  {
                      username: 'mahi',
                      fullName: 'Fit',
                      followingCount: 3011,
                      followerCount: 385,
                      biography: 'hello everyone!'
                  })

app.get(prefix + '/GetFollowersInExcel', function (req, res, next) {
                    var ws = XLSX.utils.json_to_sheet(Array);
                    var wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, ws, "Followres");
                    var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
                    res.end(wbout, 'binary');
                }
            });
        }
    });
})

This is my service code =>
GetFollowersInExcel: function (InstaId) {
        return $http({
            method: "GET",
            url: ONURL + "GetFollowersInExcel",
            responseType: "arraybuffer",
            headers: {
                'Content-type': 'application/json',
                'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }
        }).then(function (data, status, xhr) {
            debugger;
            if (data.data.byteLength > 0) {
                var file = new Blob([data.data], { type: 'application/binary' });
                var fileURL = URL.createObjectURL(file);
                $('#getexcel').show();
                var link = document.createElement('a');
                link.href = fileURL;
                link.download = "myfile.xlsx";
                link.click();
                URL.revokeObjectURL(file);
            }
        }, function (error) {
            return error;
        })
    },

using this wave I am getting like this data in excel =>

I want like this data in excel file =>

A: I've tried your first code and I've found no errors, the resulting xlsx is perfect.
Peheraps I've found the problem: var Array is declared outside the app.get callback... Are you sure that your var Array can be correctly reached by XLSX.utils.json_to_sheet? it's in the same scope? or it's declared somewhere inaccessible?
try to declare it inside the callback and probably all will work well, and, if this is the case, you can use a class or a method to retrieve the var from outside ("how" depends on your code)
P.s. change the name of the var, is not a good habit overwrite the Array object ;)


text:
Q: How to compare two percentage strings I have two strings: 50% and 60%. I'm trying to compare the two strings and figure out that 60% is bigger than 50%. What would be the easiest and most clean way to compare the two strings? I can always remove the % sign, convert the strings to ints and compare them. But is there a better way?

A: You can use parseInt to parse only the numeric part.
let x = "50%";
let y = "60%";
parseInt(x)>parseInt(y)?console.log(`${x} is greater than ${y}`):console.log(`${y} is greater than ${x}`);

Console: 60% is greater than 50%

A: let percentage1 = parseFloat('50%');
let percentage2 = parseFloat('60%');

if (percentage1 <= percentage2) {
    // Code here
}

A: Do a string replace to remove % and also parseInt it in comparison
Stackblitz example

A: function cmpPercentages(str1, str2){
    var per1 = parseFloat(str1);
    var per2 = parseFloat(str2);
    if(per1 > per2){
        return 1;
    }else if(per2 > per1){
        return -1;
    }else{
        return 0;
    }
}

Where 1 means that the first percentage is higher, -1 that the first percentage is smaller than the second and 0 that they are equal, just like localeCompare's result.


text:
Q: SSCAN vs SMEMBERS resources usage for large sets I have a large redis SET (more than 6M entries), and i need to go through all the entries and make some other redis operations with each (mostly calling a ZCARD in a redis Sorted Set using a key based on the original entry).
Which is the most efficient (in terms of resources) way of going through all the entries of the SET? Using SSCAN or doing an SMEMEBERS call.

A: SMEMBERS has to iterate over the whole set and produce the whole list of keys at once, while SSCAN returns a fraction of the keys each time you call it. While they both do pretty much the same amount of work, SSCAN does the work in smaller chunks which means, for most use cases, that it has a smaller effect on the performance of everything else the server is doing.

A: SMEMBERS returns all members in a SET, in one operation. The duration of this operation is directly proportional to the number of items in the SET (time complexity: O(N) ).
During this operation, your instance won't respond to any other request.
SSCAN allows you to iterate through all items in a SET. The time complexity is fixed ( O(1) ), depending on the number of items you get at each call (this number is defined by the COUNT parameter).
The total cost for SSCAN will probably be of the same order than for SMEMBERS, or maybe greater because you will have to make multiple calls. But it will allow other requests being processed between two calls, so your Redis instance won't look unresponsive.
All of this is pure theory. To get a definitive advice, you should test and measure, it should be rather easy to do.


text:
Q: Python creating one line statement both if-else condition and for loop with lambda function I'm trying to learn one line ternary operator in python3. And also I want to implement it to my code to save space.
My codes are:
if key==i and i not in neighbours: #up there there is an another loop
        if len(j)>1:
            neighbours=[n for n in j]
            print("0", neighbours)
        else:
            neighbours.append(j)
            print("1",neighbours)

I'm stuck with if-else and for loop. My codes works but I'm trying to write it in one line.
You see it also a pseudo code:
if key==i and i not in neighbours: #up there there is an another loop
      {lambda neighbours.append(n): for n in j} if len(j)>1 else neighbours.append(j)

For the story:
I have a j values which is a list, if this list's length is greater than 1 I need to append it seperately, if not it is okay just append.
ALL my codes are here if you want to run it:
anormal_dict={'1576665': [['02:03:00', '02:28:00'], ['22:28:00', '22:38:00']]}
neighbours = list()
c=""
for key in anormal_dict.keys():
    for i,j in intersection_dict.items():
        if key==i and i not in neighbours:
            if len(j)>1:
                neighbours=[n for n in j]
                print("0", neighbours)
            else:
                neighbours.append(j[0])
                print("1",neighbours)
        if key in j and c not in neighbours:
            findex= j.index(key)-1
            if findex== -1:
                neighbours.append(i)
                print("2", neighbours)

            else:
                c = j[findex]
                neighbours.append(c)
                print("3", neighbours)


text:
Q: JavaScript deferred image load with error check I'm setting up a script to load images (we have a lot of them) after the page has loaded using the following:
HTML:
<img class="dload" data-src="/path/to/image.jpg">

JS:
$('img.dload').each(function() {
    var img = $(this);
    var src = img.data('src');
    img.attr('src',src);
});

As we have a lot of images there's a high probability that we may have broken images, so I'm wondering the best way to run onerror against a dynamically loaded src. I'd figure the image would need to successfully run the .attr() command before it could check...


text:
Q: How to check for presence of named pipe on the file system I tried using the -f flag to test if a named pipe is present
if [[ ! -f "$fifo" ]]; then
  echo 'There should be a fifo.lock file in the dir.' > /dev/stderr
  return 0;
fi

this check does not seem correct. So perhaps a named-pipe is not a file, but something else?

A: You need to use the -p construct to see if the file is of type named pipe. It works with the standard test [ (POSIX compliant) and the extended test operators [[ ( bash/zsh specific )
if [[ -p "$fifo" ]]; then
    printf '%s is a named pipe' "$fifo"
fi

From the man pages of bash

-p file
True if file exists and is a named pipe (FIFO).

or use the file command with the -b to just print the type information without the filename. The -b might not be POSIX compliant
if [ $(file -b "$fifo") = "fifo (named pipe)" ]; then
   printf '%s is a named pipe' "$fifo"
fi

Without the -b, one could do
type=$(file "$fifo")
if [ "${type##*: }" = "fifo (named pipe)" ]; then


text:
Q: Foreach in a foreach + CodeIgniter I got an image upload function working, but there's 4 images required in this image. And my current function is simply just overwriting the image despite the number. I'm wondering how I would insert (preferably) a letter into my foreach function.
$uploads = array($this->uploads->data());
foreach ( $uploads as $key[] => $value )
{
$imagename = $cleaned . '-s' . $value['file_ext']; //outputs clean-name-s.ext
}

By the time all is said and done, 4 images will require this function. Leaving me with
clean-name-sa.ext, clean-name-sb.ext, clean-name-sc.ext, and clean-name-sd.ext (numbers work as well).
The form does require that all 4 fields are filled out before submission, so would I just create an array of my desired identifiers and create a foreach loop that outputs 4 different $imagenames? Or is there a simpler, more logical approach to this.

A: Your question is a little vague, as you've provided no indication of how the HTML is set up. If you really want an array, you can do this:
$uploads = array($this->uploads->data());
foreach ($uploads as $key => $value) {
   foreach (Array('a', 'b', 'c', 'd') as $letter) {
      $imagename = $cleaned . '-s' . $letter . '.' . $value['file_ext']; //outputs clean-name-sX.ext
      // Do something with $imagename here
   }
}

Note also I changed $key[] to $key.

A: I am a bit lost on your 'cleaned' section..  I dont know if you didnt include all the code or... ?
As for it overwriting the $imagename - in your loop you keep changing the value of $imagename...  So you need to have that be an array..
As for adding letters to the names.. thats easy..  just start off with 97 for 'a'  and then add to it...  wherever you want the letter use chr()   (also changed $imagname to an array)
// 97 is asci for 'a'
$currentChar = 97;
$imagename = array();

$uploads = array($this->uploads->data());
foreach ( $uploads as $key => $value )   {
    $imagename[] = $cleaned . '-s' . chr($currentChar) . $value['file_ext'];
     //outputs clean-name-s.ext
     $currentChar++;
}


text:
Q: how can I convert string type of special character into original? I wanted to do maths calculation using asterick (*) but what if it is in string format? how can I convert it to normal?
I tried 4 "*" 5 and first of all, I was not even expecting it to multiply it, as the operator is in string format but it gave me an error.

A: An asterisk in the form of a string variable cannot be converted directly to a mathematical operator; however, it is possible to take the string "*" and use it to perform multiplication by using an if statement.
Let's say you are given some string variable 'operator', and two integer variables 'a' and 'b'. The code would look something like this:
if operator == "*":
     product = a * b
     print(product)

In your case, you would set the 'a' and 'b' variables to 4 and 5 respectively, meaning the example above would print 20 if the 'operator' variable was "*".


text:
Q: How to get atributes in  tag when clicking an anchor inside a  that points to javascript function So I need some help.
I have a query to a sql database wich returns an array with all the data from the table.
Then I have a for to insert all array data to rows of a table.
This code block fills the table with the data from the array:
for ($i = 0; $i < $size; $i++) {
 print ("

 ".$Users[$i][0]."
 ".$Users[$i][1]."
 *****
 /td>

");
}

When we click in the anchor it points to the javascript function Delete_User();
The function Delete_User();
function Delete_User() {
$.ajax({
    type: "GET",
    url: "delete_user.php" ,
    data: { id: "TABLE ROW ID HERE" },
    success : function() {
            window.location.href='utilizadores.php';
        }
        });
}

I was trying to solve this and if I add an atribute to the  tag maybe with jQuery or js I can get it.
My first attempt:
for ($i = 0; $i < $size; $i++) {
 print ("

 ".$Users[$i][0]."
 ".$Users[$i][1]."
 *****
 /td>

");
}

So, now How can I get that row-id value in the get parameter in the ajax function on the Delete_User js function?
Thanks in advance.

A: Here's the simplest way:

and
 function Delete_User( id ) {

Alternatively:

 ...

and
function Delete_User( el ) {
    var id = $(el).closest("tr").data( "row-id" );
    ...

A: add a class to your DOM element:

and in your .js file add this:
$('a.delete-button').on('click',function(e){
    e.preventDefault();
    Delete_user($(this).closest('tr').attr('row-id'))
}

and add delcare your function
Delete_user(id){ ... }


text:
Q: Azure Pipeline flutter command in Command Line Script I am trying to build and deploy a Flutter Web App using Azure Dev Ops.
I set up a pipeline with Flutter Install and Flutter Build. Before I build the app, I want to run a command line script for some configurations. In the end of the script, I want to run flutter pub run build_runner build for the code generator. But I need to configure the flutter command, and I don't know how. Otherwise, the output is command not found: flutter
Here a screenshot of my pipeline:

At first I thought the Flutter Install task would already fix that. But it doesn't. Does someone know what I need to configure in order to run the flutter command?

A: This is the way I deployed my flutter web app into the Azure static web app:

*

*get flutter tasks from here

*use this yaml file to deploy to deploy the flutter app into Azure Static web app:

*Do not forget to set a variable for Static web app token

trigger:
  - http-request

pool:
  vmImage: ubuntu-latest

steps:
  - task: Hey24sheep.flutter.flutter-install.FlutterInstall@0
    displayName: 'Flutter Install'

  - task: Hey24sheep.flutter.flutter-command.FlutterCommand@0
    displayName: 'Flutter Command'
    inputs:
      projectDirectory: app
      arguments: 'config --enable-web'

  - task: Hey24sheep.flutter.flutter-command.FlutterCommand@0
    displayName: 'flutter run build web'
    inputs:
      projectDirectory: app #{here put your source code folder}
      arguments: 'build web'

  - task: AzureStaticWebApp@0
    displayName: "web"
    inputs:
      app_location: "app" #{here put your source code folder}
      api_location: ""
      # app_build_command: "flutter build web"
      app_build_command: ""
      output_location: "build/web"
    env:
      azure_static_web_apps_api_token: $(deployment-token-development)


text:
Q: How to create alias for nullable reference type I'm trying to create an alias for a nullable reference type so that I can refactor something like this:
public void ReceiveValues(IReadOnlyDictionary<string, object?>? values)
{
}

into something like this:
using ValuesCollection = System.Collections.Generic.IReadOnlyDictionary<string, object?>?;

// class, etc...

public void ReceiveValues(ValuesCollection values)
{
}

However, the using statement generates the following compiler errors:

CS1002: ; expected
CS1031: Type expected

Is there any way to do this?


text:
Q: How to clear screen in .py turned into .exe? I'm learning Python and I have finished my first program and I have already turned it into a .exe using py2exe.
When the program finishes, you are asked a question to either run the program again, or exit it. The thing is that if I run the program again, I can see what I did before. Instead, I want to erase all what I did before and run it as if it was the first time. I'd really appreciate.
Here's the code:
def main():
    days = input("Write how many days you will be on vacation: ")
    city = input("Write the city in which you will be staying at: ")
    expenses = input("Write how much money you will be carrying for expenses (US$): ")

    def hotelCost(days):
        days = int(days)
        return 140*days

    hotelCost(days)

    def flightCost(city):
        if city == "Charlotte" or city == "charlotte":
            return 183
        elif city == "Tempa" or city == "tempa":
            return 220
        elif city == "Pittsburgh" or city == "pittsburgh":
            return 222
        elif city == "Los Angeles" or city == "los angeles":
            return 475
        else:
            print ("Invalid destination")

    flightCost(city)

    def carCost(days):
        days = int(days)
        cost = days*40
        if days >= 7:
            cost -= 50
        elif days >= 3:
            cost -= 20
        return cost

    carCost(days)

    def totalCost():
        overallCost = hotelCost(days) + flightCost(city) + carCost(days)
        overallCost = str(overallCost)
        print ("\nThe total cost of your trip is $" + overallCost)

    totalCost()

    def again():
        yesNo = input("\nWould you like to calculate the cost of another trip? (y/n)\n")

        if yesNo == "y":
            print ("\n")
            main()

    again()

main()


text:
Q: How to impose generic constraints to the parameters and return values of a function argument of a generic Kotlin function? I want to define a Kotlin generic function that takes a lambda as a parameter, but I want to restrict the allowed types of lambdas parameters and return types. How do I do this in Kotlin?
In the following example, I expected the constraint: where T: Base, V: (T) -> Unit to mean that V can only be functions whose first parameter implements Base.
However, I see that the compiler ignores the T: Base part of the constraint and will accept any (Any) -> Unit.
interface Base

fun <T, V> exampleGenericFunction(func: V) where T: Base, V: (T) -> Unit {
    println("func is $func")
}

class ImplementsBase : Base

class DoesNotImplementBase

fun main() {
    val f1: (ImplementsBase) -> Unit = { }
    exampleGenericFunction(f1)

    val f2: (DoesNotImplementBase) -> Unit = { }
    exampleGenericFunction(f2) // expected this to be a compilation error
}

A: This unexpected behavior was caused by a bug in the Kotlin >=1.4 compiler.
This bug can be tracked here: https://youtrack.jetbrains.com/issue/KT-48935.


text:
Q: Cannot add table in DBML designer with Foreign Key I'm trying to add a small test table to the dbml designer, but it fails - nothing happends and there is no error message. The table is:
CREATE TABLE [dbo].[Car]
(
    CarID       INT NOT NULL IDENTITY(1,1)
    CONSTRAINT  PK_Car PRIMARY KEY CLUSTERED,
    RegNo       VARCHAR(7) NOT NULL,
    ModelID     INT NOT NULL
    CONSTRAINT FK_Car_Model FOREIGN KEY REFERENCES Model (ModelID)
)

If I drop the FK_Car_Model constraint it works. Am I missing something about how the designer works with relations?

A: A bit more than a year later, I came across the same situation again and this time it was solved by renaming a foreign key(!).
I have two tables Cars and Persons. Cars has a column OwnerID which is a reference to the owner. If the foreign key is named FK_Car_Owner it doesn't work. If the foreign key is renamed to FK_Cars_Owner it works.

A: I had the same problem until I restarted Visual Studio. Not ideal, but much better than removing all the foreign keys.


text:
Q: Marklogic Template Driven Extraction: insert template I'm trying to upload a template to use with MarkLogic Template Driven Extraction. I'm using Javascript in the console (on localhost). However, no matter what I try, I keep getting the same error when I try to upload. The error: "[javascript] SEC-INVALIDPERM: xdmp:document-insert...." I gave myself all the permissions that are possible, but I still keep getting the error.
'use strict'

declareUpdate();
var tde = require("/MarkLogic/tde.xqy");
var MatchesTDE = xdmp.toJSON(
  {
    "template": {
      "context": "/com.marklogic.client.mapper.MatchesDoc",
      "collections": ["com.marklogic.client.mapper.MatchesDoc"],
      "rows": [
        {
          "schemaName": "mapper",
          "viewName": "matches",
          "columns": [
            {
              "name": "nrOfDocumentsInNC",
              "scalarType": "long",
              "val": "nrOfDocumentsInNC"
            },
            {
              "name": "totalNrOfDocuments",
              "scalarType": "long",
              "val": "totalNrOfDocuments"
            },
            {
              "name": "matchesID",
              "scalarType": "long",
              "val": "matchesID"
            },
            {
              "name": "uniqueInNC",
              "scalarType": "boolean",
              "val": "uniqueInNC"
            }
          ]
        }
      ]
    }
  }
);

tde.templateInsert(
  "/MatchesDoc/TDE.json" ,
  MatchesTDE,
  xdmp.defaultPermissions(),
  ["com.marklogic.client.autorelationmapper.MatchesDoc"]
);

By the way, if I validate the template with tde.validate([MatchesTDE]); I get true. And if I test the script with
tde.nodeDataExtract(
  [cts.doc( "com.marklogic.client.mapper.MatchesDoc/2722286.json" )],
  [MatchesTDE]
);

it works. Moreover, when I follow the tutorial on TDE at https://developer.marklogic.com/learn/template-driven-extraction everything works except the insertTemplate function. I also get the same error there. What am I doing wrong?

A: Try removing all the permissions for the user running this code. Or try running the tde.templateInsert() with an empty 3rd argument:
tde.templateInsert(
  "/MatchesDoc/TDE.json" ,
  MatchesTDE,
  [],
  ["com.marklogic.client.autorelationmapper.MatchesDoc"]
);

It sounds like this is your problem:

I gave myself all the permissions that are possible, but I still keep getting the error.

Users don't have permissions, documents have permissions. Users only have default permissions for when they write documents.
A user's default permissions are the set of permissions that get assigned to a document that the user inserts. Default permissions do not grant that user any additional powers in the database. Normally, an admin user has no default permissions assigned to it.
When you assign all those default permissions to your user, you end up adding a huge list of permissions in the 3rd argument of tde.templateInsert() where you pass xdmp.defaultPermissions(). At least one of those is somehow invalid, so you're getting the SEC-INVALIDPERM error.


text:
Q: Is it possible to adjust the zoom in Safari's "responsive design mode"? Is there a way to adjust the zoom in Safari's responsive design mode? The part I highlighted can't be selected unlike the other stuff. I'm using Safari 10.0.1

I wasn't able to find anyone asking this question let alone answering it. The closest is this: In Safari's "Responsive Design Mode" can you hide all of the device options on top for more screen real estate?
Seems like a really poor design choice for the browser to automatically adjust the zoom, show the percentage, and then not allow you to alter it...
(I can't believe this is my first StackOverflow question.)

A: At the time of writing you can't. You have to manually select x1 from that little dropdown - it's a real pain as that resets on each refresh.

A: Yes, it is possible. Try and adjust the width and height of the responsive "area" in the responsive view. The adjustment is done using the handles displayed on the left/right middle and the bottom center of the responsive viewport. The aspect ratio of the responsive view area is what determines the zoom level. If you make it very tall, then the zoom level gets reduced to display the entire height of the content in the fixed available space...
Thanks.


text:
Q: SQL always returns all rows on SELECT query performed on a large table When performing the following query on a small test database (100 records), MySQL (phpMyAdmin) returns the number of rows as expected:
SELECT ReportedDate
FROM table
WHERE ReportedDate IN (
       SELECT ReportedDate
       FROM table
       GROUP BY ReportedDate
       HAVING count(*) > 1
       ORDER BY ugid, ReportedDate
 )

However when I perform the same query on the actual table (1.5 million records), MySQL returns all rows as if it would with a SELECT * FROM table query.
Thank you for any kind of help

A: Your subquery isn't needed, and with a large data set will impact performance.
Instead of using the subquery and count(*), you might try this:
SELECT ReportedDate
FROM table
GROUP BY ReportedDate
HAVING count(DISTINCT ReportedDate) > 1
ORDER BY ugid, ReportedDate

Notice the distinct in the having clause.

A: Probably your table does not have unique ReportedDate values - they appear in table at least twice each.


text:
Q: Find a closure of the set I have a set $$A=\{(x,y)\in\mathbb{R^2}\mid x>0,y=\sin\left(\frac{1}{x}\right)\}$$
and I want to find a closure of this set. In the first place I thought, that the closure ($Cl(A)$) is equal to $X=A\cup\{(0,0)\}$, but I strongly doubt about this. I am absolutely sure that $X\subset Cl(A)$.
Could you give me any hints that will help me to come to the answer?

A: Given $(x,y) \in A$ consider the sequence $\{(x_n,y_n)\}\subset A$ with
$$
\frac{1}{x_n}=2n\pi +\frac{1}{x}.
$$
Since $y_n=\sin(x^{-1})=y$ for every $n$, we have $(x_n,y_n) \to (0,y) \in \{0\}\times[-1,1]$. Hence
$$
\{0\}\times[-1,1] \subset \text{Cl}(A).
$$
Conversely if $(x,y) \in \text{Cl}(A)$, then there exists some sequence $\{(x_n,y_n)\} \subset A$ such that $(x_n,y_n) \to (x,y)$, in particular $x \ge 0$. If $x>0$ then $(x,y) \in A$, if not then $(x,y) \in \{0\}\times[-1,1]$. Thus $\text{Cl}(A)=A\cup\{0\}\times[-1,1]$.


text:
Q: How can I dump my redis database daily? I took over a project that is using Redis for temporary storage of objects in a queue. I want to know how I can dump all the objects on a nightly basis. The business only operates from 8am to 8pm and the jobs are completed daily so every day we start fresh.
So my I was wondering how to dump or delete all the data from Redis at midnight.

A: FYI - dumping data in the Redis terminology actually means saving it to disk. It appears that what you want is to remove all the data.
There are many ways to do what you want, but basically you need to set up a cron job or similar that executes a FLUSHALL for example. Alternatively, if your Redis server isn't configured with disk persistence, you can simply restart it.


text:
Q: XSRF-TOKEN in Angular I have seen all kinds of different naming conventions for the XSRF-TOKEN.
What do I need to call the XSRF cookie when using AngularJS (without any other frameworks)?
Do I need to set the XSRF-TOKEN headers explicitly, like below, or does Angular do this for me if I give the cookie the right name?
$http.defaults.headers.post['X-XSRF-TOKEN'] = $cookies.csrftoken;

The above assumes that I have named my cookie 'csrftoken'. If I call it 'XSRF-TOKEN', will Angular read this cookie automatically (assuming that ngCookies is loaded)? Or do I need the above code.
The documentation falls short on this critical point, as usual.

A: Yes $http documentation is missing this point.
AngularJS looks for a cookie named "XSRF-TOKEN" and sets the header as "X-XSRF-TOKEN"


text:
Q: VBA: Referring to active cells' row in a For/Each loop the aim of my problem is to find a specific value (Text) and then refer to the entire row (or even better only the used range to the right of my active cell) in a For/Each loop.
The first part works fine of finding my value, however, the code for targeting the row of the active cell (so the cell found by the find function), does not work yet:
Sub Search()
Dim cell As Range
Dim Count As Long
Set cell = Cells.Find(what:="Planned Supply at BP|SL (EA)", LookIn:=xlValues, lookat:=xlWhole)
For Each cell In ActiveCell.EntireRow
 If cell.Value = "0" Then
    Count = Count + 1
 End If
Next cell

Range("I1").Value = Count

End Sub

A: The following code will find the range to the right of your found cell and use your loop to do the comparision for each cell in the range. That part could probably be improved by using WorksheetFunction.CountIf.
Option Explicit

Sub Search()

    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim cell As Range, sngCell As Range
    Dim Count As Long
    Set cell = wks.Cells.Find(what:="Planned Supply at BP|SL (EA)", LookIn:=xlValues, lookat:=xlWhole)

    If cell Is Nothing Then Exit Sub  ' just stop in case no hit

    Dim rg As Range, lastColumn As Long
    With wks
        lastColumn = .Cells(cell.Row, .Columns.Count).End(xlToLeft).Column  ' last used column in cell.row
        Set rg = Range(cell, .Cells(cell.Row, lastColumn))                  ' used rg right from found cell inlcuding found cell
    End With

   ' loop from the original post
    For Each sngCell In rg
        If sngCell.Value = "0" Then
            Count = Count + 1
        End If
    Next

    Range("I1").Value = Count

End Sub


text:
Q: How to Loop Data in Codeigniter's HTML Table Class? I need to properly loop Customer's name in Codeigniter's HTML table library, but I don't how to properly use it.
So, here is my model:
<?php class Dash_model extends CI_Model {

        public function __construct()
        {
                parent::__construct();
                $this->load->database();
        }

        public function customerlist()
        {
            $query = $this->db->query("SELECT customername FROM customertable ORDER BY customerid");

            foreach ($query->result() as $row)
            {
                echo $row->customers;
            }

        }

And then here's my Controller:
class Dash_control extends CI_Controller {

    public function __construct()
       {
            parent::__construct();
            $this->load->model('dash_model');
            $this->load->library('table');
       }

    public function index()
    {
        $tmpl = array (
        'row_start'           => '
',
        'row_end'             => '
',
        'cell_start'          => '',
        'cell_end'            => '	',
        );

        $this->table->set_template($tmpl);

        $data['customerloop'] = $this->dash_model->customerlist();

        $this->load->view('dashboard',$data);
    }

After this the code was working perfectly, I can loop the customers names but I don't know how to pass them into my view file. I'm using bootstrap table, so I thought I can make it work with this:

<?php echo $customerloop;?>

but of course it didn't work in a table, it's just looping like that without a table.
One more question, does Codeigniter's table works in Bootstrap? Or it's already responsive without the bootstrap? I'm pretty new to Codeigniter so thank you for every advice you can give me guys...

A: You can use html table class in view page

  Customer data
     <?php
        foreach ($customerloop as $row) {
      ?>

      <?php echo $row->data; ?>

  <?php }
     ?>

A: Model:

    public function __construct()
    {
            parent::__construct();
            $this->load->database();
    }

    public function customerlist()
    {
        $query = $this->db->query("SELECT customername FROM customertable ORDER BY customerid");

        return $query->result();

    }

Controller:
class Dash_control extends CI_Controller {

public function __construct()
   {
        parent::__construct();
        $this->load->model('dash_model');
        $this->load->library('table');
   }

public function index()
{
    $tmpl = array (
    'row_start'           => '
',
    'row_end'             => '
',
    'cell_start'          => '',
    'cell_end'            => '	',
    );

    $this->table->set_template($tmpl);

    $data['customerloop'] = $this->dash_model->customerlist();

    $this->load->view('dashboard',$data);
}

View:

<?php foreach ($customerloop as $row)
 { ?>

<?php echo $row->customers; ?>

<?php } ?>


text:
Q: How to break out of a sourced Bash script's function I have a Bash script that is sourced. When this script is sourced, it runs a function in the Bash script. This function should terminate the script if a certain condition is matched. How can this be done without terminating the shell in which the script is sourced?
To be clear: I want the termination action to be completed by the function in the sourced shell script, not in the main body of the sourced shell script. The problems that I can see are that return simply returns from the function to the main of the script while exit 1 terminated the calling shell.
The following minimal example illustrates the problem:
main(){
    echo "starting test of environment..."
    ensure_environment
    echo "environment safe -- starting other procedures..."
}

ensure_environment(){
    if [ 1 == 1 ]; then
        echo "environment problemm -- terminating..."
        # exit 1 # <-- terminates calling shell
        return   # <-- returns only from function, not from sourced script
    fi
}

main

A: You can return from a sourced shell script. POSIX spec
So, while you can't return from the function directly to get what you want you can return from the main body of the script if your function returns non-zero (or some other agreed upon value).
For example:
$ cat foo.sh
f() {
    echo in f "$@"
}

e() {
    return 2
}

f 1
e
f 2
if ! e; then
    return
fi
f 3
$ . foo.sh
in f 1
in f 2

A: This is a recipe how you can achieve your goal with your approach. I will not write your code for you, just describe how it can be done.
Your goal is to set/alter environment variables in the current bash shell by, effectively, sourcing a possibly complex shell script. Some component of this script may decide that execution of this sourced script should stop. What makes this complicated is that this decision is not necessarily top-level, but may be located in a nested function invocation. return, then, does not help, and exit would terminate the sourcing shell, which is not desired.
Your task is made easier by this statement of yours:

additional complexity that I can't really include in a minimal example
  makes it very desirable to centralise the termination procedure in a
  function.

This is how you do it:
Instead of sourcing your real script that decides which environment to set to what ("realscript.bash"), you source another script "ipcscript.bash".
ipcscript.bash will setup some interprocess communication. This may be a pipe on some extra file descriptor that you open with exec, it may be a temporary file, it may be something else.
ipcscript.bash will then start realscript.bash as a child process. That means, the environment changes that realscript.bash does first only affect the environment of that child process instance of bash. Starting realscript.bash as a childprocess, you gain the capability of terminating the execution at any nested level with exit without terminating the sourcing shell.
Your call to exit will live, as you write, in a centralised function that is called from any level when a decision is made to terminate execution. Your terminating function now needs, before exiting, to write the current environment to the IPC mechanism in a suitable format.
ipcscript.bash will read environment settings from the IPC mechanism and reproduce all settings in the process of the sourcing shell.

A: How about this: Call everything through a simple wrapper, here "ocall", that maintains a global state, here "STILL_OK"
STILL_OK=true

ocall() {
    if $STILL_OK
    then
       echo -- "$@" # this is for debugging, you can delete this line
       if "$@"
       then
          true
       else
          STILL_OK=false
       fi
    fi
}

main(){
    ocall echo "starting test of environment..."
    ocall ensure_environment
    ocall echo "environment safe -- starting other procedures..."
}

ensure_environment(){
    if [ 1 == 1 ]; then
        ocall echo "environment problemm -- terminating..."
        # exit 1 # <-- terminates calling shell
        return 1  # <-- returns from sourced script but leaves sourcing shell running
    fi
}

ocall main

A: It is not possible.
If you source a script it is (for the aspects concerned here) like entering each line one by one in the calling (sourcing) shell.  You want to leave a scope (the sourced script) which does not exist, so it cannot be left.
The only way I can think of is by passing the exit-wish back to the calling function and checking for it:
main() {
    echo "starting test of environment..."
    [ "$(ensure_environment)" = "bailout" ] && return
    echo "environment safe -- starting other procedures..."
}

ensure_environment() {
    if [ 1 == 1 ]; then
        echo "bailout"
        return
    fi
}

main

What you ask for also is typically not possible in other languages.  Normally each function can only terminate itself (by returning), not a wider defined scope outside of itself (like a script it resides in).  An exception to this rule is exception handling using try/catch or similar.
Also consider this:  If you source this script, the shell functions become known in the sourcing shell.  So you can call them later again.  Then there (again) is no surrounding scope the function could terminate.

A: This is the solution I prefer (it comes with side effects, explained below):
#!/usr/bin/env bash
# force inheritance of ERR trap inside functions and subshells
shopt -s extdebug
# pick custom error code to force script end
CUSTOM_ERROR_CODE=13

# clear ERR trap and set a new one
trap - ERR
trap '[[ $? == "$CUSTOM_ERROR_CODE" ]] && echo "IN TRAP" && return $CUSTOM_ERROR_CODE 2>/dev/null;' ERR

# example function that triggers the trap, but does not end the script
function RETURN_ONE() { return 1; }
RETURN_ONE
echo "RETURNED ONE"

# example function that triggers the trap and ends the script
function RETURN_CUSTOM_ERROR_CODE() { return "$CUSTOM_ERROR_CODE"; }
# example function that indirectly calls the above function and returns success (0) after
function INDIRECT_RETURN_CUSTOM_ERROR_CODE() { RETURN_CUSTOM_ERROR_CODE; return 0; }
INDIRECT_RETURN_CUSTOM_ERROR_CODE
echo "RETURNED CUSTOM ERROR CODE"

# clear traps
trap - ERR
# disable inheritance of ERR trap inside functions and subshells
shopt -u extdebug

Output:
# source source_global_trap.sh
RETURNED ONE
IN TRAP
IN TRAP

Description:
In short, the code sets a trap for ERR, but, inside the trap (as the first instruction) checks the return code against CUSTOM_ERROR_CODE and returns from the sourced script only for and with the value of CUSTOM_ERROR_CODE (arbitrarily chosen as 13 in this case). That means returning CUSTOM_ERROR_CODE anywhere (due to shopt -s extdebug, otherwise just the first level functions/commands) should produce the desired result of ending the script.
Side effects:
[01] The error code in CUSTOM_ERROR_CODE may be used by a command outside the script's control and can thus force the script to end without an explicit instruction to do so. This should be easily avoidable, but can cause some discomfort.
[02] Invoking shopt -s extdebug might cause unwanted behavior, depending on other factors in the script. Details here: https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html
[03] More importantly, this is the output of sourcing the script in a clean environment, three times, one after the other:
# exec bash

# source source_global_trap.sh
RETURNED ONE
IN TRAP
IN TRAP

# source source_global_trap.sh
RETURNED ONE
IN TRAP
IN TRAP
IN TRAP

# source source_global_trap.sh
RETURNED ONE
IN TRAP
IN TRAP
IN TRAP

I have several theories as to why this (extra trap call) occurs, but no conclusive explanation. It has not caused trouble during my tests, but any clarifications are strongly encouraged.

A: Sometimes I write a script that has handy functions that I want to use outside of the script. In this case, if the script is run, then it does its thing. But if the script is sourced, it just loads some functions into the sourcing shell.
I use this form:
#!/bin/bash

# This function will be sourcable
foo() {
  echo hello world
}

# end if being sourced
if [[ $0 == bash ]]; then
  return
fi

# the rest of the script goes here

A: It is possible.
Do it like in any programming language and "raise an exception" which will propagate up the calling chain:
# cat r

set -u

err=

inner () {
   # we want to bailaout at this point:
   # so we cause -u to kick in:
   err="reason: some problem in 'inner' function"
   i=$error_occurred
   echo "will not be called"
}

inner1 () {
   echo before_inner
   inner
   echo "will not be called"
}

main () {
   echo before_inner1
   inner1
   echo "will not be called"
}

echo before_func
main || echo "even this is not shown"

# this *will* be called now, like typing next statement on the terminal:
echo after_main
echo "${err:-}" # if we failed

Test:
# echo $$
9655
# . r  || true
before_func
before_inner1
before_inner
bash: error_occurred: unbound variable
after_main
reason: some problem in 'inner' function
# echo $$
9655

You can silence the error via 2>/dev/null, clear


text:
Q: restful class don't access variable, cannot find symbol I am trying to access String operation that is in public String postForm, through a public class, but when in public String Sum I try to call optest.postForm (operation), it shows the error cannot find symbol.
public class op {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String postForm(@QueryParam("operacion") String operacion) {
        return operacion;
    }
}

@GET
@Path("/calculadora/suma")
public String Suma(@QueryParam("num1") double num1,@QueryParam("num2") double num2)    {
    return Double.toString($Suma(num1,num2));
}

double $Suma(double num1,double num2) {
    op optest = new op();
    optest.postForm(operacion);
    double resultado;
    resultado = num1 + num2;
    return resultado;
}


text:
Q: Quando e por que devo utilizar classes templates Class  em Java? Eu quando vejo que uma classe ela recebe isso, eu acho assustador.

A: Em C++ isto pode se chamar template, mas em Java estas classes são chamadas de genéricas.
Isso é necessário quando uma classe pode usar a mesma estrutura básica e os mesmo algoritmos com diversos tipos de dados. Pense em algo que pode ser feito igualzinho com Boolean, Integer, Long, Float, etc. Tudo é igualzinho, só muda o tipo do dado que será usado para armazenar na classe. Como você resolve isto? Faz uma classe para cada tipo desses, copiando elas e só mudando o tipo?
Quando tiver que dar manutenção vai lembrar de fazer em todas igualzinho? Não tem condições, certo?
Aí você pode usar o tal do generics. Com isto pode variar o tipo do dado básico que será usado na classe de acordo com a forma que ela for instanciada. Então esse T aí é uma espécie de "super-variável", que será substituído por um tipo específico quando a classe for instanciada.
class Exemplo<T> {
    private T x;
    Exemplo(T x) => this.x = x;
    public T getValue() => x;
}

Depois usa:
Exemplo<String> teste1 = new Exemplo<String>("teste");
teste1.getValue();
Exemplo<Boolean> teste2 = new Exemplo<Boolean>(true);
teste2.getValue();

Coloquei no GitHub para referência futura.
Tudo funciona. No primeiro exemplo, todos os lugares que tinha o T, vai virar String. E no segundo onde tinha T vira Boolean, ficaria algo assim:
class Exemplo<String> {
    private String x;
    Exemplo(String x) {
        this.x = x;
    }
    public String getValue() {
        return x;
    }
}

Assim uma única classe resolve o problema para todos os tipos sem ter que ficar copiando código, que vai causar problemas de manutenção.
O Java está repleto dessas classes. As coleções de dados costumam se beneficiar muito disto. No começo Java não tinha esse recurso, então você tinha um ArrayList "pelado" assim mesmo. Então ele aceitava qualquer coisa. Até funciona, mas imagine que você pode misturar números, com Strings, com Clientes (uma classe que você definiu), com qualquer outra coisa. Quando se criou o tal do ArrayList<T>, você cria uma variável que guarda ArrayList<Cliente> e esta lista só pode guardar Clientes. Fica mais seguro. Basicamente esta é uma coleção que pode ser usado com qualquer tipo já existente no Java ou criado pelos programadores.
Simplificadamente é isso. Tem maneiras de usar de forma mais avançada, fazer restrições de que tipos podem ser usados em T, ter outros slots para generalizar outras partes com um tipo diferente, enfim... vai perguntando conforme for usando e for surgindo novas dúvidas.
Documentação (continue acompanhando as páginas do tutorial).

A: Os Generics também são muito úteis em métodos nesse exemplo :
    public static <T> List<T> asList(T... objects) {
       return ...
    }

você receberá uma lista do tipo T baseado em seus parâmetros;


text:
Q: Why are methods and attributes of base template classes not immediately available? When deriving from a template base class, methods and attributes of the base class aren't immediately available, i.e if Base<T> has a void Func(), then Derived deriving from Base<T> has to call Base<T>::Func and not merely Func.
In Why must we specify template arguments for template base class when calling its constructor?, the following explanation is provided:

Injected class name are in the scope of the class. So are class member names. The general rule is that dependent base scope names are not visible at the point of definition of the derived template class. It is true that whatever T the injected class name of Base<T> is Base so compilers could infer that Base designate the injected class name of Base<T>. But that would be an other special rule. My opinion is that the c++ language has enough corner cases, and special rules which hurts coherency. So I am glad to see there is no special treatment for dependent base class injected name. - Oliv

In CppCon 2020 Back to Basics: Templates (part 1 of 2), the subject is touched upon as well and explained with

The simple nature of that is that because there is not necessarily only one of these [Base], you can publicly or privately derive multiple times from Foo just with a different type [...]

Oliv's one explains well why we can't call Base::Func, but if it also explains why we couldn't call Func, that's not clear to me.
As for the explanation by the CppCon presenter, sure, we could derive from multiple Base instantiations, but we don't. If A and B both have a void Func(), then if I derive from A, I can call Func without specifying A::Func. Only when I derive from A and B will the compiler understandably complain if I try to call Func. I would expect the same behaviour for templates: only when we derive from Base<T> and Base<U> would we get an ambiguity error. Or from A and Base<T> for that matter.
Is there a reason for things not be this way that I'm not seeing there ?


text:
Q: how to divide time in hours and minutes by production in excel vba userform i have to divide a number like this(45)by 5.30 and also need to convert minutes into decimal
the final result will :45/5.50 = 8.18 and its has to be done in vba excel userform

A: Here's a function that converts a time string expression like "5:30" to a numeric expression where the seconds are converted to decimal minutes.
Function SecondsToMinutes(ByVal TimeString As String) As Double

    Dim Fun     As Double
    Dim Sp()    As String

    Sp = Split(TimeString, ":")
    Fun = Val(Sp(UBound(Sp))) / 60
    If UBound(Sp) Then Fun = Fun + Val(Sp(UBound(Sp) - 1))
    SecondsToMinutes = Fun
End Function

You can use the number returned by the above function in calculations and assign that value to a text box in a user form. The following is syntax that would write "8.18" to TextBox1.
TextBox1.Value = Round(45 / SecondsToMinutes("5:30"), 2)

A: Use CDate:
Value = Round(45 / CDate("5.30") / 24, 2)
' Value -> 8.18


text:
Q: Notepad++ brace overwriting I've been primarily coding in Coda for the past couple years, and am now trying to familiarize myself with Notepad++ for the Windows side of things. I figured out how to enable the brace autocompletion, but I'm wondering if there is any way in N++ to have the editor "type over" or "overwrite" braces so you don't end up with duplicates?
As in... if I type a parenthesis, and the character immediately after my cursor WAS a parenthesis, it should simply be overwritten, not entered again.
Thanks.

A: Late answer, but this might be of interest to new visitors.
Yes this is possible using XBrackets Lite plugin (latest version 1.2.1). You can download it from the Plugin Manager or from SourceForge.
When installed, go to Plugins > XBrackets Lite > Settings..., check Autocomplete brackets and leave unchecked the Even if corresponding right bracket exists. That's all!

Please note that this solution isn't perfect. Consider the following example, where | is the place of your cursor:
if ($x==1) |

}

and you press {, it will autoclose the bracket resulting to
if ($x==1) {|}

}


text:
Q: Java regex possesive quantifiers Given this regex:
x[^x]*+x

and this input string for matching:
xbbbx

The result is the matched text xbbbx starting at index 0 and ending at index 5.
But, by only changing the last letter x to Z in both the regex and the string, we get this regex:
x[^x]*+Z

and this input string:
xbbbZ

and the result is: no match found.
Why would a change in a single letter produce this change in behavior?

A: The reason why is you are using the "possessive" quantifier which will match the symbol as much as it can.
So in this case with xbbbZ the regex x[^x]*+ matches all non x characters until the end of the line, where it stops.  It has already consumed the "Z" inside of the input xbbbZ.
This regex, x[^x]*+x, works with xbbbx because the "possessive" quantifier has to stop when it reaches an x.  Your input has an x at the end, and therefore the possessive quantifier stops.  This allows the last part of the regex x to be matched with x.
At the end of the Java tutorial page, you can see another example of the possessive quantifier.


text:
Q: Should I create an index on a column with repetitive values and where in lookup I have a materialized view (which is very much a table) where I need to make where in kind of queries.
The column I want to query (say view_id) definitely has repetitions (15-20).
The where in queries would also be very large i.e - it would contain a lot of view_id to query.
Should I go ahead and create an index on this column?
Will it give me some performance improvements?
I have another column which would help help me have a multi column index(unique). Should this be a better option?

A: With questions such as these on performance, there is no substitute for testing it with your exact case.  There's little harm in trying it out (even on a production system, but utilize a test system if you can!), other than perhaps slowing performance until you undo what you did.  Postgres makes this kind of tinkering safe.
@tim-biegeleisen's first comment is spot on: with your setup, your cardinality is reduced, but that doesn't mean it's not a win.
In short, try it and see.  There is no better answer you will get than what your own dataset and access patterns will give you.


text:
Q: Exception when Indexing Excel's xslx format file through Solr4.7.2 I am getting an exception while indexing excel sheet of xslx extension through Solr4.7.2 Search API.
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/solr] threw exception [Filter execution threw an exception] with root cause
java.lang.NoClassDefFoundError: Could not initialize class org.apache.poi.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller
    at org.apache.poi.openxml4j.opc.OPCPackage.init(OPCPackage.java:154)
    at org.apache.poi.openxml4j.opc.OPCPackage.<init>(OPCPackage.java:141)
    at org.apache.poi.openxml4j.opc.Package.<init>(Package.java:54)
    at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:99)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:221)
    at org.apache.tika.parser.pkg.ZipContainerDetector.detectOfficeOpenXML(ZipContainerDetector.java:194)
    at org.apache.tika.parser.pkg.ZipContainerDetector.detectZipFormat(ZipContainerDetector.java:134)
    at org.apache.tika.parser.pkg.ZipContainerDetector.detect(ZipContainerDetector.java:77)
    at org.apache.tika.detect.CompositeDetector.detect(CompositeDetector.java:61)
    at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:113)
    at org.apache.solr.handler.extraction.ExtractingDocumentLoader.load(ExtractingDocumentLoader.java:219)
    at org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:74)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:135)
    at org.apache.solr.core.RequestHandlers$LazyRequestHandlerWrapper.handleRequest(RequestHandlers.java:241)
    at org.apache.solr.core.SolrCore.execute(SolrCore.java:1916)
    at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:768)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:415)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:205)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)

I have 4 Apache POI Jars in my tomcat lib related to this Excel sheet, those are:
poi-3.9-20121203.jar,
poi-ooxml-3.9-20121203.jar,
poi-ooxml-schemas-3.9-20121203.jar,
poi-scratchpad-3.9-20121203.jar
I have checked and found the usage of different versions of POI Jars that support extensions in different way.
Please suggest some way to resolve this issue.

A: I had the same problem, it was caused by two dom4j jars, one was in tomcat/lib and the other in webapps/basic-services/WEB-INF/lib
The solution was to exclude dom4j from my app dependencies using maven
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
    <scope>provided</scope>
</dependency>

I was able to pinpoint this problem by inestigating the stack trace of the first occurrence of this exception, I found the following:
Caused by: java.lang.ClassCastException: org.dom4j.DocumentFactory cannot be cast to org.dom4j.DocumentFactory
    at org.dom4j.DocumentFactory.getInstance(DocumentFactory.java:97)
    at org.dom4j.tree.AbstractNode.<clinit>(AbstractNode.java:39)


text:
Q: Change app.config at install time How can I dynamically change a connectionString in the app.config file?
I have an application written with windows forms, c# 3.0 and Linq to Sql. I need to change the connection string when i install the application. How i do this?
When the user installs the program it must show a form with an option to change the connection string if exists or add one if it doesn't.

A: If you are using a .NET deployment project, can achieve this by using Custom Actions.

A: Write a secondary config file with an appSettings block using the settings from the installer. In your main config file, use the file attribute in appSettings to reference the second config file, like so:
<appSettings file="User.config">

Settings in the secondary config will override any matching keys in the main config.
In your installer:
public override void Install(IDictionary stateSaver)
{
    base.Install(stateSaver);

    string server = Context.Parameters["Server"];
    string port = Context.Parameters["Port"];
    string targetDir = Context.Parameters["TargetDir"];
    // Build your connection string from user-input parameters and add them to dictionary

    WriteAppConfig(targetDir, server, port);
}

private void WriteAppConfig(string targetDir, string server, string port)
{
    string configFilePath = Path.Combine(targetDir, "User.config");

    IDictionary<string, string> userConfiguration = new Dictionary<string, string>();

    userConfiguration["Server"] = server;
    userConfiguration["Port"] = port;

    ConfigGenerator.WriteExternalAppConfig(configFilePath, userConfiguration);
}

public class ConfigGenerator
{
    public static void WriteExternalAppConfig(string configFilePath, IDictionary<string, string> userConfiguration)
    {
        using (XmlTextWriter xw = new XmlTextWriter(configFilePath, Encoding.UTF8))
        {
            xw.Formatting = Formatting.Indented;
            xw.Indentation = 4;
            xw.WriteStartDocument();
            xw.WriteStartElement("appSettings");

            foreach (KeyValuePair<string, string> pair in userConfiguration)
            {
                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", pair.Key);
                xw.WriteAttributeString("value", pair.Value);
                xw.WriteEndElement();
            }

            xw.WriteEndElement();
            xw.WriteEndDocument();
        }
    }
}

A: Check out this question. It has what you need to change values in the app.config dynamically through code.


text:
Q: Database error : no such column: connect_connect.reciever_id I have created following model
 class ConnectToFrom(models.Model):
    person = models.ForeignKey(User, null=True)
    kiosk = models.ForeignKey(Kiosks, null=True)

 class Connect(models.Model):
    parent_id = models.ForeignKey("self", null = True, blank = True)
    sender = models.ForeignKey(ConnectToFrom, related_name='sent_messages' )
    reciever = models.ForeignKey(ConnectToFrom, related_name='received_messages')
    .
    .
    .

I am not able to access Connects to add any connect object through admin site !
Can i not reference same model to two fields ?
I am not able to figure out what exactly is causing the error .
Please help
Traceback :
Environment:

Request Method: GET
Request URL: http://www.example.com:8000/admin/connect/connect/

Django Version: 1.3
Python Version: 2.6.6
Installed Applications:
['broadcast',
 'shastra',
 'fb_api',
 'log',
 'nties',
 'crc',
 'connect',
 'network',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.admin',
 'kiosks',
 'content',
 'home',
 'dashboard',
 'trial',
 'meta',
 'oembed']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Traceback:
File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\contrib\admin\options.py" in wrapper
  307.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  79.         response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\contrib\admin\sites.py" in inner
  197.             return view(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapper
  28.             return bound_func(*args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in bound_func
  24.                 return func(self, *args2, **kwargs2)
File "C:\Python26\lib\site-packages\django\contrib\admin\options.py" in changelist_view
  1159.             'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "C:\Python26\lib\site-packages\django\db\models\query.py" in __len__
  82.                 self._result_cache = list(self.iterator())
File "C:\Python26\lib\site-packages\django\db\models\query.py" in iterator
  273.         for row in compiler.results_iter():
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py" in results_iter
  680.         for rows in self.execute_sql(MULTI):
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  735.         cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\util.py" in execute
  34.             return self.cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  234.             return Database.Cursor.execute(self, query, params)

Exception Type: DatabaseError at /admin/connect/connect/
Exception Value: no such column: connect_connect.reciever_id

A: Did you add the receiver field to your model after you initially created the connect_connect table? If so you'll have to manually add that field to your database (Django does not automatically sync changes to your models with your database.)
Just launch your interactive db shell, usually  dbshell, and add the field. In MySQL it would be something like:
ALTER TABLE connect_connect ADD COLUMN receiver_id integer;

I'd recommend running manage.py sqlall appname to see how Django would create your db tables now, and then make sure the db matches that by making the necessary changes through your db shell.


text:
Q: Impact of constraints on convex optimization Let me start by saying I know almost nothing about optimization so please bear with me. Basically, I am wondering whether it is possible to solve a problem with two constraints by solving the problem with each constraint individually and somehow combining the solutions. However, I'm having trouble visualizing the scenario. More specifically:
Suppose $V$ is some Banach space and $f:V \to \mathbb{R}$ is convex and continuous. Furthermore, let $K_1, K_2 \subset V$ be convex and consider the solutions $x_i$ of the optimization problems
$$\quad \min_{x \in K_i}  f(x).$$
For $K = K_1 \cap K_2$ let $x$ solve
$$\min_{x \in K} f(x).$$

*

*Is $x$ the projection of $x_1$ onto $K_2$?

*Is $x$ a linear combination of $x_1$ and $x_2$?

*Are there any relations between $x$, $x_1$ and $x_2$ at all?

*Does the situation change if we further restrict $f$? For example to be quadratic?

Thank you very much in advance.

A: For general convex sets, the sorts of simple relationships you're suggesting don't exist. I find it helps to draw two dimensional pictures to see why. (Even if the space is dimension higher than 2, we could restrict the problems to the plane spanned by $x_1,x_2,x$ and none of the answers to your questions would change.) Here's an example of what can happen even in the simple case where $f$ is linear:

The red arrow is the direction of the negative gradient of $f$. Minimizing $f$ means moving as far as possible in that direction. To address your specific questions:

*

*No. In this case, the projection of $x_2$ onto $K_1$ is not in $K_2$, so it can't equal $x$. The projection of $x_1$ onto $K_2$ is in $K$, but still doesn't equal $x$

*The origin is not depicted in the diagram, but if $x_1$ and $x_2$ are collinear with the origin, then $x$ is not a linear combination of $x_1$, $x_2$.

*The only easy, simple relationship is that $f(x_1) \le f(x)$ and $f(x_2) \le f(x)$.

*In this example, the function is linear. That's about as simple as you can get without making the problem trivial.

That said, there are methods (like ADMM) that can use solvers for subproblems to converge to a solution of a larger problem.


text:
Q: What elements does Wix use to auto generate a ComponentId guid when the keypath is a RegistryKey/Value I have a Wix (3.8) project that is relatively generic in that we are attempting to produce multiple Demo installers using a variety of tools such as the preprocessor to change the name, include different files and options. I also modify the ProductId/ProductCode/UpgradeCode for each so that they appear as 2 different products and install side by side. Installing and uninstalling one alone works fine. When I install 2 side-by-side and uninstall one there are several abandoned resources one of which is the shortcuts.
Here is the code I am using for the shortcuts:
<DirectoryRef Id="DesktopFolder">
  <Component Id="DesktopShortcuts"
             Guid="*">
    <Shortcut Id="ApplicationDesktopShortcut"
              Name="!(bind.property.ProductName)"
              Description="Demo Application"
              Target="[INSTALLDIR]Demo.exe"
              WorkingDirectory="INSTALLDIR"
              Advertise="no"/>
    <RegistryKey Root="HKMU"
                 Key="SOFTWARE\$(var.Manufacturer)\!(bind.property.ProductCode)\DesktopShortcuts">
      <RegistryValue Name="Installed"
                     Type="integer"
                     Value="1"
                     KeyPath="yes" />
    </RegistryKey>
  </Component>
</DirectoryRef>

After reviewing the installer logs I note that the ComponentId for the shortcuts is always the same which explains the abandoned resources (shortcuts).
I was under the impression that because the Path to my registry value was different for each installer (note that I bind the product code into the key) I would get a different Guid for each installer as a result of the Guid="*" attribute. However, the wix documenation is unclear WRT Registry keys as are other discussions I located. Apparently this isn't an issue with files that are in separate directories.
Such as this and the Wix docs.

A: So I figured out what is going on. It's all got to do with some subtle issues on this line:
 Key="SOFTWARE\$(var.Manufacturer)\!(bind.property.ProductCode)\DesktopShortcuts">

As noted in the question the documentation and references suggest that the Path for files and registry entries are used to dynamically generate the Guid. Note the path includes the file/Value Name. This is in fact happening but how was I getting the same Guid for the ComponentId for 2 different installers using 2 different ProductCodes? You would think that the inclusion of the ProductCode into the path would make each unique. Well, turns out it's because I was using !(bind.property.ProductCode) in the path. Binder variables don't get substituted until the Linking phase with light. The Guid="*" element is generated in the Compiling phase with Candle which is obviously before the linker. So while the substitution was occurring and the proper keys were being generated in the registry, the Guid was being generated from a non unique path:
SOFTWARE\MyCompany, Inc\!(bind.property.ProductCode)\DesktopShortcuts\Installed

So don't use binder variables in any KeyPath element when using the auto generated Guid functionality.


text:
Q: Problem in configuration project using struts + tiles + maven Here is my config in web.xml
<context-param>
        <param-name>
            org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
        <param-value>/WEB-INF/tiles.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
    </listener>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

in struts.xml
<package name="default" extends="struts-default, tiles-default">
    <action name="home" class="controller.HomeController">
        <result name="success" type="tiles">home</result>
    </action>
</package>

in tiles.xml
<definition name="home" template="/layout.jsp">
    <put-attribute name="body" value="/WEB-INF/pages/home.jsp"/>
</definition>

in pom.xml
<dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.2.1</version>
        <type>pom</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.struts.xwork</groupId>
        <artifactId>xwork-core</artifactId>
        <version>2.2.1</version>
        <type>pom</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-core</artifactId>
        <version>2.2.2</version>
        <type>pom</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-jsp</artifactId>
        <version>2.2.2</version>
        <type>pom</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-spring-plugin</artifactId>
        <version>2.2.1</version>
        <type>pom</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-extras</artifactId>
        <version>2.2.2</version>
        <type>pom</type>
        <scope>compile</scope>
    </dependency>

Here is the complete stack trace:
SEVERE: Error configuring application listener of class org.apache.struts2.tiles.StrutsTilesListener
java.lang.ClassNotFoundException: org.apache.struts2.tiles.StrutsTilesListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4537)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5097)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5092)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)

A: Missing struts2-tiles-plugin-2.2.x.jar in classpath, with dependency:
<dependency>
  <groupId>org.apache.struts</groupId>
  <artifactId>struts2-tiles-plugin</artifactId>
  <version>${version.tiles}</version>
  <scope>compile</scope>
</dependency>

You can solved ClassNotFoundException with findJAR
http://www.findjar.com/index.x?query=org.apache.struts2.tiles.StrutsTilesListener

A: I guess you are missing the struts2-tiles-plugin


text:
Q: Why is the Fabry-Perot more accurate than Michelson?
Why is the Fabry-Perot Interferometer on Na-lamp more accurate than Michelson Interferometer also on Na-lamp by counting the fringes of a circular pattern?


text:
Q: Apply matrixform to limited rows and columns of a matrix I have a big matrix, you can say 1000*1000 whose elements are functions of several parameters such as a, b. I wish to see just a few (not all) rows and columns of the matrix in the MatrixForm which is a builtin function of Mathematica. For instance, row from 92 to 101 and column corresponded with 50 to 65. How can I reach this goal?
In addition, if I want to simplify the elements, should I simply firstly and after that make use of MatrixForm or should I do vise versa? Which one is faster to run?

A: Here is a function that shows a portion of a matrix in MatrixForm, with associated row and column indices:
iMatrixView[m_, r_List, c_List] := Module[{sub = m[[r, c]]},
    augmented = ArrayFlatten[{
        {Map[Invisible, sub, {2}], List /@ istyle /@ r},
        {{istyle /@ c}, ""}
    }];
    Overlay[{
        Row[{RawBoxes@"(", Grid[sub, Spacings->1],RawBoxes@")"}],
        Row[{Invisible[RawBoxes@"("],Grid[augmented, Spacings->1]}]
    }]
]

istyle[x_] := Style[x, Gray, FontSize->Inherited-3]

For example:
SeedRandom[1]
mat = RandomInteger[150, {10, 15}];
iMatrixView[mat, {2,4,5}, {1, 6, 12}]

It is possible to use this function in a Manipulate to interactively explore the matrix:
MatrixView[mat_?MatrixQ, rows_Integer?Positive, cols_Integer?Positive] := With[
    {dim=Dimensions[mat]},

    Manipulate[
        iMatrixView[
            mat,
            Reverse[dim[[1]]+1-Range[rows]-u[[2]]],
            Range[cols]+u[[1]]
        ],
        {{u, {0,dim[[1]]-rows}}, {0,0}, Reverse@dim-{cols,rows}, 1}
    ] /; rows<dim[[1]]&&cols<dim[[2]]
]

For example:
MatrixView[mat, 6, 5]

A: M = RandomInteger[10, {1000, 1000}];
M // MatrixForm;

SubM = M[[92 ;; 101 , 50 ;; 65]];
SubM // MatrixForm

In terms of simplifying, it depends on a few things. Assuming that you only want to simplify the entries that you're extracting I think it'd be quicker to extract first, then simplify. If you simplify first then extract I'd think its almost equivalent to extracting twice since you first need to tell the computer which cells you want to simplify, which takes some time, then simplify them, then extract them, when if you extract them first and then simplify the whole thing, there are only two operations required, which logically should be quicker. Hope that helps.


text:
Q: Trying to use enumerate() on a string with lines not surrounded by quotes in Python I am trying to use enumerate() on a string already in memory (thus not from file), which string has comma separated values (or space, but uniformly, i.e. not mix of comma and spaces).
Basically I just want to get the whole line n, something quite similar to the first part of this question.
If I do a print on my string (before entering the function), it shows something like this:
89,abc,def01,ghi23
01,jkl,mno45,pqr67

however this code does not work, presumably because my lines are not individually surrounded by quotes:
def pickline(thestring, whatline):
  for i, line in enumerate(thestring):
    if i == whatline:
      return line

Question: what should I do to get this right ?
edit The expected output should be:
# string
89,abc,def01,ghi23
# if whatline value is 0,
# or string
01,jkl,mno45,pqr67
# if whatline value is 1,
# etc.

A: You have to split the string into lines first.
for i, line in enumerate(thestring.splitlines()):

However, a better way to do this is to do this:
def pickline(thestring, whatline):
    return thestring.splitlines()[whatline]


text:
Q: How to use a contentScriptFile from an external URI in a Firefox addon My latest update to a Firefox addon has been rejected because I've used a custom jquery-ui (generated by their site with just the widgets I wanted) and it fails their checksum check.

Your add-on includes a JavaScript library file that doesn't match our
  checksums for known release versions. We require all add-ons to use
  unmodified release versions, obtained directly from the developer's
  website.
  We accept JQuery/JQuery-UI libraries downloaded from
  'ajax.googleapis.com', 'jquery.com' or  'jqueryui.com'; and used
  without any modification. (file-name change does not matter) I'm
  sorry, but we cannot accept modified, re-configured or customized
  libraries.

Fair enough, I could just download the full one and resubmit, but I was wondering if it is possible to link to one instead?
If I try this:
contentScriptFile: [self.data.url("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"), self.data.url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"), self.data.url("api.js")],

I get an error at runtime telling me that content scripts much be local. Both google and the API seem to be proving illusive to me for an answer.
Does anyone know if this is possible and how?
Cheers
Rich

A:
self.data.url("https://...")

It seems like you haven't read the documentation on data.url()
It clearly states that

The data.url() method returns a resource:// url that points at an embedded data file.

Which means you cannot link to an external resource.

Does anyone know if this is possible and how?

No, contentScriptFile runs with (slightly) elevated privileges compared to regular web content, that's why you are not allowed to load scripts from sources that might change and could theoretically inject malicious code in the future.
If you want to rely on external libraries and keep them up to date you could simply write a little build script that always downloads the newest version when building a new XPI.
In principle you could just load the script via privileged XHR and then pass it as string, but that's probably not gonna pass AMO review.

And piece of personal opinion: Since you're targeting a specific browser you don't really need jquery for its cross-browser logic, modern web APIs provide lots of convenience methods that you can get pretty far just with vanilla ES6-javascript and state-of-the-art DOM APIs. Iterators and arrow functions also make bulk operations fairly concise.


text:
Q: Read AVRO structures saved in HBase columns I am new to Spark and HBase. I am working with the backups of a HBase table. These backups are in a S3 bucket. I am reading them via spark(scala) using newAPIHadoopFile like this:
conf.set("io.serializations", "org.apache.hadoop.io.serializer.WritableSerialization,org.apache.hadoop.hbase.mapreduce.ResultSerialization")
val data = sc.newAPIHadoopFile(path,classOf[SequenceFileInputFormat[ImmutableBytesWritable, Result]], classOf[ImmutableBytesWritable], classOf[Result], conf)

The table in question is called Emps. The schema of Emps is :
key: empid {COMPRESSION => 'gz' }
  family: data
    dob - date of birth of this employee.
    e_info - avro structure for storing emp info.
    e_dept- avro structure for storing info about dept.

  family: extra - Extra Metadata {NAME => 'extra', BLOOMFILTER => 'ROW', VERSIONS => '1', IN_MEMORY => 'false', KEEP_DELETED_CELLS => 'FALSE', DATA_BLOCK_ENCODING => 'NONE', TTL => 'FOREVER', COMPRESSION => 'SNAPPY', MIN_VERSIONS => '0', BLOCKCACHE => 'true', BLOCKSIZE => '65536', REPLICATION_SCOPE => '0'}
    e_region - emp region
    e_status - some data about his achievements
    .
    .
    some more meta data

The table has some columns that have simple string data in them, and some columns that has AVRO stuctures in them.
I am trying to read this data directly from the HBase backup files in the S3. I do not want to re-create this HBase table in my local machine as the table is very, very large.
This is how I am trying to read this:
data.keys.map{k=>(new String(k.get()))}.take(1)
res1: Array[String] = Array(111111111100011010102462)

data.values.map{ v =>{ for(cell <- v.rawCells()) yield{
                        val family = CellUtil.cloneFamily(cell);
                        val  column = CellUtil.cloneQualifier(cell);
                        val  value = CellUtil.cloneValue(cell);
                            new String(family) +"->"+ new String(column)+ "->"+ new String(value)
                         }
                      }
}.take(1)
res2: Array[Array[String]] = Array(Array(info->dob->01/01/1996,  info->e_info->?ж�?�ո� ?�� ???̶�?�ո� ?�� ????, info->e_dept->?ж�??�ո� ?̶�??�ո� �ո� ??, extra->e_region-> CA, extra->e_status->, .....))

As expected I can see the simple string data correctly, but the AVRO data is garbage.
I tried reading the AVRO structures using GenericDatumReader:
data.values.map{ v =>{ for(cell <- v.rawCells()) yield{
                        val family = new String(CellUtil.cloneFamily(cell));
                        val  column = new String(CellUtil.cloneQualifier(cell));
                        val  value = CellUtil.cloneValue(cell);
                        if(column=="e_info"){
                          var schema_obj =  new Schema.Parser
                          //schema_e_info contains the AVRO schema for e_info
                          var schema = schema_obj.parse(schema_e_info)
                          var READER2 = new GenericDatumReader[GenericRecord](schema)
                          var datum= READER2.read(null, DecoderFactory.defaultFactory.createBinaryDecoder(value,null))
                          var result=datum.get("type").toString()
                                family +"->"+column+ "->"+ new String(result) + "\n"
                            }
                        else
                           family +"->"+column+ "->"+ new String(value)+"\n"
                        }
                }

}

But this is giving me the following error:
org.apache.spark.SparkException: Task not serializable
  at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:298)
  at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:288)
  at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:108)
  at org.apache.spark.SparkContext.clean(SparkContext.scala:2101)
  at org.apache.spark.rdd.RDD$$anonfun$map$1.apply(RDD.scala:370)
  at org.apache.spark.rdd.RDD$$anonfun$map$1.apply(RDD.scala:369)
  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
  at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
  at org.apache.spark.rdd.RDD.map(RDD.scala:369)
  ... 74 elided
Caused by: java.io.NotSerializableException: org.apache.avro.Schema$RecordSchema
Serialization stack:
    - object not serializable (class: org.apache.avro.Schema$RecordSchema, value: .....

So I want to ask:

*

*Is there any way to make the non-serializable class RecordSchema work with the map function?

*Is my approach right upto this point? I would be glad to know about better approaches to handle this kind of data.

*I read that handling this in a Dataframe would be a lot easier. I  tried to convert the Hadoop RDD so formed into a Dataframe, but again I am running blindly there.

A: As the exception says - the schema is non-serializable. Can you initialize it inside the mapper function? So that it doesn't need to get shipped from the driver to the executors.
Alternatively, you can also create a scala singleton object that contains the schema. You get one scala singleton initialized on each executor, so when you access any member from the singleton, it doesn't need to be serialized & sent across the network. This avoids the unnecessary overhead of re-creating the schema for each and every row in the data.
Just for the purpose of checking that you can read the data fine - you can also convert it to a byte array on the executors, collect it on the driver and do the deserialization (parsing the AVRO data) in the driver code. But this obviously won't scale, it's just to make sure that your data looks good and  to avoid spark-related complications while you're writing your prototype code to extract the data.


text:
Q: Javascript if else vimeo iframe display none Hello awesome coders,
I'm working on a thumbnail grid with expanding view
example here: http://tympanus.net/codrops/2013/03/19/thumbnail-grid-with-expanding-preview/
I have added a video section in the expander which gets his video id by a html5 data-attribute which looks like this in HTML
<div id="test" class="videoPlayer"> iframecode here </div>

Now my problem is that if i haven't defined a video id it will give the me the vimeo error iframe ( the one with Sorry we can't find your video ). And now i'm trying to figure out how to display none that video if that iframe code is present. This is my code ( sorry cant get the > and < to work with me here )

    if ( document.getElementById('test').innerHTML === 'iframe width="560" height="315" frameborder="0" allowfullscreen="" mozallowfullscreen="" webkitallowfullscreen="" src="http://player.vimeo.com/video/?title=0&byline=0&portrait=0" /iframe' ){
    document.getElementById('test').css({display:'none'})
    } else {
    //dosomethingelse
     }

I don't even know if this is possible but this was the closest i could get :S
Thanks in advance!

A: document.getElementById('test').css({display:'none'})

It doesn't exist such property(it is jQuery), you have to do this instead:
document.getElementById('test').style.display = 'none';

On the other hand, your way to check if the iframe exist isn't valid, try this instead:
if (document.getElementById('test').innerHTML.indexOf('http://player.vimeo.com/video/?title=0&byline=0&portrait=0') !== -1)