text:
Q: For all $x$ and some of $y$ Prove that this works for all $x$ and and only some $y$
$$\sqrt{(x-1)^2-(y+2)^2}=0.$$
This is as far as I got so far
Difference of squares:
$\sqrt{(x-1-y-2)(x-1+y+2)}=0$
$\sqrt{x-y-3}\sqrt{x+y+1}=0$
Therefore $x-y-3=0 \implies  y=x-3$
$x+y+1=0$ and $y=-1-x$
I just don't know where to go from here?

A: What you need to show is the following:

For every real number $x$, there exists a real number $y$ such that
  $$\sqrt{(x-1)^2-(y+2)^2}=0,\tag{Eqn}$$

An equivalent way of saying "there exists a real $y$" is to say "for some real $y$". Saying "for some of $y$" brings to mind other things that aren't relevant. For each $x$, you only need to show that there is (at least) one $y$ satisfying (Eqn).
We write "for all x" and "there is y" using the quantifiers $\forall x$ and $\exists y$. In what follows, both variables $x$ and $y$ are assumed to be real numbers.
Let's rewrite what you have to show using quantifiers:
$$
(\forall x)(\exists y)\, \sqrt{(x-1)^2-(y+2)^2}=0,\tag{*}
$$
Clearly (yes?), the following statement implies (*):
$$
(\forall x)(\exists y)\, [(x-1)^2 = (y+2)^2].\tag{**}
$$
So, given $x$, simply take $y=x-3$. Then $x-1 = y+2$, so $(x-1)^2 = (y+2)^2$. This proves (**), which implies (*).

Your question (but not your title) says "only some", so it seems you also want to show the following:

For every real number $x$, there exists a real number $y$ such that
  $$\sqrt{(x-1)^2-(y+2)^2}\ne0,\tag{not-Eqn}$$

This is also straightforward. Given $x$, here's how to find a $y$ such that (not-Eqn) is true:

*

*if $x \ne 1$, let $y=-2$, and

*if $x = 1$, let $y = 0$.

So the second highlighted statement is also true.

A: What you must mean (and it really helps to write it clearly) is that for all $x$ you can find a $y$ that makes the statement true and you can find another $y$ that makes the statement false.  So given an $x$ you can exhibit a $y$ that makes the statement true-just solve for $y$
$$(x-1)^2=(y+2)^2\\y+2=\pm(x-1)\\ y=\begin {cases}x-3\\-1-x \end{cases}$$
Either of these $y$'s will work, which you can show by plugging back in. Now let $y=x-4$, for example, to show that there is at least one $y$ that doesn't work.
Note that if you choose $y$ first, the same thing happens.  For all $y$ there are some $x$ that work and some $x$ that do not work.


text:
Q: How can I make a montage with ImageMagick from images with different size and aspect ratio? I have a lot of images, different sizes and aspect ratios. Is it possible to make a montage of them? I mean to optimally arrange them in rows after I set a common height for the images which build up a common row. Images aspect ratios aren't allowed to modify of course, and none of the images are allowed to omit from the final montage nor duplication.
The height of picture rows in the montage usually aren't equal, but their values should be kept in a minimal range (in statistical sense) or in other words: standard deviation from the mean value of the row heights must be minimized.
Desired width and height of the montage are given (a.)
Or the width and an allowed ratio range (or equivalently height range) is given (b.), for example width must be 1024 pixel, height must be so that w/h < 0.9 and w/h > 0.8
1.) Images must be packed in the montage in their initial fixed order. In this case one must find the images after what a new image row should be started in the montage (easy).
2.) Order of images is allowed to be altered. In this case one must find a permutation which lead to a minimalization of the standard deviation of the final row heights when each image is packed into the montage (hard).
For example:

A: I'm not sure I understand your question correctly.
Here is what I make of it. Assuming you have 8 different images of different sizes. For demo purposes, I'll let ImageMagick create these as 8 different color patches:
convert -size  90x90  xc:yellow  y.png
convert -size 120x120 xc:red     r.png
convert -size  60x210 xc:green   g.png
convert -size 150x180 xc:blue    b.png
convert -size  30x60  xc:cyan    c.png
convert -size 150x90  xc:magenta m.png
convert -size  90x120 xc:gray    Gr.png
convert -size 120x90  xc:black   K.png

You can montage these patches in many different ways:
convert \( y.png r.png g.png  b.png +append \)  \
        \( c.png m.png Gr.png K.png +append \)  \
       -append                                  \
       -mattecolor lightblue                    \
       -frame 1x1                               \
        montage0.png

This command does not scale the different patches. It places them in 2 rows a 4 patches and montages them in their original sizes. The white spaces is where the patches do not "fit":

convert \( y.png r.png g.png  b.png -resize x60 +append \)  \
        \( c.png m.png Gr.png K.png -resize x60 +append \)  \
       -append                                              \
       -mattecolor lightblue                                \
       -frame 1x1                                           \
        montage1.png

This command scales all different patches to a common height of 60 pixels (preserving their respective aspect ratios) and places them in 2 rows a 4 patches:

convert \( y.png r.png g.png  b.png -resize 60x +append \)  \
        \( c.png m.png Gr.png K.png -resize 60x +append \)  \
       -append                                              \
       -mattecolor lightblue                                \
       -frame 1x1                                           \
        montage2.png

This command scales all different patches to a common width of 60 pixels (preserving their respective aspect ratios) and places them in 2 rows a 4 patches:

convert \( y.png r.png g.png  b.png -resize 60x80\! +append \)  \
        \( c.png m.png Gr.png K.png -resize 60x80\! +append \)  \
       -append                                                  \
       -mattecolor lightblue                                    \
       -frame 1x1                                               \
        montage3.png

This command scales all different patches to dimensions of 60x80 pixels (overriding their original aspect ratios) and places them in 2 rows a 4 patches:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spatial analysis in SAS? Is there a way to do spatial analysis (NOT just graphics) in SAS?  What I really want is the ability to geographic queries like one can do in PostGIS or SpatialLite in PROC SQL.
I asked this on the SAS-L list and got nothing.
Thanks!

A: I'm not sure whether your question is specific enough about what you're wanting to do, for someone to give you a good answer.
If you've got lat/long data, you could do detail and aggregate queries by choosing where clause criteria based on the lat/long values.
Incidentally, you might want to check out http://runsubmit.com for another stackoverflow style site with a more concentrated population of sas users.

A: I'm not familiar with PostGIS or SpatialLite, but SAS has some procedures dedicated to GIS specific tasks. This link says

SAS/GIS software enables you to do
  more than simply view your data in its
  spatial context. It also enables you
  to interact with the data by selecting
  features and performing actions that
  are based on your selections.

I don't know if proc sql will be able to easily replicate those features, but once the data is in SAS data sets, I don't see why you couldn't at least do some basic querys.
SAS also has some examples data and code working with spatial data here.

A: The answer seems to be No, SAS doesn't support spatial datatypes and operators like spatialite or postgis.
(I am answering my own question to close the discussion, but thanks to all!)

A: Actually, when you consider that the SQL queries in Spatialite/PostGIS are just being translated into a specific method of calculation. It can actually be done.
So to answer your question, can it be done in SAS in an easy way like spatialite (i.e simple queries?), No
But you could write a function to do what you need using Base SAS, i find SAS to be one of the best languages to use for quick data analysis.


text:
Q: Replace one  with 2 regex I have a string...
$str = 'bob

looked so good
tonight!';

I want to replace any instance where there is only one
 with two.
At the moment I have...
echo preg_replace('/(
\s*){1}/', '

', $str);

But this put's two
 after bob when it should only go after good.
Any help would be great!
Edit: Output should be...
bob

looked so good

tonight!

A: Basically you want a
 tag that is not preceded nor followed immediately by another. Thus:
/(?<!
)
(?!
)/

This assumes that all
 tags are literally
 and not
,
, or even
. for better parsing, you should use a DOM parser and look for BR nodes that are not preceded nor followed immediately by another BR node.

A: This replaces any number (greater than zero) of
 with two:
print preg_replace('|(?:
)+|', '

', $str);

Example:
$str = 'bob

looked so good
tonight!

Bye!';
print preg_replace('|(?:
)+|', '

', $str);
# output: "bob

looked so good

tonight!

Bye!"

A: you're specifying that you want to match one  and replace it with two.
that's not what you want - you want to only add an extra  if that one is not followed by a second one of the same thing?
try
echo preg_replace('/(
\s*){1}([^<])/', '

$1', $str);

this ensures that the  that you are matching is not followed by any other tag before replacing.
note that this wouldn't replace in the case of
bob

though so you may want to be more specific with your ending boundary
condition, as long as you ensure that you add it back to the end you can make the end boundary as complex as you like.


text:
Q: How to set ViewPager tab titles using a string resource instead of hardcoded strings I'm new to Android & stack overflow - so apologies in advance if my question is stupid!
I have a simple app with four tabs using TabLayout/ViewPager and FragmentPagerAdapter. I can get the tab titles to display using hardcoded strings, but when I try to set them using string resources my code is returning the string's index values, instead of the actual strings, as per screenshot:
enter image description here
Here is the code for my FragmentPagerAdapter class:
package com.example.thisi.londonguide;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class AttractionFragPagerAdapter extends FragmentPagerAdapter {

    AttractionFragPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new RestaurantFragment();
        } else if (position == 1) {
            return new MuseumFragment();
        } else if (position == 2) {
            return new ParksFragment();
        } else return new HotelsFragment();
    }

    @Override
    public int getCount() {
        return 4;
    }

    private String[] tabTitles = new String[]{String.valueOf(R.string.tab_title_1),String.valueOf(R.string.tab_title_2),String.valueOf(R.string.tab_title_3),String.valueOf(R.string.tab_title_4)};

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        super.getPageTitle(position);
        return tabTitles[position];
    }
}

Please can someone help me understand where I am going wrong?
Thanks!

A: you must just replace this line
 private String[] tabTitles = new String[]{String.valueOf(R.string.tab_title_1),String.valueOf(R.string.tab_title_2),String.valueOf(R.string.tab_title_3),String.valueOf(R.string.tab_title_4)};

with this line
 private String[] tabTitles = new String[]{getString(R.string.tab_title_1),getString(R.string.tab_title_2),getString(R.string.tab_title_3),getString(R.string.tab_title_4)};

or use
private String[] tabTitles = new String[]{getResources().getString(R.string.tab_title_1),getResources().getString(R.string.tab_title_2),getResources().getString(R.string.tab_title_3),getResources().getString(R.string.tab_title_4)};

getString() need context

A: You can get string from resource value by calling:
getContext().getResources().getString(R.string.page1_title);
and page1_title is the string value in the string.xml file:
title example
here is an example how to to add fragments to a ViewPagerAdapter with title:
private void setupViewPager(final ViewPager viewPager) {
    final ViewPagerAdapter adapter = new viewPagerAdapter(getChildFragmentManager());

        adapter.addFragment(Fragment1.newInstance(), getResources().getString(R.string.tab1_title));
        adapter.addFragment(Fragment2.newInstance(), getResources().getString(R.string.tab2_title));
        adapter.addFragment(Fragment3.newInstance(), getResources().getString(R.string.tab3_title));

    viewPager.setAdapter(adapter);
}


