text:
Q: DataWeave Transformer help in coding I have this as an input: "keys":[{"key":"key1","value":"testKey1"},{"key":"Key2","value":"testKey2"}]
What I am trying to do is to get this output in json format:
   { "key1": "testKey1",
     "key2":testKey2}

I am trying with the DataWeave transformer in mule:
 %dw 1.0
 %output application/json skipNullOn="everywhere"
 ---
{
price: payload.price,
"": payload.keys filter $.value !=null
}

but it displays this:
"": [
{
  "value": "key1",
  "key": "testKey1"
},
{
  "value": "key2",
  "key": "testKey12"
}
]

Any Ideas?

A: I have used the following message snippet
    {
        "keys":
        [
            {
                "key":"key1",
                "value":"testKey1"},
            {
                "key":"Key2"
            }
        ]
    }

I Have transformed using the below Dataweave
%dw 1.0
%output application/json skipNullOn="everywhere"
---
{
    keys: payload.keys map {
        key: $.key,
        value: $.value
    }
}

The response is as below. When the Values is not available then the value does not appear in the response
    {
      "keys": [
        {
          "key": "key1",
          "value": "testKey1"
        },
        {
          "key": "Key2"
        }
      ]
    }

A: This should work:
Input:
{
  "keys":[
    {
     "key":"key1",
     "value":"value1"
    },
    {
     "key":"key2",
     "value":null
    },
    {
     "key":"key3",
     "value":"value3"
    }
  ]
}

Dw script:
%dw 1.0
%input payload application/json
%output application/json
---
{
  (payload.keys filter $.value !=null map {
     ($.key): $.value
  })
}

Output:
{
  "key1": "value1",
  "key3": "value3"
}


text:
Q: How to compute the correct residue without change of modulus? Suppose $F=1857$,   $G=2017$, and we want to compute $ FG \equiv 1606$ mod $(2^{11} -1)$.
Also let $t =2^4$, then $F = 1+4t+7t^2$ and $G = 1+14t+7t^2$, where the most significant digits are bounded by $2^3$ i.e. $[0,7]$. Now
$$FG \mod (t^3−1) = (49t^4 + 126t^3 + 70t^2 + 18t + 1) \mod (t^3−1) \\
= 70t^2 + 67t + 127$$
To me this reduction is a problem because we are reducing $2^{12} -1$. So what should be done here?
We can compute the correct residue by changing modulus i.e. $2(2^{11} - 1)$ but I don't want it that way.
The other details are given below
Since we know that we have to compute FG mod $2^{11}−1$ and the most significant digits $\in [0,7]$, then we have
$127 \texttt{ mod } 16=15, \qquad 127/16=7, \qquad (67+7) \texttt{ mod } 16=10, \qquad (67+7)/16 = 4, \\ (70+4) \texttt{ mod } 8=2, \qquad (70+4)/8=9, \qquad (15+9) \texttt{ mod } 16=8, \qquad (15+9)/16=1, \\ (10+1) \texttt{ mod } 16=11, \qquad (10+1)/16=0$
Lastly,  FG mod $(2^{11}- 1)=2\cdot 28 + 11\cdot 24 + 8 = 696 \quad$ Wrong

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is riverpod failing even to initialize in project? Method not found: 'Error.throwWithStackTrace' So i am trying to get started with riverpod and creating a new flutter project with the "click and counter" default sample.
As soon as I add on the pubspec
flutter_hooks: ^0.18.0
hooks_riverpod: ^2.0.0

And

import 'package:hooks_riverpod/hooks_riverpod.dart';

I get this error on the debug console and can't figure it out what is the problem
: Error: Method not found: 'Error.throwWithStackTrace'.
../…/framework/provider_base.dart:904
  Error.throwWithStackTrace(error, chain);
        ^^^^^^^^^^^^^^^^^^^
