text:
Q: Adding checkboxes dynamically to BottomSheetDialog: setMargins() and setPadding() not working as expected I want to add checkboxes dynamically to a BottomSheetDialog. However, the buttons are not aligning as I want them to. Styling the checkboxes works if I style them directly on the XML, however, they don't style at all programmatically.
Here's my XML layout code with two hardcoded checkboxes:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/id_layout_bottom_sheet_choices"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:padding="10dp"
        android:text="Escolha uma resposta"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#000000"
        android:layout_marginStart="10dp"
        android:layout_marginBottom="10dp"
        android:textSize="20sp"
        android:textStyle="bold" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginBottom="10dp"
        android:paddingLeft="10dp"
        android:text="CheckBox" />

    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginBottom="10dp"
        android:paddingLeft="10dp"
        android:text="CheckBox" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:orientation="horizontal">

        <Button
            android:id="@+id/cancel_btn"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cancelar" />

        <Button
            android:id="@+id/confirm_btn"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OK" />
    </LinearLayout>
</LinearLayout>

Here, I try to add more of them programmatically:
LinearLayout mainLinearLayout = bottomSheetDialog.findViewById(R.id.id_layout_bottom_sheet_choices);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
);
// margin-left: 10, margin-bottom: 10, like the margins in the two hardcoded xml checkboxes
params.setMargins(10, 0, 0, 10);

for (int i = 0; i < answerChoices.size(); i++) {
    CheckBox checkBox = new CheckBox(getContext());
    checkBox.setText(answerChoices.get(i));
    // left padding
    checkBox.setPadding(10,0,0,0);
    // i + 3 since there's already a textview and two sample checkboxes added, and i want to add the new checkbox after them and before the remaining elements
    mainLinearLayout.addView(checkBox, i + 3, params);
}

Here's of the output in the BottomSheetModal with that code, after the buttons are added:

As you can see, the first hardcoded checkboxes are aligned correctly, however the two other checkboxes added via coding are not. Even the checkbox select colors are different (but why???)
Here's the output that I pretend (I hardcoded the other two checkboxes just to showcase how I want the output to be after coding)

How can I solve this problem?

A: Because in xml file you use dp unit but in code you use pixel unit. You must convert from dp to pixel before set margin for checkbox.
LinearLayout mainLinearLayout = bottomSheetDialog.findViewById(R.id.id_layout_bottom_sheet_choices);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
);

// margin-left: 10, margin-bottom: 10, like the margins in the two hardcoded xml checkboxes
int margin = (int)convertDpToPixel(10F, this);
params.setMargins(margin, 0, 0, margin);

for (int i = 0; i < answerChoices.size(); i++) {
    CheckBox checkBox = new CheckBox(getContext());
    checkBox.setText(answerChoices.get(i));
    // left padding
    checkBox.setPadding(margin, 0, 0, 0);
    // i + 3 since there's already a textview and two sample checkboxes added, and i want to add the new checkbox after them and before the remaining elements
    mainLinearLayout.addView(checkBox, i + 3, params);
}

// Add this method to convert dp to pixel
public static float convertDpToPixel(float dp, Context context){
    return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}


text:
Q: SQL Select multiple values in one column, with different conditions I've products-filter relation table.
For example: I want to select all products with color red and yellow which have medium size
WHERE (filter_id = 208 OR filter_id = 211) AND filter_id = 210

I'cant figure out how to use AND condition on same column

A: Looks like you want to group your data by product_id and the take only those having the conditions you mentioned
select product_id
from your_table
group by product_id
having sum(filter_id = 210) > 0
   and sum(filter_id = 208 OR filter_id = 211) > 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I stop my laptop screen from flickering? My laptop screen has been flickering whenever I am not charging it. The screen is readable but the brightness of the screen keeps changing from bright to dark very quickly. When charged, the flickering stops. I have tried to change the refresh rate and screensaver power options but nothing works. I am not sure if it is a settings problem or something wrong in the hardware. My laptop is Samsung Series 5 Ultrabook.

A: You can try updating your graphic drivers, see if that helps...but if this only started happening recently and you haven't made any significant changes to your computer, it is most likely a hardware issue.
If you have a second monitor, try connecting it to your computer. Is the flickering only the laptop or on the 2nd screen as well?


