Group and sum 2d array data into a flat associative array

Question: I am trying to parse an array of strings with irrelevant leading text (to be removed) then create an associative array where values are summed if the same key is encountered more than once.
$assessmentArr = [
    'a_b_money-rewards=30',
    'c_d_status-stability=15',
    'e_f_personal-professional-development=32',
    'g_h_community-support=9',
    'i_j_money-rewards=12',
    'k_l_status-stability=16',
    'm_n_personal-professional-development=29',
];

foreach($assessmentArr as $data) {
    $fullArr = explode("_", $data);
    $resultArr = explode("=", $fullArr[2]);
    // what do I do with $resultArr?
}

Desired result:
Array
(
    [community-support] => 33
    [money-rewards] => 42
    [status-stability] => 31
    [personal-professional-development] => 61
)

I found this question: How to merge two arrays by summing the merged values which will assist me in merging and adding the values together, but I'm not sure how to go about it when the arrays aren't assigned to a variable. Is what I am trying to do possible or am I going about this the wrong way?
Comment: can you tell in your desired output how you decide values. because it's not matched to the array what you are getting right now?
Comment: Also can you show `$assessmentArr` value;
Comment: [Group array data on one column and sum data from another column](https://stackoverflow.com/q/3286749/2943403)
Answer: Don't make it complicated, just check if the results array already has an element with that key and if not initialize it otherwise add it. E.g.
(Add this code in your loop):
if(!isset($result[$resultArr[0]]))
    $result[$resultArr[0]] = $resultArr[1];
else
    $result[$resultArr[0]] += $resultArr[1];

Then you have your desired array:
print_r($result);

Answer: You could do it like this
$assessmentArr = explode("&", $assessmentData);
$finalArr = array();
foreach($assessmentArr as $data) {
    $fullArr = explode("_", $data);

    // Break down to only archetype and value
    $resultArr = explode("=", $fullArr[2]);
    if(array_key_exists($resultArr[1], $finalArr)){
        $finalArr[$resultArr[0]] += $resultArr[1];
    }else{
        $finalArr[$resultArr[0]] = $resultArr[1];
    }
}

First check, if the key already exists in the array, if so you add the value to the value in the final array. Otherwise you add the new index to the final array, with the value from resultArr as inital value.
... way too slow :/
Answer: Upon parsing the text into its meaningful parts, use the hyphenated strings as keys and the numbers as values.  If a key is encountered for the first time, store the sum of 0 and the current value; otherwise sum and store the stored value and the current value.
Code: (Demo)
$result = [];
foreach (explode("&", $assessmentData) as $data) {
    sscanf(preg_replace('/.*_/', '', $data), '%[^=]=%d', $k, $v);
    $result[$k] = ($result[$k] ?? 0) + $v;
}
var_export($result);

Or for more direct parsing, use a preg_match_all() call. Demo
$result = [];
preg_match_all('/[^_]*_[^_]*_([^=]+)=(\d+)/', $assessmentData, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
    $result[$m[1]] = ($result[$m[1]] ?? 0) + $m[2];
}
var_export($result);


Pegar Inputs com type="money"

Question: $(function() {
    $("input[name*='pvn'").maskMoney({
        thousands : '.',
        decimal : ','
    });
})

Faço isso para pegar os inputs com name='pvn' e aplicar uma máscara, mas gostaria de aplicar essa máscara a todos os campos do tipo money, pois assim não preciso fazer uma função para cada input.
Answer: Basta usar o selector: [type=money]

$(function() {
  $('[type=money]').maskMoney({
    thousands: '.',
    decimal: ','
  });
})

Valor 1
<input type="money" id="valor1" />|
Valor 2:
<input type="money" id="valor2" />
Comment: Funcionou muito bem! Obrigado!!

Pegar Inputs com type="money"


Existing Angular 2 App and Cordova

Question: I have done some searching and can't seem to find an answer to my question.
I have an existing Angular 2 application. Can I use Cordova to build it for multiple platforms? If not are there special steps to take to make this happen? Is there any actual documentation on how this works?
Before it is suggested I'll make it known I want nothing to do with Ionic.
Answer: Sure you can add cordova support to your existing Angular2 app. I haven't found any official documentation but there are several resources that give some useful hints on how to.
See here,  here and here
Basic steps will be:

Create a cordova project: cordova create myApp com.example MyApp
Add necessary platforms:  cordova platform add myPlatform
Copy all the created files from your new cordova project into your existing angular project except from: www folder and package.json file
Merge your angular package.json with the contents of the new cordova ackage.json.
Change your existing angular build script to output the dist files into the www folder so cordova can find the final source files.

By here you should be able to run cordova run android/ios/browser and your app should work. If you need to use cordova specific plugins you will need to add this to your index.html

Don't worry the cordova build will make sure this file exists on the target platform.
Then on your main.ts or index.ts add a check to see if the device is ready and bootstrap your angular app. Something like this:
let bootstrap = () => {
    platformBrowserDynamic().bootstrapModule(AppModule);
}

if(window['cordova']){
    console.log("Cordova found")
    document.addEventListener('deviceready',bootstrap);
} else {
    console.log("Cordova not found")
    bootstrap()
}

Hope it helps someone.
Comment: Thanks! just one thing, there are things in node_modules in the cordova app that need to be copied to the angular app, some how, merging the tow folders didn't work for me, I don't know what those things are, but if you don't want to mess around replacing and skipping files, I'd backup and remove the angular node_modules directory, copy the cordova one, then run npm install in the angular app to restore all the project's libraries.

Existing Angular 2 App and Cordova


aws lex v2 dynamic fulfillment from backend

Question: Context
I'm using aws lex V2 and I have already set up a flow so that the user can make an appointment. The thing is that I would like to return (dynamic values) to the user something like:
Expected result
use dynamic values from the backend
ex:
Your appointment has been confirmed. Please keep the following code: {{appointment_code}} when you show up to the interview.
Actual Result
ex:
Your appointment has been confirmed.
When you set up the fulfillment output in aws lex v2, you defined the "static" content of the response, or add the value of the slots using {slotName} in the sentence. No matter what a set my message content from my backend response. i always get the response configure from the aws lex console, but not from the backend.

some code
The response that I'm using after i get all the necessary slots and generate the appointment "code reference" is the following:
function close(sessionAttributes, message) {
    return {
        "sessionState":{
            sessionAttributes,
            "dialogAction": {
                "type": 'Close',
            },
             "intent": {
                "name": "PetitionsIntent",
                "state": "Fulfilled"
            },
             "messages": [
                {
                    "contentType": "PlainText",
                    "content": `cool, the apointment code is ${ap_code}`,
                }
            ],
        }
    };
}

The code works and the intent is fulfilled, but I get the response from the pre-defined lex console(image above) and not from the backend response.
Is there a way to overwrite the predefined output and use the lambda response instead?
What am I missing?
Answer: It would appear that your Lambda function has not been invoked.
Clicking the Advanced options button under your fulfillment message will slide in a menu from the right.
Ensure that you've checked the Use a Lambda function for fulfillment option under the Fulfillment Lambda code hook heading.
This assumes that you have correctly configured your bot to make use of a Lambda function.
Also note that Lex will use a different value for invocationSource to denote that all slots have been fulfilled. So your Lambda function will need to look out for FulfillmentCodeHook instead of DialogCodeHook.
Comment: The lambda is being invoked at every turn of the bot. All the responses come from the lambda except when the intent is fulfilled. Also, i have the checked the 'Use a Lambda function for fulfillment' and i'm assuming that lex uses the same lambda for handling slots and for fulfillment (since  there is only one place to select/specified the lambda to use )
Comment: Correct, there is only one Lambda function that can be linked to a V2 Lex bot. Please confirm that you're looking for the value of `FulfillmentCodeHook` in `invocationSource` as this would signal the Lambda to provide the correct fulfillment logic. Kindly share more of your code if this doesn't solve the problem.


AS3: Function and variables

Question: What i am basically looking to do is change the name of the outputted instance.
But the problem i have is how to send variables passed thought the function 'find_name' to the 'Event.Complete' function loadNameInfo?
Code Below:
    // Finds a persons name using the ID
    private function find_name(page_Name='search.php',instance_name='name',get1='g1=1',get2='g2=2',get3='g3=3'):void
    {
        var randomParam:String = "?p=" + Math.floor(Math.random() * (10000000));
        var create_URL = (URL + page_Name + randomParam + '&'+ get1 + '&' + get2 + '&' + get3);
        _loader = new URLLoader();
        _request = new URLRequest(create_URL);
        _request.method = URLRequestMethod.POST;
        _loader.addEventListener(Event.COMPLETE, loadNameInfo);
        _loader.load(_request);
    }
    // Loads the name into the correct place
    public function loadNameInfo(e:Event)
    {
        instance_name.text = e.target.data;
    }

Is this kinda thing possible?
Eli
Answer: This is possible.  There are many topics on this out there.  Try searching here for "as3 passing variables to event handlers".
One example is the this post
Basically you can extend the event handler to change it to accept another argument that you pass to it.
Answer: You can write a custom event:
http://www.learningactionscript3.com/2008/11/11/passing-arguments-with-events/
package {
   import flash.events.Event;
   public class CustomEvent extends Event {
      public static const CUSTOM:String = "custom";
      public var arg:*;
      public function CustomEvent(type:String, customArg:*=null,
                              bubbles:Boolean=false,
                              cancelable:Boolean=false) {

         super(type, bubbles, cancelable);

         this.arg = customArg;

      }

      public override function clone():Event {
         return new CustomEvent(type, arg, bubbles, cancelable);
      }

      public override function toString():String {
         return formatToString("CustomEvent", "type", "arg",
                           "bubbles", "cancelable", "eventPhase");
      }

   }

}

Comment: To use custom event you need to write custom URLLoader class :)
Comment: Extend the URLLoader isn't to dificult and there are a thousund examples over there like http://www.mikechambers.com/blog/2008/09/12/urlloader-subclass-with-automatic-refresh-support/ . Im not sayng this is the best solution, but works and is elegant.
Comment: Anyway, the link has 4 solutions for you to choose from.
Comment: I agree that it's not difficult. Just to mention.
Answer: Another way to go about doing it that I just came across is to use an inline function.  I found it at this link.
Basically the idea is the following:
button.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){handleClickEvent(e,"Home")});
function handleClickEvent(e:MouseEvent,str:String) {
    trace("Argument :"+str,"- Event target :"+e.target.name);
}

What is interesting about this style is that you pass the event along with whatever else you want by using an inline function as the event handler that then calls the real handler you want.  Pretty neat.  I've never tried it but it looks like it should work to me.
Comment: This is an example from the link i've posted that suggests 4 solutions for this case.
Answer: You cannot attach custom values to a URLLoader object, but there are several workarounds.
If you have only one loader, you can simply store required values in class fields. If you have many loaders that load content simultaneously, you may create the Dictionary object to associate URLLoader instances with your values. Something like this:
private var _loaderValues:Dictionary = new Dictionary();

private function find_name(page_Name='search.php',instance_name='name',get1='g1=1',get2='g2=2',get3='g3=3'):void
{
    var randomParam:String = "?p=" + Math.floor(Math.random() * (10000000));
    var create_URL = (URL + page_Name + randomParam + '&'+ get1 + '&' + get2 + '&' + get3);
    var loader:URLLoader = new URLLoader();
    var request:URLRequest = new URLRequest(create_URL);
    request.method = URLRequestMethod.POST;
    loader.addEventListener(Event.COMPLETE, loadNameInfo);
    loader.load(_request);
    _loaderValues[_loader] = {"pageName": page_Name, "instanceName": instance_name};
}