: Error: A non-null value must be returned since the return type 'Never' doesn't allow null.
../…/framework/provider_base.dart:898
Never _rethrowProviderError(Object error, StackTrace stackTrace) {
      ^

A: for anyone facing " Method not found: 'Error.throwWithStackTrace' " with firebase.
try to add this to your pubspec.yaml
dependency_overrides:
  firebase_messaging_platform_interface: 3.1.6

A: Error.throwWithStackTrace was added in Dart 2.16 (Flutter version 2.10 from Feb 8, 2022).
https://api.flutter.dev/flutter/dart-core/Error/throwWithStackTrace.html
(Check the @Since annotation.)
If your Flutter/Dart version is below that, you'll get the error you saw.
Two options that may help are:

*

*Specify an exact version of dependencies (don't use ^ ahead of version)

*upgrade Flutter/Dart to at least 2.10/2.16

flutter upgrade

If your problematic package (hooks_riverpod: ^2.0.0 in your case) is listed with ^, it'll use the latest version that doesn't break dependencies.
I'm guessing that when you created a new project and used that same dependency version, upon initial pub get it downloaded a newer version of the package (or a newer version of a dependency that that package uses) into "pub cache" which is relying on the new Error API method.
Your project will store this information in:
<your_project_dir>/dart_tool/package_config.json

The min Dart SDK version listed for the package should normally have changed from 2.12 to 2.16. (update: it's been updated now)  This would give us a hint that we need to update our Flutter/Dart if we see our build failing.
In an earlier version of this answer, I noted that the ^ prefix on package dependency versions is supposed to prevent these types of issues, but I'm no longer certain it was meant to cover this situation where the underlying platform needs to be updated (as opposed to a breaking change in the API of the package itself).
Anyways, at first glance, it might make sense to go from 2.0.0 to 3.0.0 for a package version # when it depends on a new core Dart API method that did not exist when 2.0.0 was published.
Notes
The author of riverpod also wrote the new API for Error.throwWithStackTrace so likely the latest version of hooks_riverpod is using the latest API changes. (The version you're listing 2.0.0 is pre-release currently).  You could try earlier versions of riverpod in your pubspec.yaml (such as 1.0.3)

A: I saw this.
How about trying flutter pub upgrade?
If it is not resolved, then check analyzer version and check which dependency locks that.

A: As noted in Baker's answer, Error.throwWithStackTrace was recently added in Dart 2.16.
If you're getting an error about Error.throwWithStackTrace not being found for some package, the package author neglected to update their package's minimum Dart SDK version.  You should report that to the package maintainer.  In the meantime, you should use an earlier version of the problematic package or use a newer version of the Dart SDK.

A: Try running flutter upgrade
By this it will upgrade your flutter and dart SDK version and hope it resolves your issue

A: if you are still facing the issues after "flutter upgrade" or you use this line of code in pubspec.yaml
  dependency_overrides:
    firebase_messaging_platform_interface: 3.1.6

you receive this type of errors
java.lang.AssertionError: annotationType(): unrecognized Attribute name MODULE (class com.sun.tools.javac.util.UnsharedNameTable$NameImpl)
    at com.sun.tools.javac.util.Assert.error(Assert.java:133)
    at com.sun.tools.javac.code.TypeAnnotations.annotationType(TypeAnnotations.java:231)
    at com.sun.tools.javac.code.TypeAnnotations$TypeAnnotationPositions.separateAnnotationsKinds(TypeAnnotations.java:294)
    at com.sun.tools.javac.code.TypeAnnotations$TypeAnnotationPositions.visitMethodDef(TypeAnnotations.java:1066)
    at com.sun.tools.javac.tree.JCTree$JCMethodDecl.accept(JCTree.java:778)
    at com.sun.tools.javac.tree.TreeScanner.scan(TreeScanner.java:49)
    at com.sun.tools.javac.code.TypeAnnotations$TypeAnnotationPositions.scan(TypeAnnotations.java:275)
    at com.sun.tools.javac.tree.TreeScanner.scan(TreeScanner.java:57)

so Try to upgrade your gradle version, this line in your build.gradle

classpath 'com.android.tools.build:gradle:4.1.0'

after doing that it may be possible it ask you to change your
gradle-wrapper.properties

distributionUrl=https://services.gradle.org/distributions/gradle-6.1.1-all.zip

to

distributionUrl=https://services.gradle.org/distributions/gradle-6.5-all.zip

also upgarde this packages
firebase_core: ^1.10.0
firebase_messaging: ^11.1.0


text:
Q: Passing conditional arrays to WP_Query() I've looked around at a few places and could not find an answer. I was wondering what the best way to create a WP_query from possibly empty variables were. I have about 16 of these $_GET variables.
if( isset($_GET['promotion']) ){
    $promotion = $_GET['promotion'];

    if($promotion == 'promotion'){
        $promo = 1;
    } else if($promotion == 'regulier'){
        $promo = 0;
    }
}

In some cases $promo might not be set. So how can I create a meta_query let's say with dependant on if $promo is set or not.
'meta_query' => array(
    array(
        'key' => 'model-promotion',
        'value' => $promotion
    )
)

If the meta_query is not set but present in my WP_query() the query breaks. Thanks for the help!

A: Just build the static part of the args array, then add the conditional variables, then pass the args array to WP_Query():
// Static args
$custom_query_args = array( /* static args here */ );

// Conditional arg
if ( 1 == $promo ) {
    $custom_query_args['meta_query'] = array( /* meta query array */ );
}

// Instantiate query
$custom_query = new WP_Query( $custom_query_args );


text:
Q: Context free grammar design - Why is this not allowed? I am still learning about the context free grammar. A particular kind of question I have doubt about is coming up with a grammar for some specific patterns.
For example:
"At least 3 zeros."
Why not just come up with a grammar that is like: S -> 000 ?
What rule forbids this kind of grammar?

A: What it could limit your grammar (forbid some constructs) is the grammar form that you use. In the Chomsky normal form (CNF) the rules are one of:
A → BC
A → a
S → ε

In the Greibach normal form (GNF) the rules are:
A → aBCD...

There is and the Backus–Naur form, where you have more richer syntax. Then the Extended Backus–Naur form (EBNF) and at best the Augmented Backus–Naur form (ABNF).
At least 3 zeroes in CNF:
S → AB
A → ZZ
B → ZB
B → 0
Z → 0

At least 3 zeroes in GNF:
S → 0A
A → 0B
B → 0B
B → 0

At least 3 zeroes in BNF:
<S> ::= "000" <A>
<A> ::= "0" <A> | ""

At least 3 zeroes in EBNF:
S = "000", { "0" }

At least 3 zeroes in ABNF:
S = 3*"0"

Some recognition (parsing) algorithms require the grammar to be in some form. For this reason you have to convert the grammar, if it is not already in it.


text:
Q: How to redirect a POST request to a url maintaining model values in MVC I have a fairly standard sort/filter/page search form but need control over the format of the url. The sort/filter/page parameters should all be part of the url so that, for example, the address could be emailed to someone.
When another filter parameter is added, a POST request is made. My controller method looks like this:
[HttpPost]
public ActionResult Search(string filterField,
                           Operator filterOperator,
                           string filterValue,
                           PeopleGroupSearchModel model);

The PeopleGroupSearchModel is populated from query string parameters. The filter* parameters are coming from the posted form values.
I would like to parse the provided filter values, which will then add a filter to a collection in the model called Filters. Then, take the updated model and convert it to the appropriate url and pass that as the response to the user.
So, for example, if they are on this page:
PeopleGroup/Search?page=4&sort=Country

... and POST:

*

*filterField = PeopleGroupName

*filterOperator = Equals

*filterValue = Zulu

... once all the processing is done, the address in their browser should be something like:
PeopleGroup/Search?page=4&sort=Country&PeopleGroupName=Zulu&PeopleGroupName_op=Equals

So, more or less what I am trying to do:
[HttpGet]
public ActionResult Search(PeopleGroupSearchModel model)
{
    PeopleGroupData.Search(model);
    ViewData.Model = model;
    return View();
}

[HttpPost]
public ActionResult Search(string filterField,
                           Operator filterOperator,
                           string filterValue,
                           PeopleGroupSearchModel model)
{
    PeopleGroupFilter filter = ParseFilter(filterField,
                                           filterOperator,
                                           filterValue);
    model.Filters.Add(filter);
    return RedirectToAction("Search", ???);
}

I am very new to MVC, so if I am going about this completely the wrong way, please let me know!

A: You can put the values you need to keep into  ControllerContext.RouteData.Values
    public ActionResult TestRedirect()
    {
        RouteValueDictionary routeValues = ControllerContext.RouteData.Values;
        routeValues.Add("Key1","value1");
        routeValues.Add("Key2","value2");

        return RedirectToAction("TargetRedirect", routeValues);
    }

If you need something more generic you could loop through the postet form elements.
EDIT
It would look something like the top rated answer here: How do you persist querystring values in asp.net mvc?

A: This is probably a violation of MVC priciples, but once I stopped fighting the framework and just thought about what I was trying to do in HTTP-land, this simple solution works for me:
[HttpPost]
public ActionResult Search(PeopleGroupColumn filterField,
                           Operator filterOperator,
                           string filterValue)
{
    var collection =
        HttpUtility.ParseQueryString(Request.QueryString.ToString());
    collection.Set(filterField.ToString(), filterValue);
    collection.Set(filterField.ToString() + "_op", filterOperator.ToString());
    return new RedirectResult(
        Request.Url.AbsolutePath + "?" + collection.ToString());
}

A: There are a couple of possibilities to implement the Redirect-After-Post pattern (which is what you are after here and which is a very good pattern IMHO) in ASP.NET MVC:

*

*Use TempData. In the POST action store the model inside TempData and redirect:
TempData["model"] = model;
return RedirectToAction("Search");

and then inside the Search action check for TempData existence to fetch the model:
PeopleGroupSearchModel model = TempData["model"] as PeopleGroupSearchModel;

The drawback of this approach is that TempData is persisted only for a single redirect meaning that if the user hits F5 while on the Search GET action you are screwed. This could be alleviated by using Session instead. But of course Session introduces another problems of scalability. So I am not fan of this approach.

*Pass all properties on the request:
return RedirectToAction("Search", new {
    prop1 = model.Prop1,
    prop2 = model.Prop2,
    ....
});

Now when redirected to the Search GET action the Default model binder will be able to reconstruct the model. An obvious drawback of this approach is that if your model has many properties and even worse properties of complex types this could quickly become a cumbersome solution. You could probably serialize the model using some text format such as JSON as a query string parameter. Of course query string parameters are limited between different browsers so this could also be a no-no.

*Persist the model in some data storage and retrieve an unique id so that it can later be retrieved from this storage:
int id = Persist(model);
return RedirectToAction("Search", new { id = id });

And then in the GET action retrieve the model from this very same persistence storage using the id. I like this approach and use it most of the time. If persisting to the aforementioned datastore is expensive you could use caching.


text:
Q: Why am I not Joel Spolsky? (or, treating newbie questions on SO that don't come from Joel) OK, so I saw this discussion about developer laziness and decided to try and follow  Mike Houston's suggestion from the comment of posting "How do I implement bubble sort?..." question.
Now, I was ready to sacrifice some reputation for the sake of science, as well as suffer some flame, so here's the result: Bubble-Sort . To summarize:

*

*Nearly instantly got 5 down-votes with no upvotes :(

*Someone instantly re-tagged the question as "Homework"

*Someone fairly rudely but quite accurately noted that the question was not as good as it should have been.

*People posted at least 2 very good answers that I saw. Don't know if they were the same people who down-voted.
So, my biggest question is, how come Joel Spolsky's infamous LOGO turtle moving question was voted up high, while this one was downvoted into oblivion? Was it merely Joel's name on it?

A: I was the one that originally edited Joel's question; and I would have voted to close if I hadn't googled "Turtle LOGO" and found out what he was talking about.
To answer your question: It doesn't matter to me who you are.
There are stark differences between Joel's question and your question:

*

*Joel's Question didn't have the propensity to be a homework question.

*Joel didn't ask us to 'plzsendtehcodez'.

If you had asked the question in such a way that it didn't appear like you wanted us to do your homework1 for you, then it probably wouldn't have been closed.

1I realize that it wasn't a homework question for you, but it is a possible homework question for someone out there.

A: For one thing, you could have mentioned that fact that you wanted to make sure SO had a bubble-sort-related question on it, and that's why you were making the question. To make it more likely to succeed, I would have linked to the similar Joel questions as evidence that you know what you're doing.
But otherwise you hit the nail on the head. Questions like that only work because they are highly visible due to the people asking them. Stack Overflow is not very friendly to that kind of question because, frankly, it looks like a "plz send me teh codez" question.
When Joel asks the same question, people give him the benefit of the doubt. When you ask it, it looks like a new user trying to take advantage of everyone's generosity.


text:
Q: How to specify those documents from Fire Store to get fetched into a particular Users RecyclerView activity? enter image description hereHow to specify those documents from Fire Store to get fetched into a particular Users RecyclerView activity?
i have a list of documents in fireStore from multiple users and now i want to fetch those documents in recyclerView.
My problem is how to specify the documents written by a single user having same userID's to get fetched in the users recyclerview.
Query query = FStore.collection("Grievances For College");

    FirestoreRecyclerOptions<StatusAdapter> options = new FirestoreRecyclerOptions.Builder<StatusAdapter>()
            .setQuery(query, StatusAdapter.class)
            .build();


text:
Q: How to get search value from ui-select on change event I am trying to capture and call a function on the search value of a ui-select element. Specifically, I want to get the value of the ui-select-match element on each keystroke.
In a normal input element, I could do something like this:
// controller
class selectController {
  constructor($scope) {
    this.$scope = $scope;
    this.query = '';
    this.numChars = 0;

  countChars(q) {
    this.query = q;
    this.numChars = q.length;
  }
}

// template
<input ng-model="q" ng-change="ctrl.countChars(q)">...</input>

However, using the angular ui-select, I cannot capture the search input value on the onchange event.
for example:
// controller
class selectController {
  constructor($scope) {
    this.$scope = $scope;
    this.query = '';
    this.numChars = 0;
    this.advisor = {};
    this.advisors = [
      { name: 'Cheryl Aubuchon' },
      { name: 'Jerome Brown' },
      { name: 'John Doe' },
      { name: 'Jane Doe' },
      { name: 'Deborah Grimm' },
      { name: 'Tommy Harris' },
      { name: 'Sally Smith' },
      { name: 'Harry Velez' },
      { name: 'Chelsie Williamson' }
    ];
  }

  countChars(q) {
    this.query = q;
    this.numChars = q.length;
  }
}

// template

<ui-select ng-model="ctrl.advisor.selected">
    <ui-select-match allow-clear placeholder="Select an Advisor" class="ui-select-match" ng-model="q" ng-change="ctrl.countChars(q)">

    </ui-select-match>
    <ui-select-choices class="ui-select-choices" repeat="advisor in (ctrl.advisors | filter: $select.search)">

    </ui-select-choices>
</ui-select>

How can I capture the search query as the user is typing it and do something with it in the controller?

A: I was able to solve the issue by adding refresh and refresh-delay to ui-select-choices
// controller
class selectController {
  constructor($scope) {
    this.$scope = $scope;
    this.query = '';
    this.numChars = 0;
    this.advisor = {};
    this.advisors = [
      { name: 'Cheryl Aubuchon' },
      { name: 'Jerome Brown' },
      { name: 'John Doe' },
      { name: 'Jane Doe' },
      { name: 'Deborah Grimm' },
      { name: 'Tommy Harris' },
      { name: 'Sally Smith' },
      { name: 'Harry Velez' },
      { name: 'Chelsie Williamson' }
    ];
  }

  countChars(q) {
    this.query = q;
    this.numChars = q.length;
  }
}

// template

<ui-select ng-model="ctrl.advisor.selected">
    <ui-select-match allow-clear placeholder="Select an Advisor" class="ui-select-match">

    </ui-select-match>
    <ui-select-choices class="ui-select-choices" repeat="advisor in (ctrl.advisors | filter: $select.search)" refresh="ctrl.countChars($select.search)" refresh-delay="0">

    </ui-select-choices>
</ui-select>


text:
Q: Transforming temp table that uses counts into query Today I came by one query that I deem to be 'suboptimal'
it looks following:
CREATE TABLE #temp (
                    Sessionid    UNIQUEIDENTIFIER,
                    PolicyNumber VARCHAR(30),
                    StartDate    DATETIME,
                    RequestUrl   VARCHAR(255),
                    ClientSource VARCHAR(50),
                    Comment VARCHAR(250),
                    ExceptionCount INT
                )

                INSERT INTO #temp
                    SELECT sessionid, policynumber, startdate  "Timestamp", requesturl "Instance", clientsource , '' Comment
                    , (SELECT COUNT(*) from Logging.Exceptions where [Key] = sessionId) as exceptioncount
                    FROM   [Transaction].[sessions] tr WITH  (nolock)
                     WHERE sessionId = '7B851237-3790-4A6D-9688-2E77843E0BB1'

                SELECT (SELECT COUNT(*) FROM #temp WHERE exceptioncount > -1) as TotalRecords,
                       (SELECT COUNT(*) FROM #temp WHERE exceptioncount > -1) as TotalDisplayRecords,* from
                    (SELECT * FROM
                        (SELECT ROW_NUMBER() OVER (ORDER BY StartDate  desc) AS rownumber,
                            sessionid, policynumber, startdate  "Timestamp", requesturl "Instance",
                            clientsource, exceptioncount,Comment
                         FROM #temp
                         WHERE exceptioncount > -1) as cte
                     WHERE cte.rownumber BETWEEN 1 AND 10) as "Results"

                drop table #temp

which I have now rewritten in a following form
SELECT
--count(*) TotalRecords,
 --   count(*) TotalDisplayRecords,
                       * from (

SELECT ROW_NUMBER() OVER (ORDER BY "Timestamp"  desc) AS rownumber, * from (
                        SELECT sessionid, policynumber, startdate  "Timestamp", requesturl "Instance", clientsource , '' Comment
                    , (SELECT COUNT(1) from Logging.Exceptions where [Key] = sessionId) as exceptioncount
                    FROM   [Transaction].[sessions] tr WITH  (nolock)
                     WHERE sessionId = '7B851237-3790-4A6D-9688-2E77843E0BB1' ) withrownumber
                     WHERE exceptioncount > -1 ) as cte

the only thing that is missing is adding counts, Is there a way to do this without having to repeat bulk of main select?

A: Try this way..
Here I have replaced Co-related Sub query with Outer Apply. Up to my knowledge Corelated Sub query will compare every record of Outer Set with every record of Inner set. Where as Outer Apply will execute per row once.
;WITH CTE AS (
    SELECT ROW_NUMBER() OVER (ORDER BY StartDate DESC) AS rownumber
    , sessionid
    , policynumber
    , startdate  AS [Timestamp]
    , requesturl AS [Instance]
    , clientsource
    , '' Comment
    , EXC.exceptioncount
    FROM [Transaction].[sessions] tr WITH (NOLOCK)
    OUTER APPLY
    (
        SELECT COUNT(1) AS exceptioncount
            FROM Logging.Exceptions
            WHERE [Key] = tr.sessionId
    )AS EXC
    WHERE sessionId = '7B851237-3790-4A6D-9688-2E77843E0BB1'
)

SELECT
(SELECT COUNT(1) FROM CTE WHERE exceptioncount > - 1 ) AS TotalRecords
,(SELECT COUNT(1) FROM CTE WHERE exceptioncount > - 1 ) AS TotalDisplayRecords
, sessionid
, policynumber
, [Timestamp]
, [Instance]
, clientsource
, Comment
, exceptioncount
FROM CTE
WHERE rownumber BETWEEN 1 AND 10

A: This is what I ended up with, I don't like it very much and would appreciate if someone would come up with more elegant solution
    select * from
            (SELECT
                count(1) TotalRecords,
                count(1) TotalDisplayRecords,
                * from (
                    SELECT ROW_NUMBER() OVER (ORDER BY "Timestamp"  desc) AS rownumber, * from (
                        SELECT sessionid, policynumber, startdate  "Timestamp", requesturl "Instance", clientsource,
                            (SELECT COUNT(1) from Logging.Exceptions  WITH  (nolock) where [Key] = sessionId) as exceptioncount,
                        '' Comment
                        FROM [Transaction].[sessions] tr WITH (nolock)
                        WHERE sessionId = '7B851237-3790-4A6D-9688-2E77843E0BB1') withrownumber
                WHERE exceptioncount > -1 ) as cte
                group by rownumber, sessionid, policynumber,  "Timestamp",  "Instance", clientsource ,  Comment, exceptioncount) as r
        WHERE r.rownumber BETWEEN 1 AND 10


text:
Q: AngularJS & Node.JS everyone!
I have the following inquiry: Is it possible to have a mirror programming?
I mean the following:
    /* This are models ( MVC ) */

Client & Server
MyApp{
var DATA = array();
const SIDE = true // current side. On the server const SIDE = false

    // Directive Content
    function Content(){

        // Directive Title
        function Title(){

            $DATA['Content']['Title'] = function(){

                var fromWhere = URL//From where it takes the lead

                // Maybe a good idea to put in setInterval
                $.get(fromWhere) ...

                    $scope.title = $data['title'];
                    if(SIDE){
                        Here works front end
                    }
                }
            }
        }
    }
}

The main idea is to write a code and the outside and inside.The parts that relate to the side (front / back) to switch.
Is it possible to make the program fully mirror? - Outside and inside
Only certain properties are defined different.

A: Strongloop promises to do that.
DerbyJS Does something similar too.
Meteor Promises isomorphic stack.
Does that answer your question properly? :)


text:
Q: MySQL: Looping Through Multiple Fields in an IN Clause I have a universe that has one column where there are 3 types of id's. I know that I can use 3 separate OR clauses in my WHERE statement
WHERE isin IN(n)
OR cusip IN(n)
OR psedol IN(n)

but is there a more efficient way to do this?

A: Reverse the order of your IN clause:
WHERE (n) IN (isin, cusip, psedol)

EDIT: The above would only work if (n) is only one column, for example, if it's "(SELECT x FROM y)".  If it's a list of things, reversing the order won't work and you have to keep it as you have it.
Another solution if (n) is a select is to move up your selectors into your joins.  Joins are more efficient than IN clauses.  For example, if n is "SELECT a FROM z", you could do something like this:
FROM y
INNER JOIN z ON z.ID = y.ID
INNER JOIN x ON x.ID = y.ID AND (x.isin = z.a OR x.cusip = z.a OR x.psedol = z.a)

... but that depends on the structure of your entire query, so you'd have to provide more information for me to be more specific.

A: I would suggest a little bit different from spsc_tech
FROM y
LEFT JOIN z ON ( z.ID = y.ID AND Z.ISIN = n)
LEFT JOIN x ON ( x.ID = y.ID AND X.CUSIP = n)
LEFT JOIN w ON ( w.ID = y.ID AND w.psedol = n)

if you put condition in ON clause in join, its much faster then in Where clause.
Hop this will work.


text:
Q: Solving more complex diferential equations I've come up with this implicit equation
$ (y')^2(2x-2x^2+2y^2)+(y')^2=1 $
and I'd like to find the function $y(x)$ (so that it's definition doesn't contain it's derivative).
Only thing I've been able to come up with is to see if f is polynomial. I calculated that if it were, it's degree (?) would have to be 1 or 3. Trying to solve for both of those resulted in a system with no solutions.
Now I'm stuck.
I'm aware that the solution might not be unique but since this isn't a set problem but something I came up with, I can provide any parameters that are required. WolframAlpha said something about $y(0)=1$ so if that's one of the required parameters, that's fine.


text:
Q: Undefined variable: /vendor/magento/module-catalog/Controller/Adminhtml/Product/Save.php while save configurable product in magento2 When I save configurable product with big length sku then error showing

"0":"Notice: Undefined variable: product in
  /MASKED_DIR/2018-08-06_12-56-07/htdocs/vendor/magento/module-catalog/Controller/Adminhtml/Product/Save.php
  on line 156"

A: I Fixed in my website!
Please check below process

*

*set "const SKU_MAX_LENGTH = 255;" in the file
module-catalog/Model/Product/Attribute/Backend/Sku.php

*You need to change the into database as well. Go to table
eav_attribute, search for sku at column attribute code then edit
the resulted row.
Update the field frontend_class to null or validate-length
maximum-length-255 according to your requirement.

*You have to change field size at the database table.
ALTER TABLE catalog_product_entity CHANGE sku sku VARCHAR(255)
CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT
'SKU';


text:
Q: Should there be an article 'the' before 'dengue virus'? In the following sentence, should there be an article 'the' before 'dengue virus'?

According to WHO, 2.5 billion people are at risk from the four major types of dengue virus, which is transmitted to people from infected mosquitoes.

A: The sentence is correct as it stands.
You may insert the word "the" before "WHO" (a quick google survey shows both "according to WHO" and "according to the WHO" being used. (in speech one would insert a "the" if read as W. H. O but not if read as "hoo".)
You shouldn't use an article before dengue virus. In expressions like "two types of apple" or "72 breeds of sheep" or "both makes of computer", the word being classified doesn't normally require an article. Exceptions to this are when the word being classified usually has the definite article "types of the 'flu" is correct, because "the 'flu" is used idiomatically with the article.


text:
Q: Use Apollo Client or Isomorphic Fetch with GraphiQL I am trying to integrate the GraphiQL IDE into my website and am wondering if I can get some advice on whether I would be best using the Apollo Client that the rest of the site uses or using Isomorphic Fetch as recommended in the documentation.
If I use the Apollo Client then I only have one connection to worry about and don't have to think about ensuring authentication is correct but the code is more complex.
I have this code working for the fetcher function, but so far it only works with queries and to my understanding would need a fair amount of work to work with mutations as well.
graphQlFetcher = (params) => {
    return this.props.client.query({
        query: gql`
            ${params.query}
        `
    }).then(function(result) {
        return result;
    });
}

Alternatively there is the isomorphic fetch approach, but for this to work I need to get the authentication token first and I am not good enough with promises to make this work. Not working code:
import { Auth } from 'aws-amplify';

getToken = async () => {
    const session = await Auth.currentSession();
    return session.accessToken.jwtToken;
}

graphQLFetcher = (graphQLParams) => {
    return getToken().then(function(token) {
        fetch(window.location.origin + '/graphql', {
            method: 'post',
            headers: {
                  'Content-Type': 'application/json',
                  "Authorization": token
              },
            body: JSON.stringify(graphQLParams),
          }).then(response => response.json());
    })
}

Appreciate that there are two possible ways to solve this problem and that it is as much a design question as a technical one but hoping that someone can help me out.

A: The first one is fine, but you have some excess syntax on there. This is what I use:
params => client.query({ ...params, query: gql(params.query) });


text:
Q: Rails on Bluehost: "Connection reset by peer" mod_fcgid error I'm uploading a rails site to bluehost, a site that works on my local machine. I'm having trouble configuring it to run on bluehost, though. Here's the error I'm getting:
 [warn] [client 74.220.197.129] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
 [error] [client 74.220.197.129] Premature end of script headers: dispatch.fcgi ./../config/../vendor/rails/railties/lib/rails/gem_dependency.rb:119:Warning: Gem::Dependency#version_requirements is deprecated and will be removed on or after August 2010. Use #requirement
./../config/../vendor/rails/railties/lib/initializer.rb:271:in `require_frameworks':
RubyGem version error: rack(1.1.0 not ~> 1.0.1) (RuntimeError) from ./../config/../vendor/rails/railties/lib/initializer.rb:134:in `process' from ./../config/../vendor/rails/railties/lib/initializer.rb:113:in `send' from ./../config/../vendor/rails/railties/lib/initializer.rb:113:in `run' from ./../config/environment.rb:11 from dispatch.fcgi:21:in `require' from dispatch.fcgi:21

I've already installed rack 1.0.1, and renaming .htaccess correctly gives me an index list of files. This seems like a .htaccess error. Here's my .htaccess file:
AddHandler fcgid-script .fcgi
AddHandler cgi-script .cgi
# For security reasons, Option followsymlinks cannot be overridden.
# Options +FollowSymLinks +ExecCGI
Options +SymLinksIfOwnerMatch +ExecCGI

RewriteEngine On
RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

ErrorDocument 500 /500.html

#ErrorDocument 500 "
Application error
Rails application failed to start properly"

What am I doing wrong?

A: Ok, I fixed this problem by doing the following:
Adding this to the ~/.bashrc file...
export GEM_HOME=$HOME/ruby/gems
export GEM_PATH=$GEM_HOME:/usr/lib64/ruby/gems/1.8
export GEM_CACHE=$GEM_HOME/cache
export PATH=$PATH:$HOME/ruby/gems/bin

...Running this command...
gem install rails --version=2.3.5

...and adding this line to the top of the environment.rb file...
ENV['GEM_PATH'] = '/home8/opportx0/ruby/gems:/usr/lib64/ruby/gems/1.8'

finally works.

A: Your app is looking for Rack 1.1.0 or greater and it's finding 1.0.1


text:
Q: How to load a nib from a customized UIView? I have a nib call "Hello.xib", and I have a HelloView that is inherit from the UIView, and I want to do the layout in the Hello.xib, and I want to allocate them to the HelloView.m / HelloView.h, how can I do so? Thank you.

A: You normally do so on the outside. In HelloView you should have a UIViewController derived class. Then when initializing it on the outside you would call:
hello = [[HelloViewController alloc] initWithNibName:@"Hello" bundle:nil];

The bundle:nil make Cocoa use the default bundle.

A: In the interface builder's inspector for your Hello.xib's view, set the class of the view (in identity tab) to HelloView. I hope thats what you are looking for.

A: Just today I wrote a demonstration code, that also uses instantiation of custom view by loading a nib

*

*the controller has a member DetailContactHeaderView *headerView

*in the nib, I have a DetailContactHeaderView and the Files' owner type is my Controller

*the files' owner property headerView and the View get Connected

*in this controller I have this code
[[NSBundle mainBundle] loadNibNamed:@"DetailContactHeader" owner:self options:nil];

See my MyContacts for an implementation.
FYI:

*

*DetailContactHeaderView

*DetailContactHeader.xib

*DetailContactViewController

*

*especially -tableView:viewForHeaderInSection:


text:
Q: Reading a file path in a bash commad I have this script:
#! /bin/bash -

# ENVIRONMENT VARIABLES

JDK_PATH="C:\Program Files\Java\jre1.8.0_151\bin\java"
WEKA="C:\Program Files\Weka\weka-3-4\weka.jar"

# ----------------------------------

COMMONS_CLI=./lib/commons-cli-1.0.jar
MRC=./lib/jmrc.jar

LIBS=.:$WEKA:$COMMONS_CLI:$MRC:bin/

$JDK_PATH -Xmx512m -classpath $LIBS recognizer.PersonalityRecognizer $*

From this project
And I try to run this command in git bash command line
./PersonalityRecognizer -i ../output_dir -d -t 2 -a ../mairesse_Apache.arff

However I receive this error:
$ ./PersonalityRecognizer -i ../output_dir -d -t 2 -a ../mairesse_Apache.arff
./PersonalityRecognizer: line 15: C:\Program: No such file or directory

Is there any problem with the space character in Java path? How can I write it properly

A: Your command should be:
"$JDK_PATH" -Xmx512m -classpath "$LIBS" recognizer.PersonalityRecognizer $*

ot bash will see spaces as separators not as part of the path


text:
Q: Netbeans: how do I change the name of a project? I need to change the name of my application, so people who download and install it can see the name but I don't know where to do it.
What file do I need to edit?

A: if your project is mobile Project you must right click on project name , select properties options and then on Application Descriptor edit MIDlet-name value.

A: you must right click on your project in Project window [ctrl + 1] and choose rename option for
renaming your project name.

A: If you use gradle:
BuildScripts/Project/settings.gradle
rootProject.name = 'yourprojectname'

A: If your project is Maven based, you can either add/update the application name in pom.xml (found in Project Files folder) or go to File >> Project Properties and add/update the application name.

A: Open "project.xml" file under nbproject folder inside the project folder of the one you want to change the name.
it is in the tag <name>.
Just change it and that is it.

A: open project.properties in dir nbproject
look up to manifest.midlets and change the name after MIDlet

A: Rightclick on the project node and select rename.
If you want the folder of the project also to have the new name or whatever that wasnt renamd then :
1.in build.xml in text editor find old name and replace with new one. Its place is: C:\NBProjectsFolder\OldName\build.xml  Save that.
2. Remove all cash situated in , e.g.: C:\NBProjectsFolder\OldName\build\gwt-unitCache.
3. Find in C:\NBProjectsFolder\OldName\nbproject\private private.xml file and edit it in a text redactor by renaming old name within the file. Save that.
Do all the changes   when the Netbeans was closed.
After opening the Ntbeans it may ask to reimport the project and all files you changed will be recognized/recreated automatically


text:
Q: External HDD unmounting unexpectedly An externally-powered WD My Book Essential, 3TB, which I use for Time Machine and other file storage, recently began "ejecting itself" from my iMac. In an attempt to repair the disk from Disk Utility, I came across these logs:
kernel[0]: jnl: disk1s2: replay_journal: from: 99262464 to: 99508224 (joffset 0x2bae000)

kernel[0]: jnl: disk1s2: journal replay done.

fseventsd[47]: Events arrived for /Volumes/My Book after an unmount request! Re-initializing.

fseventsd[47]: creating a dls for /Volumes/My Book but it already has one...

diskarbitrationd[15]: mds [38]:23343 not responding.

kernel[0]: USBF: 670537.390 AppleUSBEHCI[0xffffff802439f000]::Found a transaction which hasn't moved in 5 seconds on bus 0x26, timing out! (Addr: 3, EP: 0)

kernel[0]: USBF: 670543.393 AppleUSBEHCI[0xffffff802439f000]::Found a transaction which hasn't moved in 5 seconds on bus 0x26, timing out! (Addr: 3, EP: 0)

kernel[0]: USBF: 670543.798 The USB Family found a device at  port 2 of hub @ 0x26000000 with a bad USB device descriptor (0x0, 0x0 )

kernel[0]: USBF: 670549.396 AppleUSBEHCI[0xffffff802439f000]::Found a transaction which hasn't moved in 5 seconds on bus 0x26, timing out! (Addr: 0, EP: 0)

This began happening shortly after I've been accessing a movie file from the drive to encode and burn to a DVD from iDVD, but I wouldn't expect this to be the issue. Each time the drive unmounts itself, the error when not ejecting a disk properly appears. Note that in the log, the third entry from fseventd, I believe the "events arrived" was me attempting to repair the volume.
What could be sending the unmount request? diskutil is. The problem, I believe, lies in the journaling. (see update, it's not this)
Update (for clarification also)
I know that repairing the volume requires the partitions to be unmounted, I meant it's ejecting by itself. Just repaired the volume from another Mac and it checked out OK...must be the Mac that uses it for Time Machine.
I'm convinced that it's this error message that is the issue, but I can't figure out what it means.
kernel[0]: USBF: 670537.390 AppleUSBEHCI[0xffffff802439f000]::Found a transaction which hasn't moved in 5 seconds on bus 0x26, timing out! (Addr: 3, EP: 0)

Update 2
Just finished an archive-and-install of the iMac in question, but I'm still getting the same logs and can't access the files. I can't blame it on a corrupt USB driver anymore, so I really am at a loss now.

A: This is symptomatic of a hardware failure in most cases. You'll want to isolate the various components:

*

*disconnect all other USB devices

*try a new cable

*try a different port on the Mac

*try that drive on another Mac (or another drive on your Mac)

*try another power source for that drive

It's likely the voltage supply to the controller chip in the drive (or the chip itself is faulty or getting power spikes from the drive motor) so I'd consider backing up that data and contacting WD to see if they have newer firmware or if more power is needed to run that drive.


text:
Q: Redirect /openvas/ to OpenVAS Scanner with NGINX I'm trying to make my OpenVAS Scanner available via path in nginx.
So I tried
location /openvas/ {
proxy_pass http://127.0.0.1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;}

thats not working, it gives a blank page
When I change it to root
location / {
proxy_pass http://127.0.0.1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; }

its working
when checking nginx logfiles it seems it gets the first page, but not the other files requested
"GET /openvas/ HTTP/2.0" 200
"GET /config.js HTTP/2.0" 404

A: I have checked the docker container image and just proxying the traffic trough NGINX will not work. You have to set the Public Hostname for your OpenVAS instance as well to tell OpenVAS how to server static files and build directories in the frontend.
I have found this on docker hub.
docker run -d -p 443:443 -e PUBLIC_HOSTNAME=myopenvas.example.org --name openvas mikesplain/openvas

In your case you should set the PUBLIC_HOSTNAME to example.com/openvas/. This will tell OpenVAS public domain used to access the application.
Your NGINX configuration will be
location /openvas/ {
  proxy_pass http://127.0.0.1:8080/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
}


text:
Q: PyQt5, : "_MEI" path errors in pyinstaller py to exe First, I am a Korean Student. So I'm not good at English. Sorry, Please excuse me.
I'm Using PyQt5 and pyinstaller. I made exe file using this code: pyinstaller --noconfirm --onefile --console --paths "C:/Users/jun/Desktop/lee/Programing/python/dll" --hidden-import "nbt.world"  "C:/Users/jun/Desktop/lee/Programing/python/Auto_Submit_dev1.py"
but I can't execute the exe file with this error.

I checked many similar questions and answers like this, It doesn't work tho.
Below is part of my code:
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        print(base_path)
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

macUI = resource_path("autosubmit.ui")

Ui_MainWindow = uic.loadUiType(macUI)[0]

class MainDialog(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

How can I execute the exe file? (.py is working and .UI file and .py file is in the same folder)

A: Your exe file does not find autosubmit.ui file
add this -->     --add-data="autosubmit.ui;."
pyinstaller --noconfirm --onefile --console --add-data="autosubmit.ui;." --paths "C:/Users/jun/Desktop/lee/Programing/python/dll" --hidden-import "nbt.world"  "C:/Users/jun/Desktop/lee/Programing/python/Auto_Submit_dev1.py"


text:
Q: R6025 Pure virtual function call: What is and how to resolve Answer can be found here:

An Excerpt from Effective C++, Third Edition, by Scott Meyers

url posted by: hmjd
Please read that page so you understand why it is happening. Also you know why substituting
        virtual void     OnRelease() = 0;

by:
        virtual void     OnRelease(){};

will work but isn't the correct way to resolve.

Original question
R6025: pure virtual function call
#include <Windows.h>

// static lib
    //file.h
    class cBaseApplication
    {
    public:
        virtual          ~cBaseApplication(){ Release(); }
        virtual void     Release()
                         {

                             OnRelease();

                         };
        virtual void     OnRelease() = 0;
    }; // class cBaseApplication

    //file1.h
    class cApplication : public cBaseApplication
    {
    public:
        virtual void     OnRelease()
                         {

                             /* what the heck do something here */

                         };
    }; // class cApplication

// executable
    // file3.h
    int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
    {

        cApplication* pApplication = new cApplication();

        /*...what the heck, do stuff...*/

        pApplication->Release();
        delete pApplication;      // R6025: pure virtual function call
        pApplication = NULL;

        return 0;

    }

At the line
delete pApplication;

R6025 occurs and when removing, all fine but memory leaks occur.
Removing the pointer reference the R6025 will happen too on 'program exit' when cApplication application will be destruct.
Due to the beep, the R6025 scares me :s
As it seems I have to choose between the two but I just don't want to, what is happening here?
Regards,
John
EDIT: Added some code, seems Eran is right as I do call virtual functions there
EDIT: Added to example, [ virtual void OnLostDevice() = 0; ]. Changing from abstract to ascoop gave an immediate solution. Starting to read that page in the comments below as I got the feeling I ain't there yet.
EDIT: After I got the answer I understood my own problem. So I rewrote the question, so the answer fits the question.
Thanks, John

A: You must not call virtual functions in constructors and in destructors. I don't see a pure virtual function here, but if cBaseApplication::Release happen to call one, you'll get that error every time you destruct a cBaseApplication. I'm not sure that's the issue because I don't have all the code, but your code calls for that kind of issues.


text:
Q: Two exercises about hypermetric spaces
Take $S$ to be the collection of all subsets of $\{1,\dots,n\}$. If $x, y$ are in $S$, define $d(x,y)$ as the number of elements of the symmetric difference $x\triangle y$.
Exercise 2.1. Show that $(S,d)$ is a metric space. Moreover, $S$ satisfies the following stronger version of the triangle inequality: if $x_1,\dots,x_k$ are elements of $S$ and $b_1,\dots,b_k$ are integers that add up to $1$, then $$\sum_{i,j=1}^k b_ib_jd(x_i,x_j)\le0$$
Exercise 2.2. Define the distance between two points $(x,y,z)$ and $(x',y',z')$ in a three-dimensional space as the biggest of the numbers $|x-x'|$, $|y-y'|$, $|z-z'|$. Show that this distance is not hypermetric.

(Transcribed from this image)
These two exercises are about hypermetric. For the first one, I believe that induction for k should work. But I don't know what's special about the metric, and cannot prove the inequality for $k=4$. As for the second exercise, it seems that the inequality might fail when $k=4$, but I have no idea how to find those four points. Any help is appreciated, thank you!

A: For the first exercise: write the metric $d$ as the sum of semi-metrics
$$d_r(A,B)=\begin{cases}1,\quad \text{ if }r\in A\triangle B \\ 0 \quad\text{otherwise}\end{cases}$$
For each $r$, we have
$$\sum_{i,j} b_ib_jd_r(A_i,A_j)
= \sum_{r\in A_i,\ r\notin A_j} b_ib_j+ \sum_{r\notin A_i,\ r\in A_j} b_ib_j \\= 2 \sum_{r\in A_i}b_i \sum_{r\notin A_j} b_j = 2\sum_{r\in A_i}b_i\left(1-\sum_{r\in A_i}b_i\right)\le 0
$$
because $N(1-N)\le 0$ for every integer $N$. Then sum over $r$.

For the second one, I don't have a conceptual explanation, but a computer search brought up this example: take five points with coordinates given by the columns of the matrix
$$ \begin{pmatrix}    1& 1& 1& 2& 0\\    0& 2& 2& 1& 1\\    0& 1& 0& 1& 0\\    \end{pmatrix}   $$
and check that the sum in the hypermetric inequality is $1>0$.
I don't have a counterexample with $4$ points; it's been more than a year since I looked for them, but I believe my search did not turn up anything.

For more on hypermetrics, I can offer my blog posts Pentagrams and hypermetrics and Polygonal inequalities: beyond the triangle.


text:
Q: How to get rid of Ionic vertical scroll bar on a blank project? When I create a new blank project using Ionic CLI, the Home page appears with a vertical scroll bar. How to get rid of it?
<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  The world is your oyster.
</ion-content>

A: add:
.scroll-content {
    overflow-y: auto;
}

to your app.scss file to override it everywhere.


text:
Q: integrate an angular 6 application into an existing HTML site as a simple JS file How can i add/integrate an Angular 6 application into an existing HTML site, can I include it as a single JS file ?
How can I bundle an Angular App into a single JS file ?
Thanks

A: You should take a look at Angular Elements. This will allow you to generate a custom web component which you can embed into a HTML page. This tutorial has good information on how to end up with a single JS file that you can import in your HTML and then use as a custom element.


text:
Q: Button title not showing up with data from Firebase So I am retrieving data from Firebase and then putting that data as a string on the title of buttons. However, the title of the buttons doesn't change for some reason.
Basically it is putting data on the button based on its tag. I setup the tag for each button in code.
Json File from Database:
{
  "mix-questions" : [ {
    "1" : "Eu Ro Wang",
    "2" : "Keerti Soundappan",
    "3" : "Galadriel Coury",
    "answer" : "Madelyn Koch",
    "question" : "Which one is not a national officer?"
  }, {
    "1" : "pure risk may deprive society of certain goods or services determined to bear excessive risk",
    "2" : "pure risk can result in feelings of mental unrest and worry that can drain human energies",
    "3" : "reserve funds may be necessitated that may not yield the highest rate of return available",
    "answer" : "pure risk results in gambling, which is a destructive social force",
    "question" : "Pure risk may be said to create an economic burden in all except which one of the following ways?"
  }, {
    "1" : "property risk",
    "2" : "insurance",
    "3" : "personal risk",
    "answer" : "liability risk",
    "question" : "The risk of potential losses to others as a result of injury or damage you may have caused is:"
  }, {
    "1" : "dishonest employee",
    "2" : "building fire, oily rags, and a dishonest employee",
    "3" : "oily rags and a gas leak",
    "answer" : "a building fire",
    "question" : "Examples of physical hazards include:"
  }, {
    "1" : "the car that Ken hit was a total loss",
    "2" : "Ken's car sustained $5,000 in damages",
    "3" : "Ken incurred $5,000 in medical expenses",
    "answer" : "the driver of the other car suffered $30,000 in bodily injuries",
    "question" : "Ken fell asleep while driving late at night. He crossed the center line and hit a car approaching from the other direction. The following losses occurred:"
  }, {
    "1" : "injuries to another person arising out of the insured's negligent operation of a vehicle",
    "2" : "medical payments resulting from the transmission of a communicable disease",
    "3" : "workers compensation medical payments",
    "answer" : "injury to a resident employee at the insured's home",
    "question" : "Which one of the following losses would be covered under the medical payments coverage of the Homeowners 3 policy?"
  }, {
    "1" : "partial disability",
    "2" : "temporary disability",
    "3" : "total disability",
    "answer" : "presumptive disability",
    "question" : "A provision in disability insurance that specifies the conditions under which the insured is automatically considered disabled is:"
  }, {
    "1" : "Peril",
    "2" : "Hazard",
    "3" : "Risk",
    "answer" : "Probability",
    "question" : "__________ is the likelihood that an event will occur."
  }, {
    "1" : "personal contracts",
    "2" : "contracts of adhesion",
    "3" : "aleatory contracts",
    "answer" : "unilateral contracts",
    "question" : " Kathy entered into an insurance contract with XYZ Insurance Company. When the agent who sold the coverage witnessed Kathy doing something that violated the terms of the contract, he threatened to sue her to make her comply with terms of the contract. Which distinct legal characteristic of insurance contracts states that only the insurer's promise to perform is legally enforceable?"
  }, {
    "1" : "agent",
    "2" : "claims adjustor",
    "3" : "risk manager",
    "answer" : "appraiser",
    "question" : "In what career would a person assess the cost of replacing or repairing damaged property?"
  }, {
    "1" : "actuary",
    "2" : "claims adjustor",
    "3" : "loss control engineer",
    "answer" : "underwriter",
    "question " : "Jan is employed by an insurance company. She reviews applications to determine whether her company should insure the applicant. If insurable, Jan assigns the applicant to a rating category based on the applicant's degree of risk. Jan is a(n):"
  } ],
  "users" : {
    "0vFQYnfIbahHdC1RsuNMW45HYNR2" : {
      "email" : "andyjiang55@yahoo.com",
      "username" : "itsandyjiang"
    },
    "Cs7sW01kSEYHYZmBISvjYc1QmDy1" : {
      "email" : "test@gmail.com",
      "games-played" : 0,
      "username" : "test"
    },
    "GypKikOJbfOPV4m43mQTnLMWBYG3" : {
      "email" : "andyjiang@yahoo.com",
      "username" : "andyjiang"
    },
    "Khf6jRX7uuZs40x8w7zapziCsr73" : {
      "email" : "andyjiang57@yahoo.com",
      "username" : "itsandyjiang3"
    },
    "OAa5bbNc65acxmr6mauyIQ6bqHb2" : {
      "email" : "andyjiang56@yahoo.com",
      "username" : "itsandyjiang2"
    },
    "R86YQRMSxGOIJFC0C6iPDQCgP0W2" : {
      "email" : "admin@gmail.com",
      "games-played" : "0",
      "username" : "admin"
    },
    "YxxBBxS2WkWtrY8PnLx4jfDqV3o2" : {
      "email" : "andyjiang1@yahoo.com",
      "username" : "itsandyjiang5"
    },
    "taikB5Gp1kaAmuPpiHxPoiKmjf03" : {
      "email" : "andyjiang2@yahoo.com",
      "username" : "itsandyjiang9"
    }
  }
}

Setup of tags:
func setup() {
    oneAnswerButton.tag = 1
    twoAnswerButton.tag = 2
    threeAnswerButton.tag = 3
    fourAnswerButton.tag = 4
}

Retrieving of data and assigning to buttons' title:
rightAnswerPlacement = arc4random_uniform(4) + 1//From 0 to n-1 (0-3)+1 = (1-4)

if (questionsArray.isEmpty == true) {
    questionNotAsked = true
    selectQuestion = arc4random_uniform(10)
}

while(!questionNotAsked) {
    selectQuestion = arc4random_uniform(10) //0-9

    for questions in self.questionsArray {
         if selectQuestion == questions {
             self.questionNotAsked = false
             break
         } else {
             self.questionNotAsked = true
         }
    }
}

questionsArray.append(selectQuestion)
questionNotAsked = false

let ref = Database.database().reference(fromURL: "https://testtest.firebaseio.com/")
ref.child("mix-questions").child(String(selectQuestion)).observeSingleEvent(of: .value, with: { (snapshot) in

// Get user value

let value = snapshot.value as? NSDictionary
let questionChoosen = value?["question"] as? String ?? ""
let answer = value?["answer"] as? String ?? ""

var button:UIButton = UIButton()

self.questionLabel.text = questionChoosen

var x = 1
let chooses = value?[String(x)] as? String ?? ""

for i in 1...4 {
    button = self.view.viewWithTag(i) as! UIButton

    if i == Int(self.rightAnswerPlacement) {
        button.setTitle(answer, for: .normal)
    } else {
        button.setTitle(chooses, for: .normal)
        x += 1
    }
}

// ...
}) { (error) in
    print(error.localizedDescription)
}


text:
Q: Java generics - map function to a list
I'm kind of new to generics in Java and I've faced such a problem: Let's say you have your own List implementation and you want to provide a mechanism to simultaneously convert all elements using some kind of mapping (functional interface) and collect them into a new list.

While the idea and use of functional interface (IMapper in my case) is straightforwad I can't quite think of what signature a function performing mapping should have?

Here's a little use case example and what I thought of as well. It does not work unfortunately and I guess the main problem is: How the second V param type should be passed in such case?
public interface IMapper<T,V> { V map(T v); }

public class MyList<T> extends ArrayList<T> {
  public MyList<V> map(IMapper <T,V> mapper) {
    MyList<V> list = new MyList<>();
    for(T v : this) {
      list.add(mapper.map(v));
    }
    return list;
  }
}
// in main
MyList<Integer> list1 = new MyList<>();
// fill etc..
IMapper<Integer,String> m = (i) -> { return i.toString(); };
// "Change" list
MyList<String> list2 = list1.map(m);

PS:
I think that such thing is most probably already implemented in Java (stream() and what follows I guess?) however it suppose to be exercise for me. Any tip would be much appreciated :)

A: You can define the generic parameter as a type parameter on your map method. Like this:
public <V> MyList<V> map(IMapper <T,V> mapper) {
    ...
}

Type parameters can be defined in two ways, either on a class or on a method. If it's defined on a class, it can be used throughout the class. If it's defined on a method, it can only be used in that method.
In your case, the T parameter is defined on the class, while the V parameter can be defined on the method.

A: You can add the map result type to you function definition as following:
class MyList<T> extends ArrayList<T> {

public <V> MyList<V> map(IMapper<T, V> mapper) {
    MyList<V> list = new MyList<>();
    for (T v : this) {
        list.add(mapper.map(v));
    }
    return list;
}

}
Example:
MyList<Integer> number = new MyList<>();

number.add(1);
number.add(2);
number.add(3);

number.map(v -> "#" + v).forEach(System.out::println);

And you can have the same result using Java8 streams as following:
List<Integer> numberStream = new ArrayList<>();
numberStream.add(1);
numberStream.add(2);
numberStream.add(3);
numberStream.stream().map(v -> "#" + v).forEach(System.out::println);


text:
Q: How to efficiently serialize a scikit-learn classifier What's the most efficient way to serialize a scikit-learn classifier?
I'm currently using Python's standard Pickle module to serialize a text classifier, but this results in a monstrously large pickle. The serialized object can be 100MB or more, which seems excessive and takes a while to generate and store. I've done similar work with Weka, and the equivalent serialized classifier is usually just a couple of MBs.
Is scikit-learn possibly caching the training data, or other extraneous info, in the pickle? If so, how can I speed up and reduce the size of serialized scikit-learn classifiers?
classifier = Pipeline([
    ('vectorizer', CountVectorizer(ngram_range=(1,4))),
    ('tfidf', TfidfTransformer()),
    ('clf', OneVsRestClassifier(LinearSVC())),
])

A: For large text datasets, use the hashing trick: replace the TfidfVectorizer by a HashingVectorizer (potentially stacked with a TfidfTransformer in the pipeline): it will be much faster to pickle as you won't have to store the vocabulary dict any more as discussed recently in this question:
How can i reduce memory usage of Scikit-Learn Vectorizers?

A: You can also use joblib.dump and pass in a compression. I noticed my classifier pickle dumps reducing by a factor of ~16 using option compress=3.


text:
Q: core.logic CLP(FD) with ClojureScript I'm trying to use core.logic to figure out answer to the following equations:
x + y = W
x - y = V

W and V are both given, while x and y are the values I'm trying to compute.
I've tried approaches like (I substituted W with 60 and V with 10):
(logic/run* [q]
          (logic/fresh [x y]
                       (logic/== q [x y])
                       (logic/project [x y]
                                      ; x + y = 60
                                      ; x - y = 10
                                      (logic/== y (- 60 x))
                                      (logic/== x (+ 10 y)))))

But it returns (["10<lvar:y_6>" NaN]) (I would expect 35 and 25).
How do I approach that? I don't want to use clojure.core.logic.fd because I'm using ClojureScript - is that possible at all? Would it be possible with fd?

Note that those equations are an example only. In my real-world scenario I want to solve something more like that:
x + H + y = W
x / y * 100 = V

For now I simplified those to get the most basic example running, but the solution to the above is also welcome :)

A: The cljs version of core.async cannot solve this kind of problem yet, because the fd namespace has not been migrated from the clj version.
Using the clojure version, we can solve it this way:
(require '[clojure.core.logic :as logic]
         '[clojure.core.logic.fd :as fd])

(logic/run* [q]
  (logic/fresh [x y]
    (logic/== q [x y])
    (fd/in x y (fd/interval 0 100))
    (fd/eq (= 60 (+ x y)))
    (fd/eq (= 10 (- x y)))))

Result: ([35 25])
Instead of using logic/project we use fd/eq to express the relation between the LVars, and fd/interval to constrain their values into that interval.
In this answer @dnolen explains that "you cannot project finite domain vars that haven't been constrained to single value".


text:
Q: Unable to update the HTML 5 data attribute array When i click on the Addons Button and check / uncheck   the items (Checkboxes ) , i am updating the data array
But even after setting the data ,when i inspect the element  i see the data -stuff array is still empty
<div class="lastItm_Wrap" data-stuff="[]">

</div>

could you please let me know how to set data /  update data stuff array
http://jsfiddle.net/tdzfhzjy/102/

A: You need to set the attribute value instead of setting its data property.
change
 $('.lastItm_Wrap').data('stuff', vendoritemsdata);

to
 $('.lastItm_Wrap').attr('data-stuff', vendoritemsdata);

Working Demo

A: You are using the jQuery data-api, which has an internal storage to store the data values that is why the attribute value is not updated.
Your values are set properly in the internal storage so it should be fine.
// checkbox checked
$(document).on('click', '.ui-checkbox-off', function (event) {
    var vendoritemsdata = $(".lastItm_Wrap").data('stuff');
    var checkboxid = $(this).next().attr("id");
    vendoritemsdata.push(checkboxid);
    $('.lastItm_Wrap').data('stuff', vendoritemsdata);
    console.log('off',vendoritemsdata)
});

// checkbox Unchecked
$(document).on('click', '.ui-checkbox-on', function (event) {
    var vendoritemsdata = $(".lastItm_Wrap").data('stuff');
    var itemtoRemove = $(this).next().attr("id");

    vendoritemsdata.splice($.inArray(itemtoRemove, vendoritemsdata), 1);
    console.log('on',vendoritemsdata)

    $('.lastItm_Wrap').data('stuff', vendoritemsdata);
});

Demo: Fiddle
Look at the logged values in the console and you could see that it is working fine


text:
Q: Zend_Date compare two dates I have two dates given as Zend_Date(). I must check the following:

*

*if theese dates are in the same month day (for example: second day of the month, year does not matter),

*if dates are from exactly the same day(for example 2 december 2012);

A: To check the dates are the exact same day, you can check each individual part separately.
Zend_Date('your-date-here',Zend_Date::DAY);

This returns a date object that specifically gives you the day for the 'your-date-here' and it accepts a variety of formats; for example, I use php's date function as:
$myDate = date('Y-m-d-H-i-s');
$dateDayObject = Zend_Date($myDate, Zend_Date::DAY);

and now $dateDayObject will have the value of the 'd' in it.
You can use DAY, WEEK, YEAR... there are many constant all defined here:
http://framework.zend.com/manual/1.12/en/zend.date.constants.html
Finally, to test if they are in the same day of the month, you can use a combination of loops and if statement and the same method as above to write your own function to check the day within the month or there may be a defined constant for it. Good luck.


text:
Q: How to Keep Selected listItem of Recyclerview Highlighted untill next Item of Recyclerview is been selected in xamarin Android public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
             myholder = holder as GeoFenceViewHolder;
            myholder.ItemView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#000000"));
            if (selectedPosition == position)
            {
                myholder.ItemView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#FF4081"));
            }
            else
            {
                myholder.ItemView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#ffffff"));
            }
        GeoFenceViewHolderItemClick(position);

        if (_lstItem[position].isApplied == true)
        {
            myholder.mradiobtngeofenceapplied.Checked = true;
        }
    }

    private void GeoFenceViewHolderItemClick(int position)
    {
       myholder.ItemView.Click += (sender, e) =>
      {
          selectedPosition = position;
          NotifyDataSetChanged();
      };
    }

A:
How to Keep Selected listItem of Recyclerview Highlighted untill next Item of Recyclerview is been selected in xamarin Android

Just add this below line in OnBindViewHolder :
viewHolder.ItemView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#000000"));

will work for you.
Highlight selected item just do like below :
//set it global
int selectedPosition = -1;

public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
     ...

     if(selectedPosition == position)
     {
         viewHolder.ItemView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#FF4081"));
     }
     else
     {
         viewHolder.ItemView.SetBackgroundColor(Android.Graphics.Color.ParseColor("#ffffff"));
     }

     viewHolder.ItemView.Click += (sender, e) =>
     {
         selectedPosition = position;
         NotifyDataSetChanged();
     };
 }

Effect like this.


text:
Q: Unable to read a maze of chars and put it into a bidimensional array I am making a maze solving game. There is a function in the middle of the game that saves the progress and prints everything into the file. But now i want to read the maze, the character, etc from the file and put it into a bidimensional array but i am not being able to do so.
The array is declared globally (because of its use in several functions) and it is maze[30][30]. N is also declared globally as a variable size but at this point it should be 10. filePath too and it gives the name of the file.
This is how they are declared globally.
int N = 10;
char* filePath = "./save.txt";
char maze[30][30];

This is the read function:
void ler()
{
    int i, j;
    ex=1; ey=0;
    sx=N-2; sy=N-1;

    int aux;
    FILE *fp = fopen(filePath, "r");
    if (fp == NULL)
    {
        printf("Unable to perform.");
    return;
    }
    system("cls");

    for(i=0 ; i<N ; i++)
    {
        for(j=0 ; j<N ; j++)
        {
        fscanf(fp, "%c", maze[j][i]);
        }
    }

    for (i = 0; i < N; i++)
    {
    for (j = 0; j < N; j++)
    {
        printf("%c", maze[j][i]);   //Double print just for visuals
        printf("%c", maze[j][i]);
    }
    printf("\n");
    }
    fclose(fp);
}

This is the save function:
void save(char maze[30][30]){
int i,j;
FILE *fp = fopen(filePath, "w");
if(fp==NULL){
    printf("Unable to perform.");
    return;
    }

for(i=0 ; i<N ; i++){
    for(j=0 ; j<N ; j++){
        fprintf(fp, "%c", maze[j][i]);
        fprintf(fp, "%c", maze[j][i]);
    }
    fprintf(fp, "\n", maze[j][i]);
}
fclose(fp);}

At this point it should only be possible to print the maze but it is not doing even that.
What save.txt file looks like after saving
The weird II is the caharcter and the other is like a highscore thing.

A: Using multidimensional arrays in C is actually more pain than they're worth. A much better option is to use a structure with a dynamically allocated array describing the maze, and accessor functions to examine and change the maze cells. Instead of putting markers in the maze data, you can put start/end/current location coordinates in the structure.
(I do realize that this does not answer the OP's stated question, but this is an answer to the underlying problem OP is trying to solve.)
Consider the following example. It limits the maze size to 255×255, but because each coordinate and maze cell is always just one byte, the save files are portable between architectures, as there is no byte order (endianness) to worry about. (You, as the programmer, do need to choose to use only codes 0..255 in the maze, though, to keep the data portable; the functions below won't enforce that.)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

typedef struct {
    unsigned char  row;
    unsigned char  col;
} mazepoint;

typedef struct {
    unsigned char  rows;
    unsigned char  cols;
    unsigned char *cell;
    mazepoint      player;
} maze;

#define  OUTSIDE    0

static inline unsigned char  maze_get(maze *const  m,
                                      const int    row,
                                      const int    col)
{
    if (m &&
        row >= 0 && row < (int)(m->rows) &&
        col >= 0 && col < (int)(m->cols))
        return m->cell[ (size_t)col + (size_t)(m->cols) * (size_t)row ];
    else
        return OUTSIDE;
}

static inline unsigned char  maze_set(maze *const          m,
                                      const int            row,
                                      const int            col,
                                      const unsigned char  val)
{
    if (m &&
        row >= 0 && row < (int)(m->rows) &&
        col >= 0 && col < (int)(m->cols))
        return m->cell[ (size_t)col + (size_t)(m->cols) * (size_t)row ] = val;
    else
        return OUTSIDE;
}

static inline void maze_free(maze *const m)
{
    if (m) {
        free(m->cell);
        m->rows = 0;
        m->cols = 0;
        m->cell = NULL;
    }
}

int maze_create(maze *const    m,
                const int      rows,
                const int      cols)
{
    size_t          cells = (size_t)rows * (size_t)cols;
    unsigned char  *cell;

    if (!m)
        return -1;  /* NULL reference to a maze variable! */

    if (rows < 1 || rows > 255 ||
        cols < 1 || cols > 255)
        return -1;  /* Invalid number of rows or columns! */

    cell = malloc(cells); /* sizeof (unsigned char) == 1. */
    if (!cell)
        return -1;

    /* Initialize all maze cells to OUTSIDE. */
    memset(cell, OUTSIDE, cells);

    m->rows = rows;
    m->cols = cols;
    m->cell = cell;

    /* Let's initialize player location to upper left corner. */
    m->player.row = 0;
    m->player.col = 0;

    return 0; /* Success. */
}

int maze_save(maze *const m, const char *filename)
{
    size_t  cells;
    FILE   *out;

    if (!m || m->rows < 1 || m->cols < 1)
        return -1; /* No maze to save! */
    if (!filename || !filename[0])
        return -1; /* NULL or empty filename! */

    cells = (size_t)(m->rows) * (size_t)(m->cols);

    out = fopen(filename, "wb");
    if (!out)
        return -1; /* Cannot open file for writing! */

    do {

        /* First byte is the number of rows. */
        if (fputc(m->rows, out) == EOF)
             break;

        /* Second byte is the number of columns. */
        if (fputc(m->cols, out) == EOF)
             break;

        /* rows*cols bytes of maze data follows. */
        if (fwrite(m->cell, 1, cells, out) != cells)
            break;

        /* Player location follows. */
        if (fputc(m->player.row, out) == EOF)
            break;
        if (fputc(m->player.col, out) == EOF)
            break;

        /* You can save additional data at this point. */

        /* That completes the save file. Ensure it is correctly saved. */
        if (fflush(out))
            break;
        if (fclose(out))
            break;

        /* Maze successfully saved. */
        return 0;

    } while (0);

    /* Save failed. */
    fclose(out);
    remove(filename);
    return -1;
}

int maze_load(maze *const m, const char *filename)
{
    size_t         cells;
    unsigned char *cell;
    int            rows, cols, r, c;
    FILE          *in;

    if (!m)
        return -1; /* No reference to a maze variable to load into! */

    /* Just in case, we clear the maze first. Might help finding bugs! */
    m->rows = 0;
    m->cols = 0;
    m->cell = NULL;

    if (!filename || !filename[0])
        return -1; /* NULL or empty filename! */

    in = fopen(filename, "rb");
    if (!in)
        return -1; /* Cannot open file for reading. */

    rows = fgetc(in);
    cols = fgetc(in);
    if (rows == EOF || rows < 1 || rows > 255 ||
        cols == EOF || cols < 1 || cols > 255) {
        fclose(in);
        return -1; /* Not a saved maze! */
    }

    cells = (size_t)(rows) * (size_t)(cols);
    cell = malloc(cells);
    if (!cell) {
        fclose(in);
        return -1; /* Not enough memory available! */
    }

    do {
        /* Read maze cell data. */
        if (fread(cell, 1, cells, in) != cells)
            break;

        /* Player location. */
        r = fgetc(in);
        c = fgetc(in);
        if (r == EOF || r < 0 || r > 255 ||
            c == EOF || c < 0 || c > 255)
            break;
        m->player.row = r;
        m->player.col = c;

        /* Load other saved data here. */

        /* All data read successfully. */
        fclose(in);

        m->rows = rows;
        m->cols = cols;
        m->cell = cell;

        return 0;
    } while (0);

    /* Read error. */
    fclose(in);
    free(cell);
    return -1;
}

In your own program, you'd create a maze thus:
    maze  m;

    /* Create a 20-row, 30-column maze. */
    if (maze_create(&m, 20, 30)) {
        /* Failed to create maze! Show an error message. */
        exit(EXIT_FAILURE);
    }

To save the maze to say maze.dat, you use
    m.player.row = /* row where the player is */
    m.player.col = /* column where the player is */
    if (maze_save(&m, "maze.dat")) {
        /* Failed! Show an error message. */
        exit(EXIT_FAILURE);
    }

If you look at the example code, you can add additional data, especially points like the player place, to be saved and loaded along with the maze cells themselves.
To destroy a maze when it is no longer needed, use
    maze_free(&m);

To load a saved maze, say from maze.dat, use
    if (maze_load(&m, "maze.dat")) {
        /* Failed! Show an error message. */
        exit(EXIT_FAILURE);
    }
    /* Restore player place from m.player.row and m.player.col */

The accessor function maze_get() is not limited to the valid coordinates (0 through rows-1 or cols-1, inclusive). If you examine outside the maze itself, it will just return the value of the OUTSIDE macro. For example,
    if (maze_get(&m, row, col) == 5) {
        /* That cell has value 5 */
    } else {
        /* Either the cell has a different value,
           or row,col is outside the maze. */
    }

Similarly, you can try to set any cell value safely. It will only "stick" if it is within the valid maze coordinate range, however; elsewhere it will return OUTSIDE:
    if (maze_set(&m, row, col, 5) == 5) {
        /* Changed cell value to 5 */
    } else {
        /* row,col is outside the maze. */
    }

The reason I wrote the accessor macros that way, is that it makes rendering only a part of the maze very simple. If the view is viewrows by viewcols in size, centered at row and col, then you can render the view using a simple loop:
    const int  top = row - viewrows / 2;
    const int  left = col - viewcols / 2;
    int        vr, vc;
    for (vr = 0; vr < viewrows; vr++) {
        for (vc = 0; vc < viewcols; vc++) {
            const unsigned char  v = maze_get(&m, top+vr, left+vc);
            /* Draw v at row vr, col vc */
        }
    }

and the cells are even drawn in the same order as you read this text; from top to bottom, left to right.
Note that instead of using the maze cell values for character codes, you should use a lookup table instead. For example,
int cell_char[256];

Instead of printing cell values directly, you'd print the corresponding cell_char, for example
fputc(cell_char[maze_get(&m, row, col)], stdout);

That way you can group e.g. different wall characters into a consecutive range, or even use the individual bits in the 8-bit cell value as identifiers. The maze cells then describe the logical contents in that maze cell, rather than its visual representation, with the logical-to-visual mapping in a separate array.
If you used Gtk+, you could have an array of GtkImage pointers,
GtkImage *cell_image[256] = {0}; /* All NULL by default */

or using SDL, you could have the maze cells as textures you can render,
SDL_Texture *cell_texture[256] = {0}; /* All NULL by default */

and in both cases, read them from either one large image (say, divided into 16×16 exact same size rectangles), or from individual image files.
For example, you could decide that the four least significant bits in the cell value specify whether movement from that cell up (previous row), down (next row), left (previous column), or right (next column) is possible:
#define  CAN_GO_UP(value)    ((value) & (1 << 0))   /* == 1 */
#define  CAN_GO_DOWN(value)  ((value) & (1 << 1))   /* == 2 */
#define  CAN_GO_LEFT(value)  ((value) & (1 << 2))   /* == 4 */
#define  CAN_GO_RIGHT(value) ((value) & (1 << 3))   /* == 8 */

Note that this allows you to do "trap walls": passages that only work one way. Maze cell values that are multiples of 16 (0, 16, 32, 48, 64, 80, 96, ..., 208, 224, and 240) represent completely blocked cells: no way out. +1 allows passage up; +2 allows passage down; +3 allows passage up and down; +4 allows passage left; +5 allows passage left and up; +6 allows passage left and down; +7 allows passage up, left, and down; +8 allows passage right; +9 allows passage up and right; +10 allows passage down and right; +11 allows passage up, down, and right; +12 allows passage left and right; +13 allows passage up, left, and right; +14 allows passage down, left, and right; and +15 allows passage up, down, left, and right.
I would personally also recommend using the wide version of the ncurses library (ncursesw). (I do not use Windows, so I am not exactly sure how you install and use it in windows, but the ncurses home page does have downloads when using mingw.)
Then, you would have a much wider variety of glyphs you could use. (When using UTF-8 locales, potentially the entire Unicode glyph set -- the Box Drawing block especially would be useful for maze drawing, and most of those glyphs are also available in the old CP437 codepage, which means they should work both in Windows and non-Windows terminals nicely.)
In that case, you'd probably use
cchar_t  cell_char[256];

As I mentioned above, you could even do a graphical version (perhaps later on, extending your terminal version?) in C using SDL or GTK+.  (Note that the above separation between logical maze cell content value and the visual describing the cell also means you can, at runtime, choose between "themes", by having more than one set of cell images. That allows you to start with crude informational versions, for debugging, and then add visual goodness.)
The approach shown in this answers allows you to start with a simple terminal-based game, and if you decide you want to, add support for graphical UI, with image-based maze cells, without having to rewrite any of your core maze code.


text:
Q: Can not start visual studio I can not start my visual studio. When I tried to run code, it said that
/snap/code/35/electron-launch: line 28: /snap/code/35/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/gdk-pixbuf-query-loaders: No such file or directory /snap/code/35/usr/share/code/bin/code: line 45: /snap/code/35/usr/share/code/bin/../code: No such file or directory
I install it via Snap
What is the problem and how to fix it?

A: here download
a deb file from here and go to the directory where it's downloaded and type
sudo apt install ./{nameofdebfile}


text:
Q: Programmatically HotBoot (Hot Reboot) Android Device I'm currently using this code to Reboot my Android Device:
try {
    Process proc = Runtime.getRuntime()
                    .exec(new String[]{ "su", "-c", "reboot" });
    proc.waitFor();
} catch (Exception ex) {
    ex.printStackTrace();
}

Now, I want to HotBoot (or "Hot Reboot") my Android Phone using Java. Does anyone know a way to do this?
(If you don't know what HotBoot is, refer to this link)

A: You will need a rooted phone. (Just in case)
su
busybox killall system_server

Or with your code
try {
Process proc = Runtime.getRuntime()
            .exec(new String[]{ "su", "-c", "busybox killall system_server"});
    proc.waitFor();
} catch (Exception ex) {
    ex.printStackTrace();
}


text:
Q: My App crashes after being installed in my iPhone for a few days In the first few days,everything is running ok.But after then if I click my App to run it, it will crash immediately.
Edit: If I install it again with Xcode, it's ok again, it's a cycle...
Here is the crash report I got:
OS Version:      iPhone OS 12.2 (Build 16E227)
Architecture:    arm64
Report Version:  28

Data Source:     KPerf Lightweight PET
Kernel Cache:    0xffffffe000000000 53367679-EAC3-F9BC-B3A1-9B4AB7EBF3CC
Shared Cache:    0x23f0c000 BFBB889C-67F5-3193-9F53-E9429CB8D4A4
Reason:          UIKit-runloop-SpringBoard: timeout 931ms

Command:         SpringBoard
Path:            /System/Library/CoreServices/SpringBoard.app/SpringBoard
Version:         ??? (???)
PID:             52

Duration:        0.90s
Steps:           18 (50ms sampling interval)

Hardware model:  N71mAP
Active cpus:     2

What's the possible reason for this? I cann't find out which part of my code   is broken, so it is hard to post my code here. And I am hoping to locate the problem with only this crash report.


text:
Q: Ruby on rails adding users to groups I am building a social networking site with user, school, and schoolgroup models.  The users join, and have different roles in, the schools through the has_many through schoolgroups.  I am having trouble writing an online form_for button that a user can click on to apply to the school.  The params I need to be included in the creation of the schoolgroup object are the user_id, the school_id, and the role 'applicant'.  I know that I can use current_user.schoolgroups.build to have the form initialize a create action and include the correct user_id, but the problem I am having is how to write a form which sends the school_id to the controller to create the new schoolgroup object.  The @school instance variables in my code are just placeholders for whatever the correct code should be
def create
  @school = School.find(params[:schoolgroups][:school_id)
  current_user.schoolgroups.build(school_id: @school.id, user_id: current_user.id, role: 'applicant')
  respond_with school_path
 end

<%= form_for( current_user.schoolgroups.build(params[school_id: @school.id]),
                                                       remote: true) do |f| %>

<%= f.hidden_field :school_id %>

   <%= f.submit "Apply", class: "btn btn-large btn-primary" %>
   <% end %>

A: I'd go this way
# in routes
resources :schools do
  member do
    put :apply
  end
end

# in schools_controller.rb
def apply
  @school = School.find(params[:id])
  @schoolgroup = current_user.schoolgroups.create(school: @school, role: 'applicant')
  respond_with @schoolgroup
end

#in your view
<%= link_to "Apply", apply_school_path(@the_school_var_you_define_somewhere), remote: true, method: :put,
  class: "btn btn-large btn-primary" %>

This is simplier, and more in the Rails spirit.


text:
Q: Quickly switch to layout editor in Android Studio Is there a commmand or shortcut for quickly jump from code editor to graphical layout editor?
For example I am editing MyActivity.java and it's layout is in activity_layout.xml.
In layout editor there is a button for jumping to code, I just need reverse.

A: First press Ctrl+F12, then press home to jump to main Class name, for example MyActivity, then press enter and now select Navigate | Related File... ( or press Ctrl+Alt+Home in Windows or CMD+ALT+Home on mac)


text:
Q: Как сделать чтобы при hover изображение оставалось на месте Есть изображение 200*200
задаем радиус 100px - получаем круг + обрамляем border 2px (увеличиваем радиус +1px)
При наведении на изображение border увеливаеться до 4px
img{
 width: 200px;
 height: 200px;
 border: 2px solid #000;
 border-radius: 101px;
}
img:hover{
 border: 4px solid #00f;
 border-radius: 102px;
}

При этом изображение не статично, отсюда вопрос как сделать чтобы при hover изображение оставалось на месте.
A: а вы делайте не border, а outline.
Либо иной вариант: box-sizing: border-box


text:
Q: Why isn't entropy constant for a closed system? Entropy is famously defined as
$S = k_B \ln(\Omega(E))$,
where $\Omega$ is the number of microstates of a system with energy $E$. If I consider a closed system with energy $E$, this immediately defines the number of microstates accessible to the system which would realize that energy. The number of microstates is therefore indifferent to the current "energy configuration" and is an invariant. How come then that entropy is supposed to increase as the system approaches its equilibrium state?

A: This is all about what we mean by a 'state' of a system, and over the years different experts
have had different views on it. I expect there will be different opinions in the replies here.
There is a good related question here Does entropy depend on the observer?
and a link to a helpful paper by E. T. Jaynes
https://bayes.wustl.edu/etj/articles/gibbs.vs.boltzmann.pdf
One way to deal with your question is to say that the claim is not that $S$ has to increase,
only that it can't decrease, and your observation is consistent with that. I feel that this
reply would be inadequate, however. It seems to me that $S$ does increase as a system comes
to thermal equilibrium. But there you have the hint of the answer to your question: we only
want to claim that $S$ increases if the system was not already in thermal equilibrium to
begin with. But how did we know that it was not in thermal equilibrium at the start? We can only know
that if we know something in addition to the energy and other fixed external constraints.
So we are claiming to know that, initially, the system state is somewhere within a bunch
of microstates which is a subset of the states counted by $\Omega(E)$. Thus the
initial entropy is $S_0 = k_B \ln ( \Omega_0(E) )$ where $\Omega_0(E) < \Omega(E)$.
The above largely settles the matter. But I can't help feeling that a little more is needed.
The difficulty is that we want to make physics as far as possible about things which
can be agreed, and which are not dependent on subjective things such as the prior
knowledge that a given observer may have. That means we want to define entropy as far
as possible as a property of a system, not a statement about knowledge of an observer.
There is disagreement about how far this can be achieved, and, for myself, I have not
yet settled the matter completely in my own mind.
For anyone else who wishes to answer, I would like to encourage them to keep in mind
phenomena such as spin echo, in which,
owing to correlations in the initial state, the evolution of an isolated system
can appear to decrease entropy (there are many examples).
It's ultimately up to us how we choose to define
technical terms in physics, but the consensus is that the 2nd law of thermodynamics is
so useful that it would be a mistake to define entropy in such a way that spin echo
is an example of a refutation of the 2nd law. In the above-mentioned article Jaynes offers the following statement as a
good way to state the 2nd law:
'The experimental entropy cannot decrease in a reproducible [adiathermal] process
that starts from a state of complete thermal equilibrium.'
I put [adiathermal] in brackets because he used the word adiabatic, but I think he
means simply 'no heat transfer' not 'constant entropy' (the word has had a changing
meaning over the years).


text:
Q: How to replicate the "Move to Dropbox" Mac OS X Finder context menu item for other apps? When Dropbox is installed on Mac OS X, it installs a "Move to Dropbox" context menu item:

I would like to install a similar menu item for other apps and actions. Specifically, I would like an "Open in AppName" menu item that allows me to quickly open files in my favorite text editor  or image editor without wading through the "Open With..." menu mess.

*

*Open in TextMate

*Open in Pixelmator

*Open in etc.

I have found ways to add Automator services for these actions.
However, these are installed at the bottom of the menu, in "Services". They also do not have an app icon, which is key for quickly visually finding the correct menu item in the list.

I would instead like to exactly replicate the "Move to Dropbox" menu item:

*

*App Icon is displayed.

*Near top of context menu, not at the very bottom.

What method does Dropbox use? How can I replicate it for any given app or action?

A: You can now use a Finder Sync Extension to add items to the Finder Context Menu in OS X 10.10 Yosemite:


text:
Q: update table1 after insert record in table2 I need to update the stock in the product table when I insert records in the sales table.
These are my tables:
Table products:
idprod int primary key
name varchar (20)
description varchar (100)
int stock

Sales table:
idsale int primary key
idprod int foreign key
quantity int

and these are my stored procedures:
create procedure update_stock()
begin
update products
inner join sales on products.idprod = sales.idprod
set products.stock = products.stock-sales.quantity;
end

create procedure add_sale(in s_id int, in p_id int, in qua int)
begin
insert into sales values(s_id, p_id, qua);
call update_stock ();
end

First I fill the table products with some data, then I call the procedure add_sale. I have no problems with the first record in the sales table, but when I add more records, the stock of all products in the products table is updated instead of just one.

A: I have read your question ,you have two stored procedure but in update_stock() stored procedure you have not defined the WHERE clause so your stored procedure should be like this
 create procedure update_stock(
    @id int
    )
    begin
    update products  p,
     sales s
    set products.stock = products.stock-s.quantity WHERE p.idprod = s.idprod and WHERE p.idprod=@idvalue ;
    end

A: The inserted product id is missing in your update clause. You have to pass it through your update_stock() call.
Modify update_stock procedure to take product id and quantity as input like below.
CREATE PROCEDURE update_stock(IN pid INT, IN qua INT)
BEGIN
  UPDATE products
  SET stock = stock - qua
  WHERE idprod = pid;
END

By passing qua to the procedure we can prevent additional join to the other table.
Then call update_stock method within add_sale by passing pid and qua like below.
call update_stock (p_id, qua);


text:
Q: Output coming unreasonably large in C for the equation x+ y^2 + z^3 //Experiment 3 Task 4 b.)
#include<stdio.h>
void main(){
    int x,y,z,ans;
    printf("\nEnter the value of x.   ");
    scanf("%i",&x);
    printf("\nEnter the value of y.   ");
    scanf("%i",&y);
    printf("\nEnter the value of z.   ");
    scanf("%i",&z);
    ans = (x + (y^2) + (z^3));
    printf("\nAnswer = %i",&ans);
}

OUTPUT:
Enter the value of x.   1
Enter the value of y.   2
Enter the value of z.   4
Answer = -483189484

A: There are two issues with your code:

*

*With regards to large value, you are printing address rather than actual answer. So remove the & when you print

*The ^ operator in C represents the bitwise XOR. So you can either use the pow function, (dont forget to put #include <math.h>) or write your own version of it to get correct results.


text:
Q: Using a wildcard on S3 Event Notification prefix I have a Lambda function that creates a thumbnail image for every image that gets uploaded to my bucket, it then places the Thumbnail inside another bucket.  When I upload a user image (profile pic) I use the users ID and name as part of the key:
System-images/users/250/john_doe.jpg
Is there a way to use a wildcard in the prefix path?  This is what I have so far but it doesn't work

A: Wildcards in prefix/suffix filters of Lambda are not supported and will never be since the asterisk (*) is a valid character that can be used in S3 object key names. However, you could somehow fix this problem by adding a filter in your Lambda function. For example:
First, get the source key:
var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));

Then, check if it is inside the users folder:
if (srcKey.indexOf('/users/') === -1) {
    callback('Not inside users folder!');
    return;
}

A: No, you can't -- it's a literal prefix.
In your example, you could use either of these prefixes, depending on what else is in the bucket (if there are things sharing the common prefix that you don't want to match):
System-images/
System-images/users/


text:
Q: Service Fabric System.BadImageFormatException I downloaded the latest version of Service Fabric SDK 2.4.164 and try to create a new simple stateless service. Build succeeded but when I run it to debug I got:

An unhandled exception of type 'System.BadImageFormatException'
  occurred in Unknown Module.
Additional information: Could not load file or assembly
  'System.Fabric, Version=5.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35' or one of its dependencies. An
  attempt was made to load a program with an incorrect format.

What is the problem? Please help to solve that. Let me know if I have to add more informations

A: Azure Service Fabri only supports x64 platform. It seems you're using some x86 tools. If you have installed dotnet (CLI) tools for x64 and x86 then check Path environment variable. The first one should be path to the x64 components, it helped me to solve the same issue

A: All Service Fabric assemblies are compiled to x64. Make sure your project is also targeting x64, and not AnyCPU.
The best way to do this is to go into Configuration Manager in Visual Studio, create x64 build configurations for each project, and then delete all of the AnyCPU build configurations. That's how the Service Fabric project templates in Visual Studio are set up. But if you create a project from a different template, like Console Application or Class Library, it will be created with an AnyCPU build configuration - you need to change that to x64 if you reference any Service Fabric assemblies.