text:
Q: How does the C compiler interpret the following code sequence I have this C code line:
int a;
a = (1, 2, 3);

printf("%d", a);

Why the value 3 is printed? (the last one).

A: The comma operator evaluates all its "members" but returns the value of the last expression.From the C11 standard:

The left operand of a comma operator is evaluated as a void
  expression; there is a sequence point between its evaluation and that
  of the right operand. Then the right operand is evaluated; the result
  has its type and value.


text:
Q: WPF Treeview, Repositories, Hierarchical data and a WPF newbie Let me start off by saying I've not used WPF or Silverlight in anger before, my only ex other than doing a view simple tutorials back in 2009...
What I'm trying to do is display a treeview containing, at the root level a DataStoreType class, and under them they're associated DataStoreEntry classes...but loaded on-demand.
The classes themselves look something like this:
public class DataStoreType
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class DataStoreEntry
{
    public int Id { get; set; }
    public int TypeId { get; set; } // Link back to the parent DataStoreType
    public string Name { get; set; }
    public DateTime Imported { get; set; }
    public DateTime? AvailableFrom { get; set; }
    public string Description { get; set; }
}

The items come from a series of repositories, they're not in any kind of child collection on the objects themselves, so the calls to get them
need to be made on these repositories.
Ideally, I'd like to get to grips with using the MVVM pattern too...but any help/ examples would be greatly appreciated!
Thanks,
Kieron

A: The perfect tutorial/ example for my needs was found here.
http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx
Covered View Models and loading on demand.

A: This is not a full answer, just a hint to get you started.
<TreeView ItemsSource="{Binding DataStoreTypes}">
  <TreeView.Resources>
    <HierarchicalDataTemplate
      DataType="{x:Type DataStoreType}"
      ItemsSource="{Binding Converter={StaticResource TypeToEntriesConverter}}">
      <TextBlock Text="{Binding}"/>
    </HierarchicalDataTemplate>
    <DataTemplate
      DataType="{x:Type DataStoreEntry}">
      <TextBlock Text="{Binding}"/>
    </DataTemplate>
  </TreeView.Resources>
</TreeView>

Now, all you got to do is implement an IValueConverter that convert a DataStoreType to an IEnumerable<DataStoreEntry> an put it in resources under the name TypeToEntriesConverter.


text:
Q: Using graphQL and sequelize find value of previous entries in sorted query relative to parent query Edit:
I have an order with has many items.
The items have one order.
The goal is to have a query that returns previous values for a column of the item as an array with the length of a supplied argument.
So if I have:
{
 orders: [
    {
      orderDate: 1,
      items: [
        {
          itemName: 'Item 1',
          orderAmount: 2,
          itemId: '1a'
        },
        {
          itemName: 'Item 2',
          orderAmount: 7,
          itemId: '1b'
        }
      ]
    },
    {
      orderDate: '2',
      items: [
        {
          itemName: 'Item 1',
          orderAmount: 3,
          itemId: '1a'
        },
        {
          itemName: 'Item 2',
          orderAmount: 6,
          itemId: '1b'
        }
      ]
    },
    {
      orderDate: '3',
      items: [
        {
          itemName: 'Item 1',
          orderAmount: 4,
          itemId: '1a'
        },
        {
          itemName: 'Item 2',
          orderAmount: 5,
          itemId: '1b'
        }
      ]
    }
  ]
}

What I would like is a query that includes returning previousOrders(count:2) to return...
  orderDate: 3,
  items: [
    {
      itemName: 'Item 1',
      orderAmount: 4,
      itemId: '1a'
      previousOrders: [3, 2]
    },
    {
      itemName: 'Item 2',
      orderAmount: 5,
      itemId: '1a'
      previousOrders: [6, 7]
    }

What I currently have working is...
previousOrders: async (item, { count }, { models }) => {
  const previous = await models.Item.findAll({
    attributes: ['id', 'orderAmount'],
    where: {
      itemId: item.itemId
    },
    include: [
      {
        attributes: [],
        model: models.Order
      }
    ],
    order: [[models.Order, 'orderDate', 'desc']],
    raw: true
  })
  const index = previous.findIndex(x => x.id === item.id)
  const sliced = previous.slice(index + 1, index + count + 1)
  const array = sliced.map(a => a.orderAmount)
  while (array.length < count) {
    array.push(0)
  }
  return array

This works but I feel like there is probably a much nicer way to do it with queries and just want to see other potentials.


text:
Q: AOSP / Android 7: How is EGL utilized in detail? I am trying to understand the Android (7) Graphics System from the system integrators point of view. My main focus is the minimum functionality that needs to be provided by libegl.
I understand that surfaceflinger is the main actor in this domain. Surfaceflinger initialized EGL, creates the actual EGL surface and acts as a consumer for buffers (frames) created by the app. The app again is executing the main part of required GLES calls. Obviously, this leads to restrictions as surfaceflinger and apps live in separate processes which is not the typical use case for GLES/EGL.
Things I do not understand:

*

*Do apps on Android 7 always render into EGL_KHR_image buffers which are send to surfaceflinger? This would mean there's always an extra copy step (even when no composition is needed), as far as I understand... Or is there also some kind of optimized fullscreen mode, where apps do directly render into the final EGL surface?

*Which inter-process sharing mechanisms are used here? My guess is that EGL_KHR_image, used with EGL_NATIVE_BUFFER_ANDROID, defines the exact binary format, so that an image object may be created in each process, where the memory is shared via ashmem. Is this already the complete/correct picture or do I miss something here?
I'd guess these are the main points I am lacking confident knowledge about, at the moment. For sure, I have some follow-up questions about this (like, how do gralloc/composition fit into this?), but, in accordance to this platform, I'd like to keep this question as compact as possible. Still, besides the main documentation page, I am missing documentation clearly targeted at system integrators. So further links would be really appreciated.
My current focus are typical use cases which would cover the vast majority of apps compatible with Android 7. If there are corner cases like long deprecated compatibility shims, I'd like to ignore them for now.


text:
Q: Should the .tool-versions file of asdf go into .gitignore? I was wondering what best practice is here? The Elixir version is defined in the mix.exs anyways and different developers might want to use different OTP versions (compatible with the Elixir version) or different minor Elixir versions.
On the other hand it simplifies things and might make bug tracking easier if everyone uses exactly the same version.


text:
Q: need help on jenkins build script my build keeps on failing, in the configuration under build script i have:
if [ ! -d "./.git" ]; then
  git init
  git remote add origin git@github.com:miranetworks/rainbow_code
fi
git fetch -q origin
git reset -q --hard $JANKY_SHA1
if [ -f script/cibuild ]; then
  script/cibuild
else
  bundle install --path vendor/gems --binstubs
  bundle exec rake
fi

i am also building without parameters
the failed build log shows the following:
Started by user helloise smit
Building remotely on i-61a1df04 in workspace /var/lib/jenkins/workspace/rainbow_code
Checkout:rainbow_code / /var/lib/jenkins/workspace/rainbow_code -
 hudson.remoting.Channel@72bbffd:i-61a1df04
Using strategy: Default
Last Built Revision: Revision 9f9d6f94c220a1ae079fded09c4d23d9c1b1801d (origin/HEAD,
origin/master)
Checkout:rainbow_code / /var/lib/jenkins/workspace/rainbow_code -
hudson.remoting.LocalChannel@142b716
Fetching changes from 1 remote Git repository
Fetching upstream changes from git@github.com:miranetworks/rainbow_code.git
Commencing build of Revision 9f9d6f94c220a1ae079fded09c4d23d9c1b1801d (origin/master)
Checking out Revision 9f9d6f94c220a1ae079fded09c4d23d9c1b1801d (origin/master)
[rainbow_code] $ /bin/sh -xe /tmp/hudson1783123371374377301.sh
+ [ ! -d ./.git ]
+ git fetch -q origin
+ git reset -q --hard
+ [ -f script/cibuild ]
+ bundle install --path vendor/gems --binstubs
/tmp/hudson1783123371374377301.sh: 1: bundle: not found
Build step 'Execute shell' marked build as failure
Finished: FAILURE

what does this all mean?
anyone that can help please?
thanks

A: It means that Hudson could not find the bundle command. It looks like it is not part of the path during hudson execution. Try supplying the full path in your script (you can find out where bundle is located with which bundle.

A: This is not a git problem but a bundler problem.

bundle: not found

That means that the bundle commands does not exists in your path.
Maybe you need to install bundler on your platform:
$ gem install bundler

If gem is configured to install into user directory, you need to install bundler for the Jenkins user:
$ su jenkins
$ gem install bundler


text:
Q: Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 56782 python I was trying to link the flutter app with python with API. My python code generated http://127.0.0.1:5000/ URL. When I used this in flutter code it threw the error
Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 56782
I found a solution in this video
Why does this solution work??

A: If you use 127.0.0.1 in your emulator, it will refer to the android emulator not you pc. And because there is no server running on android localhost at port 56782, it will create connection refused error.
In order to target you pc machine, where this emulator is running, you should be using 10.0.2.2. If you are using websocket and server is running on your pc, you can use ws://10.0.2.2 as socket url.


text:
Q: Magento: upgrade pre 1.6 version to most recent one I've seen a lot of questions about pre 1.6 Magento installations to the most recent version (at the current moment 1.7.0.2) but there are a lot of answers that don't work for everybody.
So below the answer to the question:
How to upgrade Magento from a pre 1.6 installation to the most recent one.

A: There are a lot of versions and not all of them are working. This one has worked for me for a lot of versions, as far as 1.3 to 1.7.
Please add comments with solutions to problems you're experiencing, I can update the answer so other people get help from this topic too!
What you need:
- SUDO rights/root account on your server.
- The linux package 'nohub'
- make sure NOBODY can trigger the index.php. If your version supports maintenance.flag, put an empty maintenance.flag file in your Magento root.
Walkthrough
1) Download the latest Magento. Overwrite: ./download/* ./lib/* ./mage
2) Run these steps from you Magento root als SUDOer (if you're not root, put 'sudo' for all the commands)
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod -R 777  ./var
chmod 550 mage

3) Go to your Magento root folder and type:
./mage list-upgrades
./mage config-set preferred_state stable
./mage upgrade-all --force
./mage install http://connect20.magentocommerce.com/community Mage_All_Latest --force

4) Now there is the last step. Note: In some situations this process can take up to 8+ hours!
nohup php -f ./index.php

Known issues
1) it's possible that your update gets in a loop. To find this loop, enable debugging.Edit: /lib/Varien/Db/Adapter/Pdo/Mysql.php (+/- line 112 and 112)
protected $_debug               = true;
protected $_debuglogeverything  = true;

This will write a debug to: /var/debug/[debug_file]
2) Read the file by opening the dir:
cd /var/debug/[debug_file] <-- replace with the actual filename
tail -f [debug_file]

3) If you use debug, the file will get HUGE! Make sure you delete it once in a while.
Tip: as a root user, type:
crontab -e
*/5 * * * * rm /[my_magento_base_folder]/var/debug/[debug_file] <-- add this line

If you want to read the file, add a # to this line and use tail to read it.
These steps help you find common errors and loops (if the tail shows a repeating error message)


text:
Q: Renderizar Iframe google Maps com AngularJs Eu estou montando uma diretiva para renderizar um iframe do google maps dentro da minha app.
E consegui fazer desta forma:
<google-iframe location="item.Location"></google-iframe>

diretiva.js
function googleIframe() {
    var directive = {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            location: '='
        },
        template: '<iframe src="%url%" height="250" width="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" alt="{{location.url}}"></iframe>',
        link: link
    };
    return directive;

    function link(scope, element) {
        var url = [
            'https://www.google.com/maps/embed/v1/place?',
            'key=AIzaSyCBOhDJn9LAUiqONa-y-f1l2JmFEoadkaQ',
            '&q=', scope.location.lat, ',', scope.location.lng,
            '&zoom=', scope.location.zoom
        ];
        element[0].outerHTML = element[0].outerHTML.replace('%url%', url.join(""));
    }

Porém, o que eu gostaria de verdade, é renderizar a url correta em conjunto com a diretiva, ao invés de substituir a url após a renderização da diretiva.
Alguém tem alguma idéia?


text:
Q: Why this query takes so much time on my local server but not in production? So this query takes 11 seconds to execute on my localserver, but in production is almost inmedialy.
I have no clue why
SELECT c.id, c.franquicia_id, f.name, CONCAT(c.name,' ',c.surname)
       contacto, c.created, DATE_FORMAT(c.created,'%d-%m-%Y') fecha
FROM franquicias f, contacts c where f.id = c.franquicia_id
 and c.created = (
                   select max(c2.created)
                   from contacts c2
                   WHERE c2.franquicia_id = c.franquicia_id
                 )
 and f.contract_id=2
ORDER BY created DESC
limit 10

It takes 11 seconds from the code and also tried from phpmyadmin and also takes 11 seconds
EXPLAIN
+----+--------------------+-------+------+----------------------------------+--------------------------+---------+-----------------------------+------+---------------------------------+
| id | select_type        | table | type | possible_keys                    | key                      | key_len | ref                         | rows | Extra                           |
+----+--------------------+-------+------+----------------------------------+--------------------------+---------+-----------------------------+------+---------------------------------+
| 1  | PRIMARY            | f     | ref  | PRIMARY,FK_franquicias_contracts | FK_franquicias_contracts | 5       | const                       | 94   | Using temporary; Using filesort |
+----+--------------------+-------+------+----------------------------------+--------------------------+---------+-----------------------------+------+---------------------------------+
| 1  | PRIMARY            | c     | ref  | FK_contacts_franquicias          | FK_contacts_franquicias  | 4       | admin_panel.f.id            | 73   | Using where                     |
+----+--------------------+-------+------+----------------------------------+--------------------------+---------+-----------------------------+------+---------------------------------+
| 2  | DEPENDENT SUBQUERY | c2    | ref  | FK_contacts_franquicias          | FK_contacts_franquicias  | 4       | admin_panel.c.franquicia_id | 73   | NULL                            |
+----+--------------------+-------+------+----------------------------------+--------------------------+---------+-----------------------------+------+---------------------------------+

The database contacts: has 175.000 rows
the database contracts : has 5 rows
the database franquicias: has 1618
Server : mysql Ver 15.1 Distrib 5.5.37-MariaDB, for Linux (x86_64) using readline 5.1
Server: 1GB RAM, AMD Quadcore
Local : mysql Ver 14.14 Distrib 5.6.17, for Win64 (x86_64)
Local : 16GB RAM I73820


text:
Q: robotframework ValueError: Argument 'arg' got value 'x.y' (x) that cannot be converted to x I have updated my robotframework to v4.1.0.
Now, I get error for on Enums.
I have an python code which contain an Enum like below:
@enum.unique
class x(enum.Enum):
y= 0x00
z= 0x01

and I have an arg in my robot testcase defined as below:
arg = x.y

And I get below error when I run robot testcase
ValueError: Argument 'arg' got value 'x.y' (x) that cannot be converted to x
Could you please let me why the error occurred and what is the solution?

A: I had the same issue when I updated Robot framework from v4.0 to v4.1. I have fixed it by using enum.IntEnum instead of enum.Enum. So, please try to update your example as follows:
@enum.unique
class X(enum.IntEnum):
    y = 0x00
    z = 0x01

Hope that fixes your issue.


text:
Q: Visual Studio 2010 linking errors using VTK I'm having trouble to compile VTK 5.10.1 example code in Visual Studio 2010 on Windows 7 64 bit SP1.
First of all, I installed VTK using this tutorial.
No errors occured while installing VTK and the example executables like cone.exe located at C:\VTK5.10.1_cmake\bin\Release are running just fine.
In Visual Studio 2010 I started a new Win32 console application and tested the first example code from this site.
I edited the projekt properties (additional include directories, additional Library directories and additional dependencies).
The linker errors looked like that:
vtktest.obj : error LNK2019: unresolved external symbol ""public: void __thiscall vtkRenderer::AddActor(class vtkProp *)" (?AddActor@vtkRenderer@@QAEXPAVvtkProp@@@Z)" referenced in function "_main".
Most of the the other people with the same error forgot to add the libs to the additional dependencies.
However I added all libs in the C:\VTK5.10.1_bin\lib\vtk-5.10 directory and the opengl32 library. I tried to seperate the libs by a space, a semicolon and a new line.
Then, I read that people are using the shared libraries. I'm not really familiar with dlls. I reinstalled VTK
with shared libraries options turned on and copied the resulting dlls to the System32 directory.
Now, the errors looks slightly different:
vtktest.obj : error LNK2019: unresolved external symbol ""__declspec(dllimport) public: void __thiscall vtkRenderer::AddActor(class vtkProp *)" (__imp_?AddActor@vtkRenderer@@QAEXPAVvtkProp@@@Z)" referenced in function "_main".
Any help would be appriciated!

A: Nevermind, forgot to change the platform to x64 :/


text:
Q: jQuery, ajax, php, msyql: auto-suggest form input I have a mysql db table that has every U.S. city, state, zip, lat, long. On my site page I have a form input for cities. As the user types, I'd like to suggest city, state. What current practices/techniques are good? (Limitations are jQuery, PHP, MYSQL)
Solution

A: jQuery UI has a nice autocomplete feature.
JQuery UI Autocomplete
It is quite well configurable. You should send the data in JSON format from the server, Autocomplete will mostly handle the rest. Check out the docs.

A: you may want to try a pre-existing plugin such as:
http://code.drewwilson.com/entry/autosuggest-jquery-plugin
Looks like it uses ajax and JSON to get data from your server. All styling is done in CSS too :o)


text:
Q: Calculate count (id) in different period I have the following query that allows me to store start date and date for set of numbers of  months
DECLARE @Month nvarchar(max)
DECLARE @Year int, @startDate as datetime

set @Month = ('5,11,12')
set @Year = 2014

 SELECT  Value , DATEADD(month,Value-1,DATEADD(year,@Year-1900,0)) as t  ,DATEADD(month, ((YEAR(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))) - 1900) * 12) + MONTH(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))), -1)as t1