public function loadNameInfo(e:Event)
{
    var loader:URLLoader = e.target as URLLoader;
    instance_name.text = loader.data;
    var values:Object = _loaderValues[loader];
    trace(values["pageName"], values["instanceName"]);
    loader.removeEventListener(Event.COMPLETE, loadNameInfo);
    _loaderValues[loader] = null;
}

Answer: Remove loadNameInfo and use anonymous function as event listener:
var that:* = this;
_loader.addEventListener(Event.COMPLETE, function(e:Event):void{
     //you can access instance,which has 'instance_name' name, in 2 ways
     // 1. that[instance_name]
     // 2. that.getChildByName(instance_name)

     that[instance_name].text = e.target.data;
     //Removing anonymous listener from '_loader'
     e.target.removeEventListener(e.type, arguments.callee) ;
});

Answer: Yes, it's pretty possible and surprisingly simple. Here's your code with 3+ lines that do that:
// Finds a persons name using the ID
private function find_name(page_Name = "search.php", instance_name = "name", get1 = "g1=1", get2 = "g2=2", get3 = "g3=3"):void {
  var randomParam:String = "?p=" + Math.floor(Math.random() * (10000000));
  var create_URL = (URL + page_Name + randomParam + "&" + get1 + "&" + get2 + "&" + get3);
  _loader = new URLLoader();
  _request = new URLRequest(create_URL);
  _request.method = URLRequestMethod.POST;
  var functionLoadNameInfo:Function = loadNameInfo(page_Name, instance_name, get1, get2, get3);
  _loader.addEventListener(Event.COMPLETE, functionLoadNameInfo);
  // To remove you do: _loader.removeEventListener(Event.COMPLETE, functionLoadNameInfo);
  _loader.load(_request);
}

// Loads the name into the correct place
public function loadNameInfo(pageName:String, instance_name:String, get1:String, get2:String, get3:String):Function {
  return function(e:Event):void {
    instance.text = e.target.data;
    instance.name = instance_name;
  }
}

This solution is based on this answer.

AS3: Function and variables


Maximal solution differential equation

Question: Consider equations defined in $D_x = (0,\infty) \times (0,\infty)$
1) Find the maximal solution to
$$ \dot y = \frac{3t^2}{5y^4} $$
satisfying the initial value problem $y(1) = 2^{\frac{1}{5}}$
I have found the maximum solution to be $((0,\infty), (t^3+1)^\frac{1}{5})$
2) Find the maximal solution to
$$ \dot y = -\frac{2y}{5t}+\frac{3}{5y^4}$$
satisfying the IVP $y(1) = 2^{\frac{1}{5}}$.
(HINT: Use a transformation of the form $t^{\alpha}y(t)$.
I hope someone can explain how to use the transformation to find the maximal solution.
Comment: Keyword to the answer below: This is a **Bernoulli equation** $$\dot y(t)=P(t)y(t)+Q(t)y(t)^n,$$ using the substitution $u=y^{1-n}$ it transforms into a linear DE.
Answer: Multiply both sides of $$\dot y = -\frac{2y}{5t}+\frac{3}{5y^4}$$ by $5y^4$ to get $$ 5y^4\dot y = -\frac {2}{t} y^5 +3$$
Now let $$u=y^5$$ and your equation transforms to $$ \dot u = -\frac {2}{t} u +3 $$
which is a linear equation.
Solve for $u$ and back substitute to find $y$

Maximal solution differential equation


How to update Geofield using a custom form and DrupalGap's node_save?

Question: The code below successfully updates the title, but does not update the Geofield. The node_save function is provide by DrupalGap and described here http://api.drupalgap.org/node.js_.html
        var node = {
            'nid': nid,
            title : 'New Title', // THIS WORKS!!
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude.toString(), // NONE OF THESE DO
            'field_geocoordinates[und][0][geom][lon]':tripchi.geocoordinates.coords.longitude,
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude,
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude.toString(),
            'field_geocoordinates["und"][0]["geom"]["lat"]':tripchi.geocoordinates.coords.latitude.toString(),
            'field_geocoordinates["und"][0]["geom"]["lon"]':tripchi.geocoordinates.coords.longitude.toString(),
            'field_deal_count[und][0][value]' : 3, // simpler structure also does not update
            "field_geocoordinates": {
                "und": [
                    {
                        "geom": "POINT (2 1)",
                        "geo_type": "point",
                        "lat": tripchi.geocoordinates.coords.latitude.toString(), // I've tried this as strings and integers
                        "lon": tripchi.geocoordinates.coords.longitude.toString(),
                        "left": "2.000000000000",
                        "top": "1.000000000000",
                        "right": "2.000000000000",
                        "bottom": "1.000000000000",
                        "geohash": "s01m"
                    }
                ]
            }
        };
        node_save(node, {
            success: function(result) {
                console.log(result);
                utils.mAlert("Pinpointed Location to Latitude:" + tripchi.geocoordinates.coords.latitude + ' - Longitutde:' + tripchi.geocoordinates.coords.longitude);
            }, error: function(result) {
                utils.mAlert("UPDATE ERROR: " + result);
                console.log(result);
            }
        });

How should i be targeting custom fields in custom html forms / ajax update requests?
UPDATE:
@Jimajamma is correct in the comment below, but this only works when the property to update is value. It is not working on the Geofield module object shown in my code above.
Answer: From this example it looks like the syntax is along these lines:
var node = {
  type:"donation",
  title:"Donation",
  field_donation_amount: {
    und: {
      0: {
        value: form_state.values.amount,
      },
    },
  },
};

Addition:
So have you looked at something like this then?  Nesting things further, eg:
var node = {
  field_geocoordinates: {
    und: {
         0: {
            geom: {
                  lat: FOO,
            },
         },
    },
  },
};

(I think I have the correct number of }s :)  Perhaps a js version of php's print_r (here is an example) of a valid node object from node_load() would help out?
Comment: thank you. update does work when the property is 'value'. i tested it does not matter if 'und' is an object or array format. Any ideas on updating the more complex GeoPoint structure?
Comment: I think you forgot the `0` in your structure
Comment: i f$&#ing love you!
Comment: I guess it's the same as the array format described here: https://www.drupal.org/node/1854188
Answer: The solution to create geofield by lat and lot
include_once(drupal_get_path("module", "geophp") . "/geoPHP/lib/geometry/Geometry.class.php");
        include_once(drupal_get_path("module", "geophp") . "/geoPHP/lib/geometry/Point.class.php");
$node->field_current_location['und'][0]['geom'] = new point((float)$lat, (float)$lot);


modulo division of inverse numbers

Question: I am working on some modulo arithmetic and I do not seem to understand why
$28^{-1} (mod59)= 19 (mod59)=55$ is and not $28^{-1} (mod59) = 0.0035 (mod59)$ ?
When I try to calculate this in Java it does give me 0.0035
Comment: For example, $\;28\cdot 19=9\cdot 29\color{red}{+1}\;$ ....that's *why*.
Comment: http://en.wikipedia.org/wiki/Modular_multiplicative_inverse
Answer: In modular arithmetic, the multiplicative inverse is generally not defined as $x^{-1} = \frac{1}{x}$. It's instead generally defined as an integer such that $x\cdot x^{-1} \equiv 1 \mod{n}$.
For example, the multiplicative inverse of $3$ modulo $5$ would be $2$, because $3\cdot 2 = 6 \equiv 1 \mod 5$.
In your case, $19$ is the multiplicative inverse of $28$ modulo $59$ because $28\cdot19 = 532 \equiv 1 \mod 59$.
Comment: Actually, most people would say that $x^{-1}$ and $1/x$ are the same thing, just symbols meaning "the multiplicative inverse of $x$". It is very common to see modular inverses written as fractions in the literature.

modulo division of inverse numbers


MATLAB Class Efficiency

Question: I try making it short. I got a problem involving numerical simulation of a flow withing a gas pipe. I simulate using different models for the air flow (transport equations) travelling from one boundary to the other (i.e. from right to left).
The question is, since I am using different models to represent said gas flow and boundary conditions I got a lot of functions like:
boundary_left_model_1
boundary_right_model_1
boundary_left_model_2
boundary_right_model_2
boundary_left_model_2b
boundary_right_model_2b
....
flux_model_1
flux_model_2
....
source_model_1
source_model_2
.....

I allocate the needed function before the numerical scheme via (e.g.):
boundary_left = @[needed function];
boundary_right=@ [needed function];
flux = @[needed function];
source=@ [needed function];

What follows is something like:
Solution = numerical_scheme_#1(boundary_left,boundary_right,flux,source,parameters);