text:
Q: CloudFront distribution from S3 bucket: big "bucket is public" warning. What can go wrong? I'm moving an existing static website to S3/CloudFront.
Following some documentation from AWS, I setup a policy on the S3 bucket to make it public:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::mywebsite.org/*"
        }
    ]
}

However, when applying said policy, AWS gives me a (honestly scary) warning. Same as discussed in this thread:
Serving website from Cloudfront and S3 without public bucket
I actually tried the way they describe in that answer first, setting up Origin Access Identity, but this resulted in a nasty side effect: the directory urls (https://mywebsite.org/directory/) would NOT get the index.html file in there, and result in a 403 instead.
Unfortunately, that behavior breaks a lot of existing links (including links on other websites), so I can't do that.
There's also the possibility to use lambda@edge to solve this, but honestly it just sounds like more code, more problems and more money.
So back to the big scary warning:

It's a static website, so obviously things are going to be public. However this message is still worrying. Is there anything I should know about, unexpected access or potential security issues? Is there a way I can solve that without breaking my links or using lambda@edge?

A: Just ignore that warning if you are configuring S3 as static web hosting. Your website should be public in order for anonymous access.


text:
Q: Add two layers of data to a single SVG in d3.js In d3.js, I am trying to add circles from two different datasets (actually two transformations of the same dataset) to the same SVG. Only the first ones are rendered : the other ones are not added (even if I look through the "element" pane).
What am I doing wrong ?
Thanks for your help
            canevas2.selectAll('circle')
                .data(dataSet1)
                .enter()
                .append('circle')
                    .attr('cx',(d,i) => 100+ (window.innerWidth-250)/4 *i)
                    .attr('cy',200)
                    .attr('r',d => d[1])
                    .attr('opacity',0.8)

            canevas2.selectAll('circle')
                    .data(dataSet2)
                    .enter()
                    .append('circle')
                        .attr('cx',(d,i) => 100+ (window.innerWidth-250)/4 *i)
                        .attr('cy',200)
                        .attr('r',d => d[1])
                        .attr('opacity',0.8)
            })


text:
Q: How can I get the most specific class of an instance? Suppose I have the following classes:
class A {}
class B extends A {}

A instA = new A();
A instB = new B();

Now as far Java is concerned instB is of type A.
How can I find out what is instB's actual type?

A: You can use instB.getClass(). This will return a Class object representing instB's runtime type.
Source: javadoc
You can also use the following conditional check with instanceof:
if (instB instanceof B) {
    //then we know it is of type B
}

instanceof would be the more conventional way, and the conditional will also return true if instB is a subclass of B.
You may want to further explain your use case, with code examples, to get better discussion.

A: For compile-time, I do not know of any possibility. It is not easy, because it is control flow dependent (looking at the declaration is not sufficient). But when you wrote the declaration, you decided that you only need the class-A-interface/behavior of instB.
For run-time, you can use getClass(), instanceof, as Kublai suggested. But again, you should not need it in most of the cases: With a good design of your classes, you can let dynamic dispatch make the case distinctions.


text:
Q: Link two objects in angular I've got 2 data sets
posts
[
 {
  "postId": 1,
  "postContent": "Lorem Ipsum",
  "user": 1
 },
 {
  "postId": 2,
  "postContent": "Lorem Ipsum",
  "user": 2
 },
]

and users
[
 {
  "user": 1,
  "firstName": "John",
  "lastName": "Doe"
 },
 {
  "user": 2,
  "firstName": "Johny",
  "lastName": "Doey"
 }
]

I am repeating all the posts and i would like to access a user data throught the $scope.post.user.firstName etc.
how should i aproach it?

A: You can implement a method like getUserById() with the use of Array.prototype.find() to use it when iterating over your posts.
Code in AngularJS:

angular
  .module('App', [])
  .controller('AppController', ['$scope', function ($scope) {
    $scope.posts = [{"postId": 1,"postContent": "Lorem Ipsum","user": 1},{"postId": 2,"postContent": "Lorem Ipsum","user": 2}];
    $scope.users = [{"user": 1,  "firstName": "John",  "lastName": "Doe"},{  "user": 2,  "firstName": "Johny",  "lastName": "Doey"}];

    $scope.getUserById = function (id) {
      return $scope.users.find(function (user) {
        return id === user.user;
      });
    };
  }]);

{{p.postContent}} by {{getUserById(p.user).firstName}}

A: find() the matching user for each post.
Note that if you are not using ES6 features, you will need a polyfill for Object.assign() and should use regular function() {}s instead array functions.

var posts = [{"postId":1,"postContent":"LoremIpsum","user":1},{"postId":2,"postContent":"LoremIpsum","user":2}];
var users = [{"user":1,"firstName":"John","lastName":"Doe"},{"user":2,"firstName":"Johny","lastName":"Doey"}];

var out = posts.map(post => Object.assign({}, post, {
  user: users.find(user => user.user === post.user)
}));

console.log(out);

A: You can create a function that maps each user object to your post object. Then you can access user details as $scope.post.user.first_name; Here is simple code that will make you an new object with users.
var new_object = [];
function mapUsersToPosts(users, posts){
   angular.forEach(posts, function(post){
      angular.forEach(users, function(user){
         if(post.user_id == user.user_id){
            new_object.push({
                'post' : post,
                'user' : user
            });
         }
      });
   });
}

Now you can loop new_object and use user data and post data in same object.


text:
Q: Angular directive removes ng-click functionality I have a directive that is almost an exact copy of the old uiIf directive from the angular-ui project.
What is happening is that when I add my "restrict" directive, the button is successfully added/removed based upon what the user is authorized to do.
The problem is that the ng-click action no longer works. It doesn't call in to the controller's scope and trigger the function to be called. Does anyone see what might be causing my issue?
See: http://plnkr.co/edit/38UeVCCYkdzxBkxOLe5g?p=preview
<button restrict="'canPerformAction'" ng-click="action()">Action</button>

'use strict';
angular.module('directives.restrict', [])
.directive('restrict', function(_){
  return{
    transclude: 'element',
    prioriry: 1000,
    terminal: true,
    restrict: 'A',
    compile:  function(element, attr, transclude) {
      var user = { caps: [ 'canPerformAction', 'canDance', 'canWrite' ] };

      return function(scope, element, attr) {
        var childElement;
        var childScope;

        scope.$watch(attr.restrict, function(attributes) {
          if (childElement) {
            childElement.remove();
            childElement = undefined;
          }
          if (childScope) {
            childScope.$destroy();
            childScope = undefined;
          }

          if(_.intersection(user.caps, attributes.split(' ')).length > 0) {
            childScope = scope.$new();
            transclude(childScope, function(clone) {
              childElement = clone;
              element.after(clone);
            });
          }
        });
      };
    }
  };
});


text:
Q: Google Maps using custom icon for marker sometimes doesn't show up I am getting weird and unpredictable behavior when specifying an icon to use with google.maps.Markers.  Basically, the markers show up (with default icon) if I don't specify an icon property, but if I do specify the icon property, no markers show up (although I have other case where I can get a custom icon to show, so that's why it's weird).
Here's the relevant code:
              function initMap() {
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng)
                  });
                });

                ...calculate bounds..

                var map = new google.maps.Map(document.getElementById('route_log_map_map'), {
                  position: bounds.getCenter(),
                  zoom: 15
                });

                ...other unrelated code...

                for(i=0; i < markers.length; i++) {
                   markers[i].setMap(map);
                }
              }

This is called with:
<script src="https://maps.googleapis.com/maps/api/js?key=...key...&callback=initMap" async="" defer=""></script>

and the above results in:

Obviously that's a lousy marker to use in this case (there's almost 2000 points), so if I change the marker creation to be like this:
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 1
                    }
                  });
                });

the markers don't show up (and there's no errors either) (note those blue circles are unrelated to this code):

EDIT
This is interesting.  It works if the array I'm building the markers from has only one element, but fails to display if it has more than one.  E.g. this works and displays one marker:
                var route_log = [
                  {lat: 41.86219805, lng: -71.04886590000001}
                ];
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 10
                    }
                  });
                });

but this displays no markers (only change is to add another element to the array):
                var route_log = [
                  {lat: 41.86219805, lng: -71.04886590000001},
                  {lat: 41.87219805, lng: -71.05886590000001}
                ];
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 10
                    }
                  });
                });

A: Wow.
I have position in the options to the new google.maps.Map call.  It should be center, which is required.  position is not even a valid option for google.maps.MapOptions.
I blame the Google Maps API for this one. :-)


text:
Q: I'm trying to make a call to an API, but i'm getting errors I'm trying to make a call to Spotify API. When I run Spotify.getSongs(), I get an error. This is the error I get:

TypeError: Cannot read property 'items' of undefined.

However when I define getSongs as a function outside of this object, it works fine. How can I make the call to "Spotify.getSongs()" work?
let Spotify = {
  getOAuth() {
    fetch("https://accounts.spotify.com/api/token", {
      method: "POST",
      body:
        "grant_type=client_credentials&client_id=" +
        clientId +
        "&client_secret=" +
        clientSecret,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      }
    })
      .then(function(resp) {
        // Return the response as JSON
        return resp.json();
      })
      .then(function(data) {
        // Log the API data
        console.log("token", data);

        // Store token data
        this.token = data.access_token;
        this.tokenType = data.token_type;
        this.expires = new Date().getTime() + data.expires_in * 1000;
      })
      .catch(function(err) {
        // Log any errors
        console.log("something went wrong", err);
      });
  },

  getSongs() {
    return fetch(
      `https://api.spotify.com/v1/search?q=inception%20soundtrack&type=playlist`,
      {
        headers: {
          Authorization: this.tokenType + " " + this.token,
          "Content-Type": "application/json"
        }
      }
    )
      .then(resp => resp.json())
      .then(function(data) {
        console.log(data);
        let tracks = data.playlists.items[0].href;

        return fetch(
          `${tracks}/tracks?fields=items(track(name,artists(name),album(name,href)))`,
          {
            headers: {
              Authorization: this.tokenType + " " + this.token,
              "Content-Type": "application/json"
            }
          }
        );
      })
      .then(response => response.json())
      .then(data => {
        console.log(data);
        return data.items.map(info => ({
          name: info.track.name,
          artist: info.track.artists[0].name,
          album: info.track.album.name
        }));
      });
  }

  // If current token is invalid, get a new one
  // makeCall() {
  //   if (!this.expires || this.expires - new Date().getTime() < 1) {
  //     console.log("new call");
  //     this.getOAuth().then(function() {
  //       this.getSongs();
  //     });
  //   }
  // }
};


text:
Q: Is the Pusey-Barrett-Rudolph (PBR) theorem only applicable in two dimensions? In the Pusey-Barrett-Rudolph (PBR) paper, https://arxiv.org/abs/1111.3328 it is shown that two non-colinear  pure states $|\psi_0\rangle$ and $|\psi_1\rangle$ cannot have overlapping ontic supports (modulo some assumptions). However, the demonstration given in the paper seems to be done only for a two dimensional Hilbert space.
Does the strength of the PBR argument cover quantum states that are elements of arbitrary dimensional Hilbert spaces?

A: Yes, the argument given in that paper is completely general and applies to pairs of states in Hilbert spaces of arbitrary dimension. The choose two linearly independent vectors and look at the two-dimensional subspace generated by these vectors. They do not assume that the Hilbert space itself is two-dimensional. In fact, they they say this explicitly:

These states span a two-dimensional subspace of the Hilbert space. We can restrict attention to this subspace and from hereon, without loss of generality, treat the systems as qubits.

This is a perfectly standard approach to theorems in linear algebra that is used all the time. We use it in QM very often too, e.g. when we diagonalize operators simultaneously, where we fix the eigenvalue for one of them (i.e., we restrict the attention to one of its eigenspaces) and study the eigenvalues of the other one.

A: Motivated by AccidentalFourierTransform's answer I decided to fill in some of the details.
Let $|\psi_0\rangle$ and $|\psi_1\rangle$ be two normalized non-colinear elements of an $N$ dimensional Hilbert space $\mathcal{H}$.  They then span a two dimensional subspace $\mathcal{S}_2$ of $\mathcal{H}$.  A basis $|0\rangle$, $|1\rangle$,...,$|N-1\rangle$ for $\mathcal{H}$ exists such that $|0\rangle$ and $|1\rangle$ span $\mathcal{S}_2$.
Following the first example given in the PBR paper, let
\begin{equation}
     |\psi_0\rangle=|0\rangle,\:\:\:\:\:|\psi_1\rangle=|+\rangle=\frac{1}{\sqrt{2}}(|0\rangle+|1\rangle).
\end{equation}
Then, as discussed in the paper, bringing two copies of the these quantum states together generates an $N^2$ dimensional Hilbert space $\mathcal{H}\otimes\mathcal{H}$, which in particular has the four elements $|0\rangle\otimes|0\rangle$, $|0\rangle\otimes|+\rangle$, $|+\rangle\otimes|0\rangle$, and  $|+\rangle\otimes|+\rangle$, each of which is compatible with the physical state $\lambda$. These four vectors as well as $|\xi_1\rangle$, $|\xi_2\rangle$, $|\xi_3\rangle$, and $|\xi_4\rangle$ (as defined in the paper) span the same four dimensional subspace $\mathcal{S}_4$ of $\mathcal{H}\otimes\mathcal{H}$. Since the $|\xi_i\rangle$ elements are orthonormal, an additional $N^2-4$ orthonormal elements exist so that $\{|\xi_i\rangle\}$ can be extended into a orthonormal basis for $\mathcal{H}\otimes\mathcal{H}$. Then there exists a projective measurement onto this basis. As stated in the paper, $\langle\xi_1|(|0\rangle\otimes|0\rangle)=0$, $\langle\xi_2|(|0\rangle\otimes|+\rangle)=0$, $\langle\xi_3|(|+\rangle\otimes|0\rangle)=0$, $\langle\xi_4|(|+\rangle\otimes|+\rangle)=0$. But, additionally each of these is also orthogonal to the remaining $|\xi_i\rangle_{i>4}$, since each $|\xi_i\rangle_{i>4}$ is orthogonal to any element of $\mathcal{S}_4$. Thus if the physical state $\lambda$ happens to be prepared and a $\hat{\xi}$ measurement is made, every possible outcome has zero probability of being realized, which contradicts the tenets of QM.
A similar argument can be applied to the next part of the paper where two arbitrary normalized non-colinear elements  $|\psi_0\rangle$ and $|\psi_1\rangle$ are considered. As discussed in the paper n copies of these states are brought together generating a $N^n$ dimensional Hilbert space $\mathcal{H}^{\otimes{n}}$. This Hilbert space contains the elements $|\psi_{x_1}\rangle\otimes...\otimes|\psi_{x_n}\rangle$ where $x_i\in\{0,1\}$, which taken together span a $2^n$ dimensional subspace $\mathcal{S}_{2^n}$ of $\mathcal{H}^{\otimes{n}}$. The authors also provide an orthonormal basis $\{(H^{\otimes{n}}R_{\alpha}Z_{\beta}^{\otimes{n}})^{\dagger}|x_1...x_n\rangle\}$ for $\mathcal{S}_{2^n}$ such that for each $|\psi_{x_1}\rangle\otimes...\otimes|\psi_{x_n}\rangle\in\mathcal{S}_{2^n}$
\begin{equation}
\langle{x_1...x_n}|{H}^{\otimes{n}}R_{\alpha}Z_{\beta}^{\otimes{n}}|\psi_{x_1}\rangle\otimes...\otimes|\psi_{x_n}\rangle=0.
\end{equation}
As in the previous example $\{(H^{\otimes{n}}R_{\alpha}Z_{\beta}^{\otimes{n}})^{\dagger}|x_1...x_n\rangle\}$ can be extended into an orthonormal basis for $\mathcal{H}^{\otimes{n}}$ such that each basis element is orthogonal to at least one $|\psi_{x_1}\rangle\otimes...\otimes|\psi_{x_n}\rangle$. Assuming again that the physical state $\lambda$ is compatible with each $|\psi_{x_1}\rangle\otimes...\otimes|\psi_{x_n}\rangle$, then a measurement projecting onto the aforementioned basis will have no realizable outcome.


text:
Q: Web Api 2 Routing Issue: "No action was found on the controller..." I am having the issue of getting a 404 on my web api routing.  Although there are many posts about this issue, they mainly seem to be about changing the order of the routes so that the MVC routes don't override the api routes.
I have tried all of the solution I have come across yet nothing seems to fix my issue.
Here is my controller:
[RoutePrefix("api/paving-designer")]
public class PavingDesignerController : ApiController
{
    [HttpGet]
    [Route("get-forms/{userId}")]
    public IHttpActionResult GetForms(Guid userId)
    {
        ICollection<PavingDesignerFlatForm> forms = _helper.GetForms(userId);

        if (forms != null)
        {
            return Ok(forms);
        }
        else
        {
            return NotFound();
        }
    }
}

And this is my Web Api Config
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

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

and this is my global asax
    private void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);

        // RouteConfig.RegisterRoutes(RouteTable.Routes);
        // Initialize Castle & install application components
        _bootstrapper = CastleInitialiser.Initialise();
    }

As you can see I have even tried to comment out the mvc routes to see if that made a difference
If I browse to http://localhost/api/paving-designer/get-forms/c6c489a7-46c6-420e-9e39-56797c8094cf
I get the following error:

No type was found that matches the controller named 'paving-designer'.

I have tried changing the route prefix to the following but to no avail
/api/paving-designer
/paving-designer
paving-designer
And if I browse to http://localhost/api/pavingdesigner/get-forms/c6c489a7-46c6-420e-9e39-56797c8094cf
I get the following error:

Multiple types were found that match the controller named 'pavingdesigner'. This can happen if the route that services this request ('api/{controller}/{action}/{id}') found multiple controllers defined with the same name but differing namespaces

I don't see how I can have multiple controllers as this is the only one I have.
Can anyone see where I am going wrong?

A: You are using both routing types.
Using attribute routing defined next route:
/api/paving-designer/get-forms/{userId}

Using default routing there is other route:
/api/{controller}/{action}/{id}

These routes are have the same template.
But using the first of them - ControllerSelector can not find paving-designerController.
Using the second - there is no action named get-forms. There are GetForms
If you remove one of them - it should work.

A: Ok in my particular case, the error was being caused as my IoC was registering the controller twice.
This was causing the duplicate entries, which in turn made the attribute routing fail.


text:
Q: How to load web-animations-js polyfill in angular 5 without breaking ie9? I have an Angular 6 app.
I would like to load Web Animations Js polyfill, but when its loaded IE9 displays an error and stops loading the App.
Is there any work around?
-I've tried to check the browser version using JS and then load the player using a require () call. This approach works well on Angular 5, but in Angular 6 require () its not available anymore.
-Another option is to wrap the pollyfill content in a function an call, it only when the browser is not IE9.
Any other idea that doesn't involve using server side browser detection?
Thanks!


text:
Q: How to apply SQL 'between' keyword on TIME data type --I want to use SQL - BETWEEN on TIME datatype.
I want to execute below query but it does not give correct result.
here, starttime and endtime both fields are typeof smalldatetime whichi do cast into TIME field as i need time comparision only and date's value is not actual its just dummy.
SELECT
  count(1)
FROM
  t1 INNER JOIN t2
WHERE
  CAST(t1.StartTime as TIME)
  BETWEEN CAST(t2.StartTime as TIME)
  AND CAST(t2.EndTime as TIME)

CAST(t1.StartTime as TIME)  is 08:00:00.0000000
CAST(t2.StartTime as TIME)  is 07:00:00.0000000
CAST(t2.StartTime as TIME)  is 12:00:00.0000000

so, above query should result record count 1 (as 8 o'clock is between 7 to 12). but it returns null.
Please suggest me what is wrong here and how to correct.
Thank You

A: WHERE CAST(t1.StartTime as TIME)  >= CAST(t2.StartTime as TIME)
AND CAST(t1.StartTime as TIME) <= CAST(t2.EndTime as TIME)

Using this Snytax makes your queries SARGable. Read Here for more information about making your queries sargable when working with datetime/date/time datatypes.

A: the syntax of between is correct. you need to specify the join and provide an on clause like this:
SELECT count(1) FROM t1 INNER JOIN t2 on t1.col = t2.col
WHERE CAST(t1.StartTime as TIME)  BETWEEN CAST(t2.StartTime as TIME) AND CAST(t2.EndTime as TIME)

A: I suspect based on your example you are looking for times in t1 between a start and end time in t2 but the two tables do not necessarily have a relationship between them on any key.
Trying to use a join in that scenario will not work easily, you'd have to move M. Ali's solution to the join predicates rather than in the where conditions.
If my assumption is correct and your simply looking for t1 rows that match your between criteria in t2 this should get you that set without the two tables having a relationship:
DECLARE @sampleTime AS smalldatetime = GETDATE()

CREATE TABLE #t1 (StartTime smalldatetime)
CREATE TABLE #t2 (StartTime smalldatetime, EndTime smalldatetime)

INSERT INTO #t1 (StartTime) VALUES (@sampleTime)
INSERT INTO #t1 (StartTime) VALUES (DATEADD(hh, 6, @sampleTime))

INSERT INTO #t2 (StartTime, EndTime) VALUES (DATEADD(hh, -1, @sampleTime), DATEADD(hh, 3, @sampleTime))

--  you can see only one row in t1 lands between the Start and End in t2
SELECT  * FROM #t1
WHERE   EXISTS(SELECT * FROM #t2  WHERE CAST(#t1.StartTime AS time) BETWEEN CAST(#t2.StartTime AS time) AND CAST(#t2.EndTime AS time))

--  adding another row to t1 that now lands between the Start and End in t2 and the result
INSERT INTO #t1 (StartTime) VALUES (DATEADD(hh, 1, @sampleTime))

SELECT  * FROM #t1
WHERE   EXISTS(SELECT * FROM #t2  WHERE CAST(#t1.StartTime AS time) BETWEEN CAST(#t2.StartTime AS time) AND CAST(#t2.EndTime AS time))

DROP TABLE #t1, #t2


text:
Q: Tensorflow cond doesn't stop gradient on the false branch I am building a RNN model, where the init_state could come from one of two cases. 1) a static init_state that is fed in via feed_dict, from the previous time-step output state. 2) some function of a variable, which I call score.
init_state = cell.zero_state(batch,tf.float32)
with tf.name_scope('hidden1'):
     weights_h1 = tf.Variable(
                        tf.truncated_normal([T, cells_dim],
                        stddev=1.0 / np.sqrt(T)),
                        name='weights')
     biases_h1 = tf.Variable(tf.zeros([cells_dim]),
                        name='biases')
     hidden1 = tf.nn.relu(tf.matmul(score, weights_h1) + biases_h1)

init_state2 = tf.cond(is_start, lambda: hidden1, lambda: init_state)

init_state2 is then used as input to static_rnn, which eventually is used to calculate loss and train_op. I would expect the train_op to have no impact on weights_h1 when is_start is False. However, the weight changes after each updates. Any help is greatly appreciated.

A: This should work:
def return_init_state():
    init_state = cell.zero_state(batch,tf.float32)
    return init_state

def return_hidden_1():
    with tf.name_scope('hidden1'):
        weights_h1 = tf.Variable(
                            tf.truncated_normal([T, cells_dim],
                            stddev=1.0 / np.sqrt(T)),
                            name='weights')
        biases_h1 = tf.Variable(tf.zeros([cells_dim]),
                            name='biases')
        hidden1 = tf.nn.relu(tf.matmul(score, weights_h1) + biases_h1)

        return hidden1

init_state2 = tf.cond(is_start, lambda: return_hidden_1, lambda: return_init_state)

Notice how the methods are called within the context of tf.cond. Therefore, whatever op is created, will be within the context of tf.cond. Otherwise, in your case, the ops will run either ways.


text:
Q: Unsplash API - How to obtain search / suggestion words? I have a task of making a search bar in React. When you type at least 3 characters in, the suggestions start popping up. Then, after selecting one, the related photos from Unsplash show up on the page.
I've already got two separate components - a search bar that will give suggestions from a hard coded / provided array and a search bar that will show Unsplash photos after typing a word.
But I don't know how to connect them - Do I need an array with Unsplash keywords? But how do I obtain it? I don't think I should be preloading all millions of photos first, do I?
Thank you for the answers.

A: In documentation of the project theres no word about returning suggestions, so I think they don't support this.
If you ask how is it working on production - api is returning an object with 5 suggestions related to sent query. You can check this in "Network" tab when you type something into the searchbar on their website, just paste the link they fetch into your browser.
Does it answer your question?


text:
Q: how i use in c# form data send by ajax I have written this javascript code:
$(document).ready(function(){
     $("form").submit(function(){
             var form = $("form").serialize();
             $.ajax({
                   type:"post",
                   url: "App_Code/data.cs/myFunction",
                   data:form,
                   datatype:"json",
                   success: function
           });
     });
});

How do I get the posted form data in the C# function?

A: You can't just call a function from the brower.
You need use with asp.net MVC.
Your function has to be part of a controller, so you can call it from the client side.
You have here official documentation and here good tutorial in hebrew.


text:
Q: Unable to Update R on Linux Mint 18 I am unable to install the R package ggplot2 because it depends on the package digest, which requires R (>= 3.3.0) and I only have 3.2.3. I tried upgrading R as described here, but I get an unusual message after the first line and an error after the third. The results of the first 3 lines are below exactly as the appear on the command terminal, edited for privacy and empty lines before commands added for clarity.
Name1@Name2 ~ $ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
[sudo] password for Name1:
Executing: /tmp/tmp.BIQ28xf0ql/gpg.1.sh --keyserver
keyserver.ubuntu.com
--recv-keys
E298A3A825C0D65DFD57CBB651716619E084DAB9
gpg: requesting key E084DAB9 from hkp server keyserver.ubuntu.com
gpg: key E084DAB9: "Michael Rutter <marutter@gmail.com>" not changed
gpg: Total number processed: 1
gpg:              unchanged: 1

Name1@Name2 ~ $ sudo echo "deb http://cran.wustl.edu/bin/linux/ubuntu xenial/" | sudo tee -a /etc/apt/sources.list
deb http://cran.wustl.edu/bin/linux/ubuntu xenial/

Name1@Name2 ~ $ sudo apt update
E: Malformed entry 2 in list file /etc/apt/sources.list (Suite)
E: The list of sources could not be read.

All commands after the third give the same errors, with commands 4 and 6 giving the errors twice for some reason.
I will be frank and admit that this whole think is very beyond me and I am just copying and pasting the code that supplied without understanding most of it. Any help will be greatly appreciated.
EDIT: Answer available here.

A: You are almost there, but it seems like your sources.list may be malformed.
First delete all entries related to R by using nano /etc/apt/sources.list (or your favorite editor).
Then as you did add the key
$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
Then add the correct repository
sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'
Quick update
sudo apt update
Install r-base by
sudo apt-get install r-base
And confirm everything is working with
R --version


text:
Q: detect AVPlayerViewController Done button click? I'm writing Plugin for AVPlayer in ios. I need to know when user click on Done button in AVPlayerViewController ( I want to know when user close video) and I don't access to AVPlayerViewController object. I checked event and found only rate property in AVPlayer set to 0 but in pause situation also the rate set to 0 . how I figure out these two situations ?
thanks all.

A: I met the problem when I was developing the player in windowed mode. It is currently impossible without tricks. Therefore, I used KVO to observe contentOverlayView which is actually a full-size view of AVPlayerViewController. Code is a bit complicated.  In the example below, playerView property is a view from xib/storyboard on the view controller (see attached).
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>

static NSString * const kBoundsProperty = @"bounds";
static void * kBoundsContext = &kBoundsContext;

@interface ViewController ()

@property (nonatomic, strong) AVPlayerViewController *playerViewController;
// View for windowed mode.
@property (weak, nonatomic) IBOutlet UIView *playerView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.playerViewController = [[AVPlayerViewController alloc] init];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // Because in -viewDidLoad frame is unknown.
    [self loadPlayerView];
}

- (void)loadPlayerView {
    NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
    AVPlayer *player = [[AVPlayer alloc] initWithURL:videoURL];
    self.playerViewController.player = player;

    [player play];

    [self addChildViewController:self.playerViewController];
    [self.playerView addSubview:self.playerViewController.view];

    // MARK: I would recommend to use constraints instead of frame.
    self.playerViewController.view.frame = self.playerView.bounds;

    [self.playerViewController.contentOverlayView addObserver:self forKeyPath:kBoundsProperty options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:kBoundsContext];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (context == kBoundsContext) {
        CGRect oldBounds = [change[NSKeyValueChangeOldKey] CGRectValue];
        CGRect newBounds = [change[NSKeyValueChangeNewKey] CGRectValue];

        BOOL wasFullscreen = CGRectEqualToRect(oldBounds, [UIScreen mainScreen].bounds);
        BOOL isFullscreen  = CGRectEqualToRect(newBounds, [UIScreen mainScreen].bounds);
        if (isFullscreen && !wasFullscreen) {
            if (CGRectEqualToRect(oldBounds, CGRectMake(0.0, 0.0, newBounds.size.height, newBounds.size.width))) {
                NSLog(@"Rotated fullscreen");
            } else {
                NSLog(@"Entered fullscreen");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"DidEnterInFullscreen" object:nil];
                });
            }
        } else if (!isFullscreen && wasFullscreen) {
            NSLog(@"Exited fullscreen");
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"DidExitFromFullscreen" object:nil];
            });
        }
    }
}

@end


text:
Q: Send array of data to mqtt node js I am trying to send an array of data by node to my mqtt server.
I have a receive function working but I cannot get it working in the other way.
  var message = new Array();
  message[0]  = 108;
  message[1]  = 11;
  client.publish("/topic", message, {
            retain: false,
            qos: 0
        });

But I get
[ERROR] TypeError: invalid data

I don't know how I have to declare the array to be able to fill all the data and send it. In my recevie function I get the message variable as an argument and I can read it like an array: message[x]...

A: mqtt supports Buffer or String
to use typed Array you have to convert it to buffer
you can use this npm module https://www.npmjs.com/package/typedarray-to-buffer
var toBuffer = require('typedarray-to-buffer')
  var message = [];
  message[0]  = 108;
  message[1]  = 11;
var arr = new Uint8Array(message)
arr = toBuffer(arr)

/*
arr.toString()  // '\u0001\u0002\u0003'
arr.readUInt16BE(0)  // 258
*/
// arr is a buffer now!
  client.publish("/topic", arr, {
            retain: false,
            qos: 0
        }, function(){
  console.log("message published"));


text:
Q: Core 3.1 EF 6 in Database-first: unable to determine the many-to-many relationship I have a problem with using EF "database-first" in Core 3.1 with many-to-many relationship.
There are two tables: ResourcesAZEZ and AsezPoolFileStore
And third table AsezPoolFileLink, which contains only two columns: idRes and idFile
Auto-generated code of that classes:
 public partial class AsezPoolFileStore
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public AsezPoolFileStore()
        {
            this.ResourcesAZEZs = new HashSet<ResourcesAZEZ>();
        }

        public int id { get; set; }
        public string fileId { get; set; }
        public string filePath { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ResourcesAZEZ> ResourcesAZEZs { get; set; }
    }

public partial class ResourcesAZEZ
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public ResourcesAZEZ()
        {
            this.AsezDictResLinks = new HashSet<AsezDictResLink>();
            this.AsezPoolFileStores = new HashSet<AsezPoolFileStore>();
        }

        public int id { get; set; }
        public string id_outer { get; set; }
        public string number_customer { get; set; }
        public string material_text_full { get; set; }
        public string mark { get; set; }
        public string requirements { get; set; }
        public string mark_main { get; set; }
        public string unit { get; set; }
        public Nullable<double> quantity { get; set; }
        public string producer_text { get; set; }
        public string delivery_date { get; set; }
        public Nullable<decimal> price { get; set; }
        public string currency { get; set; }
....

        public virtual AsezBSCatalog AsezBSCatalog { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AsezDictResLink> AsezDictResLinks { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AsezPoolFileStore> AsezPoolFileStores { get; set; }
    }

And in model.edmx:
          <EntitySetMapping Name="AsezPoolFileStore">
            <EntityTypeMapping TypeName="BCR_ASEZModel.AsezPoolFileStore">
              <MappingFragment StoreEntitySet="AsezPoolFileStore">
                <ScalarProperty Name="id" ColumnName="id" />
                <ScalarProperty Name="fileId" ColumnName="fileId" />
                <ScalarProperty Name="filePath" ColumnName="filePath" />
              </MappingFragment>
            </EntityTypeMapping>
          </EntitySetMapping>

<EntitySetMapping Name="ResourcesAZEZs">
            <EntityTypeMapping TypeName="BCR_ASEZModel.ResourcesAZEZ">
              <MappingFragment StoreEntitySet="ResourcesAZEZ">
                <ScalarProperty Name="winner_okved" ColumnName="winner_okved" />
                <ScalarProperty Name="winner_kpp" ColumnName="winner_kpp" />
                <ScalarProperty Name="winner_inn" ColumnName="winner_inn" />
                <ScalarProperty Name="winner_id_asez" ColumnName="winner_id_asez" />
                <ScalarProperty Name="okved2" ColumnName="okved2" />
                <ScalarProperty Name="okpd2" ColumnName="okpd2" />
                <ScalarProperty Name="dictId" ColumnName="dictId" />
                <ScalarProperty Name="numberpubl" ColumnName="numberpubl" />
                <ScalarProperty Name="previous_ppid" ColumnName="previous_ppid" />
                <ScalarProperty Name="number_cgg" ColumnName="number_cgg" />
...
                <ScalarProperty Name="id_outer" ColumnName="id_outer" />
                <ScalarProperty Name="id" ColumnName="id" />
              </MappingFragment>
            </EntityTypeMapping>
          </EntitySetMapping>

          <AssociationSetMapping Name="AsezPoolFileLink" TypeName="BCR_ASEZModel.AsezPoolFileLink" StoreEntitySet="AsezPoolFileLink">
            <EndProperty Name="ResourcesAZEZ">
              <ScalarProperty Name="id" ColumnName="idRes" />
            </EndProperty>
            <EndProperty Name="AsezPoolFileStore">
              <ScalarProperty Name="id" ColumnName="idFile" />
            </EndProperty>
          </AssociationSetMapping>

Everything look goodm the same as in the article.
But for some reasn I'm getting error:

System.InvalidOperationException   HResult=0x80131509   Message=Unable
to determine the relationship represented by navigation property
'ResourcesAZEZ.AsezPoolFileStores' of type
'ICollection'. Either manually configure the
relationship, or ignore this property using the '[NotMapped]'
attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Source=Microsoft.EntityFrameworkCore   StackTrace:    at
Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidatePropertyMapping(IModel
model, IDiagnosticsLogger1 logger)    at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger1 logger)    at
Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel
model, IDiagnosticsLogger1 logger)    at Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.NpgsqlModelValidator.Validate(IModel model, IDiagnosticsLogger1 logger)    at
Microsoft.EntityFrameworkCore.Metadata.Conventions.ValidatingConvention.ProcessModelFinalized(IConventionModelBuilder
modelBuilder, IConventionContext1 context)    at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelFinalized(IConventionModelBuilder modelBuilder)    at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalized(IConventionModelBuilder modelBuilder)    at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()  at Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()    at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder)    at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder)    at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite
callSite, TArgument argument)    at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite
callSite, RuntimeResolverContext context, ServiceProviderEngineScope
serviceProviderEngine, RuntimeResolverLock lockType)    at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite
singletonCallSite, RuntimeResolverContext context)    at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument)    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite
callSite, TArgument argument)    at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite
callSite, RuntimeResolverContext context, ServiceProviderEngineScope
serviceProviderEngine, RuntimeResolverLock lockType)    at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite
singletonCallSite, RuntimeResolverContext context)    at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument)    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)    at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)    at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()    at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()  at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.get_Model()    at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityType()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.CheckState() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityQueryable()
at
Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.System.Linq.IQueryable.get_Provider() at System.Linq.Queryable.Select[TSource,TResult](IQueryable1 source,
Expression`1 selector)    at
KROSS_Core.BLL.ASEZ.GSResourcesAZEZ.GetFilterFieldValues(String
entityName) in C:\Estimates Core\KROSS
Core\BLL\ASEZ\GSResourcesAZEZ.cs:line 1550    at
KROSS_Core.Controllers.GlobalSearchAsezController.AsezFiltersRead(HttpContext
context) in C:\Estimates Core\KROSS
Core\Controllers\GlobalSearchAsezController.cs:line 489    at
KROSS_Core.Controllers.GlobalSearchAsezController.Post() in
C:\Estimates Core\KROSS
Core\Controllers\GlobalSearchAsezController.cs:line 70    at
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object
target, Object[] parameters)    at
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper
mapper, ObjectMethodExecutor executor, Object controller, Object[]
arguments)    at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<g__Logged|12_1>d.MoveNext()

What am I doing wrong? Or how can I reconfigure relationship to make it working? Or where I can add [NotMapped] attribute in this database-first model? Appreciate for any help!

A: NM relationships in EFCore are a bit tricky. I see you have both ICollection<ResourcesAZEZ> property on AsezPoolFileStore and ICollection<AsezPoolFileStore> on ResourcesAZEZ this is not supported, as you need to have an "relationship entity", which I guess is AsezPoolFileLink.
So you should have a ICollection<AsezPoolFileLink> on both entities. Later you can map those entities to you application model or domain and remove the AsezPoolFileLink intermediate structure, so you can end having the collections you have now. Or always work with the "relationship entity" in between your two entites, up to you.
About your question on how to use [NotMapped] attribute, you do it like this:
[NotMapped]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ResourcesAZEZ> ResourcesAZEZs { get; set; }

This will make any property with this attribute to not being mapped to a field in the database by EFCore.
You can achieve the same functionality using FluentAPI by creating an override of void OnModelCreating(ModelBuilder modelBuilder) method of your DbContext like
public class SomeDbContext : DbContext
{
    public SomeDbContext(DbContextOptions<SomeDbContext> options)
        : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ResourcesAZEZ>()
        .Ignore(r => r.AsezPoolFileStores);

        modelBuilder.Entity<ResourcesAZEZ>()
        .HasMany(r => r.AsezDictResLinks)
        .WithOne(l => l.Resource);
    }
}

Official documentation on modeling with efcore can be found here https://learn.microsoft.com/en-us/ef/core/modeling/


text:
Q: labeling points in metafont's proofs? I am following the http://metafont.tutorial.free.fr/ tutorial, where labels is used to show given points in the proofs. I am not able to get them in my case. Can someone help?
mg:=1.5;
mode_setup;
tracingtitles:=1;
height#:=mg*9.6pt#;
midheight#:=mg*4pt#;
depth#:=mg*5pt#;
fullwidth#:=mg*3pt#;
pensize#:=mg*.3pt;
define_pixels(height,midheight,depth,fullwidth)

% points used for curves, and I also will have them labeled
pair pAA,pBB,pCC;
pAA:=(0,midheight);
pBB:=(0,0);
pCC:=(fullwidth,0);

beginchar("a",fullwidth#,midheight#,0); "a";
    pickup pencircle scaled pensize#;
    draw pAA .. pBB .. pCC;
    draw pCC -- pAA;
    %% label points here -- does not work :-(
    labels(pAA,pBB,pCC);
endchar

end;

after running mf foo.mf, gftodvi foo.2602gf, the foo.dvi looks like this (no points shown):

EDIT:
Besides the answers by egreg below, labeled points can be shown with makelabel("label",point):
    makelabel("AA",pAA);
    makelabel("BB",pBB);
    makelabel("CC",pCC);

produces

A: The instruction label takes as argument a list of suffixes, not of pairs; for example, labels(1) will show a dot and a 1 corresponding to point z1.
mg:=1.5;
mode_setup;
tracingtitles:=1;
height#:=mg*9.6pt#;
midheight#:=mg*4pt#;
depth#:=mg*5pt#;
fullwidth#:=mg*3pt#;
pensize#:=mg*.3pt;
define_pixels(height,midheight,depth,fullwidth)

% points used for curves, and I also will have them labeled

beginchar("a",fullwidth#,midheight#,0); "a";
z1=(0,midheight);
z2=(0,0);
z3=(fullwidth,0);
pickup pencircle scaled pensize#;
draw z1 .. z2 .. z3;
draw z3 -- z1;
%% label points here
labels(1,2,3);
endchar;

end;


text:
Q: Find character on next line based on postion on current line in regex Is it possible to find a character based on the previous line match position in regex?
The matching character does not have a fixed position.
Example. Where the # sign is positioned in the first line would match the character value from the next line.
This would give: 2
X#ZEAKBLA
123456789

This would give: 7
XIZEAK#LA
123456789

A: Here's a really complex version using conditionals:
^(?(?=#).*\n(.)|(?(?=.#).*\n.(.)|(?(?=..#).*\n..(.)|(?(?=...#).*\n...(.)|(?(?=^....#).*\n....(.)|(?(?=^.{5}#).*\n.{5}(.)|(?(?=^.{6}#).*\n.{6}(.)|#))))))).*$

Basically what it does is to first check for beginning of line and start a multi leveled conditional (if/then/else).
Then follows a test for an increasing number of any characters, starting with 0 (and in this example going up to 7) and after that it test for a match of #.
If that is fulfilled, it matches the rest of the line, a line feed, and the same number of any character found in the previous test which puts us in the same position as the # from the in above.
So now we just capture a single character, which is the result!
If the match with n characters followed by a # wasn't met, it test the next else which has n+1 charaters before the #, and so on...
If the final test fails, a match for # is made (which in a full scale version shouldn't be present) to make the match fail.
Finally, after closing the conditional, the rest of the line is matched to avoid continued matching on the current line, if a global flag is used.
See it here at regex101.
Edit
Reduced complexity somewhat by movinf the actual capturing out of the test, to outside it at the end, before matched rest of line:
^(?(?=#).*\n|(?(?=.#).*\n.|(?(?=..#).*\n..|(?(?=...#).*\n...|(?(?=....#).*\n....|(?(?=.{5}#).*\n.{5}|(?(?=.{6}#).*\n.{6}|#)))))))(.).*$

Here at regex101.
Edit2
Kinda got stuck on this one ;)
Here's an even simpler version. (I've replaced the index character with ■ (ASCII 254), mainly to allow for comments within the regex, but also to improve readability (imo).)
^               # Match start of line
(?(?=■).*\n|.   # Test if first character is a ■. If not match one of anything
(?(?=■).*\n|.   # Test if second character is a ■. If not match one of anything
(?(?=■).*\n|.   # Test if third character is a ■. If not match one of anything
(?(?=■).*\n|.   # and so on...
(?(?=■).*\n|.   # and so on...
(?(?=■).*\n|.   # and so on...
(?(?=■).*\n|■   # Match a last ! or force a fail (match ■)
.).).).).).).)  # "On the way out" of the match, "eat" characters on the next line
(.).*$          # Capture the character and match the rest of the line

As stated in the comments, it matches an arbitrary character after the match in all levels removing the need for specific match of each levels characters.
This one also makes it very much easier to add levels to the tests.
At regex101.

A: Regex and slice? As EASY solution to implement, for complexity check best answer in this same question, from @ClasG  -amazing
<button onclick="myFunction()">Try it</button>

     "123#4678911"

    1943215927


text:
Q: With scientific notation, two different floats evaluate as equal How come the following expression evaluates to true?
In [0]: 1e18 == (1e18 + 50)
Out[0]: True

When replacing the scientific notation by exponentiation, this evaluates, as one would expected, to False:
In [1]: 10**18 == (10**18 + 50)
Out[1]: False

A: You do not have two pairs of floats.  The top example, being scientific notation, is a pair of floats.  Since the added difference is less than float precision, they compare as equal.
The bottom example is a pair of integers.  You can easily check this with the type function.  Python's long integers have no problem keeping the needed 18 digits of accuracy.
>>> type(1e18)
<class 'float'>
>>> type(10**18)
<class 'int'>


text:
Q: Modifying Vue query with beforeEnter The scenario: I'm replacing one application with another - both have a /search route with potentially very long queries. The new data structure has changed considerably and, unfortunately, some URLs for the old application have been distributed elsewhere containing multiple parameters which no longer exist.
One way to deal with this might be to intercept each call to search and, by means of beforeEnter() modify query by looking up and replacing the offending terms. I'd have thought something like this:
{
    name: "search",
    path: "/search",
    component: Records,
    beforeEnter(to, from, next) {
        let query = hackSearch(to.query);  // replaces the old terms
        next({name: 'search', query: query});
    }

},

This causes Uncaught (in promise) InternalError: too much recursion, though. But, from what I understand of documentation and examples I've seen, this, or something like it, should work.

A: It's not great, but I modified hackSearch() so it would return whether or not it had found an offending term and replaced it. This enables the code above to be modified as follows:
{
    name: "search",
    path: "/search",
    component: Records,
    beforeEnter(to, from, next) {
        let [query, modified] = hackSearch(to.query);
        if (modified) {
            next({name: 'search', query: query});
        }
        else {
            next();
        }
    }

},


text:
Q: PHP Login Script Serving 500 Error Upon Submission First time PHPer looking for some help.
<?php
DEFINE ('DB_USER', 'hiddenforsecurity');
DEFINE ('DB_PSWD', 'hiddenforsecurity');
DEFINE ('DB_HOST', 'hiddenforsecurity');
DEFINE ('DB_NAME', 'hiddenforsecurity');

    $email = $_POST['email'];
    $password = $_POST['password'];

    if($email && $password){
      $dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME) or die("cant connect");

      $query = mysql_query("SELECT * FROM users WHERE email='$email'");

      $numrows = mysql_num_rows($query);

      if($numrows != 0){
        echo "Account Located";
      } else {
          die("that user doesn't exist");
      }
    } else {
      die("Please enter an email and a password.");
    }
 ?>

Here is my HTML form:
 <form method="POST" action="login.php">

    Email address
    <input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">

    Password
    <input type="password" name="password" class="form-control password" id="exampleInputPassword1" placeholder="Password">

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

When I press submit without anything in the inputs, I get the error specified in the PHP ("please enter an email and a password"). When I submit with test values for email and password that I manually placed in the DB, Chrome tells me that localhost is unable to handle this request, http error 500. I'm sure this is just a novice error and will be extremely grateful for any help. Thanks!
Other info:
I am running the PHP on MAMP.

A: You mixed up mysqli and mysql function so that can caused the 500 error


text:
Q: How to run "SELECT FOR UPDATE" for the default "Delete selected" in Django Admin Actions? I have Person model as shown below:
# "store/models.py"

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=30)

And, this is Person admin below:
# "store/admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    pass

Then, when clicking Go to go to delete the selected persons as shown below:

Then, clicking Yes I'm sure to delete the selected persons:

Only DELETE query is run in transaction as shown below:

Now, how can I run SELECT FOR UPDATE for the default "Delete selected" in Django Admin Actions?

A: You need to override delete_queryset() with @transaction.atomic as shown below to run SELECT FOR UPDATE for the default "Delete selected" in Django Admin Actions. *print(qs) is important to run SELECT FOR UPDATE:
# "store/admin.py"

from django.contrib import admin
from .models import Person
from django.db import transaction
from django.db import connection

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):

    @transaction.atomic # Here
    def delete_queryset(self, request, queryset):
        ids = []

        for obj in queryset:
            ids.append(obj.id)

        qs = queryset.select_for_update().filter(id__in=ids)
        print(qs) # <- Important to run "SELECT FOR UPDATE"
        qs.delete()

Then, when clicking Go to go to delete the selected persons as shown below:

Then, clicking Yes I'm sure to delete the selected persons:

SELECT FOR UPDATE query and DELETE query are run in transaction as shown below:

In addition, you can use raw queries as shown below if you want to run shorter queries:
# "store/admin.py"

from django.contrib import admin
from .models import Person
from django.db import transaction
from django.db import connection

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):

    @transaction.atomic # Here
    def delete_queryset(self, request, queryset):
        ids = ()
        qs_length = len(queryset)

        if qs_length > 1:
            for obj in queryset:
                ids += (obj.id,)
            ids = str(ids)
        elif qs_length == 1:
            ids = "(" + str(queryset[0].id) + ")"
        else:
            return

        with connection.cursor() as cursor: # Here
            query = "SELECT * FROM store_person WHERE id IN " + ids + " FOR UPDATE"
            cursor.execute(query)
            query = "DELETE FROM store_person WHERE id IN " + ids
            cursor.execute(query)

Then, when clicking Go to go to delete the selected persons as shown below:

Then, clicking Yes I'm sure to delete the selected persons:

shorter SELECT FOR UPDATE query and shorter DELETE query are run in transaction as shown below:

In addition, you can check the default code of delete_queryset() which is not overridden as shown below:
class ModelAdmin(BaseModelAdmin):

    # ...

    def delete_queryset(self, request, queryset):
        """Given a queryset, delete it from the database."""
        queryset.delete()


text:
Q: Is it better to put the id attribute in a "a" tag or in the "h1/h2" tag? I'm learning html in w3 school website and I'm at the "html link" chapter. What I don't understand is why they propose using the id attribute in the link tag instead of the heading tag.
Their example:

See also Chapter 4.

Chapter 4

This chapter explains ba bla bla

My try:

See also Chapter 4.

Chapter 4

This chapter explains ba bla bla

Both work the same when I try them but my try take less writing. Is there something wrong in my try that I don't understand.

A: It often seems something of a well-kept secret that you can anchor link to elements by their ID, rather than, as more usually, an a tag via its name attribute. This is probably because the former was a later introduction, and so the a tag approach used to be the only means of internal linkage.
So yes, your approach is perfectly valid.
W3SChools, incidentally, while undoubtedly useful at times, has come under fire for some less than solid content over the years. Do not treat it as gospel - it is not affiliated with the W3C, it's just someone's attempt to teach web dev.
Finally, don't confuse head*er* tags with head*ing* tags; in your case it's heading, not header. That's a different tag entirely.

A: Before linking to any element by its id was possible, you could link to  elements by their name.
The transitional period used id and name on anchors. There's no need to worry about that unless you are targeting Netscape 4 (I might be misremembering, that could the the first browser to support id linking rather than the last to not, but either way, it's ancient history).
W3Schools just has a lot of legacy rubbish in it (and is best avoided as a learning resource).
Use the id on the heading (or on the container (
 maybe?) that the heading and associated content is inside).

A: W3Schools is far from an authoritative resource (see http://www.w3fools.com/ for more on that).
It's perfectly fine to define an id on the heading tag, and indeed the w3 documentation for HTML4.01  does exactly that.

A: The other answers here explain the actual answer very well, but since the original (poor) recommendation came from a W3Schools tutorial, I would like to point you to some more reputable resources:
Firstly, there is MDN, the Mozilla Developer Network. Although run by the makers of Firefox, it has a very good coverage of where things are standardised, and how well different browsers support them. It tends to be better for technical reference than tutorials, and I didn't find anything directly relevant, but the page documenting the  element includes this note on the name attribute:

Usage note: This attribute is obsolete in HTML5, use global attribute id instead.

I mention MDN mostly because it is a very mature reference site, and a good replacement for that part of W3Schools content.
Secondly, there is WebPlatform.org which unlike W3Schools is affiliated with both the W3C and the developers of the major browsers, and aims to include both reference and tutorial information which is accurate and up to date, although some of it is still work in progress.
They have an HTML link tutorial which directly answers your question:

You can also put an id attribute on an  element, to make it into a page anchor.
  [...]
  But most browsers you'll want to support these days allow you to write a shortcut for this, and put the ID directly on the element you want to link to
  [...]
  This is much simpler, so we'd recommend that you stick to this.


text:
Q: Error 'Notice: trying to get property of non-object' on host's webserver but not on my localhost I've got the above error message when trying to use the block.io API on my web host's server. The JSON object returns 'success' with an object on my localhost using the exact same script. The PHP version of my localhost is 5.6.10 and on my web host they run 5.5.
Is there any reason for getting the correct response on my localhost but not on the web host's server?
here is my code:
<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once('block_io.php');

$apiKey = "my API key";
$version = 2; // API version
$pin = "my password";
$block_io = new BlockIo($apiKey, $pin, $version);

$newAddressInfo = $block_io->get_new_address(array());

var_dump($newAddressInfo);

?>

This is the response from my localhost:
object(stdClass)#2 (2) { ["status"]=> string(7) "success" ["data"]=> object(stdClass)#3 (4) { ["network"]=> string(4) "DOGE" ["user_id"]=> int(27) ["address"]=> string(34) "A7wNbTJYhJb5FYJbg1cYW67fJNRGwXLBiP" ["label"]=> string(7) "quine46" } }

This is the response from my hosted script:
Notice: Trying to get property of non-object in /home/sites/**************.com/public_html/block_io.php on line 121

Fatal error: Uncaught exception 'Exception' with message 'Failed: ' in /home/sites/**************.com/public_html/block_io.php:121 Stack trace: #0 /home/sites/**************.com/public_html/block_io.php(65): BlockIo->_request('get_new_address', Array) #1 /home/sites/**************.com/public_html/block.php(14): BlockIo->__call('get_new_address', Array) #2 /home/sites/**************.com/public_html/block.php(14): BlockIo->get_new_address(Array) #3 {main} thrown in /home/sites/**************.com/public_html/block_io.php on line 121

exact same script, different outcome. Any ideas?


text:
Q: javascript getattribute issues IE 11 i m using getattribute in javascript and its not working in IE 11. Is there any equivalent for getattribute. below is my code.
code :-
var innerFrames = currentRow.all.tags("iframe");

if(innerFrames.length > 0)
{
  var currentFrame = innerFrames[0];
  var frmID = currentFrame.getAttribute("id");
  var ownerID = currentFrame.getAttribute("displayID");
}
var sGroupCaption = (currentFrame.getAttribute("Caption") == null) ? "" : currentFrame.getAttribute("Caption");

if (currentFrame.getAttribute("isEmpty")!= null){ }

    var Type = (currentFrame.getAttribute("displayType") == null) ? "" : currentFrame.getAttribute("displayType");

pls suggest with what i can replcae this getattribute in javscript
Thanks

A: You can directly access in property like this:

*

*currentFrame.myProperty

*currentFrame["myProperty"]


text:
Q: While loop not executing C# using System;
using System.Data;

namespace HelloWorld
{
    class Program
    {

        static void Main(string[] args)
        {
            bool calc1 = false;

            bool end = false;

            double answer = 0.0;

            double num1 = Convert.ToDouble(Console.ReadLine());
            string op1 = Console.ReadLine();
            double num2 = Convert.ToDouble(Console.ReadLine());

            if (op1 == "*") ;
            {
                answer = (num1 * num2);
                calc1 = true;
            }

            if (op1 == "/") ;
            {
                answer = (num1 / num2);
                calc1 = true;
            }

            if (op1 == "+") ;
            {
                answer = (num1 + num2);
                calc1 = true;
            }

            if (op1 == "-") ;
            {
                answer = (num1 - num2);
                calc1 = true;
            }

            while (end == false) ;
            {
                string op2 = Console.ReadLine();

                if (op2 == "*") ;
                {
                    double num3 = Convert.ToDouble(Console.ReadLine());
                    answer = (answer * num3);
                }

                if (op2 == "/") ;
                {
                    double num3 = Convert.ToDouble(Console.ReadLine());
                    answer = (answer / num3);
                }

                if (op2 == "+") ;
                {
                    double num3 = Convert.ToDouble(Console.ReadLine());
                    answer = (answer + num3);
                }

                if (op2 == "-") ;
                {
                    double num3 = Convert.ToDouble(Console.ReadLine());
                    answer = (answer - num3);
                }

                if (op2 == "=") ;
                {
                    Console.WriteLine(answer);
                    end = true;
                }

            }

        }
    }
}

I am trying to create a multi integer calculator but for some reason, my while loop does not execute so once I enter the first 2 digits and operator, it stops running. Before hand, I had 2 while loops and it would run the second one but it would not print the answer variable when the user entered =.

A: your issue is the semicolon ; after the while condition.
Remove it. (and also all the ; after the if conditions!)
Currently the code is like that:
while (condition);
{ you big block of code }  // <--- this is not part of the while loop

Because of the semicolon, it's actually the same as
while (condition)
    ;

the big block of code // <--- this is not part of the while loop

or even:
while (condition)
{
}

the big block of code // <--- this is not part of the while loop

If you remove the semicolon, then the block is now part of the loop;
while (condition)
{
    the big block of code // <--- Now it's like you intended to write!
}

This is the same problem with the ifs, by the way.
If you write a if (condition);, that's like if (condition) { }, and the other block below will be always executed.

A: You put a semicolon after the while loop, nothing is inside of it.
If you want to have a forever loop, I suggest you use while(true)
Edit:
OP, If you wanted to exit the loop at any time, you could simply just do break; instead of setting the condition equal to false.


text:
Q: GORM: lazily save a) I try to save a contact item belonging to the datastore domain classe as following:
class Contacts implements Serializable{

    static belongsTo = [dataStore:DataStore]

    DataStore dataStore
    String emailaddress

Class DS:
class DataStore implements Serializable{

    static belongsTo = [service:Service,user:User]
    static hasMany = [users:User,contacts:Contacts,groups:Groups]

    Service service
    User user
    User users
    List<Contacts> contacts

b) At the controller level i create a contact as an ajax request:
def create() {
        String key = session["KEY"]
        DataStore ds = session["DS"]
        def user = springSecurityService.currentUser
        def c = new Contacts(dataStore:ds,emailaddress:params.contacts.email)
        if (c.validate()) {
            ds.addToContacts(c).save(flush:true)
            c.save()

c) The following error prevents the saving
failed to lazily initialize a collection of role: $$$.DataStore.contacts, no session or session was closed. Stacktrace follows:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: $$$.DataStore.contacts, no session or session was closed
    at $$$$.ContactsController$$EO4iccbg.create(ContactsController.groovy:115)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)
    at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
    at net.bull.javamelody.JspWrapper.invoke(JspWrapper.java:149)
    at net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:259)
    at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:202)
    at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:175)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:680)

A session is active ... what does it means ? Any idea to solve this issue ? Thanks

A: After lookine a while on hibernate side about GrailsOpenSessionInViewFilter, I finally came to a solution by resetting the dataStore session like this:
def dsx = DataStore.get(ds.id)


text:
Q: Magento 2 problem with remote DB connection I have set host value to use a remote IP in my env.php file.
But I got an error saying "Access denied for user 'manager'@'localhost'(using password: YES)"
why Magento 2 still says I'm using the localhost?
I have tested the username and password for mysql, so I'm sure they are correct.
And the mysql user I used have remote access
I have cleared the Cache, di, generation folder.

A: It already happened here, maybe your database doesn't have permit to this user, to check use this command below changing the user (-u parameter), password (-p parameter), host (-h parameter) and database (-D parameter):

mysql -uroot -proot -h 127.0.0.1 -D database

If it doesn't work, try access with your root user to check.


text:
Q: Scrape table with BeautifulSoup I have a table structure that looks like this :

testtestestes

8-K
Current report, items 1.01, 3.02, and 9.01

Accession Number: 0001283140-16-000129  Act: 34  Size: 520 KB

2016-09-19
17:30:01
 2016-09-19	001-03473

161891888

That is one row of data. This is my script using beautifulSoup. I can get the
 and  just fine. But they are in a separate list.
for tr in (soup.find_all('tr')):
        tds = tr.find_all('td')
        print tds

My problem is how can I get the data from two separate
 and make it look like they're one row of data. I am trying to get the text between

A: If you want to pair them up, create an iterator from soup.find_all('tr') and zip them into pairs:
it = iter(soup.find_all('tr'))
for tr1, tr2  in zip(it, it):
        tds = tr1.find_all('td') + tr2.find_all("td")
        print(tds)

The equivalent with slicing would be to start with a different start pos and use a step of 2:
it = soup.find_all('tr')
for tr1, tr2  in zip(it[::2], it[1::2]):
        tds = tr1.find_all('td') + tr2.find_all("td")
        print(tds)

Using iter  means you don't need to shallow copy the list.
Not sure how having an uneven amount of trs fits into the logic as there would be nothing to pair but if there is you can use izip_longest:
from itertools import izip_longest # python3 zip_longest

it = iter(soup.find_all('tr'))
for tr1, tr2  in izip_longest(it, it):
        tds = tr1.find_all('td') + tr2.find_all("td") if tr2 else []
        print(tds)


text:
Q: Confirm Email address available before submitting rails 3 i am using devise for my user authentication in my app, something that i would like to do is after the user types their email address a little icon appears on the side of the field to state whether the email address is available, i know that this will be confirmed upon submission of the form, but I thought it would be a nice touch to have this confirm before submission.The same with the password and confirm password field.
I was looking for some resources on where to start looking or take some advice off someone who has done this before?
Thanks

A: Seems I should have googled a bit more before asking question,
check out
http://railscasts.com/episodes/263-client-side-validations?view=asciicast


text:
Q: Sort a container with a lambda with captured value I'm trying to declare a std::set with a compare function to specify the order of elements by using a lambda with a captured value.
I've tried creating a lambda with the captured value an pass that lambda as a templated argument to the std::set.
I've also tried with a functor, and could't make it work either.
//Using a lambda

int value = 3; //This is not known at compile time

std::function cmp = [&value](int a, int b){
   return value > 123 ? a < b : a >= b;
};

std::set<int, cmp> mySet;

// Using a functor

class Cmp{
    int value;
public:
    Cmp(int value) : value(value){};
    bool operator()(const int&a, const int& b){
        return value > 123 ? a < b : a >= b;
    }
};

int val = 3; //This is not known at compile time

Cmp cmp(val);
set<int, cmp> mySet;

I get this error when using the lambda:

note: a lambda closure type has a deleted default constructor

And this one when using the functor:

error: no matching function for call to 'Cmp::Cmp()'

A: You can't pass a runtime variable in a template parameter.
The Compare template parameter of std:set expects a typename, not a variable.  The actual comparison function matching the typename can be passed to the set::set constructor.
Try this instead:
//Using a lambda

int value = 3; //This is not known at compile time

auto cmp = [&value](int a, int b){
   return value > 123 ? a < b : a >= b;
};

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

//Using a functor

class MySetComparer{
    int value;
public:
    MySetComparer(int value) : value(value) {}
    bool operator()(int a, int b) const {
        return value > 123 ? a < b : a >= b;
    }
};

int val = 3; //This is not known at compile time

MySetComparer cmp(val);
set<int, MySetComparer/*decltype(cmp)*/> mySet(cmp);

NOTE: either way, do be aware that your comparer's use of a >= b breaks strict weak ordering of the Compare requirement used by standard C++ containers:

The return value of the function call operation applied to an object of a type satisfying Compare, when contextually converted to bool, yields true if the first argument of the call appears before the second in the strict weak ordering relation induced by this type, and false otherwise.

a < b satisfies that requirement, but a >= b does not, which will cause Undefined Behavior in your code at runtime when value > 123 is not true.


text:
Q: selenium opens Chrome instance after making changes in code I have a simple scraper using selenium. It worked as expected until I started debugging the code and after a second I suddenly stopped the debugger. After this, whenever I make any changes in the code, the Chrome browser instance is opened automatically, stays open for a few seconds, repeats all the steps that I have defined in the code (scrolling a webpage, waiting for the element to show, and clicking some elements and so on), and quits after that.
Why do I have this sort of behavior and how can I solve this? The smallest change in code triggers selenium to open Chrome.
Edit:
Here is almost full code:

    class Scraper:

        def __init__(self, driver=selenium.webdriver.Chrome, scroll_pause=1, timeout=10):
            options = Options()
            options.add_argument("--headless")
            self.driver = driver(chrome_options=options)
            self.scroll_pause = scroll_pause
            self.timeout = timeout
            self.driver.get("https://www.example.com")
            self.driver.set_window_size(1920, 1080)

        def wait(self, condition):
            return WebDriverWait(self.driver, self.timeout).until(condition)

        def wait_for_el(self, selector):
            return self.wait(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))

        def count_elements(self):
            return self.driver.find_elements(By.CSS_SELECTOR, ".element_css_here")

        def scroll_to_bottom(self):
            start = datetime.now()
            while True:
                self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
                time.sleep(self.scroll_pause)
                try:
                    if self.driver.find_element(By.XPATH, '//div[@class="display-flex p5"]/button').is_displayed():
                        self.driver.find_element(By.XPATH, '//div[@class="display-flex p5"]/button').click()
                        self.wait_for_el(".element_css_here")
                        self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
                except NoSuchElementException:
                   self.count_elements
                   break
            logger.info(f"Scrolled to bottom in {datetime.now() - start}")

        def scrape(self, page):
            self.driver.get(page)
            try:
                self.wait_for_el(".css_selector_here")
            except TimeoutException:
                self.driver.quit()

            total_connections_text = self.driver.find_element(By.CSS_SELECTOR, ".css_selector_here").text
            self.count_elements = int(re.search(r"(\d+)", total_connections_text).group(1))
            logger.info(f"Found {self.count_elements} elements")

            logger.info("Scrolling to bottom...")
            self.scroll_to_bottom()
            result = self.get_all_data()
            self.driver.quit()
            return result

Second Edit:
I'm using vscode and I suspect it's vscode fault but cannot verify that.
Another update:
I observed this behavior right now. When I make changes in VSCode settings selenium script is triggered and opens the Chrome browser.


text:
Q: Running Yii framework testing by Phing I'm using yii framework and I build some tests.
one test the database and model and one test ui by selenium.
I try to build xml file for phing to run this tests (I'm using Jenkins).
But phing didn't like to take phpunit.xml as a configuration. and my selenium test fails.
This is log using phpunit ->
phpunit functional/signupTest.php

PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from /var/www/myProject/protected/tests/phpunit.xml

............

Time: 01:29, Memory: 6.00Mb

OK (12 tests, 0 assertions)

This is log using Phing for the same test ->
    Buildfile: /var/www/myProject/protected/tests/build.xml

myProject > test:

  [phpunit] Testsuite: signupTest
  [phpunit] Tests run: 6, Failures: 0, Errors: 6, Incomplete: 0, Skipped: 0, Time elapsed: 0.05331 s
  [phpunit] testShow ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?
  [phpunit] testCreate ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?
  [phpunit] testUpdate ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?
  [phpunit] testDelete ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?
  [phpunit] testList ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?
  [phpunit] testAdmin ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?
  [phpunit] Testsuite: SiteTest
  [phpunit] Tests run: 3, Failures: 0, Errors: 3, Incomplete: 0, Skipped: 0, Time elapsed: 0.02317 s
  [phpunit] testIndex ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?
  [phpunit] testContact ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?
  [phpunit] testLoginLogout ERROR
  [phpunit] Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/': ERROR Server Exception: sessionId should not be null; has this session been started yet?

BUILD FINISHED
Total time: 0.2542 seconds
This is PHPunit.xml configuration ->
<phpunit bootstrap="bootstrap.php"
        colors="false"
        convertErrorsToExceptions="true"
        convertNoticesToExceptions="true"
        convertWarningsToExceptions="true"
        timeout="30000"
        stopOnFailure="false">

    <selenium>
        <browser name="Google Chrome" browser="*chrome" />
        <browser name="Firefox" browser="*firefox" />
    </selenium>

</phpunit>

This is build.xml (Phing) configuration ->
<?xml version="1.0" encoding="UTF-8"?>
<project name="myProject" default="test">

        <target name="test" description="Launch PHPUnit Testing">
                <phpunit bootstrap="bootstrap.php" printsummary="false">
                        <formatter type="plain" usefile="false"/>
                        <batchtest>
                                <fileset dir=".">
                                        <include name="unit/Test.php"/>
                                         <include name="functional/*Test.php"/>
                                </fileset>

                        </batchtest>
                </phpunit>
        </target>
</project>

How can I run Jenkins test to my yii project?

A: Here's a guess, I've never used Yii.
I'm guessing that when you run your tests you run them from the tests folder. Also that, when you run phing you run from the root of the project.
To fix I think you need to tell phing to run PHPUnit in the tests folder, not from the root folder.


text:
Q: Power BI/DAX: Filter SUMMARIZE or GROUPBY by added column value because of confidential nature of data, I'll try to describe what I'm struggling with using some random examples.
Let's say I have a fact table with invoices data in Power BI. I need to count number of distinct product ID's with sales over let's say €50k in last 12 months or to be more precise in 12 months prior selected date. At the same time I need to be able to narrow down results to selected Country, Product group and Product category.
I've started with setting the dates range for DATESBETWEEN like this:
productsCount =
VAR lastDay = IF(MAX('Calendar table'[Date]) > NOW(); NOW(); MAX('Calendar table'[Date]))
VAR firstDay = EDATE(lastDay; -12)
RETURN

But then I got lost:
CALCULATE(
    COUNTROWS('Sales');
    SUMMARIZE(
        'Sales';
        'Sales'[ProductID];
        "prodSales"; SUM('Sales'[EUR])
    );
    DATESBETWEEN('Sales'[Date]; firstDay; lastDay);
    ALLEXCEPT(
        'Sales';
        'Sales'[Product group];
        'Sales'[Product category];
        'Sales'[Country]
    );
    [prodSales] > 50000
)

The thing is that I need to be able to filter summarized data by sum of sales before I'll count rows.

A: I haven't tested this but I think something like this might work where you filter after summarizing:
productsCount =
VAR lastDay =
    IF (
        MAX ( 'Calendar table'[Date] ) > NOW ();
        NOW ();
        MAX ( 'Calendar table'[Date] )
    )
VAR firstDay = EDATE ( lastDay; -12 )
RETURN
    COUNTROWS (
        FILTER (
            CALCULATETABLE (
                SUMMARIZE ( 'Sales';
                   'Sales'[ProductID];
                   "prodSales"; SUM ( 'Sales'[EUR] )
                );
                DATESBETWEEN ( 'Sales'[Date]; firstDay; lastDay );
                ALLEXCEPT (
                    'Sales';
                    'Sales'[Product group];
                    'Sales'[Product category];
                    'Sales'[Country]
                )
            );
            [prodSales] > 50000
        )
    )

A: In summarise, we can do filter after the summarize table
My input table is

I'm writing query
App Downlaod Count =

FILTER(
    SUMMARIZE(events_intraday,
    events_intraday[event_name],
    events_intraday[event_date],
    events_intraday[platform],
    events_intraday[stream_id],
    "Count",CALCULATE(
        COUNT(events_intraday[event_name]),
            FILTER(events_intraday,
                    (events_intraday[platform] = "ANDROID" ||
                    events_intraday[platform] = "IOS")
                )
            )
        ),
        events_intraday[event_name] = "first_open" &&
        (events_intraday[stream_id] = "1415470954" ||
        events_intraday[stream_id] = "1420775080")
    )

Output is

A: You can create a summarized table in power query editor and then create a measure in dax to filter the result over 50k.


text:
Q: node.js get batch output on console I am using a remote windows batch file through node.js in below script.
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const { stdout, stderr } = await exec('PsExec64 \\\\xxx.xx.xx.xx -u username -p password cmd /c "C:\\work\\test"');
  console.log('stdout:', stdout);
  console.log('stder:', stderr);
}
lsExample();

It is working in background and completes successfully. The problem is , i am not getting batch file "test.bat" output in console. It just gives below output.
D:\angular\app\server\try>node try.js
stdout:
PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com

Starting cmd on xxx.xx.xx.xx... xxx.xx.xx.xx...
cmd exited on xxx.xx.xx.xx with error code 0.

No output is shown in local console. Batch file is very simple,
echo batch start >output.log
FOR /L %%x in (1,1,10) DO echo %%x Hello Testing>>output.log

I also want to read output.log. Please suggest, if I am missing something.
Thanks

A: The node.js part is working, it shows the output of the invoked command (PsExec64) in the console, it seems more a systems programming problem. Anyway, reading this ( https://learn.microsoft.com/es-es/sysinternals/downloads/psexec ) I would add -i to the PsExec64 options. (Disclaimer: I can't test it right now)


text:
Q: Using `_%` together in `LIKE` is not returning exact data I can guesss it may be easy to answer type question but I am facing it first time, so any help will be more appreciated.
My Query:
SELECT remarks FROM enroll WHERE remarks LIKE 'REC_%'

OUTPUT:
remarks
REC_59161
Reclassify Hedge

Expected Output is only REC_59161. Yes _ is used for matching any single character but I am just looking for achieving my expected output.

A: _ is a wildcard Character. So that you have to escape it using [].
Query
select remarks
from enroll
where remarks like 'REC[_]%';

A: The underscore _ character is actually a special character with the LIKE operator, as are %, [] and ^:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql
In that article, you'll see that an underscore _ matches any single character.
Use the ESCAPE keyword to define an escape character to allow you to escape the pattern-matching characters. We can use ! as the escape character, so:
WHERE remarks LIKE 'REC!_%' ESCAPE '!'

A: _ is a wildcard character, Try this :
declare @enroll table (remarks varchar(50));
insert into @enroll values ('REC_59161') , ('Reclassify Hedge');
SELECT remarks FROM @enroll WHERE remarks LIKE 'REC[_]%';

Demo

A: There are two issues:

*

*It seems that the column is case insensitive, see Is the LIKE operator case-sensitive with MS SQL server? for details. That's why Rec in Reclassify Hedge fits REC in the Like

*_ (as well as %) is a wild card, you should escape _ in the pattern

Query:
  SELECT remarks
    FROM enroll
   WHERE remarks LIKE 'REC*_%' ESCAPE '*' /* SQL 92 standard */

http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

 uses the triadic operator LIKE (or the inverse, NOT
  LIKE), operating on three character strings and returning a Boolean.
  LIKE determines whether or not a character string "matches" a given
  "pattern" (also a character string). The characters '%' (percent)
  and '_' (underscore) have special meaning when they occur in the
  pattern. The optional third argument is a character string
  containing exactly one character, known as the "escape character", for
  use when a percent or underscore is required in the pattern without
  its special meaning.