INTO TempWeek
FROM dbo.SplitString(@Month,',')

I got the following results
Value  t                      t1
5   2014-05-01 00:00:00.000 2014-05-31 00:00:00.000
11  2014-11-01 00:00:00.000 2014-11-30 00:00:00.000
12  2014-12-01 00:00:00.000 2014-12-31 00:00:00.000

I have the following query that I can get count(id)
SELECT count(DISTINCT ID)
 FROM
  test EF
  WHERE cond BETWEEN '2014-01-01 00:00:00' AND '2014-01-31 00:00:00'

My problem is how can I combine the both queries in order to reapeat the treatment above for each t and t1 stored in TempWeek ?

A: If I understand correctly, you can do a join and group by:
SELECT tempweek.t, tempweek.t1, count(DISTINCT ID)
FROM (SELECT Value, DATEADD(month,Value-1,DATEADD(year,@Year-1900,0)) as t,
            DATEADD(month, ((YEAR(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))) - 1900) * 12) + MONTH(DATEADD(month, Value-1,DATEADD(year, @Year-1900,0))), -1) as t1
      FROM dbo.SplitString(@Month, ',')
     ) tempweek left join
     test EF
     on cond BETWEEN tempweek.t AND tempweek.t1
GROUP BY tempweek.t, tempweek.t1;

A: I think you can wrap your first query in a common table expression like this:
;WITH cte AS (
    SELECT
      Value,
      DATEADD(month,Value-1,DATEADD(year,@Year-1900,0)) as t,
      DATEADD(month, ((YEAR(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))) - 1900) * 12) + MONTH(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))), -1)as t1
    FROM dbo.SplitString(@Month,',')
)
SELECT T, T1, COUNT(DISTINCT ID)
FROM test EF, cte
WHERE cond BETWEEN t AND t1
GROUP BY T, T1


text:
Q: How to find all records that have a duplicate based on a column I'm trying to construct a query in LINQ/Entity Framework that will return all rows that have a duplicate based on one column. However, I don't want to group them, I actually want to get all the rows that have the duplicate.
name age
---- ---
john 15
john 16
jack 20
jill 26
sam  10
sam  12

How can I get a list of rows that have duplicates based on the name column? This is the resultset I'm expecting:
name age
---- ---
john 15
john 16
sam  10
sam  12

I tried something like this, but I think this will give me a grouped result I think:
var duplicates = Shop.GroupBy(r => r.Name)
                     .Where(x => x.Count() > 1)
                     .Select(val => val.Key);

A: Use SelectMany:
var duplicates = Shop.GroupBy(r => r.Name)
                     .Where(x => x.Count() > 1)
                     .SelectMany(g=> g);

It will help you to flatten the result of each group that have more than one element in just one collection


text:
Q: Unix time difference in minutes gives unexpected results I have the following simple code for testing:
$start_time_unix = time();
$end_time_unix = time();
$seconds_diff = $end_time_unix - $start_time_unix;
$duration = round(abs($seconds_diff/1000) / 60,2);

When i store it in MySQL (int), the results are big values like 25634 even for a few seconds. How can i get the minutes, even in fraction of minutes?? What is wrong with my code above ??

A: First of all int cannot store fractions, so you will probably want to use float or double instead.
But why are you dividing by 1000. $seconds_diff consists of a seconds, so dividing by 60 will give you fraction of a minute.
For example: If $seconds_diff is a value of 13 [seconds]:
$duration_in_minutes = round($seconds_diff / 60, 2);
$duration_in_milliseconds = $seconds_diff * 1000;

If it is your goal to use milliseconds then use microtime() instead of time():
http://php.net/manual/de/function.microtime.php
Recommendation
Just measure the time with microtime() and directly store the result in the database without rounding, dividing or formatting. Then later on, do the formatting when you have to output it. This will give you more precise results and more freedom.
$start_time = microtime();
…
$end_time = microtime();
$duration = $end_time - $start_time; // duration in milliseconds --> save to database

When outputting, for example:
$duration = get_duration_from_database(); // pseudo function
printf('%.2f minutes', $duration / 1000 / 60);