you get the point.
Now, what is the most efficient way (while being structured) to build the program? As far as I can tell I have three options:
1) I define every function in a matlab function file (will result in a lot of files)
2) I define every function in the script for the numerical scheme (will result in long file, which is less clear to adjust/read)
3) I create a class for boundary conditions with methods containing all the models, one class for fluxes and sources containing corresponding functions. In my function allocation for the numerical scheme I then call the methods I need. (seems complicated and inefficient, not sure about the time needed calling methods in matlab, but is for me the most structured way)
I should probably note that I am relatively new to matlab and numerical simulation (student) and I am also asking on how this kind of problem is generally solved. Thanks in advance!
Also as a bonus: if someone is fond of practical simulation of PDE systems with matlab - I got questions like "How do I decide on a numerical scheme - which criteria should I consider?"
Thanks again, I wish all of you a pleasent day!
Comment: Are all the functions for "model 1" related? Or do you run simulations where you use e.g. different models on different boundaries?
Comment: Sorry for not stating this clearly. Not all functions are related to model one. I get a different set of flux,source and boundaries for each model. To elaborate this: For example could I run a simulation with the flux and sources for model 1, then I also got to use the corresponding boundary conditions for model 1. I got four different models right now (It may be more in the end tho)
Comment: OK, so you run a simulation for model 1, or one for model 2, but never one where you use e.g. the flux of model 1 with the source of model 2. That makes it easy to isolate the code for each model into its own source file.
Comment: exactly. problem here is (and I didn't mention it), that I got some kind of decision tree:
First I decide on the model (and corresponding flux, source and boundaries)
And then I also got to decide on a numerical scheme (how these are put to use).
My current work consists of comparing different numerical schemes on different models (different grade of simplifications)
Answer: Assuming that the methods associated to model 1 are always used together, and not mixed with those for model 2 or 3, then you could set up your code with all functions for one model in one file:
% MODEL1   Methods that implement model 1
function [boundary_left,boundary_right,flux,source] = model1
boundary_left = @boundary_left_method;
boundary_right = @boundary_right_method;
flux = @flux_method;
source = @source_method;

function [out, args] = boundary_left_method(input, args)
  % [implementation]
end

function [out, args] = boundary_right_method(input, args)
  % [implementation]
end

function [out, args] = flux_method(input, args)
  % [implementation]
end

function [out, args] = source_method(input, args)
  % [implementation]
end

end

Basically, here you have a function that returns the handles to a set of functions that implement one method. boundary_left_method is a private function, so cannot be accessed directly, but model1 can return handles to these functions, which makes them accessible.
You can now do:
[boundary_left,boundary_right,flux,source] = model1;
Solution = numerical_scheme_1(boundary_left,boundary_right,flux,source,parameters);

This solution is fairly similar to the custom class solution suggested by OP, but somewhat simpler. I don't think there would be a big difference in performance, but the only way to know for sure is implementing and timing the various options. What is most efficient changes over time as MATLAB's JIT improves.
Note that the scheme proposed here also allows for data (parameters) to be included in these functions:
% MODEL1   Methods that implement model 1
function [boundary_left,boundary_right,flux,source] = model1(parameters)
boundary_left = @boundary_left_method;
boundary_right = @boundary_right_method;
flux = @flux_method;
source = @source_method;

function [out, args] = boundary_left_method(input, args)
  out = input * parameters; % You can use PARAMETERS here, note that it is not
                            % an input argument to this nested function, it is
                            % found in the parent scope.
end

% ...

end % This end here is important now, this way `boundary_left_method` is an
    % nested function, not simply a separate function within the same file.

Now the function handle boundary_left returned has the data of parameters embedded in it. See the relevant documentation.

If you control also the code to the numerical scheme functions that take these function handles, you could write method1 et al. to return a cell array of handles instead, and the numerical_scheme_1 et al. functions to take a cell array of handles. Then you can simply do:
numerical_scheme_1(method1,parameters);
numerical_scheme_1(method2,parameters);
numerical_scheme_1(method3,parameters);
numerical_scheme_2(method1,parameters);
numerical_scheme_2(method2,parameters);
numerical_scheme_2(method3,parameters);
% etc.

You could then use a loop to go through all combinations:
schemes = {@numerical_scheme_1, @numerical_scheme_2, ... };
methods = {method1, method2, method3, ... };
for ii=1:numel(schemes)
   for jj=1:numel(methods)
      schemes{ii}(methods{jj},parameters);
   end
end

[Disclaimer: this code not tested, but I don't see why it wouldn't work...]
Comment: works like a charm and gives me more options than before. thanks!

MATLAB Class Efficiency


Stubbing a computed function in vue with Cypress

Question: I am trying to stub this out in Cypress. I have a computed that returns true or false. I just want it to return true.
<code>  computed: {

      isAdmin() {
          return this.$store.state.User.isRegistered &&
           this.$store.state.User.isAdmin
        }
}
</code>
There is a great article on using the vuex store
https://www.cypress.io/blog/2017/11/28/testing-vue-web-application-with-vuex-data-store-and-rest-backend/
but I don't even want to touch the store. Is this possible?
Answer: Havent tested this but it should go like this:
<code>        cy.stub(YourComponent.computed, 'isAdmin').callsFake(() => { return true })
</code>


Can I avoid deserializing JSON Jackson http response body twice if I want to set READ_UNKNOWN_ENUM_VALUES_AS_NULL?

Question:
I am deserializing a JSON http response and reading it into a Java object.

My first solution was:
javax.ws.rs.core.Response response = ...
MyClass obj = response.readEntity(MyClass.class);

I want to read unknown enum values of enum members in MyClass as null and not throw an exception, so I modified the above to:
String str = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
MyClass obj = mapper.readValue(string, Class<MyClass>);

Does anyone know how I could avoid the double deserialization here i.e. instead of Response -> String -> Class, just do Response -> Class?
Answer: So the solution to this is to register an ObjectMapperContextResolver with the client
private final ObjectMapperContextResolver OBJECT_MAPPER_CONTEXT_RESOLVER = new ObjectMapperContextResolver();

javax.ws.rs.client.Client client = ...
javax.ws.rs.client.WebTarget target = client.target("...");
client.register(OBJECT_MAPPER_CONTEXT_RESOLVER).target("...");

javax.ws.rs.core.Response response = target.path("...").request(MediaType.APPLICATION_JSON).get();
MyClass obj = response.readEntity(MyClass.class);


Backport of hook_library() for Drupal 6?

Question: I've come to love the hook_library() of Drupal 7 as an extremely clean way of including assets etc. I'm fully aware of the many different ways to include assets intelligently (including the context_addassets module) but I'd love a near exact drop in backport for the hook_library() that Drupal 7 provides.
Note: Using mymodule_library() essentially defines a list of css/js (and their dependant libraries) which can be added in one simple call to drupal_add_library()
Answer: The module that originated the patch that introduced hook_library() in Drupal 7 is the jQ module (see Allow to add JS/CSS libraries (sets of files, settings, and dependent libraries). The hooks used by that module are different, but that is the module that is closer to what you are looking for. That module requires you to call a different function, but using drupal_add_js() would require you to hack the Drupal core, which is something it is never suggested to do, in the cases where you want absolute compatibility between Drupal 6 and Drupal 7.
Answer: There is the Libraries API module available for Drupal 6 which is similar to the native Drupal 7 hook_libraries.
Comment: This is good for global libraries that are shared between modules but I was really looking for a simple way to add a group of single module assets (css/js) in one call vs many.
Comment: In that case I'd use kiamlalunos suggestion. jQ allows you to dump the files in a plugins folder then call them via jq_add('library.js'). A little known feature is that if you have a css file make sure it's the same name as the js library (e.g. library.css) and in the same folder and it will be including in the same call.


What is the main use of the Python built-in 'compile'?

Question: When looking through the list of Python built-in functions, I struggle with understanding the usefulness the method compile.  All of the examples I could find point to a simple "hello world".  It make sense what it does, but not when to use it.
Is this the same method Python uses to generate the .pyc files?
Can this be used to remove some of the dynamic nature of Python to improve performance on certain blocks of code? (Knowing full well that a module in C is the way to go precompiled modules.)
Answer: From here: What's the difference between eval, exec, and compile in Python?:
compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.
compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.
compile(string, '', 'single') is like the exec mode, but it will ignore everything except for the first statement. Note that an if/else statement with its results is considered a single statement.

UPDATE:
When to compile Python?
Generally you compile Python to take advantage of performance. Compiled code has a much faster startup time since it doesn't have to be compiled, but it doesn't run any faster.
Most notably, you would use compile if you want to convert code into bytecode by hand. This brings up another important, but pertinent question why do this?
As referenced in this magnificent article:

if you want to use exec and you plan on executing that code more than
  once, make sure you compile it into bytecode first and then execute
  that bytecode only and only in a new dictionary as namespace.

Of particular note is this:

Now how much faster is executing bytecode over creating bytecode and
  executing that?:
$ python -mtimeit -s 'code = "a = 2; b = 3; c = a * b"' 'exec code'
  10000 loops, best of 3: 22.7 usec per loop
$ python -mtimeit -s 'code = compile("a = 2; b = 3; c = a * b",
  "", "exec")' 'exec code' 1000000 loops, best of 3: 0.765 usec
  per loop
32 times as fast for a very short code example. It becomes a lot worse
  the more code you have. Why is that the case? Because parsing Python
  code and converting that into Bytecode is an expensive operation
  compared to evaluating the bytecode. That of course also affects
  execfile which totally does not use bytecode caches, how should it.
  It's not gonna magically check if there is a .pyc file if you are
  passing the path to a foo.py file.
Comment: Great update.  I had a hunch that it was geared towards only really being useful when using the `exec` built-in.  Thanks for taking the time to shed some light on the topic.
Comment: This is what I have gathered as to what it does, but it's still not clear on when / why to use it.  The only thing that comes to mind would a quick check to see if there are any syntax error prior to calling an 'eval' / 'exec'.
Comment: @AdamLewis, my apologies. Updated.
Answer: To answer the dynamic nature thing, no, not really. The resulting code object is still interpreted; the same bytecode still runs.
The most useful/impressive use of compile() (and code generation) that I've seen is in Jinja2. It actually generates Python code from your templates, then uses compile so it runs at 'native' (== interpreter) speed, if that makes sense.
https://github.com/mitsuhiko/jinja2/blob/master/jinja2/environment.py#L506
In contrast with, say, django.template, which does variable lookups, etc in "userspace" (again, so to speak - metaphor is kind of weird).
https://github.com/django/django/blob/master/django/template/base.py#L752
Comment: I've used django and jinja both, but never dug that deep into the template system before.  I agree that that's pretty way to process the templates.  Maybe this is part of the reason I've used jinga as the templating system in django :)


Limit question factoring

Question:
Possible Duplicate:
How do I find the delta analytically for $f(x)$ with a degree other than $1$

There is a question, prove that:
$$\displaystyle \lim_{x\to3} x^{2} = 9$$
in linear problems of this type I simplify $0<|f(x)-L| \lt \epsilon$ to look like
$0 \lt |x-a| \lt \delta$.
Example:
$$\displaystyle \lim_{x\to3} 4x - 5 = 7$$
ends up
$0 \lt |x-3| \lt \delta$ then $|(4x-5)-7| \lt e$
ends up
$ 0 \lt |x-3| \lt \delta$ then $|x-3| \lt \epsilon/4$
then $\delta = \epsilon/4$
But with quadratics I have a problem with the factoring/simplification...
step 1. $|x^{2}-9| \lt \epsilon$
step 2. $|(x+3)(x-3)| \lt \epsilon$
now I know that I have to make $|(x+3)(x-3)| \lt \epsilon$  look like $0 \lt |x-3| \lt \delta$ but I don't know how to go about it.  Any help would be appreciated!
Answer: First we give an informal description, and then condense that into a one line formal argument at the end of the post.
We want control over $|x^2-9|$, so we want control over both $x+3$ and $x-3$. First we concentrate on controlling $|x+3|$, making sure it can't get too big.
Ultimately we will insist $x$ be reasonably close to $3$, in particular within $1$ of $3$. Suppose that  $\delta \le 1$.  That forces $x$ to be in the interval $[2,4]$, so it forces $5\le x+3\le 7$. Now $[x+3|$ cannot be very big.
Note that $x^2-9=(x+3)(x-3)$.  So if $|x-3|\lt \delta$ and $\delta\le 1$, we will have $|x^2-3|\lt 7\delta$. Thus we will be OK if we furthermore make $7\delta$ less than $ \epsilon$.
It follows that if $\delta\lt \epsilon/7$ and $\delta\le 1$, we will be OK. More briefly, we will be OK if $\delta=\min(1,\epsilon/7)$.
We described the thinking that goes into the following formal argument.
Let $\delta=\min(1,\epsilon/7)$. If $|x-3|\lt \delta$, then $|x+3|\lt 7$, and therefore
$$|x^2-9|=|x+3||x-3|\lt 7\delta\lt \epsilon.$$
Comment: Very nice exposition!
Comment: Thank You for your help Andre'!

Limit question factoring


Intersection Observer Not Triggering Section Linked To From Other Page

Question: I have set up the Intersection Observer API on my home page. I have sections with ids that are linked to from the navigation menu. Each section successfully triggers the Intersection Observer callback as it is scrolled to from the page when clicked.
I link to these same sections from other pages in the navigation menu however when one of these links is clicked, the section on the home page is navigated to but the Intersection Observer callback is not executed.
Here's an example of the navigation link: index.html#about-us
The Intersection Observer Code:
var aboutUs = document.querySelector('#about-us');

var observer = new IntersectionObserver(function(entries) {
        if(entries[0].isIntersecting === true) {
            entries[0].target.style.opacity = '1';
        }
    }, { threshold: [0.5] });

observer.observe(aboutUs);

If anyone has any experience with this please let me know.
Answer: I found a solution. Checking the window.scrollY position in a conditional and then executing code for that section:
if (window.scrollY > 1700 && window.scrollY < 1800) {
        for (let i = 0; i < serviceDivs.length; i++) {
            var el = serviceDivs[i];
            el.style.opacity = '1';
        }
    }


Métodos de armazenamento de imagens

Question: Estou estudando qual a melhor maneira de armazenar algumas imagens dos usuários que são cadastrados em meu sistema.
Encontrei 3 maneiras de se resolver esse problema: Salvar em um diretório local, Salvar como BLOB e Salvar como Base64.
Gostaria de saber quais os prós e contras dessas opções e qual delas se destacaria das demais. E também se existe alguma outra maneira de salvar essas imagens.
Comment: De cara, posso dizer que Base64 ocupa 25% a mais de espaço do que as outras 2 opções e para armazenamento não faz sentido. Para transmissão, aí talvez seja ser necessário dependendo muito do meio utilizado. (os detalhes deixo para quem for postar resposta completa).
Comment: Aliás, o correto é eu dizer que Base64 ocupa 33% a mais do que a informação original. 25% é apenas o _overhead_ contido na informação codificada.
Answer:
Vantagens de Salvar em um diretório local: Não usa espaço do seu banco
  de dados, e sim da própria área de aramazenamento do sistema, isso faz
  o armazenamento ser mais barato e
      ser mais simples caso você precise salvar apenas a imagem, só criar uma estrutura de armazenamento conforme suas necessidades.
Vantagens de armazenamento em Blob: Se você possuir espaço de sobra
  para banco de dados, esse é um ótimo método visto que você pode
  adicionar colunas complementares a imagem salva
      contendo mais informaçoes sobre elas, chega a ser mais facil de programar porque linguagens de programaçao novas trazem ferramentas que
  facilitam o armazenamento e também é mais facil de organizar pois elas
  ficam entabeladas em um DB.
Sobre armazenamento em BASE64: Não recomendado pelo aumento do tamanho
  da imagem em até 25%, esse método seria como uma alternativa de
  transmissão da imagem.
Comment: Sobre armazenamento em diretório local, isso é 100% verdade, depois de um tempo, tudo acaba ficando confuso demais. Renomear a imagem como id e tudo mais acaba sendo um gerenciamento complicado caso você tenha coleções, "imagens dentro de imagens" ex: sistema imobiliário, se tem a foto de capa e as fotos do imóvel, diferenciar acaba sendo mais complicado e bagunçado.
Comment: Entendi, mais uma dúvida. Se eu tenho várias imagens salvas em um diretório é mais viável eu passar essas imagens pro Front end utilizando Base64 ou então eu carregar essas imagens no Front direto do diretório?
Comment: A codificação Base64 é frequentemente utilizada quando existe uma necessidade de transferência e armazenamento de dados binários para um dispositivo designado para trabalhar com dados textuais. Esta codificação é amplamente utilizada por aplicações em conjunto com a linguagem de marcação XML, possibilitando o armazenamento de dados binários em forma de texto. Acho que não tem essa necessidade extrema de utilizar Base64 para você retornar sua imagem. Você precisa esconder o diretório onde está a imagem?
Comment: Já que o sistema ira ficar na rede local creio que não tenho a necessidade de esconder o diretório
Answer: Minha resposta é baseada nas seguintes respostas de dezenas encontradas no SOEN
1
2
3
Diretório Local

As imagens podem ser facilmente armazenados em cache quando
armazenados no sistema de arquivos.
Manter imagens em DB é mais caro que manter em um sistema de arquivos.
Em termos de performance é provavelmente melhor armazenar o arquivo
no sistema de arquivos e apenas escrever o nome do arquivo ou
caminho do arquivo e, talvez, o tipo de mime para o banco de dados.
Outra razão para ir para o sistema de arquivos é quando você tem que
compartilhar seus dados (imagens ou sons, vídeo, qualquer que seja)
com acesso de terceiros: no caso aplicação web que usa imagens que
têm de ser acessado a partir de "fora" da rede local de tal forma que
um acesso de banco de dados para recuperar dados binário é
simplesmente impossível.
Você não terá problemas com o aumento da carga DB e conexões que
consomem (que pode ser caro para servidores de banco de dados por
conexãolicenciados).

Banco de Dados

A razão para armazenar binários (imagens) em um banco de dados é a
contenção. Quando todos os dados estiverem em um banco de dados,
dessa forma simplifica muito a estratégia de backup.

Métodos de armazenamento de imagens


Triangular matrix building with Matlab

Question: Need to fill a triangular matrix on MATLAB with the ndgrid command without using loops.
$\mathbf{Example:}$
To fill a square matrix $a_{ij} = i+2j$, for $i,j = 1..10$, the code would be :
[I,J] = ndgrid(1:10,1:10); A = I+2.*J;

But I don't know how to do so if my matrix is triangular. Say, the matrix defined by :
$a_{ij} = i+2j \quad$, if $i \le  j$ and
$a_{ij} = 0 \quad\quad\quad$, if $i > j$
Comment: Is there really no such thing? I have heard people use such term, usually more informally or in context when they did not need to specify upper/lower triangular.
Answer: Try [I,J] = ndgrid(1:10,1:10); A = I+2.*J; A(I > J) = 0;
The last line creates a boolean mask which is true for the indices where $i > j$, and then zeroes out those entries of $A$.

Triangular matrix building with Matlab


Dando "Segmentation fault" quando tento abrir arquivos em C

Question: O seguinte código me dá "Segmentation fault (core dumped)" quando tenta abrir o arquivo depois da declaração e preenchimento de uma string com sprintf.
//Sem as duas seguintes linhas, o código roda normalmente
char Xseqpath[90];
sprintf(Xseqpath, "%s/xseqpath", mainfile);

FILE *File1 = fopen("ref.fasta", "r");
char *file1char;
int charnumber = 0;
while(fscanf(File1, "%c", &file1char[charnumber]) != EOF)
{
    printf("%c\n", file1char[charnumber]);
}
pclose(File1);
return 0;

Answer: Seu problema é relacionado com alocacao de memoria em C, voce esta inserindo dados no ponteiro char *file1char que nao foi alocado, somente declarado.
Substitua a declaracao char *file1char por char file1char[1024], tome cuidado pois se seu arquivo ref.fasta tiver mais de 1024 bytes ira acontecer invasao de memoria e possivelmente outro sigsegv.
Seu codigo ficaria assim:
char Xseqpath[90];
sprintf(Xseqpath, "%s/xseqpath", mainfile);

FILE *File1 = fopen("ref.fasta", "r");
char file1char[1024];

int charnumber = 0;

while(fscanf(File1, "%c", &file1char[charnumber]) != EOF)
    printf("%c\n", file1char[charnumber]);

pclose(File1);

return 0;

Answer: Como já foi respondido aqui, o problema é que você não alocou nenhum espaço na memória para file1char.
Você pode também ter uma abordagem dinâmica sem muita complicação, podendo realizar o processo em arquivos de qualquer tamanho, já que você obtem caracter por caracter:
char Xseqpath[90];
sprintf(Xseqpath, "%s/xseqpath", mainfile);

FILE *File1 = fopen("ref.fasta", "r");
char* file1char = calloc(1,sizeof(char)); //calloc é mais seguro que malloc

int charnumber = 0;

while(fscanf(File1, "%c", &file1char[charnumber]) != EOF)
{
    //"charnumber++" retorna o valor anterior de charnumber, e incrementa após retornar.
    printf("%c", file1char[charnumber++]);
    //Aumenta o tamanho de file1char dinâmicamente
    file1char = realloc(file1char,(charnumber+1)*sizeof(char));
}

fclose(File1);
free(file1char);

return 0;

Mas se você não precisar deste vetor de caracteres para usar em algo mais tarde, não há necessidade de salvar todo o conteúdo do arquivo em uma string, você pode utilizar apenas um caracter e atribuir sempre a ele:
char Xseqpath[90];
sprintf(Xseqpath, "%s/xseqpath", mainfile);

FILE *File1 = fopen("ref.fasta", "r");
char file1char; //1 caracter

int charnumber = 0;

while(fscanf(File1, "%c", &file1char) != EOF) //Salva sobrescrevendo
    printf("%c", file1char);

fclose(File1);

return 0;

Dando “Segmentation fault” quando tento abrir arquivos em C


Prove sum is commutative with measure theory result

Question: Given a measured space $(X,\mathcal{A},\mu)$, consider the following function $f:X\rightarrow \mathbb{R}^+$ defined by
$$
f(x)=\sum_{n=0}^\infty f_n(x),
$$
where $f_n(x)$ are positive measurable functions in $X$.
It is proven that
$$
\int_X f \;d\mu = \sum_{n=0}^\infty \int_X f_n \;d\mu.
$$
I would like to use this result to prove that
$$
\sum_{i=0}^\infty\sum_{j=0}^\infty a_{ij} = \sum_{j=0}^\infty\sum_{i=0}^\infty a_{ij},
$$
where $a_{ij}\ge 0$.
For this I consider the measured space $(\mathbb{N},\mathcal{P}(\mathbb{N}),\mu)$ where $\mu$ is the counting measure, and the function $f$ defined on $\mathbb{N}$:
$$
f(j)=\sum_{i=0}^\infty a_{ij}.
$$
Using the previous result, and given that we are using the counting measure, I get:
$$
\int_{\mathbb{N}} f \;d\mu = \sum_{i=0}^\infty \int_{\mathbb{N}} a_i \;d\mu = \sum_{i=0}^\infty \sum_{j=0}^\infty a_{ij}.
$$
But we also have
$$
\int_{\mathbb{N}} f \;d\mu = \sum_{i=0}^\infty \int_{\mathbb{N}} a_i \;d\mu =
\int_{\mathbb{N}} \sum_{i=0}^\infty  a_i \;d\mu = \sum_{j=0}^\infty \sum_{i=0}^\infty a_{ij},
$$
hence the result.
Is this correct ? Thanks.
Answer: It looks ok, the only thing I would suggest (and this is just a proof-writing issue) is that in your last line of equalities, by definition $\int_\mathbb{N}f(j)d\mu(j)=\int_\mathbb{N}\sum_i a_{ij}d\mu(j)$, and it is actually the result you use in the previous line that allows you to write the integral inside the sum. Also since the last equality follows immediately from the definition, it might not be a bad idea to write it before the more "nontrivial" equality. Also it's not a bad idea to mention that these equalities hold in the "$=+\infty$" case in the sense that if one side equals infinity then the other side is infinite as well.


Does the existence of a mathematical object imply that it is possible to construct the object?

Question: In mathematics the existence of a mathematical object is often proved by contradiction without showing how to construct the object.
Does the existence of the object imply that it is at least possible to construct the object?
Or are there mathematical objects that do exist but are impossible to construct?
Comment: Relevant : [Constructive Mathematics](https://plato.stanford.edu/entries/mathematics-constructive/).
Comment: Why is this downvoted?
Comment: Which is your primary question: 1. What are examples of mathematical objects that we say exist that can't be constructed? Or 2. What does it mean when we say a mathematical object exists?
Comment: Have a look at Klein-bottles
Comment: See also [this](https://math.stackexchange.com/q/2782078/622) and [that](https://math.stackexchange.com/q/2722910/622) which are somewhat related questions.
Comment: @Mark S. I rephrased the question now. It is about the first. If my question title is false, Im interested in examples.
Comment: If we want to prove that something with property $P(\cdot)$ exists, mathematically this breaks down to deriving $\exists x:P(x)$ from the axioms. Some axioms and inference rules got the "arbitrary" label *constructive*. Use only such and you got a *construction* (this does not always work). This feels kind of unsatisfactory and arbitrary sometimes.
Comment: Possibly related: https://math.stackexchange.com/questions/1594412/existence-of-mathematical-objets-constructed-using-the-axiom-of-choice
Answer: Really the answer to this question will come down to the way we define the terms "existence" (and "construct"). Going philosophical for a moment, one may argue that constructibility is a priori required for existence, and so ; this, broadly speaking, is part of the impetus for intuitionism and constructivism, and related to the impetus for (ultra)finitism.$^1$ Incidentally, at least to some degree we can produce formal systems which capture this point of view (although the philosophical stance should really be understood as preceding the formal systems which try to reflect them; I believe this was a point Brouwer and others made strenuously in the early history of intuitionism).
A less philosophical take would be to interpret "existence" as simply "provable existence relative to some fixed theory" (say, ZFC, or ZFC + large cardinals). In this case it's clear what "exists" means, and the remaining weasel word is "construct." Computability theory can give us some results which may be relevant, depending on how we interpret this word: there are lots of objects we can define in a complicated way but provably have no "concrete" definitions:

The halting problem is not computable.
Kleene's $\mathcal{O}$ - or, the set of indices for computable well-orderings - is not hyperarithmetic.
A much deeper example: while we know that for all Turing degrees ${\bf a}$ there is a degree strictly between ${\bf a}$ and ${\bf a'}$ which is c.e. in $\bf a$, we can also show that there is no "uniform" way to produce such a degree in a precise sense.

Going further up the ladder, ideas from inner model theory and descriptive set theory become relevant. For example:

We can show in ZFC that there is a (Hamel) basis for $\mathbb{R}$ as a vector space over $\mathbb{Q}$; however, we can also show that no such basis is "nicely definable," in various precise senses (and we get stronger results along these lines as we add large cardinal axioms to ZFC). For example, no such basis can be Borel.
Other examples of the same flavor: a nontrivial ultrafilter on $\mathbb{N}$; a well-ordering of $\mathbb{R}$; a Vitali (or Bernstein or Luzin) set, or indeed any non-measurable set (or set without the property of Baire, or without the perfect set property); ...
On the other side of the aisle, the theory ZFC + a measurable cardinal proves that there is a set of natural numbers which is not "constructible" in a precise set-theoretic sense (basically, can be built just from "definable transfinite recursion" starting with the emptyset). Now the connection between $L$-flavored constructibility and the informal notion of a mathematical construction is tenuous at best, but this does in my opinion say that a measurable cardinal yields a hard-to-construct set of naturals in a precise sense.

$^1$I don't actually hold these stances except very rarely, and so I'm really not the best person to comment on their motivations; please take this sentence with a grain of salt.
Comment: @Théophile: computably enumerable, see https://en.wikipedia.org/wiki/Recursively_enumerable_set
Comment: Could ypu give a reference for the result about the Turing degree? Or at least what precisely is meant with a "uniform" way?
Comment: What does *c.e.* stand for?
Answer: There exists a Hamel basis for the vector space $\Bbb{R}$ over $\Bbb{Q}$, but nobody has seen one so far. It is the axiom of choice which ensures existence.
Comment: @Barmar Actually, results from descriptive set theory *do* rule out "explicit" constructions.
Comment: Another consequence of the axiom of choice: there is a well order in $\mathbb R$. But no one knows how it is.
Comment: @AndrésE.Caicedo I have no problem saying that $\Delta^2_2$ is not explicit, but you're right that that's important to mention.
Comment: These might just be cases where we haven't discovered the construction yet. I assume the construction hasn't been proved impossible (or you'd have said so).
Comment: @Noah Yes, although one can always force a $\Delta^2_2$ well-ordering without adding reals, so I guess this gives us a concrete limit to what we should mean by "explicit" within the realm of descriptive set theory.
Answer: I am not sure if "constructible" in this context is related, but I think this example also counts.
Not all the regular polygons are constructible. The Gauss–Wantzel theorem stated that,
A regular $n$-gon is constructible with compass and straightedge iff

$n$ is a Fermat prime (A prime in form of $2^{2^m}+1$)
$n=2^k$
$n$ is the product of a power of $2$ and distinct Fermat primes.

So, for instance, regular heptagon ($7$-gon) exists but it is not constructible.
Comment: +1 for an interesting reading of the problem, even though it's probably not what the OP had in mind. The heptagon can't be constructed with _Euclidean tools_ but can with a more general definition of constructible, as in @NoahSchweber 's answer.
Answer: It may be worth mentioning that Errett Bishop developed his version of constructive mathematics precisely because of his disillusionment with his earlier research in complex analysis which he felt involved objects that don't admit any construction.  His last work in classical mathematics was the article

Bishop, Errett.  Differentiable manifolds in complex Euclidean space. Duke Math. J. 32 1965 1–21

which was and continues to be influential.  After 1965, he published about a dozen articles, all dealing with constructive mathematics.
Answer: As others already said, it dependes on your notion of constructible.
Can you construct infinite objects? I think most people agree that you can construct any natural or integer or rational number. But the whole set is infinite. Can you construct it? On the other hand, most real numbers are "infinite" themselves. Can you construct $\sqrt{2}$? What about $\pi$ or $e$?
Things get complicated. Once you have a precise definition for $\pi$, you can trivialy construct it with this steps:

Take $\pi$.
Done.

Is that satisfactory?
Constructive Mathematics (see also links therein) attempt(s) to answer your question. Unfortunately, once you deviate from traditional mathematics, you face the reality of it: a human endeavour. I.e. multiple interpretations, different logics, proof systems, axioms sets, notations... So there are also multiple approaches to constructive mathematics...
Comment: See Bishop's [Constructive Analysis] (https://www.springer.com/gp/book/9783642649059).
Comment: Given a Euclidean length of $1$, a ruler and compass construction of a straight length of $\sqrt{2}$ is rather easy, as is a curved length of $\pi$
Comment: I'd love to see a readable and _usable_ (practical) introduction to constructive mathematics. Say, up to basic linear algebra, group theory and analysis.
Answer: I come from computer science and would like to define "construct" like this:
A real decimal number is constructible if you can write a program that prints out digits of the number forever.  A decimal point must be printed at some time.  The program must be of finite fixed size but can use more and more memory without limit as further digits are computed.
Given this definition, it is possible to describe a number that exists, but is impossible to construct.
This is related to the Halting Problem.  Like in any version of the HP, we assign a number to each possible computer program in a certain language. The Halting Problem Theorem then states that there is no finite program that can decide whether another program will halt or get caught in an infinite loop.
In this version, we then asks for the real number between $0$ and $1$ where digit number $n$ after the decimal point is $1$ if program number $n$ halts and $0$ otherwise.
Any given program $n$ will either halt, or it will not.  This means the number is well defined and exists.
However, writing an actual program to compute it would violate the HPT, so that is impossible.
Comment: The standard term for what Stig described is "computable" or "recursive". The confusion then arises from the distinction between "computable" and "computably enumerable": for the former, the program must specify after some finite amount of time that the nth digit has been computed, whereas for the latter, the digit could remain 0 for arbitrarily long and we can never be sure that it won't be updated to a 1 at some later time.
Comment: Addendum: in constructive mathematics, the halting problem might not have a well-defined solution for all programs, and so it is consistent that your non-constructible number "does not exist". One formal version of this principle is the formal Church's thesis, which explicitly asserts that the only real numbers which exist are those which are computable (and not merely computably enumerable).
Comment: Of course, you would struggle to find the computer with unlimited memory on which to run it but, even if you could get one, you would not violate the HPT, the program would just continue to run until something (e.g. end of the universe) stopped it.
Comment: For this particular example, "write all $0$s", then for each $n$ spawn a thread [universal Turing machine] for $n$, so that when (if) program $n$ finishes, the $n$-th $0$ is replaced by a $1$. An infinte-memory computer has infinite cores, right?
Comment: It seems like my definition is not entirely water-proof. However, fixing it would drown the answer in technical details, so I won't
Comment: @PabloH You can't go back and change stuff that you have already written, that is the crucial part here.
Answer: Taking yet another definition of the terms, a 6 dimensional surface trivially exists, but I'm not sure what one would construct it from in the real world, so the object exists but cannot be (physically and real-world) constructed
Comment: A sphere cannot be constructed physically, only an approximation to one.
Comment: Taking "construct" that literally would eliminate a vast number of mathematical objects.  Irrational numbers would go, however accurate we get, we could never measure the diagonal of a unit square as exactly $\sqrt{2}$.  Even larger integers would go since it is easy to name one larger than the number of atoms in the universe.
Comment: But you can easily construct one in the mathematical world, for example $x^2 + y^2 + z^2 + w^2 + u^2 + v^2 = 100$ describes a 6D equivalent of a sphere. You can plot all the coordinates on the sphere to arbitrary resolution, for example. You can project it down into 3D if you want.
Comment: Yes. Mathematically. But construct and object  can also have a literal meaning. A cube and a sphere are mathematical objects and can be literally constructed. A 6-sphere, so far, cannot, it can only be mathematically constructed, or at best projected instead.
Comment: True - and on that case even more so. But I think an everyday meaning of "construct" allows for real-world scale imperfections. If I went to a carpenter/engineet and said ""here is a mathematical description of a 3d box 10cm on each side, please construct it", they would. But if I said "construct me a 6D box" or "construct me a _perfect_ box", they wouldn't be able to
Comment: You could still define $\sqrt{2}$ as a pair $(0,1)$ with a multiplication defined on it, similar as how complex numbers are defined.
Answer: Another sort of an example: there is a positive real $x\approx 1.16730397826142$ where $x^5-x-1=0$. The Intermediate Value Theorem proves that there is one. But it can't be constructed: we do not have the mathematical language to express it.
Comment: Surely we have the mathematical language to express it. _"The real number $x$ for which $x^5 - x - 1 = 0$"_ is one way to express it. In what sense is that less mathematical language than, say "$\sqrt{2}$"?
Comment: But we *can* construct the number: you started constructing it yourself by listing the first few digits. We can use any root-finding algorithm (bisection, Newton, etc.) to get the rest of the number to arbitrary precision. Perhaps you mean that it can't be described in terms of roots and elementary operations. But that's like saying, "We don't have the mathematical language to express $\sqrt2$" on the basis that it can't be described as a ratio of whole numbers.
Comment: @RosieF What construction takes place in "$\sqrt{2}$"? That merely restates the property that that the number has. You can construct an approximation to it to arbitrary precision, but how is that constructing the number itself?
Comment: Thanks, that is an example, I can really follow with my knowledge of mathematics.
Comment: @JiK But that merely restates the property that the number has. What construction has taken place?
Comment: I constructed an approximation to it, and root-finding algorithms can also be used to construct  approximations to it, to arbitrary precision, as you say. But to do so is not to construct the number itself.


How to decrease data precision correctly?

Question: I have a set of experimental points with redundant precision:
0.76830000353409, 0.76905556061933, 0.76984210235954, 0.77044444666848, 0.77073683346394, 0.77172222236626, 0.77189475013729, 0.77244443774892, 0.77252632859429, 0.77405555879927, 0.77457894100626, 0.77447368503809, 0.77522222435638, 0.77599999469657, 0.77655555537466, 0.77673685030291, 0.77783333429085, 0.77852632906592, 0.77933333866885, 0.77894736537636, 0.78049999893792, 0.78099999695525, 0.78083333389189, 0.78189472927855, 0.7822222219637, 0.78278947532915, 0.78344444830302, 0.78431578813441, 0.78477777916282, 0.78636842390638, 0.78752631227753, 0.78716666774599, 0.78810525816448, 0.7887777844003, 0.7897368537224, 0.79072221420677, 0.79173684221561, 0.7917222207179, 0.7936842060682, 0.79444443860504, 0.79510525960659, 0.79666666536945, 0.79821053060793, 0.79872221677701, 0.79994735717834, 0.80127776980302, 0.80278947668309, 0.80472222117779, 0.80663157385513, 0.80688888354156, 0.80863157531867, 0.80947367916974, 0.81300000057358, 0.81457894116818, 0.81594444754848, 0.81747367664672, 0.82027776600105, 0.82205263206088, 0.82466667558694, 0.82694737182462, 0.82811110515044, 0.83126315806774, 0.83366666694876, 0.83542104161291, 0.83800000665901, 0.8375789411755, 0.8391111063308, 0.83921053646259, 0.8393333307965, 0.83873683162237, 0.83831579018282, 0.83738889684352, 0.83494736511185, 0.8337777908235, 0.83284210603323, 0.83116666724805, 0.8296842029795, 0.82911110946161, 0.82673684843226, 0.82538889264577

I need to automatically decrease data precision without losing information. How I can do it correctly? How to detect how many digits after the decimal point I should leave?
Comment: @AdamO This doesn't seem like a pure programming question: issues of precision ought to concern statisticians and statistical ideas provide some solutions.  For instance, multiplying all values by 342000 and rounding will preserve an unusual amount of precision relative to the sizes of the resulting numbers. No smaller multiplier does anywhere near as well. Indeed, the only surprise is in the first value of the data: perhaps it should be closer to 0.7683012?
Comment: Why are they redundant? If these are measurements from some particle collider they're probably not redundant, but if it's an IQ test, I would leave something of, yes. But it depends on the meaning and even more on how it was measured. There is no way to answer this question. You are always losing information if you leave of digits.
Comment: @Gijs Sure if you remove digits you lose information. But if you plot data, than you remove one digit and plot again you will see that that the information you lose is insignificant.
Comment: I accidentally voted to migrate this to stack overflow. However, since you do not specify software, it is not appropriate for their site. It is not appropriate for ours either. Programming questions are not on-topic for CV.
Answer: This is a fascinating question because (a) this issue does come up in practical work and (b) its solution can reveal hidden information in the data.  Such is the case for the 80 values given in the post.
Most numbers represented in floating point format are far more precise than the data that originally produced them.  No physical quantity, for instance, has ever been measured to more than 10 significant figures.  Measurement systems vary widely.  Analog instruments allow us to read numbers from graduated values marked on rulers or dials: these are inherently quantized to relatively low precision, usually only two or three significant figures (relative to some baseline).  Other instruments may return rational numbers (with small denominators).  Geiger counters and other radiological instruments, which count things and divide by some standard interval, are examples.  Some digital instruments collect analog input but then round them to some power of two.  Photosensors do something like this.
In many such cases, a set of numbers collected by an instrument may have a common denominator.  That denominator might not be apparent in the decimal representations of the numbers.  For instance, consider this set of random numbers between $0$ and $1$:
0.00947867298578199 0.23696682464454977 0.36966824644549762 0.41232227488151657
0.55924170616113744 0.60189573459715640 0.71563981042654023 0.86729857819905209

Although they certainly look random when represented as decimals, consider this representation of the original data:
2/211 50/211 78/211 87/211 118/211 127/211 151/211 183/211

Being integral multiples of $211$, each is really precise only to $\pm 0.5/211\approx 0.0025$: less than three significant figures.
Notice that we could see this property immediately upon multiplying all the data by their common denominator of $211$.  Except for possible floating point roundoff error, all the results will be integral.
The problem is to find this common denominator.  The possibility of roundoff error and other bits of imprecision introduced during processing of the data almost precludes implementing any mathematically elegant solution, such as inspecting continued fraction representations or Fourier representations of the data: in my experience, those rarely work.  However, a brute force search can be strikingly effective.
The brute force search systematically multiplies all the data by some positive integer $n$ and compares the results to integers.  When all, or at least most, of the results are unusually close to integral, we have a possible match to the denominator that was inherent in the original data.
There are some subtleties in implementation.

First, we need some way to measure how close a batch of numbers is to being integral.  I propose comparing each to its rounded value (via subtraction), thereby producing an "error" in the range $[-0.5,0.5]$, and simply averaging their squares.  This is the second moment.
During the search we will produce many second moments and retain the very smallest among them.  Random errors will have second moments near $1/12 \approx 0.083$.  The variance of these second moments for $n$ independent data is $1/(180n)$.   Data that are "almost" integral will have smaller moments.  Integral data will have a moment of zero.  Because we are selecting denominators that yield small second moments, the best will be substantially better than these calculations suggest.  Therefore it would be wise to compare our search results to what a truly random set of high-precision values would produce.  (Such values typically have 10 to 16 significant figures; even a small batch of them will generally not have any discernible common denominator.)
We shouldn't look at extremely small denominators when the range of the data is small: that can produce near-integral data only because the range is narrow.  You might start the search at several times the reciprocal of the range.

Let's see this approach in action with the values given in the question.  First, let's examine a search of all denominators $n$ up to $n=10^4$.

The top row presents error histograms for the five best $n$, ordered by $n$ and colored according to their second moment: red and orange are bad; violet and blue are good.  The bottom row presents error histograms for uniform random data pulled from the same range as the data and searched (independently) in the same way.
This figure is rather uninteresting: no histogram for the data looks exceptionally better than histograms for the random values.
Let's extend the search.  The next one goes out to $n=10^5$.

Obviously something is going on: the data histograms are remarkably better than the random ones.  (The range of variances has expanded, so the colors--although comparable within this graphic--don't correspond to those in the previous graphic.)  The first four have marked spikes at zero: multiplying by these denominators makes the majority of the data integral.  Nothing comparable happens with the random data.  And take a look at the denominators that emerge for the data: they are all multiples of $19000$.  There's something special about this number!
However, the spread of values even in the best data histograms shows that not all the data are whole multiples of $1/19000$.  The distinct spacing exhibited in two of the histograms (for $n=57000$ and $n=76000$) suggests that a small multiple of $19000$ might do the trick.  We might consider continuing our search for $n=6\times 19000, 7\times 19000, \ldots$ and see what happens.  To make sure no possibility is overlooked, though, I simply prolonged the search to all $n$ up to one million ($10^6$):

The denominator $n=342000$ is the first (smallest) which makes almost all the numerators integral: only one is not.  The difference between the data and the random values is striking and large.
When the original data are multiplied by this $n$, all but the first value are within $0.005$ of an integer.  (The first one is $0.40$ too low.)  This suggests we could retain essentially all the precision in the data by representing them as fractions with a denominator of $342000$.  The numerators are
262759 263017 263286 ... 282744 282283

If this seems like too much precision, we might retreat to the smaller denominator of $n=19000$: the errors are at most $0.5/19000 \approx 3\times 10^{-5}$ and many are zero.  That's $4.5$ significant digits, more than enough for most statistical calculations and visualizations.
Appendix
Here is the R code implementing the calculations and graphical displays.  It begins with assigning the data to the array x (not shown, since the data already appear in the question).
library(ggplot2)
library(data.table)
analyze <- function(x, N=20, Id="", n.min=1e3, n.max=1e6) {
  error <- function(n) x*n - round(x*n)
  v <- function(n) mean(error(n)^2)
  N <- min(N, length(x))
  y <- sapply(n.min:n.max, v)
  m <- (n.min:n.max)[order(y)[1:N]]
  X <- data.table(Rank=rep(1:length(m), each=length(x)),
                  m=rep(m, each=length(x)),
                  x=rep(x, each=length(m)),
                  Moment.2=rep(y[m - n.min + 1], each=length(x)))
  X[, Error := error(m)]
  X[, m := ordered(m)]
  X[, Group := Id]
  return(X)
}
set.seed(17)
x.0 <- runif(80, min(x), max(x))
n.min <- ceiling(1/diff(range(x)))
n.min.0 <- ceiling(1/diff(range(x.0)))
for (n.max in c(1e4, 1e5, 1e6)) {
  X <- rbind(analyze(x, n.max=n.max, n.min=n.min, Id="Data"),
             analyze(x.0, n.max=n.max, n.min=n.min.0, Id="Random")
  )
  g <- ggplot(X[Rank <= 5], aes(Error, fill=Moment.2, group=Group)) +
    geom_histogram(color="Black", bins=20) +
    # facet_grid(Group ~ Rank, scales="free_x") +
    facet_wrap(~ Group + m, nrow=2, scales="free_y") +
    scale_fill_gradientn(colors=rev(rainbow(40)[1:34])) +
    ylab("Count")
  print(g)
}


Como encontrar um item em um campo separado por virgulas?

Question: Tenho um campo em uma tabela com dados separados por vírgula:
id_regioes: 1,2,3,4,5,6.
Quando faço a query "SELECT * FROM `tb_operadora` WHERE `id_regioes` = 1", ou "= 6" retorna ok, mas não quando são em 2,3,4,5. Mesmo usando LIKE. Acho que por que eu preciso montar um array antes da query.
Como faço para encontrar os dados em PHP + MySQL?
Quando faço a busca nesse campo separado por vírgulas, ele só encontra itens que se encaixem no primeiro e/ou no último registro do campo.
Comment: Pode ajudar http://pt.stackoverflow.com/q/1788
Answer: Podes fazer uso da função FIND_IN_SET():
SELECT *
FROM `tb_operadora`
WHERE FIND_IN_SET( 3, `id_regioes` )

O que é efeito é localizar o valor do primeiro parâmetro num conjunto definido no segundo parâmetro.
Comment: Perfeito! Muito obrigado!
Comment: Vi agora o link colocado pelo @rray nos comentários que efetivamente responde à pergunta com a solução adequada.
Comment: OK, vou tentar essa solução, depois aviso se funcionou para o que eu quero! Obrigado por enquanto!


Why is int2word program only prining first ten lines?

Question: I am importing a file the counts in words from one to ninety-nine. The goal is to read each line and return an integer value corresponding to the word in the file. However, I cannot seem to figure out why my code is only working for the first ten numbers/lines?
def word_to_int(w):
  i = 0

  ones = [[1,'one'], [2,'two'], [3,'three'], [4,'four'], [5,'five'], [6,'six'], [7,'seven'], [8,'eight'], [9,'nine']]

  teens = [[10,'ten'], [11,'eleven'], [12,'twelve'], [13,'thirteen'], [14,'fourteen'], [15,'fifteen'], [16,'sixteen'], [17,'seventeen'], [18,'eighteen'],[19,'nineteen']]

  tens = [[2,'twenty'], [3,'thirty'], [4,'forty'], [5,'fifty'], [6,'sixty'], [7,'seventy'], [8,'eighty'], [9,'ninety']]

  if(w.find ('-') != -1):
    a = w.split('-')                          #gets rid of hyphen and seperates parts
    for first in tens:
      if(a[0] == first[1]):                   #first half of word
        i = first[0]*10
    for second in ones:
      if (a[1] == second[1]):                 #second half of word
        i += second[0]

  else:
    for num in ones:
      if w == num[1]:
        i = num[0]

  if(i == 0):
    for num2 in teens:
      if w == num2[1]:
        i == num2[0]

  if(i == 0):
    for num3 in tens:
      if w == num3[1]:
        i = num3[0]*10
    return i

any ideas?
Comment: Please provide code which is a [mre] - I should be able to paste the code in your question into a file and run it __without adding anything__ and see the problem you are seeing. Also check that your return is correctly indented. If you code needs data, provide a minimal example in the code which shows the problem.
Answer: Please change code like this:
if(i == 0):
    for num2 in teens:
        if w == num2[1]:
            i = num2[0]   # not i == num2[0]
            print(num2)

Thanks


Having trouble solving $\log (x − 21) = 2 − \log x$ for $x$

Question: I'm having trouble with this problem:

$\log (x − 21) = 2 − \log x$, solve for $x$.

I'm coming up with $x=-5$ but that can't be right.
Answer: $$\begin{align}\log(x-21) & = 2- \log x \iff e^{\log(x - 21)} = e^{2-\log x}\\ \\
& \iff x-21 = e^2\cdot e^{-\log x}\\ \\ & \iff x-21 = \frac{e^2}{x}\end{align}$$
Can you take it from here? Remember, we must have $x>21$, or else $\log(x- 21)$ will not be defined!
Note: if you're working with $\log_{10}$, then simply replace every $e$ with $10$, and you're good to go! For any base, $\log_b$, you'd use $b$ where I've used $e$.
Comment: What base is the logarithm $\log$? If it's base 10, then you'd have $$x - 21 = \frac{(10)^2}{x} \iff x(x-21) - 100 = 0$$ $$\iff x^2 - 21 x -100 = 0 \iff (x - 25)(x + 4) = 0$$ $$\iff x = 25\text{ or } x = -4$$ We throw out $x = -4$ because we cannot take the log of non-positive numbers.
Comment: Thanks amWhy. I wasn't expecting such a quick response. This is a great community!
Comment: You're welcome, @Amos!
Answer: Assuming that $\log x = \log_{10} x$, here are the steps
\[
\log(x-21)=2-\log x
\]
\[
\log(x-21)+\log x=2
\]
\[
\log(x(x-21))=2
\]
\[
10^{\log(x(x-21))}=10^2
\]
\[
x(x-21)=x^2-21x=100
\]
Now just solve the quadratic equation
\[
x^2-21x-100=0
\]
\[
(x-25)(x+4)=0
\]
Thus the solution is $x=25$. We cannot use $x=-4$ as a solution because $\log(-4)$ is undefined. I hope this helps you understand.
Comment: Thanks for your help! I really appreciate it.
Comment: @Amos, anytime. Welcome to math SE!


NIFI || Send Mail only for True boolean expression

Question: I am calculating value using below expression:
${alert:gt(${Lower}):or(${alert:lt(${UPPER})})} which in turn is returning either True or false value.
As per requirement I have to send a mail notification for True condition only.
can someone tell me suitable condition to send only true condition from above calculation.
Comment: before `PutEmail` add the `RouteOnAttribute` processor where you could check the required value / expression and forward to notification only valid flow files
Answer: before PutEmail add the RouteOnAttribute processor where you could check the required value / expression and forward to notification only valid flow files


Discrete math: determining whether a relation is a function

Question: In my book, they ask us to determine whether the following is a function:
$S \subseteq \mathbb{R} \times \mathbb{R}$ with $S = \{(a, b) \mid a + b = 10\}$
For previous problems like this, they gave us a relation of ordered pairs on a set, which I easily plugged into domain/codomain and mapped to each other to determine if it satisfied the definition of a function. For this question, I have no idea where to start.
I know it is saying that $S$ is a subset of $\mathbb{R} \times \mathbb{R}$ (not sure what $\mathbb{R} \times \mathbb{R}$ means here), and that $S =$ a set where $\{(a,b)~\text{such that}~a + b =10\}$. I'm not sure how to use this information.
Comment: Welcome to MathSE.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: Please, if you are satisfied with the answer below, accept it.
Answer: $\mathbb R\times\mathbb R$ means the set of all ordered pairs $(a,b)$ such that $a$ and $b$ are in $\mathbb R$.
Recall that a function can be thought of as a set of ordered pairs (the first entry is the input, the second is the output). So, for example $\{(1,2), (2,5), (3,2)\}$ is indeed a function. On the other hand, $\{(1,2), (1,5), (3,2)\}$ is not, since $1$ gets mapped to both $2$ and $5$.
Now, our set (relation) is the set of all of ordered pairs that sum to $10$. Can find two ordered pairs $(a,b)$ and $(a,c)$ with $b\neq c$ such that $a+b=10$ and $a+c=10$? If so, you will have that $a$ maps to both $b$ and $c$, and $S$ would not be a function.
If you cannot think of two such ordered pairs, it may be the case that it is indeed a function. To show that it is, you would need to show that if $(a,b)$ and $(a,c)$ are in $S$, then $b=c$. Can you show that if $a+b=10$ and $a+c=10$ then $b=c$? If so, you have shown that $S$ is a function.
Comment: thank you so much!


Microkernel with low bootstrap level?

Question: Drupal 7 had a neat feature of different bootstrap levels that allowed to write really fast micro services that didn't require to fully bootstrap Drupal.
Drupal bootstrap levels no longer exists in Drupal 8, but what would be the best approach to build some kind of microkernel to handle simple database queries? I'd like to initialize the database and configuration to do some SQL queries and send a JSON response.
Answer: A lot of the bootstrap process happens now implicitly as services are requested.
If nothing requests the database service then Drupal won't open the connection to it and so on.
The minimal amount of code to do a custom php file that bootstraps Drupal and does some queries can be seen in statistics.php:
<code>$autoloader = require_once 'autoload.php';

$kernel = DrupalKernel::createFromRequest(Request::createFromGlobals(), $autoloader, 'prod');
$kernel->boot();
$container = $kernel->getContainer();

$views = $container
  ->get('config.factory')
  ->get('statistics.settings')
  ->get('count_content_views');

if ($views) {
  $nid = filter_input(INPUT_POST, 'nid', FILTER_VALIDATE_INT);
  if ($nid) {
    $container->get('request_stack')->push(Request::createFromGlobals());
    $container->get('statistics.storage.node')->recordView($nid);
  }
}
</code>
Depending on what it is for, you could also do a normal controller and return a cacheable JsonResponse with the right cache tags and contexts, then Drupal will automatically cache that in the internal and dynamic page cache. Which, depending on your queries, might not be much or not at all slower.
Comment: Thanks that sounds promising. The main issue here is that I can't cache response but in other hand all I need to generate it is one SQL query. That's why I thought of this micro kernel approach to reduce unnecessary overhead.
Comment: Why can't it be cached?
Comment: Because response depends on one of the request headers and varies between anonymous users.

Microkernel with low bootstrap level?


Qt5: Preventing another instance of the application doesn't work anymore...!

Question: I am using Qt5 on a Windows7 platform.
My application is some kind of TCP server listening on port 8002, so I only want one instance of it.
In order to prevent multiple instances of my application, I use(d) the code below (found here on StackOverflow):
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QSharedMemory sharedMemory;

    sharedMemory.setKey("TcpServer-Key");
    if(sharedMemory.create(1) == false)
    {
       QMessageBox::warning(NULL, "Warning!", "Another instance already running!");
       a.exit(); // exit already a process running
       return 0;
    }
...

Well, the code above used to work just fine, until I upgraded my Qt to 5.5.1.
Now, with Qt 5.5.1, I don't see the warning message-box anymore!... When I try to start another instance, the running app disappears/stops and a new app is started!!!
Please help, what should I do? But don't tell me to switch back to Qt 5.4.x  :(
Remark: I forgot to mention that I set & used msvc2012 compiler during tests (not minGW, as I wasn't able to build log4cxx for it).
UPDATE: Could it be an issue related to the antivirus installed on that PC (at the office, i.e. McAfee)?... Now I'm at home (AVG antivirus and MinGW compiler and log4cxx removed) and I am unable to reproduce the above described issue :(
Comment: Qt (for Windows) is implemented using *"Microsoft stuff"*. Anything in the Windows API is available to MinGW. No extra packages required.
Comment: Works for me on Qt 5.5.0.
Comment: Yup, used to work for me on Qt 5.5.0 too,,, So, I think maybe I did something wrong during development process, while playing, fiddling with it...?
Comment: If you need this on Windows only, use a name mutex (see [CreateMutex](https://msdn.microsoft.com/en-us/library/windows/desktop/ms682411.aspx)) instead of Qt's abominations. See [Preventing multiple instances of my application](http://stackoverflow.com/q/8799646/1889329) for possible implementations.
Comment: You can use QtSingleApplication http://stackoverflow.com/questions/5006547/qt-best-practice-for-a-single-instance-app-protection
Comment: @IInspectable: That's a Microsoft stuff, I don't think it would work under Qt (minGW compiler)... would it?
Comment: @demonplus : Well, it seems QtSingleApplication is not part of Qt's main/basic distribution. I suppose the issue can be solve without adding extra packages... Nowadays people tend to install as many extra packs as possible: QtExtra, Boost, etc-etc... I prefer to keep things minimal and simple (years of experience taught me so).
Answer: I finally discovered where the problem was... and it's not the antivirus to be blamed :)
When I upgraded the Qt (Creator v3.6.0) to the newest version (5.5.1), there is a setting in Tools->Options->Build&Run named [Stop app before building]... that was set to Current project or something. Hence, the Qt Creator was killing the old instance before launching a new one(!).
Setting this option to None solved the issue.
So, it seems the code was just fine, antivirus was fine, yet launching the app from within Qt Creator was somehow restricted to only one instance :)
I decided to share this, maybe it will be helpful for other folks as well.
Remark : I checked again and now I can confirm: That setting didn't exist before, at least not in Qt Creator v3.3.2.


How to keep the code running even after exception

Question: I am using Jsoup to connect to a website to get the HTML data.
I have a list of around 1000 URLs that I need to pull the data from and I am iterating on these URLs. For few scenarios, I get an exception:
Exception in thread "main" java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)

This stops the processing of the remaining URLs. I have tried to change the timeout() to timeout(0), but this lets the code to run for that URL endlessly.
Is there a way that I can skip the URLs where I get an exception so that the code runs for the remaining ones.
Comment: Can't you catch the exception? I've never used Jsoup, mind.
Comment: Catching the exception makes the code stop for other URLs in the list
Comment: I mistakenly put for loop inside my try block. Silly mistake.
Comment: you learnt something so. Perhaps consider upvoting and/or accepting any answer which helped you.
Answer: You could wrap your call within a try { ... } catch (E e) { ... } clause
try {
    // Connect to the website
} catch (SocketTimeoutException ste) {
    ste.printStackTrace();
}

Answer: You should use a try-catch inside your loop:
public static void main(String[] args){
    for (int i=0; i<10; i++) {
        try {
            //your code goes here
        } catch (ExceptionType name) {
            //error-handling code
        }
    }
}

Learn more about it here.
Comment: Oh! I mistakenly put for loop inside the try block. Silly mistake.
Answer: you need the code in a try-catch block and after catching this exception you can handle by writing this into a logger or so. Handling the exception will make the program continue.


Derivative of $x^{x^{\cdot^{\cdot}}}$?

Question: The infinite tetration is defined as
$$f(x)=x^{x^{\cdot^{\cdot}}}$$
This function is defined for $e^{-e} \leq x \leq e^{e-1}$.
(Wikipedia image)

Can one determine the derivative of this function?
Comment: If you're talking about the infinite power tower, then you shouldn't be ending the tower with an $x$.
Comment: @J.M. Very true.  Edited.
Comment: http://math.stackexchange.com/a/868528/3936
Answer: Letting $h(x)$ be your infinite power tower, one can solve the functional equation $h(x)=x^{h(x)}$ in terms of the Lambert function $W(x)$, the inverse function of $x\exp\,x$. More specifically, we have
$$h(x)=\exp(-W(-\log\,x))$$
One can then apply the chain rule as usual. The formula
$$W^\prime(x)=\frac{\exp(-W(x))}{1+W(x)}$$
is easily derived through implicit differentiation of the relationship $W(x)\exp(W(x))=x$.
We thus have
$$h^\prime(x)=\frac{\exp(-2 W(-\log\,x))}{x (1+W(-\log\,x))}=\frac{h(x)^2}{x(1-h(x)\log\,x)}$$

As lhf says, the functional equation for $h(x)$ can be differentiated implicitly, without needing to take the Lambert route:
$$\begin{align*}
h^\prime(x)&=\frac{\mathrm d}{\mathrm dx}x^{h(x)}\\
h^\prime(x)&=x^{h(x)}\left(\frac{h(x)}{x}+h^\prime(x)\log\,x\right)\\
h^\prime(x)&=\frac{h(x)^2}{x}+h(x)h^\prime(x)\log\,x\\
h^\prime(x)-h(x)h^\prime(x)\log\,x&=\frac{h(x)^2}{x}\\
h^\prime(x)&=\frac{h(x)^2}{x(1-h(x)\log\,x)}\\
\end{align*}$$
Comment: There is no need to bring $W$ into this. You can just differentiate $h(x)=x^{h(x)}$ and solve for $h'$.
Comment: @lhf: huh, I really was getting lazy there. Thanks for the note; I edited my answer.
Answer: its given that $y=f(x)=x^{x^{x^{x^\cdots}}}$
 I can write this function as,
$$y=x^{y}$$
Taking $log_e$ on both sides, we have,
$$\log y=y\log x$$
Now, differentiate w.r.to $x$ on both sides,
$$\frac 1 y y'=\frac y x + y'\log x $$
$$ \left(\frac 1 y-\log x\right)y'=\frac y x$$
$$y'=\frac {y^2}{x(1-x\log x)}$$
$$f'(x)=\frac {x^{x^{x^{x^\cdots}}}}{x(1-x\log x)}$$

Derivative of $x^{x^{\cdot^{\cdot}}}$?


A "parallel manifold" is always orientable

Question: I want to solve the following problem from Spivak's Calculus on Manifolds:

Let $M$ be an $(n-1)$ dimensional manifold in $\mathbb{R}^n$. Let $M(\varepsilon)$ be the set of end points of normal vectors (in both directions) of length $\varepsilon$ and suppose $\varepsilon$ is small enough so that $M(\varepsilon)$ is also an $(n-1)$ dimensional manifold. Show that $M(\varepsilon)$ is orientable (even if $M$ is not).

I'm aware that the question was already asked here, but I'm not completely satisfied with the answer, that basically defines a normal field on $M(\varepsilon)$ by aiming back for $M$. As I've said in the comment, what if a point $q \in M(\varepsilon)$ is the end point of several normal vectors in $M$? (if this can always be avoided by taking $\varepsilon$ sufficiently small, I would like a proof of that). Also, why is the resulting normal field really is continuous?
Alternate solutions are also welcome. Thank you!
Comment: There are non-compact submanifolds for which $M(\epsilon)$ is not a manifold for any $\epsilon$, for example. Consider any curve in the plane which contains both the $x$ axis and the part of the graph of $\exp(-x)$ in the first quadrant.
Comment: It would have been a good idea to ask why one can choose $\epsilon$ small so that what worries does not occur instead of reasking the same question! (In order to elucidate what my comment on my answer on the old question means)
Comment: @MarianoSuárez-Alvarez you're right, sorry. I just thought that I shouldn't bother you on someone else's question.
Answer: The trouble is that Spivak's statement of the problem is imprecise. If we take his statement literally, then it's not true. For example, we could start with an embedded Möbius band $B\subseteq\mathbb R^3$, and let $M$ be the set of points at a small distance $\epsilon$ from $B$. Then $M$ is an embedded submanifold diffeomorphic to a cylinder. In this case, $M(\epsilon)$ is also a $2$-dimensional manifold, so you'd have to say that "$\epsilon$ is small enough." But one connected component of $M(\epsilon)$ is $B$, which is not orientable.
What Spivak evidently had in mind was to choose $\epsilon$ small enough that the map $h\colon N(M)\to\mathbb R^3$ defined in @squirrel's answer is a diffeomorphism on an open subset containing $\{(x,v)\in N(M): \|v\|\le \epsilon\}$. In that case, @squirrel's argument shows that $M(\epsilon)$ is orientable.
Comment: I'm not sure if I get this right, but why does $M(\epsilon)$ contain a Möbius band component? Doesn't it look something like [this](http://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Orientation_cover_of_Mobius_strip.webm/450px--Orientation_cover_of_Mobius_strip.webm.jpg)?
Comment: It's easier to see using [this picture](https://www.math.washington.edu/~lee/mobius-cover.png), taken from the same Wikipedia animation as the one you linked to. The surface in the picture is $M$; the set $M(\epsilon)$ consists of two connected components, one that you get to by moving a distance $\epsilon$ from the red side, and another that you get to by moving a distance $\epsilon$ from the blue side. If you choose $\epsilon$ just right, the red-side component will be a Möbius band, each point of which is exactly $\epsilon$ away from two different points on the red side.
Comment: @user1337: Just to add to Jack Lee's response, let me point out that if $M$ is the set of points a distance $\epsilon$ from $B$, then $B$ is contained in the set of points a distance $\epsilon$ from $M$. That's why $M(\epsilon)$ contains $B$, a nonorientable surface.
Answer: Here's how Guillemin & Pollack explain it: Define the normal bundle
$$N(M) =\{(x,v) \in M \times \mathbb{R}^n \mid v \perp T_x M \}.$$
Its straightforward to see that $N(M)$ is a manifold. Now define $h: N(M) \to \mathbb{R}^n$ by $h(x,v)=x+v$. This map is regular at $M_0 =\{(x,0) \in N(M)\}$ and restricts to a diffeomorphism $h|_{M_0}: M_0 \to M$. Then a generalization of the Inverse Function Theorem implies that $h$ must be a diffeomorphism on a neighborhood $U\subset N(M)$ of $M_0$. For convenience, let $V=h(U)$, the corresponding neighborhood of $M$ in $\mathbb{R}^n$.
Next, define $\sigma: N(M) \to M$ by $(x,v)\mapsto x$ and $\pi: V \to M$ by $\pi=\sigma \circ h^{-1}$. Then $\pi$ is our desired projection that takes every point in a neighborhood of $M$ and sends it to a point $y\in M$ such that $y-x$ is normal to $M$. If $M$ is compact, there is a constant $\epsilon>0$ such that $$N_\epsilon(M) = \{ (x,v) \in N(M) \mid \|v\|=\epsilon\}$$ is contained in $U$, hence $M_\epsilon=h(N_\epsilon (M))$ is contained in $V$. (Just let $\epsilon$ be the minimal value of the distance function from $M_0$ to $N(M) \setminus U$.) If $M$ is not compact, we can cover it with open sets $U_\alpha$ whose closures $\overline U_\alpha$ are compact, do the above calculation to find a constant $\epsilon_\alpha$ on each $\overline U_\alpha$, then use a partition of unity to get a function $\epsilon: M \to (0,\infty)$ such that $M_\epsilon$ lies inside $V$, as desired. The restriction of $\pi$ to $M_\epsilon$ does exactly what we want: Define a normal vector field at $y\in M_\epsilon$ by $y-\pi(y)$. This is well-defined, smooth, and nonvanishing, so the hypersurface $M_\epsilon$ is orientable.
Comment: Surely, the positive result is the one wanted. I am just emphasizing that what the OP wants to know how to do —how do we choose $\epsilon$ small enough?— is simply not doable in some cases. To get around this, you have changed his objective, and that is the sensible thing to do in that circumstance
Comment: If $M$ is not compact the subset $M(\epsilon)$ need not be a manifold.
Comment: @MarianoSuárez-Alvarez: What's your concern? Self-intersection?
Comment: $\epsilon$ is a number. The concern of the *OP* is self-intersection, in fact.
Comment: @MarianoSuárez-Alvarez: As pointed out in your observation and also in Jack Lee's observation about $M(\epsilon)$ being nonorientable in some cases, we have to clarify Spivak's question.  Since Spivak is looking for a *positive* result, it seems reasonable to me to allow $\epsilon$ to vary, since that includes the special case where $\epsilon$ is constant --- always an option when $M$ is compact --- as well as opening up the possibility of $M$ being noncompact.


Quais os comandos de um Superusuario?

Question: Gostaria de saber quais são os Direitos que um Superusuario possuí dentro de um banco de dados.

Ele pode fazer quais alterações?
Answer: Privilégio  Descrição
ALL [PRIVILEGES]    Todos os privilégios exceto GRANT OPTION

ALTER    Permite executar ALTER TABLE
CREATE   Permite executar CREATE TABLE
CREATE TEMPORARY TABLES  Permite executar CREATE TEMPORARY TABLE
DELETE   Permite executar DELETEtexto em negrito
DROP Permite executar DROP TABLE
EXECUTE  Permite executar stored procedures (MySQL 5.0)
FILE Permite executar SELECT ... INTO OUTFILE e LOAD DATA INFILE
INDEX    Permite executar CREATE INDEX e DROP INDEX
INSERT   Permite executar INSERT
LOCK TABLES  Permite executar LOCK TABLES em tabelas que você tenha o privilégio SELECT
PROCESS  Permite executar SHOW FULL PROCESSLIST
REFERENCES   Ainda não está implementado
RELOAD   Permite executar FLUSH
REPLICATION CLIENT   Permite ao usuário obter a localização do Master ou Slave
REPLICATION SLAVE    Necessário para a replicação Slave (leitura dos eventos do log binário do Master)
SELECT   Permite executar SELECT
SHOW DATABASES   exibe todos os bancos de dados
SHUTDOWN Permite executar mysqladmin shutdown
SUPER    Permite executar CHANGE MASTER, KILL , PURGE MASTER LOGS e SET GLOBAL. Permite conectar-se ao servidor uma vez, mesmo que o max_connections tenha sido atingido
UPDATE   Permite executar UPDATE
USAGE    Sinônimo para "no privileges''
GRANT OPTION Permite ao usuário repassar os seus privilégios

Quais os comandos de um Superusuario?