A: The time() function returns the current Unix timestamp in seconds. There is no need to divide it by 1000. Since MySQL is expecting an integer, you must round to 0 decimal places:
$seconds_diff = abs($end_time_unix - $start_time_unix);
$duration = round($seconds_diff / 60, 0);


text:
Q: JComboBoxes - Using setModel to access Objects (in Swing) Quick background, I am using Netbeans to develop this (I don't have much experience with Swing and have lost points on experience at the chance to gain development speed).
In Netbeans it is obviously restrictive as to what code you can modify to stop novice users breaking the code (which I have already amusingly done once)
Anyway, I have a class of Objects, these Objects have a name property. Within the application I have directly initialised an array of these objects and called them "things";
Objects[] things = new Objects[2];
things[0] = new Objects("The first thing");
things[1] = new Objects("The second thing");

The contents and names are deliberately inane as this is a test to get this working (rather than pulling apart a part written program).
After some research and reading I have discovered that I "should" be able to load objects into the setModel parameter using the following code;
    new javax.swing.DefaultComboBoxModel(things[].name)
//The above is the code to use within setModel, the below is the completed example
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(things[].name));

This hasn't worked, and despite my best efforts to google this seems to be too specific to nail down a decent answer. The end result is that I would like to have;
"The first thing" and "The second thing" displayed within the drop down list, and then obviously I can expand on this within the real program by referencing any other data held in that object on the screen.
Any suggestions or even pointers to help me think this out would be appreciated.

A: First of all, the constructor of the DefaultComboBoxModel can take an array, but the property name does not exist in an array so you cannot do that. You would have to modify your objects or the combobox to show the correct property of your object.
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(things[]));

You have several options :)

*

*The quick and easy override toString to return name (assuming Objects is your class)

*Create a wrapper class (ObjectsWrapper) that in its toString() method returns Objects name

*Modify the JComboBox in some way, either the model or the renderer to show the desired property

A: Wouldn't just implementing a toString() on your objects to return their .name property work with the default Combo Box model?
See the similar question: Java Swing: Extend DefaultComboBoxModel and override methods


text:
Q: How to "send" python function to javascript in htm I have FastAPI app, with jinja2 templates. I wish to send a python function to one of my teplate,
i render template this way return templates.TemplateResponse('index.html', context={"request": request, "func":func}) in index.html I'd like to use this function in javascript as onclick event, so when the user clicks the button python will do smth also with yield in order to show progress on javascript progressbar, but var func = {{ func }} doesn't work. So how can I send my python function to javascript in html (probably using jinja2 in some way)


text:
Q: Datagridview with date-header I have a datagridview with appointment information. There are four columns Name, Appointment Type, Appointment Date, Appointment Time. I need to find the day of any appointment and display a header for each day with the day and date with. It would look like this:
**Monday 07/03/2016**
Amy      New     13:00
**Tuesday 08/03/2016**
Betty    Second  14:30
Sally    New     16:00

A: You can only have one headerline in a DataGridView.
I would suggest highlighting (or better darklight) the DateRows in your DataGrid.
Here is a quick sample how this would look like:

What did I do:
First I added a Class which describes your Data.
public class Entry
{
    public DateTime DateTime { get; set; } //Combine the Date and the Time
    public string AppointmentType { get; set; }
    public string Name { get; set;  }

    public override string ToString()
    {
        return Name + " " + AppointmentType + " " + DateTime.ToString("dd.MM.yyyy HH:mm:ss");
    }
}

Then I created a List for debugging:
        List<Entry> entries = new List<Entry>(); //This is your Input

        entries.Add(new Entry()
        {
            Name = "Betty",
            AppointmentType = "New",
            DateTime = DateTime.Now.AddDays(-1)
        });

        entries.Add(new Entry()
        {
            Name = "Sally",
            AppointmentType = "New",
            DateTime = DateTime.Now
        });

        entries.Add(new Entry()
        {
            Name = "Amy",
            AppointmentType = "New",
            DateTime = DateTime.Now.AddHours(-15)
        });

You might get your Data from elsewhere...
Then parse it to a List<Entry>.
Then I sorted the Data:
entries.Sort(new Comparison<Entry>((x, y) => DateTime.Compare(x.DateTime, y.DateTime))); -- Ascending

entries.Sort(new Comparison<Entry>((x, y) => -DateTime.Compare(x.DateTime, y.DateTime))); --Descending

Then group 'em by Date:
        List<Entry> newList = new List<Entry>();
        //Now adding the new "headers"
        for (int i = 0; i < entries.Count; i++)
        {
            DateTime dateOfAppointment = (DateTime)entries[i].DateTime;
            if (i > 0)
            {
                if (dateOfAppointment.Date != entries[i - 1].DateTime.Date)//Not the same Date as the previous one => Add new Header with Date
                {
                    newList.Add(new Entry() {DateTime = dateOfAppointment});
                }
            }
            //Else: we add the entry under the current date cause its still the same...
            newList.Add(entries[i]);//Add Entry
        }

Last but not least fill your DataGridView:
//Fill the Grid
        for (int i = 0; i < newList.Count; i++)
        {
            dataGridView1.Rows.Add(new DataGridViewRow());

            dataGridView1.Rows[i].Cells[2].Value = newList[i].DateTime.ToString("dd.MM.yyyy");

             if (!string.IsNullOrEmpty(newList[i].Name)) //=> Is not a Header
            {
                dataGridView1.Rows[i].Cells[2].Value = newList[i].DateTime.ToString("dd.MM.yyyy");
                dataGridView1.Rows[i].Cells[0].Value = newList[i].Name;
                dataGridView1.Rows[i].Cells[1].Value = newList[i].AppointmentType;
                dataGridView1.Rows[i].Cells[3].Value = newList[i].DateTime.ToString("HH:mm:ss");
            }
            else
            {
                dataGridView1.Rows[i].Cells[2].Value = newList[i].DateTime.ToString("dddd dd.MM.yyyy", new CultureInfo("en-GB"));
                dataGridView1.Rows[i].Cells[0].Value = newList[i].Name = null;
                dataGridView1.Rows[i].Cells[1].Value = newList[i].AppointmentType = null;
                dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Gray;
            }
        }


text:
Q: Execute a included exe with C# Since I'm not able to know why my clickOnce application is not able to verify If the prerequisite is already installed on the Target PC https://stackoverflow.com/questions/24614637/prerequisite-visual-studio-2012.
I'm wondering if I can include the Redistribuable Visual C++ pour Visual Studio 2012 Update 4 (vcredist_x86.exe) into my application and at Run time I`ll check if the product is installed with the ProductCode and than Execute the vcredist_x86.exe
Do you think that it's a good way to do ?
Thanks

A: I would suggest just including the necessary DLLs which are part of the required VC Redistributable version in your application's installation folder. If your app is linked to one of those DLLs it will be default search the current working directory of the application for it first before looking in the standard installation directory in C:\Windows\...


text:
Q: get last 6 characters of a match (javascript regex) I am trying to parse txt files with js + regex and my problem is as follows:
I have multiple txt files, and inside each one I need to search for an Id, made by 6 characters (numb + letters)
this is the string inside one of those files:
**IFCPROPERTYSINGLEVALUE('codice sito',$,IFCTEXT('I013FR'),$);**

I need to extract the I013FR only, and so far the closest js-regex I wrote is:
(codice sito',\$,IFCTEXT\('[a-zA-Z\d]{6})

using that, I get in return:
codice sito',$,IFCTEXT('I372TO

now I need to "add something" at the end of the regex, in order to only take the last 6 characters from the match.
Is that possible? am I on the right way? or maybe there is another better way to do that?

A: To extract the sequence of symbols, you need to put it in parenthesis. This pattern is called a "capturing group". Read more
/codice sito',\$,IFCTEXT\('([a-zA-Z\d]{6})/g

And then you can get your id using RegExp.exec() method.
const str = "**IFCPROPERTYSINGLEVALUE('codice sito',$,IFCTEXT('I013FR'),$);**";
const regex = /codice sito',\$,IFCTEXT\('([a-zA-Z\d]{6})/g;

const id = regex.exec(str)[1];


text:
Q: white pixels cluster extraction I am working on a fingerprint pore extraction project and stuck at the last stage of pore (white pixels clusters) extraction..I am having two output images from which we will get the pores but don't know how to do it..also the two images are of different size..image1 of size 240*320 and image2 is of size 230*310 ..here are my images..
           image 1 (240*320)                         image2 (230*310)

here is what i am doing to extract white clusters of pores..
for i = 1:230
    for j = 1:310
        if image1(i,j)==1 && image2(i,j)==1
            result(i,j)=1;
        else
            result(i,j)= 0;
        end;
    end;
end;
figure(4);imshow(result,[]);

here are my output
      output (230*310)            expected (different than input image)

image 3 (output) shows the resultant image from above code ..these errors are may be due to difference in size of two images i think...so what should i do to get the pores(white clusters)..Note that fourth image (expected) is different than the input images just to show you what should be the output look like...thanks in advance..

A: I have done this "type" of feature extraction before.  Normally how I have seen it done (and I was somewhat the inventor of this process at a company I worked for in the past) was:
1D Blob detection:

*

*Move through each row pixel by pixel from left to right (or from right to left)

*if you move from a black pixel to a pixel right of it where you transition into your definition of white  (as set by a threshold), then mark that point

*from a black to white transition, you now concentrate your search for a white to black transition

*when white to black is found, pair the black to white transition boundary and white to black transition boundary into (what I call) a "1D blob" and store in a list of 1D Blobs

2D Blob correlation:

*

*After you now have your list of 1D Blobs, you need to correlate the 1D Blobs into 2D blobs by looking for ones that are adjacent

You CAN define a boundary many different ways:

*

*Binary decision of whether a pixel is above or below threshold value (easiest, and fastest)

*bottom, mid, or top point of transition, where the transition could be slow from black-to-white / white-to-black or fast (this is called transient response), also known as the slope that you are looking for

In your case it LOOKS as if your images are truly binary (black and white without gray shades), so binary thresholding will work just fine.


text:
Q: Counting the Frequency of three words I have the code below to find the frequencies of two word phrases. I need to do the same for three word phrases.
However the code below does not seem to work for 3 word phrases.
from collections import Counter
import re

sentence = "I love TV show makes me happy, I love also comedy show makes me feel like flying"
words = re.findall(r'\w+', sentence)
two_words = [' '.join(ws) for ws in zip(words, words[1:])]
wordscount = {w:f for w, f in Counter(two_words).most_common() if f > 1}
wordscount
{'show makes': 2, 'makes me': 2, 'I love': 2}

A: I suggest factoring the functionality out to a seperate function:
def nwise(iterable, n):
    """
    Iterate over n-grams of an iterable.
    Has a bit of an overhead compared to pairwise (although only during
    initialization), so the two functions are implemented independently.
    """
    iterables = [iter(iterable) for _ in range(n)]
    for index, it in enumerate(iterables):
        for _ in range(index):
            next(it)
    yield from zip(*iterables)

Then you can do
two_words = [" ".join(bigram) for bigram in nwise(words, 2))]

and
three_words = [" ".join(trigram) for trigram in nwise(words, 3))]

and so on.
You can then use collections.Counter on top of that:
three_word_counts = Counter(" ".join(trigram) for trigram in nwise(words, 3))

A: You can use collections.Counter on an iterable of 3-word groupings. The latter is constructed via a generator comprehension and list slicing.
from collections import Counter

three_words = (words[i:i+3] for i in range(len(words)-2))
counts = Counter(map(tuple, three_words))
wordscount = {' '.join(word): freq for word, freq in counts.items() if freq > 1}

print(wordscount)

{'show makes me': 2}

Notice we don't use str.join until the very end to avoid unnecessary repeated string operations. In addition, tuple conversion is required for Counter as dict keys must be hashable.

A: Try zip(words, words[1:], words[2:])
Ex:
from collections import Counter
import re

sentence = "I love TV show makes me happy, I love also comedy show makes me feel like flying"
words = re.findall(r'\w+', sentence)

three_words = [' '.join(ws) for ws in zip(words, words[1:], words[2:])]
wordscount = {w:f for w, f in Counter(three_words).most_common() if f > 1}
print( wordscount )

Output:
{'show makes me': 2}

A: What about:
from collections import Counter

sentence = "I love TV show makes me happy, I love also comedy show makes me feel like flying"
words = sentence.split()
r = Counter([' '.join(words[i:i+3]) for i in range(len(words)-3)])

>>> r.most_common()[0] #get the most common 3-words
('show makes me', 2)


text:
Q: Define Name with Global Scope but Local Reference I have an Excel project with multiple datasheets. I want to define a name for a cell that can be used in all sheets within the project, but keep the referenced cell local.
For example, say in datasheet Burton I have a cell O16 that I want to name Total_Production. I would first define a name with the following properties:
Now in datasheet Middlefield I want to use that same defined name Total_Production but have it reference the Middlefield O16 cell. However, when I use that name, the cell being referenced is from the Burton datasheet.
How can I define a name that has global scope but refers to a local cell?
I have already tried modifying the Refers to: field to =$O$16 or =Workbook!$O$16 but neither seem to function how I would have expected.
I plan to use this with many many more datasheets, but I gave 2 sheets for explanatory purposes.
Thanks for your time.


text:
Q: How to catch "org.springframework.web.multipart.MultipartException" in Grails 3 I'm having an awfully hard time catching the error: org.springframework.web.multipart.MultipartException
I have the following code:
final class UploadTextCommand  {
   MultipartFile contents
   static constraints = {
   }
}

Additionally to handle the post of the file I have this action:
def upload = { UploadTextCommand ->
   ...code...
}

I've got these settings in the "application.yml" file to force the error:
controllers:
    upload:
        maxFileSize: 100
        maxRequestSize: 100

So I can reliably recreate the exception, but I can't catch it before the browser shows a horrible view:
HTTP Status 500 - Request processing failed;
nested exception is org.springframework.web.multipart.MultipartException

Please tell me how to catch this error in Grails. Just using a try/catch in the upload action fails miserably.
Added stack trace on request of commenter:
javax.servlet.ServletException: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (318635) exceeds the configured maximum (100000)
grails.plugin.cache.web.filter.AbstractFilter.logThrowable(AbstractFilter.java:116)
grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:70)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:73)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:113)
org.springframework.boot.context.web.ErrorPageFilter.forwardToErrorPage(ErrorPageFilter.java:188)
org.springframework.boot.context.web.ErrorPageFilter.handleException(ErrorPageFilter.java:171)
org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:135)
org.springframework.boot.context.web.ErrorPageFilter.access$000(ErrorPageFilter.java:61)
org.springframework.boot.context.web.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:95)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:113)

A: You can find in a stacktrace:

the request was rejected because its size (318635) exceeds the
  configured maximum (100000)

and in your code:
controllers:
    upload:
        maxFileSize: 100
        maxRequestSize: 100

you should exceed maxFileSize, but if you want to handle exception check this solution. IMHO cleaner solution would be implementation of your own before filter or interceptor.


text:
Q: Prove that for every positive rational number $r$ where $r^2<2$, there must be another rational number $r+h$, such that $(r+h)^2<2$ Question
Prove that for every positive rational number $r$ satisfying the condition $r^2<2$ one can always find a larger rational number $r+h$ ($h>0$) for which $(r+h)^2<2$.
The book's solution
We may assume $h<1$.
Then $h^2<h$ and $(r+h)^2<r^2+2rh+h$.
That is why it is sufficient to put $r^2+2rh+h = 2$, i.e., $h = \frac{2-r^2}{2r+1}$.
Note: As Ben in the comment section pointed out, this solution is wrong .
For example, when $r=\frac{1}{10}$, the value of h comes out to be $\frac{199}{120}$ and thus contradicts the assumption $h<1$.
My attempt
We have been given the following information:-
$$r \in Q$$
$$r > 0$$
$$r^2<2$$
Let us first use the third piece of information to find the interval in which $r$ lies:-
$$r^2<2$$
$$r^2-2>0$$
$$(r-\sqrt2)(r+\sqrt2)<0$$

We can see that the value of the product is negative only in the interval between $-\sqrt2$ and $\sqrt2$.
But also $r$ is positive, therefore we get
$$r \in (0,\sqrt2)$$
Now we have to prove that for every $r$, there exists a larger rational number $r+h$ which is bound by the following conditions:-
$$(r+h)\in Q$$
$$(r+h) > 0$$
$$(r+h)^2 < 2$$
Again we can figure out the following:-
$$ (r+h) \in (0,\sqrt2)$$
So for every positive rational number $r$ which satisfies the condition $r^2<2$, we can always find a larger number $r+h$ in the interval $(0,\sqrt2)$ that satisfies the condition $(r+h)^2<2$. This is because there are an infinite number of positive rational numbers in the interval $(0,\sqrt2)$, just like there are an infinite number of natural numbers.
Do you think this solution is right?

A: You can not assume that there exists a real number that you refer to as $\sqrt 2$.  Namely you have no reason to presume that there exists a real number, $x$ so that $x^2 = 2$.  That is precisely what this proof is supposed to establish.
If we know what irrational real numbers are, and if we know that $\sqrt 2$ actually exists, then this exercise simply follows by definitions.  To be a real number, by definition, $\sqrt{2}$ is a least upper bound of a sequence of rational numbers all less than $\sqrt{2}$.  So if any rational number, $r < \sqrt{2} = $ least upper bound of rational numbers less than $\sqrt{2}$ then there must be, by definition of least upper bound, a rational number $q$ (and $h= q-r$) so that $r < q=r+h \le \sqrt 2$.  And as there is no rational number $q$ so that $q^2 = 2$ we know that $r < q=r+h < \sqrt 2$.
There was nothing to prove.  It all followed by definition.
This exercise usually comes before the definition of the real numbers as an exercise to introduce the idea of a least upper bound.  For any rational $r$ so that $r^2 < 2$, we must show that we can "get closer" to the idea of the square root of $2$ by finding a larger rational $q$ so that $r < q$ and $q^2 < 2$.
The book answer makes a few unstated assumptions (well, actually only one very obvious assumption) but it is correct (although it doesn't explicitly spell it out so it is hard to see).  But here it is with more and correct details.
Preliminary:  For any $0 < p < q$ it is true that $0< p^2 < q^2$.  This is because $p< q$ and $p > 0$ so $p*p < q*p$.  And $q > 0$ and $p < q$ we know that $p*q < q*q$ and so $p^2 < p*q < q^2$.
We can assume $r \ge 1$ because $1^2 = 1 < 2$. so if $r < 1$ we are done by letting $r+h = 1$.  But we need to prove this is true for ALL rational $r$ where $r^2 < 2$.
So if $r \ge 1$ and IF such an $h$ exist we can assume $h < 1$.  Because if $h \ge 1$ then $(r + h)^2 = r^2 + 2rh + h^2 \ge 1 + 2*1*1 + 1^2 = 4 > 2$.
Now we can do what your book does.  .... Let's see; what does your book do?....
Let $h = \frac {2 - r^2}{2r + 1}$.  We must prove that 1) $h> 0$ (and therefore $r < r+h$) 2) that $h$ is rational,  and 3)that $(r+h)^2 < 2$.
1)Well $r^2 < 2$ so $2 -r^2 > 0$ and if we assume $r > 0$ we know $2r + 1 > 0$, so we have $h > 0$.
2) As $r$ is rational, so is $r^2, 2 -r^2, 2r+1$ and therefore $h =\frac {2-r^2}{2r+1}$ is rational.
And 3) is the real meat:
And as $r^2 \ge 1$ then $2-r^2 < 1$ and as $2r + 1 > 1$ we know that $h < 1$ and so $h^2 < 1$.
So
And $(r + h)^2 = r^2 + 2rh + h^2$
$ < r^2 + 2rh + h$
$ = r^2 + h(2r + 1) $
$ = r^2 + \frac {2-r^2}{2r+1}(2r+1)$
$= r^2 + 2 - r^2 = 2$.
And that completes the proof.
If $r < 1 $ then $h = 1 -r$ and $r+h = 1$ is one such rational rational number we want. (There are of course others.)
And if $r \ge 1$ and $r^2 < 2$ then $h =\frac {2-r^2}{2r+1}$ is one positive rational $h$ that we want so that $(r + h)^2 < 2$.
....
Now from there we know that we can create an infinite string of rational numbers  $r < r+h =r_1 < r_q + h_1 = r_2 < r_3 < r_4 < ......... $ all so that $r^2  < r_1^2 < r_2^2 < r_3^2 < r_4^2 < ...... < 2$.
And once we define that the real numbers have the least upper bound property, we will know that some irrational real number, $x$,  is the least upper bound of $r_i$.  And we will be able to prove that $x^2 = ($ least upper bound $r_i)^2 = 2$.  Thus THEN we will have proven that $\sqrt 2$ exists.


text:
Q: sql query group by one in join I've a couple of tables:
--> task: task_id, status, datetime, code
--> task_action: action_id, task_id, action_type, action_details, action_datetime

And I've an action_type:  ASSIGNED which has this JSON as its action_type : {"assigned_to": "some_email_id"}
So what I want are all the tasks with all columns which have status in task table as: PROCESSING
and there corresponding action_type is ASSIGNED with latest datetime, (A task can have multiple ASSIGNED action_type)
and assigned_to email id is queried with.
only the latest ASSIGNED action_type should be matched with given email id in assigned_to
This is one of the queries I tried with:
select task_action.task_id
     , max(action_datetime) as dt
     , action_details
as adt
  FROM task_action
  JOIN task
    on task.task_id = task_action.task_id
 WHERE action_type = 'ASSIGNED'
   and task.status = 'PROCESSING'
   and JSON_VALUE(adt, '$.assigned_to') = 'someEmail'
 GROUP
    BY task_id

Obviously, this does not work..I guess there is something minor am missing.

A: In MySQL 5.7, you can use this:
WHERE ... adt->>'$.assigned_to' = 'someEmail'

If you just use -> then the value has literal double-quotes. Use ->> to get the bare value.
Read https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html for more details.

A: The problem is that you are searching for a row in task_action with maximum datetime, not just the maximum value. That is a bit more complicated to express in SQL. You can search for a task_action where no other task_action with a greater datetime exists:
WITH assigned_action as (
  select
    task_id,
    action_datetime,
    action_details
  from
    task_action
  where
    action_type='ASSIGNED' and
    JSON_VALUE(action_details, '$.assigned_to')='someEmail'
)

SELECT
   t.task_id,
   a.action_datetime as dt,
   a.action_details as adt
FROM
  task t inner join (
    select *
    from
      assigned_action a1
    where not exists (
      select *
      from assigned_action a2
      where
        a2.action_datetime > a1.action_datetime and
        a2.task_id = a1.task_id
    )
  ) a on t.task_id = a.task_id
WHERE
  t.status='PROCESSING'


text:
Q: why ToDoubleBiFunction doesn't extend BiFunction I wonder why ToDoubleBiFunction doesn't extend BiFunction. Just how I did:
import java.util.function.BiFunction;

public class Test {
  public static void main(String[] args) {
    MyToDoubleBiFunction<Integer, Integer> f = (a, b) -> a.doubleValue() + b.doubleValue();
    System.out.println(f.apply(1, 2));
  }
}

@FunctionalInterface
interface MyToDoubleBiFunction<T, U> extends BiFunction<T, U, Double> {
}

This code works and prints 3.0.
Also what is the point of using wordy applyAsDouble method instead of well-known apply?

A: The point of specific versions of BiFunction such as ToDoubleBiFunction is to avoid auto(un)boxing - in this case, autoboxing / -unboxing a primitive double value to / from a java.lang.Double object.
If ToDoubleBiFunction would extend BiFunction<T, U, Double> then you'd have auto(un)boxing.
Note that you cannot use primitive types as type arguments in Java, so BiFunction<T, U, double> (note that double is the primitive type here) is not possible.


text:
Q: How to call at JSF elements registered java script methods by using JQuery? I have some selectBooleanCheckbox elements in my jsf page. All elements have a javaScript function, which is bind at the attribute "onchange":
<h:selectBooleanCheckbox value="#{bean.value_1}" onchange="updating(this, '#{textprop.value_1}', '#specific_html_dom_element');"/>

In addition, i have createt a functionality with JQuery to select all availabe selectBooleanCheckboxes in the xhtml jsf page.
JQuery code for select checkboxes:
jQuery('.class_1').find('input[type="checkbox"]').each(function() {
    jQuery(this).attr("checked","checked").val("1");
});

JQuery code for deselect checkboxes:
jQuery('.class_1').find('input[type="checkbox"]').each(function() {
    jQuery(this).attr("checked","").val("0");
});

The current problem is, that the java script method "updating" won´t be executed, if the JQuery functionality is executed. If i select or deselect a single selectBooleanCheckbox, the javascript method will be executed. The updating method get different parameter values for each checkbox.
How can i solve this problem?

A: onchange only fires when the user check/uncheck.
You can manually call the onchange event, after setting the value:
jQuery('.class_1').find('input[type="checkbox"]').each(function() {
   jQuery(this).attr("checked","checked").val("1");
   jQuery(this).change();// manual call
});

or you can trigger the event using:
jQuery('.class_1').find('input[type="checkbox"]').each(function() {
   jQuery(this).attr("checked","checked").val("1");
   jQuery(this).trigger("change");
});

Hope this helps.


text:
Q: Disable 'Prices' appearing in Magento How do I disable ALL Prices being shown on the public end of Magento?
I basically want to allow my customer to add products to their cart but for the item prices/totals etc to be invisible.
Many thanks for any pointers

A: Either remove the template code which renders the price or simply add a css class and hide it using styling!
You should do that in your catalog/navigation, catalog/product/view, checkout/cart, sales/order/view, in checkout/review, etc...

A: Hide price-box class from css it will help you

A: A css (partial ?) solution to play around:
.price-box .price{
    display: none;
}
.price-box:after {
    content: '-'; /*contact us for price*/
}
.cart-price .price {
    display: none;
}
.cart-price:after {
    content: '-';
}
.cart-table-totals {
    display: none;
}
label[for=s_method_flatrate_flatrate] {
    display: none;
}
#checkout-review-table tfoot {
    display: none;
}
#shipping_method-progress-opcheckout .price {
    display: none;
}

A: EDIT here is a free module that will do this for you: http://www.magentocommerce.com/magento-connect/red2black-hideprices.html
I am not sure how advanced or not you are but this could be done as a module. You would add an attribute to the product, and based on whether it is true or no you would hide the pricing in the relevant templates.
Here is a detailed thread on how to do this:
http://www.magentocommerce.com/boards/viewthread/22673/
If you are in the mood to spend a few $$ you could buy this module:
http://www.magentocommerce.com/magento-connect/bolasevich/extension/2096/hide-product-price-for-non-registered-users
Or if you are in the mood to spend tons of money you could buy this one:
http://www.magentocommerce.com/magento-connect/Cart2Quote/extension/5905/not2order_hide_price_disable_ordering

A: This post was very useful for me:
http://www.magentocommerce.com/boards/viewreply/87901/
hiding price:
app/design/frontend/default/default/template/catalog/product/price.phtml
insert at the very beggining of the file:
<?php if (Mage::getSingleton('customer/session')->isLoggedIn()) { ?>

insert at the very end of the file
<?php } ?>


text:
Q: How can I disable mouse movement of a PyQtGraph legend? I'm creating a simple PyQtGraph plot with a legend, and I'd like to disable all interactivity.
I'm able to disable panning and zooming as well as the right-click context menu, but the legend can still be moved. How can I prevent the user from dragging the legend around with the mouse?
import pyqtgraph as pg

widget = pg.plot()

# Disable interactivity
widget.setMouseEnabled(x=False, y=False)  # Disable mouse panning & zooming
widget.hideButtons()  # Disable corner auto-scale button
widget.getPlotItem().setMenuEnabled(False)  # Disable right-click context menu

widget.addLegend(enableMouse=False)  # This doesn't disable legend interaction
widget.plot([1, 3, 2, 5, 4], name="Example plot")

if __name__ == "__main__":
    pg.exec()

A: Legend itself implements two mouse events: mouseDragEvent and hoverEvent. To disable it, you can simply override it with lambda function, that does nothing.
Also, you might want to disable hide / show functionality of legend. This can be done by overriding legend.sampleType.mouseClickEvent.
Here is modified code you can use. I left legend.sampleType.mouseClickEvent commented out:
import pyqtgraph as pg

widget = pg.plot()

# Disable interactivity
widget.setMouseEnabled(x=False, y=False)  # Disable mouse panning & zooming
widget.hideButtons()  # Disable corner auto-scale button
widget.getPlotItem().setMenuEnabled(False)  # Disable right-click context menu

legend = widget.addLegend()  # This doesn't disable legend interaction
# Override both methods responsible for mouse events
legend.mouseDragEvent = lambda *args, **kwargs: None
legend.hoverEvent = lambda *args, **kwargs: None
# Uncomment if you want to disable show / hide event of legend click
# legend.sampleType.mouseClickEvent = lambda *args, **kwargs: None

widget.plot([1, 3, 2, 5, 4], name="Example plot")

if __name__ == "__main__":
    pg.exec()


text:
Q: Problems with twitter bootstrap scroll-spy What is wrong with this code  jsFiddle.
I have done everything that the example said, tried $('#navbar').scrollspy() but still no success.
Please Explain my problem and point me to a solution.
Thank you!
Updated fiddle

A: The ScrollSpy object needs to be attached to the element which triggers scroll events.  In your current markup, that element would actually be the <body> not the <table> element.
Try removing the data-spy="scroll" data-target=".nav" attributes from the table, and adding them to the <body> instead.
Otherwise, if you want the <table> to originate scroll events, it needs to have a scroll bar, i.e. fixed height and overflow: auto (which is how the Bootstrap Documentation Scrollspy example does it).

Update
If you are placing the form in a modal, the element with the class modal-body is going to be the one which triggers scroll events.  Attach the Scrollspy object to it.


text:
Q: Error while loading larger files with setContent(&file) at a qt DOM xml Parser I'm running into a strange problem which i cannot solve. It seems nobody has this problem. While loading a small XML file (4mb) everything ist fine and the programm runs normal, but when i'm trying to load a larger file (200mb) the programm crashes without any error (even in debug mode). It also does not print out the error messages since the programm crashes before their call. Thanks for helping.
Errorlog from the QT creator is:

The program has unexpectedly finished.
  C:/Parser [path]/XmlDOM crashed

Code:
QFile file("./file.osm");
qDebug() << file.exists();
qDebug() << file.size();

QString errorStr;
int errorLine;
int errorColumn;

QDomDocument document;

if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
    qDebug() << "Failed to open file";
    return -1;
}
else
{
    if(!document.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) //here the programm crashes
    {
        std::cerr << "Error: Parse error at line " << errorLine << ", "
                          << "column " << errorColumn << ": "
                          << qPrintable(errorStr) << std::endl;
       return -1;
    }
    qDebug() << file.isReadable(); //with small files this becomes true
    file.close();
    }
QDomElement root = document.firstChildElement();

Solution:
Activate a swap partition or get more RAM, the program chrashes because the PC is/was out of RAM. The updates are left in the question only for the reason to document my further steps.
Update:
I installed everything on another machine. Now im getting some output:

Error: Parse error at line 1, column 1: unexpected end of file

Funny thing now even the small files are not working and return the Error. After some digging some people set the path to the file wrong so i checked my path.
qDebug() << "File exists: " << file.exists();
qDebug() << "File path: " << QFileInfo(file).absoluteFilePath();
qDebug() << "File size: " << file.size();

This returns: true, /path/to/file/file.osm , correct size
I also checked if my XML files are valid and they are. So any new suggestions? So far im stuck
Update2:
First thank you for your answers! One desperate attempt was:
else{
  document.setContent(&file); //passed and worked, funny
}
qDebug() << file.isReadable();
file.close();

This finally works with the larger and smaller files on the new setup:
else
{

    if(!document.setContent(&file))
    {
       std::cerr << "Error: Open file "<< std::endl;
       return -1;
    }
    qDebug() << file.isReadable();
    file.close();

Why i used a DOM Parser: The XML Structure is like this:
<osm>
    <node id ="1" lat="value", lon="value" />
    <node id ="2" lat="value", lon="value" />
    <node id ="3" lat="value", lon="value" />

    <way id="12345">
      <nd ref ="1"/>
      <nd ref ="2"/>
      <nd ref ="3"/>
    </way>
</osm>

I want to rebuild the way points for that the lat,lon values from the node´s are necessary. For this i want to be able to match the way ref id with the node id and get the values into the way. Is the Sax parser the better solution for this? I tought with the DOM tree i could easy go through the "node"s and match the id´s without parsing the complete XML again. I´m using Ubuntu and with the new setup qt5. I got a i5 2nd generation and 8GB of RAM which are full when the big file is being processed. One run in release mode needs 50 minutes für 1000ways with 5-50 nodes.

A: The package Qt XML and QDomDocument is not supposed to be used with very large XML documents.
The object QDomDocument keeps entire XML document structure in RAM. It is crucial threshold 200MB for XML file size, since with such files QDomDocument can use 2GB or RAM.
Available Qt4 releases for Windows are built with 32 bit compilers. So, it is limit for such applications, for example How much memory can a 32 bit process access on a 64 bit operating system?
In general entire large XML documents should not be loaded to RAM. Such documents should be handled by stream parsers.
On the other hand if the XML document is not much larger than 200MB and the project is already working with QDomDocument and there is enough RAM on the PC (8GB - 16GB) it is possible to compile the project using 64 bit compilers. In that case Qt4 should be manually compiled. Also Release build may use two times less RAM than Debug.

A: The solution is activate a swap partition or get more RAM, the program chrashed because the PC is/was out of RAM.
A even better solution is to use a SAX parser.
To the runtime Problem: use maps instead of vectors. The runtime scaled down to ~20 secs for a big file.


text:
Q: Adding view onto Window of Twitter Hi i am facing a strange problem. I have a class which is NSObject type, and on same class i want to share image on Facebook and Email and also on Twitter. I successfully done FB and Email, On Email i use [[[UIApplication sharedApplication] keyWindow]  addSubview:mailer.view]; to show Mail controller onto Window instread of Presenting Model view controller and same as on Dismiss i use Remove from super view. But when i do same with twitter controller then twitter controller just show me few mili seconds and then hide. I also add new View controller onto Window and then Present its controller onto that View controller but same output. Don't know what going wrong. Please help on that. Thanks in advance. This will be great for me :)
Edited
 if (_engine != nil) {
    _engine = nil;
    [_engine release];
}
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;

UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate: self];

if (controller) {
    NSLog(@"Sharing on Twitter on loading controller of twitter");
     [[UIApplication sharedApplication].keyWindow addSubview:controller.view];

}
else {
    NSLog(@"Sharing on Twitter in else condition");
    [self sharetoTwitter:screenImg];
}

ShareToTwitterMethod
- (void) sharetoTwitter:(UIImage *)img {
NSString *response = [_engine _uploadImage:img requestType:MGTwitterPublicTimelineRequest responseType:MGTwitterStatus];
NSLog(@"twitter post notification");
}

I used Add subview to load view instead of Presenting View.

A: Have you tried this
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
[window addSubView:controller.view];
[window makeKeyAndVisible];//important line dont forget to set this line


text:
Q: Previous post id not showing using this code Trying to get previous post ID with this code but its only showing current post id
$prev_post = get_adjacent_post(false, '', true);
if(!empty($prev_post)) {

$xx = get_the_ID($prev_post->ID);
$yy = get_the_ID($post->ID);
echo $xx;
echo $yy;

A: please try it:
$prev_post = get_adjacent_post(false, '', true);
echo $prev_post->ID;


text:
Q: How can I center equations? My code is:
onde
\begin{equation}
\pi(\textbf{x})=\frac{1}{1+e^{-(\beta_0+\sum_{i=1}^{p}\beta_ix_i)}}
\end{equation}

How can I put the equation in the middle?

A: I can more or less reproduce your screenshot with the following code (observe that the amsmath package is loaded with the option fleqn):

\documentclass{book}
\usepackage[a4paper,margin=2.5cm]{geometry}
\usepackage[fleqn]{amsmath}
\begin{document}
\setcounter{chapter}{2}
\setcounter{equation}{1}

\noindent
onde,
\begin{equation}
\pi(\textbf{x})=\frac{1}{1+e^{-(\beta_0+\sum_{i=1}^{p}\beta_ix_i)}}
\end{equation}
\end{document}

If you want to have the displayed equations centered rather than left-justified, don't specify the fleqn option while loading amsmath.
Separately, you should use \mathbf rather than \textbf in math mode. Also, do consider using \exp[...] notation instead of e^{...}; your readers will thank you.

\documentclass{book}
\usepackage[a4paper,margin=2.5cm]{geometry}
\usepackage{amsmath}
\begin{document}
\setcounter{chapter}{2}
\setcounter{equation}{1}

\noindent
onde,
\begin{equation}
\pi(\mathbf{x})=\frac{1}{1+\exp[-(\beta_0+\sum_{i=1}^p \beta_ix_i)]}
\end{equation}
\end{document}


text:
Q: CakePHP and Android Auth Idea. Suggestions Please Well I have this situation where I should authenticate user with CakePHP 2.x site which is using blowfish to save password and I am using GCM for push notifications.
I am thinking it this way. First I will generate a registration ID for the device and then use the web view to open a custom login page designed for android in Server. There if the user successfully authenticates, his device id, registration id and the site recognized username are stored in a table. All requests with saved device id and registration id are used to authenticate a user and perform his actions. There would be mechanisms to control the problems with registration id where it gets deactivated or re issued.
Does this have any security issues or design flaws?

A: What you're looking for is a token based stateless auth system I think.
Use http://oauth.net/2/ for that. This is exactly what it was made for.
And I don't think your idea is secure: It sounds like the device id and the registration id will be the always the same (per device) and stored on the device - not a good idea. However it works, no need to re-invent the wheel.
And use HTTPS for that, OAuth2 requires it because unlike OAuth1 it doesn't deal with the cryptographic part any more but passes this task on to HTTPS.


text:
Q: Field is required in specific form ASP MVC 4 I'm working in ASP .NET MVC 4 and I'm trying to validate a field as required in a specific form, but in the database the field is not required. Is it possible to do this with ValidationMessageFor or will do I have to do in Javascript?

A: Remove Required attribute from your model

A: It seems you are employing just one model for view and for business domain/data access as well. I assume your application is small enough to live up with this.
When it becomes larger enough, more impedance mismatch could come up. It is recommended then to separate your model at least for views and business domain/data access. There are good tools to automate obvious conversions like Automapper.
Updated (as it both relates to view models):
The problem is known and has several approaches, from which I prefer most this one:
@Html.TexBoxFor(model => model.YourField,
    new Dictionary<string, object> { { "data-val", false }})

as it employs ASP.NET MVC helpers and you are free from maintaining additional js code


text:
Q: wso2 api manager 1.6.0 problems with User store management using ActiveDirectoryUserStoreManager I'm trying to setup a ActiveDirectoryUserStoreManager as a secondary user store. But I cannot seem to get the Role assignment of users correct.
What I have done so far:
- Made the AD ldap-connection
- Retrieved the users from the AD
- Retrieved the roles from the AD
- Can view Users that are connected to a specific role in API Manager Gui
My problem:
When I go to a user and click "View Roles" in the API Manager Gui ({IP}:9443/carbon/user/user-mgt.jsp) I get a "No matching roles found" dialog. But when I go to a Role ({IP}:9443/carbon/role/role-mgt.jsp) and click "View Users" I can see that the user I "View Roles" of above is actually in that role.
So obviously I have some sort of miss connection between the Users that are connected to Roles and the Roles that are connected to a User. I just cannot figure out where I'm getting it wrong.
If anyone would give me any hint or even ask a question about something I haven't already tried that would be awesome!

A: Seems to be a problem with your RoleDNPattern. You can first try by commenting it and see if it resolves the problem. If it does, then have to compose the correct query for that.


text:
Q: How to differentiate between Integer and integer stored as a string in BigQuery Using Bigquery procedures, I need to detect the data type of a value in a column of a table. I cannot read it from schema of the table.
Sometimes, the value can be an integer or an integer stored as a string. How to differentiate between both in BigQuery.
I tried SAFE_CAST like below
sql Select count(*) from table where SAFE_CAST(column AS STRING) is NULL
sql Select count(*) from table where SAFE_CAST(column AS INT64) is NULL
And, I tried Regular expression
But, both scenarios pass these conditions. Please help


text:
Q: PHP debugging code formatting I want to enchance my PHP development power and like to introduce code formatting, rectangle selection mode and debugging php.
I have Eclipse XDebug working but code formatting is not working as expected.
Using Netbeans PHP problem with debugging.
Switched to JetBrains PHP Storm problem with debugging.
My environment is Mac OS X with MAMP and a good version of xdebug.so (works in Eclipse).
This is in my PHP 5.5.10 version ini file
[xdebug]
xdebug.remote_enable = On
xdebug.remote_autostart = 1
xdebug.default_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=8888
zend_extension="/Applications/MAMP/bin/php/php5.5.10/lib/php/extensions/no-debug-non-zts-20121212/xdebug.so"
xdebug.remote_mode=req
xdebug.idekey="netbeans-xdebug"
xdebug.max_nesting_level = 250

checked with php --version.
I installed JetBrains browser plugin testing with Chrome. I played with ports.
Hardware is MacBook Pro stand alone debug and testing.


text:
Q: An error occured  while compiling qtHaskell After qmake and mingw32-make from these instructions succeeds,
and I execute runhaskell Setup.hs build, I get the following error:
[651 of 662] Compiling Qtc.Core.Attributes ( Qtc\Core\Attributes.hs, dist\build\Qtc\Core\Attributes.o )
Qtc\Core\Attributes.hs:584:13:
Could not deduce (Qstt a (QDialogSc b))
  arising from a use of `slotReject''
from the context (Qstt a (QDialogSc b1))
  bound by the instance declaration
  at Qtc\Core\Attributes.hs:582:10-52
Possible fix:
  add (Qstt a (QDialogSc b)) to the context of
    the instance declaration
  or add an instance declaration for (Qstt a (QDialogSc b))
In the expression: slotReject'
In an equation for `reject'': reject' = slotReject'
In the instance declaration for `QsaSlotReject a'

the Attributes.hs file (line 578 - 583):
class QsaSlotReject w where
  slotReject', reject' ::  (Qslot w (w -> ()), (w -> ()))

instance (Qstt a (QDialogSc b)) => QsaSlotReject (a) where
  slotReject' = (Qslot "reject()", \_ -> ())
  reject' = slotReject'

Environment :

*

*Windows 7

*Haskell Platform 2011.2.0

*Qt sdk 4.7

btw, I encountered an out of memory twice in the process, but I guess that doesn't matter.

A: The trouble comes from the fact that
data Qslot x f = Qslot String

so there's a bit of difficulty inferring what x and f might be from a given item of the form Qslot "Blah blah".  Perhaps there has been a subtle change in the inference mechanism GHC uses since the last version of qthaskell went up last Fall.
In any case, it seems to compile, with some curious warnings, and the examples work, if you replace
 instance (Qstt a (QDialogSc b)) => QsaSlotReject (a) where
    slotReject' = (Qslot "reject()", \_ -> ())
    reject' = slotReject'

with
 instance (Qstt a (QDialogSc b)) => QsaSlotReject (a) where
   slotReject' = (Qslot "reject()", \_ -> ())
   reject' = (Qslot "reject()", \_ -> ())

That way ghc does't have to wonder quite as much...
There must be something that would make things more precise. I don't know if the eta reduce warnings that start cropping up systematically later have to do with this line.


text:
Q: How to build List by using data from another List using LINQ i have some List that hold 1 or more Guid.
var getMyfirstListGuids = (from dlist in db.MyTable
    where dlist.id == theid
    select dlist).ToList();

List<MyfirstList> myfirstList = new List<MyfirstList>();

foreach (var item in myLandingPageList)
{
    Guid theguid = new Guid(item.guid);
    MyfirstList addnewRow = new MyfirstList();
    addnewRow.LpGuid = new Guid(theguid);
    myfirstList.Add(addnewRow);
}

Now i have a list with 1 or more guids.
my next step is to make list with data from SQL by the first list guids.
In the SQL could be 1 row or more for each guid. with one row result i can guess what to do. but if there is many results i dont have an idea.

A: Okay so you wanna do it like this:
List<SecondListGUID> secondListGUID = new List<SecondListGUID>();
foreach (var item in myfirstList)
{
    for(int i = 0; i<_yourDBEntity.GUIDs.Count(); i++)
    {
        if(item.LpGuid == _yourDBEntity.GUIDs[i].GUID)
        secondListGUID.add(
            new SecondListGUID() {
                // add the corresponding GUID's here
        });
    }
}

Basically you have to do a foreach through your first List and then do a for loop (or  foreach - whichever you prefer) through your DB table (entity in this case if you're using Entity framework) and simply compare the GUID's from your DB table and if they match you'll wanna add the item to your third list.
P.S. I've worked with the informations that you've provided, you can change the 2nd list type into the one you need, and change your entity framwork data model name into the one you actually use :)

A: You can try this
List<Guid>getMyfirstListGuids =  new List<Guid>();

getMyfirstListGuids.addRange(from dlist in db.MyTable
    where dlist.id == theid
    select dlist).ToList());

List<MySecList> mySecList = new List<MySecList>();

mySecList.AddRange(_db.myLandingPageList.Where(p => p.Guid.Any(x => getMyfirstListGuids.Contains(x));


text:
Q: How to load a pkcs12 from database in python I want to parse a pkcs12 file from my database, I uses the command load_pkcs12
but this one, takes a file in parameters or I want to use an object from database that I got with get query. How do I need to proceed?

A: Solution :
blob_file = Xx.objects.get(id=X_id).pkcs12
p12 = load_pkcs12(blob_file,'password')


text:
Q: iOS 9: view is not rendered properly after I rotate device This is my custom UIView:

After I rotate to horizontal, and then back to Portrait it looks like this:

Why?
After I rotate device this method is called:
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
    tableView.reloadData()
}

What Am I doing wrong? It works perfect for ios8, but not for ios9


text:
Q: Why is font-size CSS property affecting background-size property in my rails app? I have an app https://bootstrapp3.herokuapp.com/ the background image changes size when I add text. After using the inspect element function on the browser it seems that it is the font-size property that is affecting the background-size property, since when I uncheck the box related to font-size using inspect element, the background-size returns to the normal size. Why is the background size changing? compare the following two pages from the app:
Without text and font-size:
https://bootstrapp3.herokuapp.com/pages/page1
Background-size changing due to font-size:
https://bootstrapp3.herokuapp.com/pages/consulta
note that the only difference between the pages is the content in the view.  Both pages inherit from the application layout.
css with the background size:
body {
    background-image:image-url('gotita.png');
    background-size: cover;
    background-repeat: repeat;
    background-position: 0 51px;
}

font-size element:
p {
  font-family: 'Architects Daughter';
  font-size: 20px;
}

A: You have set background property to cover. If you want to make it independent then apply the background to an empty div having the size you want to set. Then add text in another div having its position to absolute.
Now, changing the font size will not affect the background image.

A: It's because you are using:
background-size: cover;

on the body element. The height of the body is relative to all of the child elements. So, because of that, the background-image has to adapt to fill the height.
To make the background image the same on all the pages not depending on the content you could remove the background image from the body tag and make a div inside the body tag with position fixed, like:
background-image: url(/assets/gotita-7c57f01….png);
background-size: cover;
background-repeat: repeat;
background-position: 0 51px;
position: fixed;

A: Have a look at the background-size attribute you have assigned. This attribute can be described as follows:

*

*contain : "Scales the image as large as possible without cropping or stretching the image."

*cover : "Scales the image as large as possible without stretching the image. If the proportions of the image differ from the element, it is cropped either vertically or horizontally so that no empty space remains."

Source: MDN Web Docs


text:
Q: Pandas: Efficient way to select rows from a dataframe using multiple criteria I am selecting/filtering a DataFrame using multiple criteria (comparsion with variables), like so:
results = df1[
    (df1.Year == Year) &
    (df1.headline == text) &
    (df1.price > price1) &
    (df1.price < price2) &
    (df1.promo > promo1) &
    (df1.promo < promo2)
]

While this approach works, it is very slow. Hence I wonder, is there any more efficient way of filtering/selecting rows based on multiple criteria using pandas?

A: Your current approach is pretty by-the-book as fair as Pandas syntax goes, in my personal opinion.
One way to optimize, if you really need to do so, is to use the underlying NumPy arrays for generating the boolean masks.  Generally speaking, Pandas may come with a bit of additional overhead in how it overloads operators versus NumPy.  (With the tradeoff being arguably greater flexibility and intrinsically smooth handling of NaN data.)
price = df1.price.values
promo = df1.promo.values

# Note: this is a view to a slice of df1
results = df1.loc[
    (df1.Year.values == Year) &
    (df1.headline.values == text) &
    (price > price1) &
    (price < price2) &
    (promo > promo1) &
    (promo < promo2)
]

Secondly, check that you are already taking advantage of numexpr, which Pandas is enabled to do:
>>> import pandas as pd
>>> pd.get_option('compute.use_numexpr')  # use `pd.set_option()` if False
True


text:
Q: NDSolve Error "message text not found" I am trying to solve a nonlinear PDE - 1D diffusive heat equation.
I'm not sure what is wrong (am new to Mathematica).
I'm trying to use https://reference.wolfram.com/language/FEMDocumentation/tutorial/SolvingPDEwithFEM.html#243862001 as a reference.
parameters = {v -> -0.000001, DT -> 0.000000143, rho -> 1000,
c -> 4200, eta -> 0.001002};
HEATIMP = {-D[u[r, t], t] - v.D[u[r, t], r] + (DT/r^2).D[r^2. D[u[r, t], r],
  r] + (12. eta)/(rho.c).(v/r).(v/r)} /. parameters
BCE1 = DirichletCondition[u[r, t] == 1, r == 2];
BCE2 = DirichletCondition[u[r, t] == 0, r == 1];
BCTot = {BCE1, BCE2};
ic = {u[r, 0] == 0};
heatdist = NDSolve[{HEATIMP == 0, BCTot, ic}, u, {r, 1, 2}, {t, 0.000001, 100}]

Gives the message:
NDSolve::t parsing failed: -- Message text not found -- ({{-u$6579-(-1.*10^-6).u$6580+(1.43*10^-7/r^2).(2. r^1. u$6580+r^2. u$6581)+0.012024/1000.4200.(-(1.*10^-6/r)).(-(1.*10^-6/r))}})

I had this solved on Mathematica 9 using a different framework (that did not appear to be robust enough). However I would like to use the features and formalism introduced in Mathematica 10 and 11. Any help would be appreciated.


text:
Q: How to word it when you are asking for corrections Let's say I'm asking a coworker to review a proposal. I say:

Could you find and fix mistakes, if any?

Should I put the article "the" before the word "mistakes" in that sentence?

Could you find and fix the mistakes, if any?

Also, does "if any" sound natural? I mean to say "if there is" (if mistakes exist).

Could you find and fix mistakes, if there is?
  Could you find and fix mistakes, if they exist?

A: There are some mistakes in the sentences mentioned above.

Could you find and fix mistakes, if any?

Usually, no comma is put in front of if but there appear to be some cases when this rule is overwritten.
On the other hand, if any is quite an elliptical phrase, there need to be put, for example, a subject into it.

Find the mistakes if there's any. (NB: this is an imperative sentence)

Concerning the, I don't think it should be used because it is a definite article but the mistakes are unknown to the reader (co-worker) if they haven't read the text yet. Using any is a good quantifier to stand before mistakes. But if you stick to your plan (of using the), here's the following sentence I advise you to use:

Could you please find the mistakes and fix them (if there's any)?

Mistakes is in plural, so the word that refers to it has to be them.


text:
Q: Sitefinity user control In Sitefinity - the page controls section I created a new tool and linked it up to the user control. But when I try and add that control to the page I am getting an error?

Is there a step I am missing?

UserControl
 Control Language="C#" AutoEventWireup="true" CodeBehind="TransparencyControl.ascx.cs" Inherits="SitefinityWebApp.transparency.TransparencyControl" %>
<%@ Register TagPrefix="ucTransparency" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<asp:Xml ID="XmlForm" runat="server"></asp:Xml>

PageControl

PageControl tool linked to ascx page

A: You need to set the path to the user control (ascx) not in the Controller CLR Type field, but in Control CLR Type or Virtual Path field.
So, just cut it from the former field and paste it in the latter field and you should be fine.


text:
Q: Special variable in hunchentoot Currently, I'm developing 2 web-based tools for my own need with hunchentoot.
Before starting hunchentoot, I want to set some special variable with let so there values will be available while hunchentoot is running.
Like :
(let ((*db-path* "my-db-file"))
  (start-hunchentoot))

But, once the handlers get invoiced, they don't seam to be in the let anymore and db-path falls back to its global state (which is nil).
At the moment I'm resolving this by writing the let in every handler.
But, I want a more general approach so I will be able to run both applications with different db-path in one run-time.
Is it possible to set db-path in a way so it will be valid for one instance of hunchentoot and not the other?
The used environment is SBCL 1.2.4 on Debian Jessie.

A: Around method
Adding db-path as a slot in the acceptor might be a suitable option. However, you can also write an around method for handle-request. Assuming *my-acceptor* is globally bound:
(defmethod hunchentoot:handle-request :around ((acceptor (eql *my-acceptor*)) request)
  (let ((*db-path* "my-db-file"))
    (call-next-method)))

Of course, you don't need to specialize with EQL, you can define your own subclass instead. The advantage of an around method over storing a configuration variable in the class instance is that you keep the benefits of using special variables, i.e. bindings are visible from everywhere in the dynamic scope.
Here is what the documentation string, visible on Lispdoc, says about handle-request (emphasis mine):

This function is called once the request has been read and
  a REQUEST object has been created. Its job is to actually handle the
  request, i.e. to return something to the client.
Might be a good place
  for around methods specialized for your subclass of ACCEPTOR which
  bind or rebind special variables which can then be accessed by your
  handlers.

I encourage you to read Hunchentoot's documentation.
Special variables and threads
The behavior you observe is because:

*

*The server is running in another thread.

*Dynamic bindings are local to each thread, as explained in the manual:

The interaction of special variables with multiple threads is mostly as one would expect, with behaviour very similar to other implementations.

*

*global special values are visible across all threads;

*bindings (e.g. using LET) are local to the thread;

*threads do not inherit dynamic bindings from the parent thread

If you make your own threads, you can build a closure which binds variables as you want. You can also rely on the portable bordeaux-threads library which takes a list of bindings to be effective inside a thread.