Best practice for moving content from production server to dev server

Question: I have used GIT to build my Drupal 7 site (following these guidelines). In order to move changed content downstream before updating the site – in order not to overwrite new content with old content – I would like to find out what the best practice is for that. I was thinking about using the d2d migration module, but maybe there are more established and proven methods?
How do the professionals do this?
Answer: Modifying an existing project without loosing data is a common need.
Use Features
One of the best practice I know, is to use the Features module to deliver all the modifications you have made on the production server. Features allow you to make custom modules containing content type structures, views definitions, and a lot more.
You'll probably also need to use the Strongarm module to be able to retrieve the settings variables of some part (modules configuration for instance).
Those modules really help to deploy modifications on a production site, even using git. You'll find easily some good tutorials about using Features.
The only important part to know is when you start using Features, it's difficult to stop using it. Because it will create and implement custom module containing all the specifications of your website (content types, fields, views, pages, ...). If you disable it / them, everything disappear.
Export modifications
If the modifications on your project are not to complicate (mainly content types structures and views), you can use the export / import possibilities offer by some modules (views for instance).
You can also use Bundle Copy module for the node content types export and import part.
Hard way
After, there is a hard way I use sometimes. It is working only if you did not change the fields settings of your existing content types, and if you just add some (fields and content types).
You can copy in your development server database the content tables of your production server. You have to well know all your content types, and specifically the fields used in them (specially the machine names of the fields).
=> You will lose all the new and modified nodes of your dev server. Then do not hesitate to make a backup of your database first.
If you are in the case, you can copy from the production server all the content tables :

node : the base node table with all the content informations
node_revision : if you want to get back the revisions informations
for each one of your content type fields :

the data table : field_data_[field_name] (ie : field_data_body)
the revision table : field_revision_[field_name] (ie : field_revision_body)

url_alias : The custom path of your content (if needed)
taxonomy tables : if you need to, but it can be tricky
user tables : users and users_roles (if needed)
Answer: Since D7 keeps its configuration in sql, when you sql-sync from production to dev (as described below), any configuration changes made to dev will be overwritten. (This has been fixed in Drupal 8, where configuration is stored separate from the content.)
It is sometimes recommended that one use Features to push database configuration changes made on dev to files outside of the sql database, which then can be file-synced to production and then re-imported into the database. Unfortunately, it is not trivial to retrofit an already existing site to use Features for configuration, and not all modules support Features.  While some people report they have success with this method, I have not been able to make it work for my sites - but YMMV.
Instead, the way I do this is to keep a fairly detailed diary of all configuration changes and additions that I make to the dev site.  After the sql-sync, I use this diary as a script and manually add these configuration changes back to dev.
Since you're running the same code base on both servers, there is no need to use d2d migration or any other module to migrate the sql database - standard shell tools will do.
Given that the database holding Drupal is named "drupal7":
I first clear all caches (to reduce the size of the dump) and then do a full dump of the "drupal7" DB on my production server:
drush cc all
mysqldump -u root -p drupal7 > productionYYMMDD.sql

I then move the dump file (using scp) from production to dev and insert the full dump on the dev server:
mysql -u root -p drupal7 < productionYYMMDD.sql

After manually adding the configuration changes (using the diary as a script), dev is now ready to be deployed.
Git isn't relevant here, as it is used for syncing code, not content.
Comment: @FreeRadical : About your prior comment: "*Solution to the problem, changes the problem*", right? Even without "mea culpa ...!". Anyway, I like the spirit of your answer, somehow it reminds me about (what I call) [FCM](http://drupal.stackexchange.com/questions/199206/how-to-use-the-features-module-in-a-3-dev-environnement/199860#199860) ...
Comment: But that would overwrite all the development changes I made in the dev site, since the database holds both content and configuration in Drupal 7?
Comment: You can set configuration in settings.php with `$conf`.
Comment: Jimmy Ko. Let's say that I add a couple of modules and some new content types with a lot of settings. How do you put that in settings.php?
Comment: Your question didn't specify that you've changed the configuration on the dev server - however, I've now expanded the answer to describe how to deal with that.
Answer: Thanks for all your suggestions!
In case anyone else looks for an alternative solution I decided to post this answer to my own question. When the production site needs to be updated with changed theming, new functions, custom modules, new code etc, I do the following for the time being:

Using Putty I login at the remote production server and export all nodes from each content type using the Node Export module with Drush (>drush ne-export --type=mycontent_type --file=transfer/mycontent_type.txt).
After exporting all nodes from each content type I use FileZilla to transfer the transfer folder with all (8) export files to the dev site.
On the dev site I use Drush to import all nodes of each content type. These three steps takes about 10-15 minutes with around one thousand nodes and 8 content types.
The production site and the dev site now has the exact same content. If needed I also transfer images from the production sites/default/files to the dev side, which makes it easier to see that everything looks identical.
On the dev site I now use Migrate & Backup to backup the database. On my production branch I add, commit and push my local changes to my GitHub repo.
Then I login at my staging site with Putty and pull my production branch from Github.
On the staging site I restore the database backup from step 5 with Backup & Migrate.
If everything looks good I put the production site in Maintenance mode and repeat step 6 and 7 there.

This way I will have a fresh copy of the live content on the dev side (and I can easily move content downstream at any time).
As for the answers provided I will certainly explore the Features module and the other possibilities suggested. Thanks again. And please let me know if you spot a flaw in my current method.
Maybe I should mention that there are only a few people that are permitted to add new content or make changes on the live site. That means that I can see to that no new content changes are made during the update procedure.


Detect start and end of an event callback?

Question: I'm working with the new mapbox.js API, especially the event callback 'panned'. The callback is fired about 50-100 times when the user moves the map, which is way too much. What's the best way to get only the first and the last event (or only the last) out of this?
map.addCallback('panned', function(move) {
  console.log('panned');
});

Answer: Use .setTimeout:
var timeout = null;
map.addCallback('panned', function (move) {
    timeout && window.clearTimeout(timeout);
    timeout = window.setTimeout(function () {
        console.log('panned')
    }, 100)
})

For the timeout time choose an appropriate time, which you have to find out by fiddling around with several values.
Answer: UnderscoreJS has a few useful functions.
Debounce might be best suited for you, based on what you describe: ... postpone its execution until after wait milliseconds have elapsed since the last time it was invoked
"Throttle" is also useful: "... will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with."
HTH


vSphere - Virtual Network Device Issue

Question: So I have network monitoring at our business and since we have been monitoring I have noticed massive spikes on one of our core switches in particular -it is causing our internal network to slow down. The problematic interfaces that are throttling data are connected to our host that runs our vSphere. We have around 60 VMs running on that one host including an RSA Authentication Server which might explain why we are having people complain about their VPN connection dropping. The hardware is handling the load fine but I have looked up possible issues and found that Old Virtual Machine Network Devices might be the issue.
I guess im just looking for confirmation about the issue here. I have looked at all 60 odd VMs and found 36 running Flexible/E1000E/E1000 and the rest running VMXNET3. VMXNET3 is stated to be the preferred network device, would using the same virtual network device improve network performance? Or should the way it's currently set up not make much of a difference?
Answer:
would using the same virtual network device improve network
  performance?

VMXNET3 is, with up to date vmtools installed, easily the most efficient method to use, it should reduce your hosts CPU load but won't actually lower the amount of traffic your VMs are sending, in fact it may increase it as it's more efficient. Sounds like your switch is out of steam.

Or should the way it's currently set up not make much of a difference?

No, do change them, it makes sense, no massive rush but it will help.
Comment: OK, good to get that confirmed, will put it on my 'to-do-list'. There shouldn't be adverse effects i should be aware off changing devices from E1000E/E1000/Flexible to VMXNET3 is there? Thanks for your time and quick response btw!
Comment: No, but if shutdown a VM, remove the e1000 and add a vmxnet3 then your vNICs may have different port enumerations so you may well have to rebuild your IP configs but that's easy enough.

vSphere - Virtual Network Device Issue


Determining isometry group of symmetric spaces

Question: I am learning some symmetric spaces, and I tried to look at some example, including Grassmannian (say, $p$-dimensional subspaces in $\mathbb{C}^{p+q}$) and the projective space $\mathbb{CP}^n$. I follow Helgason, therefore I wish to describe them in terms of Lie groups. My problem is:
How to determine the isometry group of a manifold whose geometric description is known?
Let me elaborate more. For $\mathbb{CP}^n$, I understand that the special unitary group $SU(n+1)$ acts transitively on it. Also, I know the isotropy group for a certain point is $U(n)$. It is tempting now to claim $\mathbb{CP}^n = SU(n+1)/U(n)$. But I have not checked that $SU(n+1)$ is the isometry group!
Similar problems arise when I try Grassmannians, Lagrangian Grassmannians, Orthogonal Grassmannians, etc. I usually can find a group acting well on these spaces but I cannot determine whether that group is the isometry group.
Anyone can help? Thanks a lot!
Comment: Why do you care about isometries? What structure do your spaces have? Do they have metrics at all?
Comment: @AmitaiYuval Aha, yes, they do. Let me illustrate with the projective space. It naturally carries the Fubini-Study metric which turns it into a Hermitian (and hence Riemannian, of course) symmetric space. We can even describe the involutive isometries explicitly using homogeneous coordinates. Similar metrics can be given to the Grassmannians.
Answer: It usually goes the other way around.
Take the real Grassmannian space $Gr_k(n)$ for example. The group $O(n)$ acts on it transitively by diffeomorphisms, and the isotropy group is $O(k)\times O(n-k)$. This indeed shows that $$Gr_k(n)=O(n)/(O(k)\times O(n-k)),$$as a diffeomorphism of smooth manifolds. Then, it is natural to equip $Gr_k(n)$ with the unique Riemannian metric which makes the quotient map $O(n)\to Gr_k(n)$ a Riemannian submersion.
The same reasoning applies for all the other examples. If you deal with complex and Hermitian structures, just make sure that the group acts by biholomorphisms.
It is true that, if your symmetric space already has a metric, you need to verify that the group acts on it by isometries. This may be the case with $\mathbb{C}P^n$, as the Fubini-Study metric can be constructed by a few different approaches.
Comment: Thanks for your answer! There are a few points I'm not too sure about. First, I can realize the Grassmannian as a submanifold of a big projective space, via the so called Plucker embedding. Thus I am specifying a metric on Gr, which is induced from the Fubini-Study metric of the ambient projective space, and I would like to find the isometry group with respect to this particular metric. Secondly, not only O(n) but SO(n) also acts transitively on Gr, and that is exactly where my question arise: How can I know there is not a larger group of isometries than O(n) that acts transitively?
Comment: @WuYaochen Does it bother you so much if there is a bigger isometry group? There may be more than one way to represent a space as a quotient of a group.


Area of a triangle and a trapezium

Question: I have this triangle, of which I want to find an area. Is the given information enough? The length of the dotted line is 2, whereas, the length of dotted + line is sqrt(5). I can get the area of two small right angled triangle in top with 1/2 * base * height. But how do I get the area of lower trapezium?
Thanks a lot!
Comment: Note that the right triangle with hypotenuse labelled by the dotted line of length $\sqrt{5}$ is similar to the right triangles at the top of the diagram. Can you use this to deduce the height of the trapezium?
Answer: You can use similar Triangles.
Using Pythagoras the side length of the smaller triangle is $\sqrt{1^2 + 2^2} = \sqrt{5}$.
Knowing that the side length of the bigger triangle is the side length of the smaller triangle $+ \sqrt{5}$ we have that the side length of the larger triangle is $2\sqrt{5}$ so the ratio of smaller:bigger is 1:2.
Can you figure out the height of the bigger triangle now and consequently the area of the bigger triangle?

Area of a triangle and a trapezium


Receiving 404 error when trying to load static urls directly in Django

Question: When I visit the url of my static files (http://127.0.0.1:8000/site_media/static/css/site_base.css) I receive a 404 error message.
404 from the log
[27/Oct/2012 14:14:54] "GET /site_media/static/js/libs/modernizr-2.5.2.min.js HTTP/1.1" 404 1716
[27/Oct/2012 14:34:20] "GET /site_media/static/css/site_base.css HTTP/1.1" 404 1677

Directory Structure
mysite
    |-- manage.py
    |-- mysite
         |-- settings
             |-- base.py
             |-- dev.py
             |-- prod.py
    |-- site_media
       |-- static
           |-- css
               |-- site_base.css

site_base.html
<link rel="stylesheet" href="{{ STATIC_URL }}css/site_base.css" />

settings
TEMPLATE_CONTEXT_PROCESSORS = [
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.static",
]

STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
]

STATIC_URL = "/site_media/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")

Updated:
urls.py
from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),
    url(r'^profile/', include('profiles.urls')),
)

urlpatterns += staticfiles_urlpatterns()

Comment: Have you configured a `STATIC_URL` and `STATIC_ROOT`? Check out the docs at https://docs.djangoproject.com/en/dev/howto/static-files/. If you have done this, please update those values in the code above, and also post what you get when you do http://127.0.0.1:8000/static/
Comment: yes I have see updated settings above
Comment: As mentioned in [the link @jpic provides](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development), you need `urlpatterns += staticfiles_urlpatterns()` in your main url conf. Could you post your main `urls.py` and add your `DEBUG` setting?
Comment: Ive included the main urls file as requested. I have included the additional urls settings and I have not been able to repair this issue.
Answer: Short answer
Django does not serve STATIC_ROOT on STATIC_URL, unless you tell it too.
Long answer
This should be a FAQ, here's an article about using django.contrib.staticfiles right (disclamer: written by me, feedback appreciated). It's like the documentation but tries to be shorter and more pragmatic.
Answer: use <link rel="stylesheet" href="{{ STATIC_URL }}css/site_base.css" /> instead of
<link href="{%static 'css/style.css'%}" rel="stylesheet">  and make sure your value is
STATIC_URL = '/static/' in the settings.py


Como faço para abrir uma janela, tipo windows explorer, a partir de um site

Question: Estou desenvolvendo um site que irá trabalhar com imagens. As imagens estão no micro local. Eu quero pegar todas as imagens (são +- 10 imagens) que estão em uma pasta e as colocar em um grid. Para depois permitir que possa ser dado um zoon. Estou achando que pelo java script eu consiga fazer isso.
Para ser entendido melhor, hoje com o programa rodando no Windows, eu chamo, a partir do programa, o Windows explorer apontando para a pasta com as imagens.
Answer: Você pode utilizar um simples input do tipo file
Veja este exemplo
Html:
<form id="post-form" class="post-form" method="post">
    Select multiple files:
    <input id="files" type="file" multiple/>
    <output id="result" />
</form>

Javascript:
window.onload = function(){
    //Check File API support
    if(window.File && window.FileList && window.FileReader)
    {
        var filesInput = document.getElementById("files");
        filesInput.addEventListener("change", function(event){
            var files = event.target.files; //FileList object
            var output = document.getElementById("result");
            for(var i = 0; i< files.length; i++)
            {
                var file = files[i];
                //Only pics
                if(!file.type.match('image'))
                    continue;
                var picReader = new FileReader();
                picReader.addEventListener("load",function(event){
                    var picFile = event.target;
                    var div = document.createElement("div");
                    div.innerHTML = "";
                    output.insertBefore(div,null);
                });
                //Read the image
                picReader.readAsDataURL(file);
            }
        });
    }
    else
    {
        console.log("Your browser does not support File API");
    }
}

Css:
body{
font-family: 'Segoe UI';
font-size: 12pt;
}

header h1{
font-size:12pt;
color: #fff;
background-color: #1BA1E2;
padding: 20px;

}
article
{
width: 80%;
margin:auto;
margin-top:10px;
}

.thumbnail{

height: 100px;
margin: 10px;
}

Resultado: http://jsfiddle.net/0GiS0/Yvgc2/
Fonte: https://stackoverflow.com/questions/20779983/multiple-image-upload-and-preview
Comment: Alterado nobre amigo.


ARCH and GARCH Models

Question: I found excellent notes on ARCH and GARCH models here. On page 3 it is given that:
Standard time series models:
\begin{eqnarray*}
Y_{t} & = & E\left(Y_{t}|\Omega_{t-1}\right)+\epsilon_{t}\\
E\left(Y_{t}|\Omega_{t-1}\right) & = & \mu_{t}\left(\theta\right)\\
E\left(Y_{t}|\Omega_{t-1}\right) & = & E\left(\epsilon_{t}^{2}|\Omega_{t-1}\right)=\sigma^{2}
\end{eqnarray*}
What does this $\Omega$ means here? Any help will be highly appreciated. Thanks
Answer: Roughly speaking, $\Omega_{t-1}$ is all the information available up to time $t-1$. For example, it can be considered as the observed values of your time series i.e. $Y_0, Y_1, Y_2, ...,  Y_{t-1}$. If I want to be more precise, it is the $\sigma$-algebra generated by all these random variables i.e. $\Omega_{t-1}=\sigma\{Y_0, Y_1, Y_2, ...,  Y_{t-1}\}$.

ARCH and GARCH Models


Deleting object completely after collision event in action script 3.0

Question: I have a basic game function that drops a ball every 500 milliseconds (with a timer event) and suppose to get rid of it when it hits a plate that drags after the mouse. The thing is; I tried to use the deleteChild(); function, but it only removes the visual appearance of the ball object' without stopping its functionality, which causes a couple of problems:

The ball keeps going, and triggers an event of hitting the floor.
The dropBall(); function which animates the dropping ball, doesn't actually animate a new ball.

this is the complete script:
//imports:
import flash.events.Event;
import fl.transitions.Tween;
import flash.text.TextField;
import flash.utils.Timer;
import flash.events.TimerEvent;

//the function 'startGame, handles all basic game functions.
function startGame() {

//inisializes the variable 'Score' and gives it a value of 0.
var Score = 0;

//enter_frame listener. calls 'movePlate'
stage.addEventListener(Event.ENTER_FRAME, movePlate);

//function 'movePlate'. makes the plate follow the mouse
function movePlate(event:Event):void {
    plate.x = mouseX;
}

//calls the dropBall function
dropBall()

//the function 'dropBall'. animates the droping ball
function dropBall() {
    var oldpost = 0;
    var randomNum:Number = Math.random() * 550;
    var xAxis:int = Math.round(randomNum);
    trace(randomNum);
    trace(xAxis);
    ball.x = xAxis;
    base.x = xAxis;
    var oldpost = xAxis;
    var ballTween:Tween = new Tween(ball, "y", null, 0, 500, 1.2, true);
    oldpost = xAxis;
}

//function 'gameTime'. the timer function that controlls the intervals between falling eggs and ratio of good to bad eggs.
var gameTime1:Timer = new Timer(1000);
gameTime1.addEventListener(TimerEvent.TIMER, gameTimer1Function)

function gameTimer1Function(evt:TimerEvent):void {
    dropBall();
}

gameTime1.start();

//enter frame event listener. calls  'checkCollision'
addEventListener(Event.ENTER_FRAME,checkCollision);

//function checl collision. checks if the ball hits the plate
function checkCollision(event: Event):void {
    if(ball.hitTestObject(plate)) collisionDetected();
}

//function collision detected
function collisionDetected():void {
    Score ++;
    trace(Score);
    scoreText.text = Score;

}

//enter frame event listener. calls  'checkGameOver'.
addEventListener(Event.ENTER_FRAME,checkGameOver);
 //function 'checkGameOver.
function checkGameOver(event: Event):void {
    if(ball.hitTestObject(floor)) gameOver();
}

//function 'gameOver'.
function gameOver():void {
    trace('GAME OVER!!! Your Score Is: ' + Score + '.');
    trace('Asta la Vista Baby :D');

}
}
startGame();

Answer: Your'e code is not working as you explained. It is working like this:
You have only one ball, and it is beeing thorwn up, every second, refering to gameTime1 tick calls dropBall (), which doing the following:

it replaces the single ball you have to the 0 possition, and animating it withhin 1.2 seconds to the bottom. var ballTween:Tween = new Tween(ball, "y", null, 0, 500, 1.2, true);
then the score++ is triggered independantly from the ball movement because it is on the enterframe event handler, and each frame the ball is hitting the plate the score increases
YOU SHOULD REALLY LOOK INTO YOUR CODE AGAIN, and rething the architecture, how what and when it should work ( basicaly not only you need to know, what the software should do, but you need to explain this to the software.

UPDATE:
For how to export the movieclipt int oclass follow the tutorial:
http://www.kirupa.com/developer/flashcs3/movieclips_classes_AS3_pg1.htm
Then  in your logics:
Function ( createBall )

Create a instance of the ball. ( if you followed tutorial then you know how to )
start the enterFrame which checks if the ball hitted the panel or the ground if it did stop the enterFrame event.
After stop deside what to do depending on what was hitted

Should look like this:
if ( hitPanel )
{
    increaseScrore ()
}
if ( hitFloor )
{
    decreaseLive ()
}

in each of those functions increase... and decrease.. after they done everything should be removeBall function, and in increase.. then a call to the createBall so everything is starting to repeat.

P.S. No offence please, but you can learn the programming language, in this case i see you know a bit, but if you are missing some logics, you will not find it on forums... Read some basics info about logics / architectures of the applications etc... and please take a look how the instances needed to be handeled.
P.S.S. Invest some to to know wtf is OOP. ;)
best wishes! Happy holidays :)
Comment: so how can I change it so it will make a new ball every time? And lets say it works like that, how do I make sure it will get rid of it?
Comment: now i changed the code so it will instantiate a new ball object every time the drop ball function goes off, but i still don't get how to check the collision, because right now the collision checking function makes errors. is it possible to check if an object that was instantiated from the library object 'ball1' hits the plate?
Comment: you should use only one global variable ball. which is defined outside of the functions. and each time you create a ball you creating `ballMC = new Ball (); addChild ( ballMC )`, and on removeBall function `removeChild ( ballMC ); ballMC = null`. And remember to stop all enterframe ticks, when you are removing the ball.
Comment: but on the collision detection, way should i put (like i have plate and i need the ball object)
Comment: what you had was quite good, but if you want more accurate look here: http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/
Answer: Did you try to set the ball to null ?


Is $r^2-4r\cos(\theta)=14$ an equation of a circle or cylinder?

Question: A question asks to identify the surface of the polar equation
\begin{equation}\tag{1}
r^2-4r\cos(\theta)=14.
\end{equation}
I converted $(1)$ into Cartesian coordinates:
\begin{equation}\tag{2}
(x-2)^2+y^2 = (3\sqrt{2})^2.
\end{equation}
I would have thought $(2)$ represents the equation of a cylinder, because the question asks to identify a surface.
Comment: In $\mathbb{R}^2$ it's a circle.  In $\mathbb{R}^3$ it's a cylinder (using *cylindrical coordinates* $(x,y,z)=(r\cos\theta,r\sin\theta,z)$).
Comment: in how many dimensions?
Comment: @BarryCipra Okay. So is the answer dependent on the context of the question?
Comment: @Gurjinder, yes, exactly.
Comment: @BarryCipra Cool, thanks.
Answer: This is of course a circle. General formula for the circle is $$(x-p)^2+(y-q)^2 =r^2$$
where $O=(p,q)$ is a center and $r$ radius. At your case $O=(2,0)$ and $r=3\sqrt{2}$
Comment: I think we should recognize that this is also the equation of a cylinder whose axis of symmetry is parallel to the $z$ axis
Answer: $$\begin{equation}\tag{1}
r^2-4r\cos(\theta)=14.
\end{equation}$$
$$x^2+y^2-4x=14$$
$$(x-2)^2+y^2=18$$
$$(x-2)^2+y^2=(3\sqrt{2})^2$$


query all fields of a MongoDB document

Question: import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
db = client['db']
collection = db['foo']

data = [{           # doc 1

        'foo': 'x',
        'bar': 'y',
        'baz': 'z'

        },

        {
                    # doc 2
        'foo': 'a',
        'bar': 'b',
        'baz': 'c'

        },

        {           # doc 3

        'foo': 'd',
        'bar': 'a',
        'baz': 'e'

        }]

result = collection.insert_many(data)

I'm looking for a way to query the collection for the value 'a' without having to specify the field. Ideally it would be something like...
cursor = collection.find({'*': 'a'})

...where '*' means that all fields should be queried and documents 2 and 3 in the above example code should be returned.
I can work around this, but I'm hoping there's a way to do it purely with Mongo commands to keep my code concise. I have looked through Mongo's documentation but can only query examples that match specific fields, not any field.
Answer: So I think you need an index to do that : https://docs.mongodb.com/manual/core/index-text/
After creating an index :
db.collection.createIndex( { "$**": "text" } ) #taken from docs

You can search it like this
cursor = collection.find({ $text: { $search: 'stringYouAreLookingFor' } });

Hope it helps
Answer: This solution uses text search functionality. This requires creating a compound index on all the fields that are to be searched as a text index. In the example collection, below, the fields fld1, fld2, fld3 of the collection srch3.
1. Sample collection:
{ _id: 1, fld1: "app", fld2: "ban", fld3: "pin" },
{ _id: 2, fld1: "gua", fld2: "ora", fld3: "kiw" },
{ _id: 3, fld1: "man", fld2: "ban", fld3: "pin" },
{ _id: 4, fld1: "pom", fld2: "lit", fld3: "fig" },
{ _id: 5, fld1: "app", fld2: "cus", fld3: "ora" }

2. Create text index:
db.srch3.createIndex( { fld1: "text", fld2: "text", fld3: "text" } )

3. Query:
db.srch3.find( { $text: { $search: "ora" } } )

Returns documents with _id's 2 and 5.
db.srch3.find( { $text: { $search: "cus" } } )

Returns document with _id = 5
db.srch3.find( { $text: { $search: "ban" } } )

Returns documents with _id's 3 and 1.
db.srch3.find( { $text: { $search: "gas" } } )

No documents are matched.

SOLUTION #2
This is a workaround solution. Create a dummy additional field with an array of all the field values for each document in the collection; e.g., foo_bar_baz as in the example below. Query on this new field.
{ _id: 1,
   'foo':'x',
   'bar':'y',
   'baz':'z',
   'foo_bar_baz': [ 'x', 'y', 'z' ]
},
{ _id: 2,
   'foo':'a',
   'bar':'b',
   'baz':'c',
   'foo_bar_baz': [ 'a', 'b', 'c' ]
},
{ _id: 3,
   'foo':'d',
   'bar':'a',
   'baz':'e',
   'foo_bar_baz': [ 'd', 'a', 'e' ]
}

Query:
db.srch1.find( { foo_bar_baz: 'a' } )

The query returns the two documents with the _id values 2 and 3.

NOTE: This will require the application keep the field values with the foo_bar_baz field in sync.

query all fields of a MongoDB document


Combine 2 MongoDB collections into one api URL (not merging the collections, keeping them separate)

Question: Im new to all this and need a little help please:
I have two Mongodb collections (Im using mongoose), Clients and Options.
They are not linked to each other.
I need to access both sets f data on one page in another app.
I can create an API Route pointing to each of these collections:
Clients: https://example.com/api/clients
Options: https://example.com/api/options
But what is the best way to merge these two into one API Route eg:
https://example.com/api/clients_options (URL is irrelevant I just need both sets of data Clients & Options to be accessible from both.)
Here is my Clients Model/Schema:
const ClientSchema = new mongoose.Schema({
    client: String,
    brands: [
        {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'Brand'
        }
    ]

});

module.exports = mongoose.model('Client', ClientSchema);

here is my Options Model/Schema:
const OptionsSchema = new mongoose.Schema({
    agencies: Array,
    asset_types: Array,
    format: Array,
});

module.exports = mongoose.model('Options', OptionsSchema);

I was thinking the best way to do this is to create a master Model/Schema that wraps both the Clients and Options schemas the way the Client Model/Schema wraps the Brand Schema.
eg:
const MasterSchema = new mongoose.Schema({
    clients: {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'Clients'
       },
    options: {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'Options'
       }

});

module.exports = mongoose.model('Master', MasterSchema);

But when I do this, my new Masters Model/Schema doesn't seem to populate with the existing Client and Option Model/Schemas, so my new Master Model/Schema stays blank and doesn't get created as a collection?
Is there a better way to do this?
These are my Routes for each:
//CLIENT API
    app.get('/api/clients',function(req, res){
        Client.find({})
            .populate({
                path: 'brands',
                populate: {
                    path: 'campaigns',
                    model: 'Campaign'
                }
            }).exec(function(err, clients){
                if(err) {
                    console.log('ERROR!');
                } else {
                    let data = [];
                    clients.forEach(client => {

                        //console.log(client);
                        data.push(client);
                    });
                    res.send({clients: data});
                }
            });
    });

    //OPTIONS API
    app.get('/api/options',function(req, res){
        Options.find({})
            .exec(function(err, options){
                if(err) {
                    console.log('ERROR!');
                } else {
                    let data = [];
                    options.forEach(option => {

                        //console.log(client);
                        data.push(option);
                    });
                    res.send({options: data});
                }
            });
    });

I would like to merge the data of the two into a single api so that I can call only one API URL in another app to access all the data, but cant figure out how/the best way to do it?
Comment: Exactly, simply do Promise.all([Options.find().exec(), Client.find().exec()]) and add them to single object on results
Comment: What is in your controller?  The one that selects data and returns it to user? Show us ur routes.
Creating Collection will ref fields, will not automatically fill some data without actully having data in it that references those collections ...
What you will have to do is merge two collections response to one call
Comment: Added routes above for clarity, I need to make a single route that includes data from both collections.
Comment: thank you @noitse, Ive managed to figure it out, but, posted answer below, but I will try your method too, I need to get my head around promises properly, Im not too familiar with it.
Answer: Ive managed to figure it out, I did it in the following way:
//ALL DATA API
    app.get('/api/data',function(req, res){
        Client.find({})
            .populate({
                path: 'brands',
                populate: {
                    path: 'campaigns',
                    model: 'Campaign'
                }
            }).exec(function(err, clients){
                if(err) {
                    console.log('ERROR!');
                } else {
                    let clientData = [];
                    clients.forEach(client => {

                        //console.log(client);
                        clientData.push(client);
                    });

                    Options.find({})
                        .exec(function(err, options){
                            if(err) {
                                console.log('ERROR!');
                            } else {
                                let optionsData = [];
                                options.forEach(option => {

                                    //console.log(client);
                                    optionsData.push(option);
                                });
                                res.send({clients: clientData, options: optionsData});
                            }
                        });
                }
            });
    });


gcp docker push - permission denied

Question: The default service account that a GCP VM use has been granted storage.buckets.* and storage.objects.* roles yet I get the error that storage.buckets.create permission isn't setup.

denied: Token exchange failed for project 'test-307504'. Caller does
not have permission 'storage.buckets.create'. To configure
permissions, follow instructions at:
https://cloud.google.com/container-registry/docs/access-control

The default service account is email@example.com and I've created roles related to storage and assigned to the IAM service account and I ran the command gcloud auth configure-docker. But still I'm unable to push docker images to the GCR repository.
Is there something else I should be doing after assigning the roles to refresh on the VM?
Answer: Apart from permissions, check for the access scope at the VM level.
While you are at, read up on Using the Compute Engine Default Service Account and Best Practices too.
Comment: Actually it is mentioned on the [page](https://cloud.google.com/container-registry/docs/access-control#vm-push) from the error you get when trying to push the image.
Comment: Damn that was it. I spent hours troubleshooting it but forgot to check this. New to GCP :-)
Comment: nobody has mentioned this anywhere. I looked at a lot of answers on stackoverflow.

gcp docker push - permission denied


Why is a pointer being returned in function?

Question: I am trying to take a file of a 2d array of grades (for example, file "grades2.txt") and store it into a 2d array. I am not sure how pointers work, as I haven't got that far yet, so I am not sure why a pointer is being returned.
So far, I have a main function that just plugs in values to the parameters, and I have my read function which opens the file and tries to read the file and put the file's values into the grades array.
It is okay if the output is wrong, I just want an array to show.
So far, I have tried to check if the array had the same dimension as the file, but that did not help.
grades2.txt
 10.0  20.0  30.0  40.0  50.0
100.0  90.0  80.0  70.0  60.0
 95.0  85.0  75.0  65.0  55.0
 25.2  27.2  29.3  31.2  33.2
 88.9  78.8  68.7  58.6  48.5
 10.1  20.1  30.1  40.1  50.1
100.1  90.1  80.1  70.1  60.1
 95.1  85.1  75.1  65.1  55.1
 25.2  27.3  29.4  31.3  33.3
 88.0  78.9  68.8  58.7  48.6
 10.9  20.8  30.7  40.6  50.5
100.9  90.8  80.7  70.6  60.5
 95.9  85.8  75.7  65.6  55.5
 25.8  27.7  29.6  31.5  33.4
 88.7  78.6  68.5  58.4  48.3
 20.0  30.0  40.0  50.0  60.0
 90.0  80.0  70.0  60.0  50.0
 85.0  75.0  65.0  55.0  45.0
 45.2  47.2  49.3  51.2  53.2
 48.9  58.8  68.7  78.6  88.5
 0.01  0.02  0.03  0.04  0.05

code
#include <iostream>
#include <fstream>
using namespace std;

void read (string filename, double grades[30][5]);

//main function
int main() {
    double grades[30][5];
    read("grades2.txt", grades);
    return 0;
}

void read (string filename, double grades[30][5]){
    ifstream input_file(filename);
    if(input_file.is_open()){
        for(int i = 0; i < 30; i++) {
            for (int j = 0; j < 5; j++) {
                input_file >> grades[i][j];
            }
        }
        cout << grades << endl;
    }
    input_file.close();
}

My result should be
grades [30]{{10.0,  20.0,  30.0,  40.0,  50.0}
{100.0,  90.0,  80.0,  70.0,  60.0}
{95.0,  85.0,  75.0,  65.0,  55.0}
{25.2,  27.2,  29.3,  31.2,  33.2}
{88.9,  78.8,  68.7,  58.6,  48.5}
{10.1,  20.1,  30.1,  40.1,  50.1}
{100.1,  90.1,  80.1,  70.1,  60.1}
{95.1,  85.1,  75.1,  65.1,  55.1}
{25.2,  27.3,  29.4,  31.3,  33.3}
{88.0,  78.9,  68.8,  58.7,  48.6}
{10.9,  20.8,  30.7,  40.6,  50.5}
{100.9,  90.8,  80.7,  70.6,  60.5}
{95.9,  85.8,  75.7,  65.6,  55.5}
{25.8,  27.7,  29.6,  31.5,  33.4}
{88.7,  78.6,  68.5,  58.4,  48.3}
{20.0,  30.0,  40.0,  50.0,  60.0}
{90.0,  80.0,  70.0,  60.0,  50.0}
{85.0,  75.0,  65.0,  55.0,  45.0}
{45.2,  47.2,  49.3,  51.2,  53.2}
{48.9,  58.8,  68.7,  78.6,  88.5}
{0.01,  0.02,  0.03,  0.04,  0.05}}

Comment: I don't see a pointer being returned anywhere, but I do see a pointer being printed to stdout via the `cout << grades << endl;` line.  If you want to print out the contents of the array, you'll need to do a nested-for-loop and print out each of the values individually, as C++ isn't clever enough to print out the array for you as a unit.
Comment: I disagree slightly with "C++ isn't clever enough". It's more than clever, but us dumb humans can't agree on what the output should look like.
Comment: You cannot print a whole array like that: `cout << grades << endl;`. Use another two loops instead.
Comment: C++ is not Python.  There is no "preformatted" way to print out an array.  You have to get your hands dirty and write the code to print out the individual elements, preferably in a loop.
Comment: ohhh, I got it sorry I have been working with python and I just recently have been learning c++
Answer: Note that you don't necessarily have to use arrays for storing the information(like double values) in 2D manner because you can also use dynamically sized containers like std::vector as shown below. The advantage of using std::vector is that you don't have to know the number of rows and columns beforehand in your input file(grades2.txt). So you don't have to allocate memory beforehand for rows and columns. You can add the values dynamically.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
    std::string line;
    double word;

    std::ifstream inFile("data.mat");

    //create/use a std::vector instead of builit in array
    std::vector<std::vector<double>> vec;

    if(inFile)
    {
        while(getline(inFile, line, '\n'))
        {
            //create a temporary vector that will contain all the columns
            std::vector<double> tempVec;

            std::istringstream ss(line);

            //read word by word(or double by double)
            while(ss >> word)
            {
                //std::cout<<"word:"<<word<<std::endl;
                //add the word to the temporary vector
                tempVec.push_back(word);

            }

            //now all the words from the current line has been added to the temporary vector
            vec.emplace_back(tempVec);
        }
    }

    else
    {
        std::cout<<"file cannot be opened"<<std::endl;
    }

    inFile.close();

    //lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
    for(std::vector<double> &newvec: vec)
    {
        for(const double &elem: newvec)
        {
            std::cout<<elem<<" ";
        }
        std::cout<<std::endl;
    }

    return 0;
}

The output of the above program can be seen here.


android java socket write and receive byte[] data

Question: I need to sent a packet to a server using socket from my android application. I only know a packet layout:
Packet ID 4 bytes | Packet length 4 bytes(minus len + ID) | payload (protobuf message)

The whole stuff about TLSv1.2 connection and self-signed certificate works well. For example, I need to send authentication packet - LoginRequest and server will response with LoginResponse if the packet was sent successfully. What I am trying do to is connect to a server inside AsyncTask class, write data and receive response, but obviously I am doing  it wrong because I got no response. The code for writing and reading a message:
LoginRequest protobuf message:
Protos.LoginRequest loginRequest = Protos.LoginRequest.newBuilder()
                    .setUsername(mailAddress)
                    .setPassword(pass).build();

And the code(inside doInBackground() method):
//TLSSocketFactory is custom SSLSocketFactory class for forcing TLSv1.2 on devices > 16 & < 20
socket = tlsSocketFactory.createSocket("airwave1.exurion.com", 2559);

byte[] payload = loginRequest.toByteArray();

DataOutputStream out = new DataOutputStream(socket.getOutputStream());
InputStream inStream = socket.getInputStream();

out.writeInt(10); //ID of the packet
out.writeInt(payload.length);
out.write(payload);

out.flush();

byte[] data = new byte[100];
int count = inStream.read(data);

out.close();
inStream.close();
socket.close();

As I said I got no response, Sometimes I also get an SSLException while reading the message:
javax.net.ssl.SSLException: Read error: ssl=0xb3a28580: I/O error during system call, Connection timed out

Has anyone an idea how to solve this?
//UPDATED
I figured out that the byte order needs to be in LITTLE_ENDIAN, so I tried to use ByteBuffer:
//based on previous packet layout (4 bytes for ID, 4 bytes for payload length, and payload) - is it ByteBuffer.allocate() fine?
    ByteBuffer buffer = ByteBuffer.allocate(8 + payload.length);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.putInt(LoginPacketType.LOGIN_REQUEST.getId());
    buffer.putInt(payload.length);
    buffer.put(payload);

    buffer.rewind();
    byte[] result = new byte[buffer.capacity()]; // Could also use result = buffer.array();
    buffer.get(result);

    out.write(result);

But now I am getting OOM exception:
Failed to allocate a 184549388 byte allocation with 16777216 free bytes and 155MB until OOM

Details about that:
After writing to an DataOutputStream, I make:
buffer.clear()
out.flush();

//code for reading from InputStream

And now, in my log appears this message several times:
Starting a blocking GC Alloc
and than throws OOM exception.
Answer: The problem was with LITTLE_ENDIAN and BIG_ENDIAN order. Servers sends response in LITTLE_ENDIAN order so I rewrite your answer a bit:
int type = inStream.readInt();
type = Integer.reverseBytes(type);
int length = inStream.readInt();
length = Integer.reverseBytes(length);

if (length > 0) {
    byte[] data = new byte[length];
    inStream.readFully(data);
    Protos.LoginResponse response = Protos.LoginResponse.parseFrom(data);
}

Thanks for the hint.
Answer: You're writing a packet type and length and payload, but you're only reading a payload. You're also assuming that read() fills the buffer.
int type = din.readInt();
int length = din.readInt();
byte[] data = new byte[length];
din.readyFully(data);

Comment: Thanks for the hint but still is not working, it stuck on reading. Probably the problem is when sending packet but I can't figure it out.
Comment: If this code is stuck in reading, the other end isn't sending this protocol.
Comment: What is `din` here supposed to be?


mapstruct : Convert array of object to list of object using mapstruct

Question: I have a class
public class A {

Person[] getPersons() { .. }

}

public class B {

List<Person> getPersons() { .. }

}

I have Mapper which converts A to B,
@Mapper
public interface AMapper {
    AMapperINSTANCE = Mappers.getMapper(AMapper.class);

    B AtoB(A entity);

}

While mapping, How can I convert array of persons to list of persons?
Answer: MapStruct automatically creates intermediate methods for mapping between an array and a List.
What you have defined with:
public interface AMapper {
    AMapperINSTANCE = Mappers.getMapper(AMapper.class);

    B AtoB(A entity);

}

Should generated:
public class AMapperImpl implements AMapper {

    @Override
    public B AtoB(A entity) {
        if ( entity == null ) {
            return null;
        }

        B b = new B();

        b.setPersons( personArrayToPersonList( entity.getPersons() ) );

        return b;
    }

    protected List<Person> personArrayToPersonList(Person[] personArray) {
        if ( personArray == null ) {
            return null;
        }

        List<Person> list = new ArrayList<Person>( personArray.length );
        for ( Person person : personArray ) {
            list.add( person );
        }

        return list;
    }
}

Having said all this. You should make sure that the getters / setters for persons in your classes are public. MapStruct is an Annotation Processing Tool, that generates java code and does no reflection
Answer: Use the static method Array.asList(T...a) from java.util.Arrays package.
Example:
class Person {
    private String name;

    Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}
@Test
public void arrayToList() {
    Person[] persons = {new Person("Yasuo"),new Person("Jinx")};

    List<Person> personList = Arrays.asList(persons);

    System.out.println(personList);
}

Output:
[Person{name='Yasuo'}, Person{name='Jinx'}]


Efficient way to copy data from 10 google sheet files based on two criteria?

Question: I created a single google sheet Masterfile wherein every time I enter data on any of the other google sheet files, it will automatically copy the same record on the Masterfile. There are multiple columns which I need to copy separately from these sheets and I was able to achieve this using VLOOKUP based on two criteria. However, the Masterfile is performing very slow when it executes multiple VLOOKUP on individual columns of the Masterfile.
Here is the formula when I use IMPORTRANGE to copy the data from the other 27 google sheets:
<code>=QUERY({
 IMPORTRANGE("15jruPpoXmZ8ABbqdvq-kio0lJ61K7f2DdnmbnzrQpuA", "Sheet1!A2:H");
 IMPORTRANGE("1NHtCTgP5tysHqDml2zwmJCJiJ2JVi7PGJy6ombHL9EE", "Sheet1!A2:H");
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!A2:H");
 IMPORTRANGE("1JlHRU2vkSWSer_3CFU-TxYYXzXA3vjhFxqOVjmZIWTY", "Sheet1!A2:H");
 IMPORTRANGE("1LxS-sfcX0Xp-q0fdcekzx1v9KI7-xxBBof2gbeOAPG4", "Sheet1!A2:H");
 IMPORTRANGE("1T6sKenv9ZwerOzGrLsGnlR3bVWAtAKgzx3q4PKq0sIY", "Sheet1!A2:H");
 IMPORTRANGE("15Xh_jZ2SdgQgn8TWaGO6Hp982uSZ6Ixtzg7kmAWthyc", "Sheet1!A2:H");
 IMPORTRANGE("1b_Y6Avxx81u3VKAFkcrTQUMNjMJ-BAoijaPZpr1xerY", "Sheet1!A2:H");
 IMPORTRANGE("1nNNZlJkoQV4buyfvbBIeTNGplSxZZyke3huuxudb2-s", "Sheet1!A2:H");
 IMPORTRANGE("1xPA1f1CO0qMh_MnjwmGk4Y1dYzOqTQUof-mHwwvZasE", "Sheet1!A2:H");
 IMPORTRANGE("1JC7kXt5wP696s6xfs-7hZ7xFnkdbba5w__lJidsenmc", "Sheet1!A2:H");
 IMPORTRANGE("1spget0KBDMWHZOZ7Nygr7Llf_3efIbqgkbTpcsqn9R0", "Sheet1!A2:H");
 IMPORTRANGE("1c-LJFy4tbHpPHb7ep63mYZEENJHpo40lpnZnElC3Wbw", "Sheet1!A2:H");
 IMPORTRANGE("1kv26cftBOmOBKSglhRGtWG9VRwwxG8lFDlId1sY8-mM", "Sheet1!A2:H");
 IMPORTRANGE("1IXceiMp2O7EN9YpMkwghuqD303_xR0ecqCSu43hNz6U", "Sheet1!A2:H");
 IMPORTRANGE("1F72S2u6EvzJkWS1gfDadK7PNykONL9gPoCQo7PC1eNI", "Sheet1!A2:H");
 IMPORTRANGE("1Ob-bu08x7b_QfhZRN2e_46PmFezOunrBCEDeJwtrqqs", "Sheet1!A2:H");
 IMPORTRANGE("1UWcMTinmLBS71_Yr97pPJTzEMcRQwwAgRNyxrqR5mkk", "Sheet1!A2:H");
 IMPORTRANGE("1vBxul2erb4k_bem4c1osAD3Aht_aKbYYuzQp2Z4rao8", "Sheet1!A2:H");
 IMPORTRANGE("1Ih86OTEvjlYF_sw7PVgAgExxBoOm8c48dI5qwA0FDzY", "Sheet1!A2:H");
 IMPORTRANGE("1NP1bfENxKLZqLrQNKcFeYm8zZh1_aC28WVEla9icMWs", "Sheet1!A2:H");
 IMPORTRANGE("1PxgbiYTeeG-mbmVa9zw0eFAU6WkyO7yDlI661P8MOhM", "Sheet1!A2:H");
 IMPORTRANGE("1TPXhSjBBEsNFB8kwWUYw7Cs5bcKNz02a7EsPRtWi9PI", "Sheet1!A2:H");
 IMPORTRANGE("1LjB7z5mUUeou0mUJp4Df4hxSBpniIY9Z1jHX33UQo6w", "Sheet1!A2:H");
 IMPORTRANGE("1zgg4J9F1sEz2RmfWShaQdDRVT3hm6ltXTPWD4MR3ISI", "Sheet1!A2:H");
 IMPORTRANGE("1zxbZ9k2BZI-7L_F2T4t3iLpPpcVgbscp1Op34PmjFPI", "Sheet1!A2:H");
 IMPORTRANGE("1qR04z7PqJvyDn_nSFya-lhHMxGdX6C1Z_PopBz6ysDA", "Sheet1!A2:H")},
 "WHERE Col2 IS NOT NULL ORDER BY Col1 ASC")
</code>
And here is the sample formula I use to copy data from the sheets based on two criteria:
<code>=ARRAYFORMULA(IFNA(VLOOKUP(A2&" "&B2, {
 IMPORTRANGE("15jruPpoXmZ8ABbqdvq-kio0lJ61K7f2DdnmbnzrQpuA", "Sheet2!A2:A")&" "&
 IMPORTRANGE("15jruPpoXmZ8ABbqdvq-kio0lJ61K7f2DdnmbnzrQpuA", "Sheet2!B2:B"),
 IMPORTRANGE("15jruPpoXmZ8ABbqdvq-kio0lJ61K7f2DdnmbnzrQpuA", "Sheet2!E2:E");
 IMPORTRANGE("1NHtCTgP5tysHqDml2zwmJCJiJ2JVi7PGJy6ombHL9EE", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1NHtCTgP5tysHqDml2zwmJCJiJ2JVi7PGJy6ombHL9EE", "Sheet2!B2:B"),
 IMPORTRANGE("1NHtCTgP5tysHqDml2zwmJCJiJ2JVi7PGJy6ombHL9EE", "Sheet2!E2:E");
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet2!B2:B"),
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet2!E2:E");
 IMPORTRANGE("1JlHRU2vkSWSer_3CFU-TxYYXzXA3vjhFxqOVjmZIWTY", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1JlHRU2vkSWSer_3CFU-TxYYXzXA3vjhFxqOVjmZIWTY", "Sheet2!B2:B"),
 IMPORTRANGE("1JlHRU2vkSWSer_3CFU-TxYYXzXA3vjhFxqOVjmZIWTY", "Sheet2!E2:E");
 IMPORTRANGE("1LxS-sfcX0Xp-q0fdcekzx1v9KI7-xxBBof2gbeOAPG4", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1LxS-sfcX0Xp-q0fdcekzx1v9KI7-xxBBof2gbeOAPG4", "Sheet2!B2:B"),
 IMPORTRANGE("1LxS-sfcX0Xp-q0fdcekzx1v9KI7-xxBBof2gbeOAPG4", "Sheet2!E2:E");
 IMPORTRANGE("1T6sKenv9ZwerOzGrLsGnlR3bVWAtAKgzx3q4PKq0sIY", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1T6sKenv9ZwerOzGrLsGnlR3bVWAtAKgzx3q4PKq0sIY", "Sheet2!B2:B"),
 IMPORTRANGE("1T6sKenv9ZwerOzGrLsGnlR3bVWAtAKgzx3q4PKq0sIY", "Sheet2!E2:E");
 IMPORTRANGE("15Xh_jZ2SdgQgn8TWaGO6Hp982uSZ6Ixtzg7kmAWthyc", "Sheet2!A2:A")&" "&
 IMPORTRANGE("15Xh_jZ2SdgQgn8TWaGO6Hp982uSZ6Ixtzg7kmAWthyc", "Sheet2!B2:B"),
 IMPORTRANGE("15Xh_jZ2SdgQgn8TWaGO6Hp982uSZ6Ixtzg7kmAWthyc", "Sheet2!E2:E");
 IMPORTRANGE("1b_Y6Avxx81u3VKAFkcrTQUMNjMJ-BAoijaPZpr1xerY", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1b_Y6Avxx81u3VKAFkcrTQUMNjMJ-BAoijaPZpr1xerY", "Sheet2!B2:B"),
 IMPORTRANGE("1b_Y6Avxx81u3VKAFkcrTQUMNjMJ-BAoijaPZpr1xerY", "Sheet2!E2:E");
 IMPORTRANGE("1nNNZlJkoQV4buyfvbBIeTNGplSxZZyke3huuxudb2-s", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1nNNZlJkoQV4buyfvbBIeTNGplSxZZyke3huuxudb2-s", "Sheet2!B2:B"),
 IMPORTRANGE("1nNNZlJkoQV4buyfvbBIeTNGplSxZZyke3huuxudb2-s", "Sheet2!E2:E");
 IMPORTRANGE("1xPA1f1CO0qMh_MnjwmGk4Y1dYzOqTQUof-mHwwvZasE", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1xPA1f1CO0qMh_MnjwmGk4Y1dYzOqTQUof-mHwwvZasE", "Sheet2!B2:B"),
 IMPORTRANGE("1xPA1f1CO0qMh_MnjwmGk4Y1dYzOqTQUof-mHwwvZasE", "Sheet2!E2:E");
 IMPORTRANGE("1JC7kXt5wP696s6xfs-7hZ7xFnkdbba5w__lJidsenmc", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1JC7kXt5wP696s6xfs-7hZ7xFnkdbba5w__lJidsenmc", "Sheet2!B2:B"),
 IMPORTRANGE("1JC7kXt5wP696s6xfs-7hZ7xFnkdbba5w__lJidsenmc", "Sheet2!E2:E");
 IMPORTRANGE("1spget0KBDMWHZOZ7Nygr7Llf_3efIbqgkbTpcsqn9R0", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1spget0KBDMWHZOZ7Nygr7Llf_3efIbqgkbTpcsqn9R0", "Sheet2!B2:B"),
 IMPORTRANGE("1spget0KBDMWHZOZ7Nygr7Llf_3efIbqgkbTpcsqn9R0", "Sheet2!E2:E");
 IMPORTRANGE("1c-LJFy4tbHpPHb7ep63mYZEENJHpo40lpnZnElC3Wbw", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1c-LJFy4tbHpPHb7ep63mYZEENJHpo40lpnZnElC3Wbw", "Sheet2!B2:B"),
 IMPORTRANGE("1c-LJFy4tbHpPHb7ep63mYZEENJHpo40lpnZnElC3Wbw", "Sheet2!E2:E");
 IMPORTRANGE("1kv26cftBOmOBKSglhRGtWG9VRwwxG8lFDlId1sY8-mM", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1kv26cftBOmOBKSglhRGtWG9VRwwxG8lFDlId1sY8-mM", "Sheet2!B2:B"),
 IMPORTRANGE("1kv26cftBOmOBKSglhRGtWG9VRwwxG8lFDlId1sY8-mM", "Sheet2!E2:E");
 IMPORTRANGE("1IXceiMp2O7EN9YpMkwghuqD303_xR0ecqCSu43hNz6U", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1IXceiMp2O7EN9YpMkwghuqD303_xR0ecqCSu43hNz6U", "Sheet2!B2:B"),
 IMPORTRANGE("1IXceiMp2O7EN9YpMkwghuqD303_xR0ecqCSu43hNz6U", "Sheet2!E2:E");
 IMPORTRANGE("1F72S2u6EvzJkWS1gfDadK7PNykONL9gPoCQo7PC1eNI", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1F72S2u6EvzJkWS1gfDadK7PNykONL9gPoCQo7PC1eNI", "Sheet2!B2:B"),
 IMPORTRANGE("1F72S2u6EvzJkWS1gfDadK7PNykONL9gPoCQo7PC1eNI", "Sheet2!E2:E");
 IMPORTRANGE("1Ob-bu08x7b_QfhZRN2e_46PmFezOunrBCEDeJwtrqqs", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1Ob-bu08x7b_QfhZRN2e_46PmFezOunrBCEDeJwtrqqs", "Sheet2!B2:B"),
 IMPORTRANGE("1Ob-bu08x7b_QfhZRN2e_46PmFezOunrBCEDeJwtrqqs", "Sheet2!E2:E");
 IMPORTRANGE("1UWcMTinmLBS71_Yr97pPJTzEMcRQwwAgRNyxrqR5mkk", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1UWcMTinmLBS71_Yr97pPJTzEMcRQwwAgRNyxrqR5mkk", "Sheet2!B2:B"),
 IMPORTRANGE("1UWcMTinmLBS71_Yr97pPJTzEMcRQwwAgRNyxrqR5mkk", "Sheet2!E2:E");
 IMPORTRANGE("1vBxul2erb4k_bem4c1osAD3Aht_aKbYYuzQp2Z4rao8", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1vBxul2erb4k_bem4c1osAD3Aht_aKbYYuzQp2Z4rao8", "Sheet2!B2:B"),
 IMPORTRANGE("1vBxul2erb4k_bem4c1osAD3Aht_aKbYYuzQp2Z4rao8", "Sheet2!E2:E");
 IMPORTRANGE("1Ih86OTEvjlYF_sw7PVgAgExxBoOm8c48dI5qwA0FDzY", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1Ih86OTEvjlYF_sw7PVgAgExxBoOm8c48dI5qwA0FDzY", "Sheet2!B2:B"),
 IMPORTRANGE("1Ih86OTEvjlYF_sw7PVgAgExxBoOm8c48dI5qwA0FDzY", "Sheet2!E2:E");
 IMPORTRANGE("1NP1bfENxKLZqLrQNKcFeYm8zZh1_aC28WVEla9icMWs", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1NP1bfENxKLZqLrQNKcFeYm8zZh1_aC28WVEla9icMWs", "Sheet2!B2:B"),
 IMPORTRANGE("1NP1bfENxKLZqLrQNKcFeYm8zZh1_aC28WVEla9icMWs", "Sheet2!E2:E");
 IMPORTRANGE("1PxgbiYTeeG-mbmVa9zw0eFAU6WkyO7yDlI661P8MOhM", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1PxgbiYTeeG-mbmVa9zw0eFAU6WkyO7yDlI661P8MOhM", "Sheet2!B2:B"),
 IMPORTRANGE("1PxgbiYTeeG-mbmVa9zw0eFAU6WkyO7yDlI661P8MOhM", "Sheet2!E2:E");
 IMPORTRANGE("1TPXhSjBBEsNFB8kwWUYw7Cs5bcKNz02a7EsPRtWi9PI", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1TPXhSjBBEsNFB8kwWUYw7Cs5bcKNz02a7EsPRtWi9PI", "Sheet2!B2:B"),
 IMPORTRANGE("1TPXhSjBBEsNFB8kwWUYw7Cs5bcKNz02a7EsPRtWi9PI", "Sheet2!E2:E");
 IMPORTRANGE("1LjB7z5mUUeou0mUJp4Df4hxSBpniIY9Z1jHX33UQo6w", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1LjB7z5mUUeou0mUJp4Df4hxSBpniIY9Z1jHX33UQo6w", "Sheet2!B2:B"),
 IMPORTRANGE("1LjB7z5mUUeou0mUJp4Df4hxSBpniIY9Z1jHX33UQo6w", "Sheet2!E2:E");
 IMPORTRANGE("1zgg4J9F1sEz2RmfWShaQdDRVT3hm6ltXTPWD4MR3ISI", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1zgg4J9F1sEz2RmfWShaQdDRVT3hm6ltXTPWD4MR3ISI", "Sheet2!B2:B"),
 IMPORTRANGE("1zgg4J9F1sEz2RmfWShaQdDRVT3hm6ltXTPWD4MR3ISI", "Sheet2!E2:E");
 IMPORTRANGE("1zxbZ9k2BZI-7L_F2T4t3iLpPpcVgbscp1Op34PmjFPI", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1zxbZ9k2BZI-7L_F2T4t3iLpPpcVgbscp1Op34PmjFPI", "Sheet2!B2:B"),
 IMPORTRANGE("1zxbZ9k2BZI-7L_F2T4t3iLpPpcVgbscp1Op34PmjFPI", "Sheet2!E2:E");
 IMPORTRANGE("1qR04z7PqJvyDn_nSFya-lhHMxGdX6C1Z_PopBz6ysDA", "Sheet2!A2:A")&" "&
 IMPORTRANGE("1qR04z7PqJvyDn_nSFya-lhHMxGdX6C1Z_PopBz6ysDA", "Sheet2!B2:B"),
 IMPORTRANGE("1qR04z7PqJvyDn_nSFya-lhHMxGdX6C1Z_PopBz6ysDA", "Sheet2!E2:E")}, 2, )))
</code>
My question would be is there an efficient way for me to achieve the result I am aiming to get aside from VLOOKUP? as vlookup is really slow for this operation.
Answer: in this case, the recommended solution would be to use an intermediate spreadsheet with 2 formulae and then you import the final product into your sheet. vlookup is pretty fast fx but every iportrange fx has a toll on it. with that much importranges it is just expected overall fx to drop on performance.
create a new spreadsheet and paste this into A1:
<code>=SORT(QUERY({
 IMPORTRANGE("15jruPpoXmZ8ABbqdvq-kio0lJ61K7f2DdnmbnzrQpuA", "Sheet1!A2:E");
 IMPORTRANGE("1NHtCTgP5tysHqDml2zwmJCJiJ2JVi7PGJy6ombHL9EE", "Sheet1!A2:E");
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!A2:E");
 IMPORTRANGE("1JlHRU2vkSWSer_3CFU-TxYYXzXA3vjhFxqOVjmZIWTY", "Sheet1!A2:E");
 IMPORTRANGE("1LxS-sfcX0Xp-q0fdcekzx1v9KI7-xxBBof2gbeOAPG4", "Sheet1!A2:E");
 IMPORTRANGE("1T6sKenv9ZwerOzGrLsGnlR3bVWAtAKgzx3q4PKq0sIY", "Sheet1!A2:E");
 IMPORTRANGE("15Xh_jZ2SdgQgn8TWaGO6Hp982uSZ6Ixtzg7kmAWthyc", "Sheet1!A2:E");
 IMPORTRANGE("1b_Y6Avxx81u3VKAFkcrTQUMNjMJ-BAoijaPZpr1xerY", "Sheet1!A2:E");
 IMPORTRANGE("1nNNZlJkoQV4buyfvbBIeTNGplSxZZyke3huuxudb2-s", "Sheet1!A2:E");
 IMPORTRANGE("1xPA1f1CO0qMh_MnjwmGk4Y1dYzOqTQUof-mHwwvZasE", "Sheet1!A2:E");
 IMPORTRANGE("1JC7kXt5wP696s6xfs-7hZ7xFnkdbba5w__lJidsenmc", "Sheet1!A2:E");
 IMPORTRANGE("1spget0KBDMWHZOZ7Nygr7Llf_3efIbqgkbTpcsqn9R0", "Sheet1!A2:E");
 IMPORTRANGE("1c-LJFy4tbHpPHb7ep63mYZEENJHpo40lpnZnElC3Wbw", "Sheet1!A2:E");
 IMPORTRANGE("1kv26cftBOmOBKSglhRGtWG9VRwwxG8lFDlId1sY8-mM", "Sheet1!A2:E");
 IMPORTRANGE("1IXceiMp2O7EN9YpMkwghuqD303_xR0ecqCSu43hNz6U", "Sheet1!A2:E");
 IMPORTRANGE("1F72S2u6EvzJkWS1gfDadK7PNykONL9gPoCQo7PC1eNI", "Sheet1!A2:E");
 IMPORTRANGE("1Ob-bu08x7b_QfhZRN2e_46PmFezOunrBCEDeJwtrqqs", "Sheet1!A2:E");
 IMPORTRANGE("1UWcMTinmLBS71_Yr97pPJTzEMcRQwwAgRNyxrqR5mkk", "Sheet1!A2:E");
 IMPORTRANGE("1vBxul2erb4k_bem4c1osAD3Aht_aKbYYuzQp2Z4rao8", "Sheet1!A2:E");
 IMPORTRANGE("1Ih86OTEvjlYF_sw7PVgAgExxBoOm8c48dI5qwA0FDzY", "Sheet1!A2:E");
 IMPORTRANGE("1NP1bfENxKLZqLrQNKcFeYm8zZh1_aC28WVEla9icMWs", "Sheet1!A2:E");
 IMPORTRANGE("1PxgbiYTeeG-mbmVa9zw0eFAU6WkyO7yDlI661P8MOhM", "Sheet1!A2:E");
 IMPORTRANGE("1TPXhSjBBEsNFB8kwWUYw7Cs5bcKNz02a7EsPRtWi9PI", "Sheet1!A2:E");
 IMPORTRANGE("1LjB7z5mUUeou0mUJp4Df4hxSBpniIY9Z1jHX33UQo6w", "Sheet1!A2:E");
 IMPORTRANGE("1zgg4J9F1sEz2RmfWShaQdDRVT3hm6ltXTPWD4MR3ISI", "Sheet1!A2:E");
 IMPORTRANGE("1zxbZ9k2BZI-7L_F2T4t3iLpPpcVgbscp1Op34PmjFPI", "Sheet1!A2:E");
 IMPORTRANGE("1qR04z7PqJvyDn_nSFya-lhHMxGdX6C1Z_PopBz6ysDA", "Sheet1!A2:E")},
 "WHERE Col2 IS NOT NULL", IFERROR(NOW()/0)))
</code>
in F1 use:
<code>={FLATTEN(QUERY(TRANSPOSE(A:B),,9^9)), E:E}
</code>
in spreadsheet settings you can set recalculation like:

then in your final sheet, you will just use:
<code>=ARRAYFORMULA(IFNA(VLOOKUP(A2:A&" "&B2:B,
 IMPORTRANGE("id", "Sheet1!F:G"), 2, IFERROR(NOW()/0))
</code>


Difficult integral with dirac comb

Question: I'm trying to solve the following integral:
$\int_{-\infty}^{\infty} \frac{\cos(\pi (x+1))}{x}[\sum_{n=1}^{\infty}\delta (x-n)]dx$
So this seems pretty terrible, and there is also a hint
Hint: "Don't be afraid". Nevertheless, I am afraid.
How do you start solving this? I know I'm supposed to show some effort, but I really have no idea where to start. Maybe integration by parts?
Comment: Do you know what $\cos(n \pi)$ evaluates to for an integer number $n$?
Comment: What would the answer be if you replaced the sum of deltas with one delta?
Comment: Ofcourse. It's $(-1)^{n}$
Comment: Do you know what the delta distribution does to functions? It may be better for you to consider $\sum_{n=0}^N \delta (x-n)$, do the integral and then take the limit $N \to \infty$.
Comment: It should cancel out all the none integer values so the integrand is equivalent to $\sum_{n=1}^{\infty} (-1)^n$ correct?
Comment: I'm not sure what you mean with cancelling out the non-integer values, but in general the delta distribution acts on continuous functions in the following way: $\int dx\, f(x)\, \delta (x-y) = f(y)$ if $y$ is in the domain which is being integrated over. A (finite) sum of delta functions acts in the same way. Also, don't forget the factor $1/x$ in your integrand.
Answer: We simply use the "sifting" property of the Dirac Delta to obtain
$$\begin{align}
\int_{-\infty}^{\infty}\frac{\cos(\pi(x+1))}{x}\sum_{n=1}^{\infty}\delta(x-n)\,dx&=\sum_{n=1}^{\infty}\frac{\cos(\pi(n+1))}{n}\\\\
&=\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n}\\\\
&=\log 2
\end{align}$$

Difficult integral with dirac comb


Count filtered data in Elasticsearch(ElasticClient nest)

Question: I am using ElasticClient 2.4.4.
I have one query
var sample = client.Search<TestMenuItem>(s => s
            .Query(q =>
                q.Term(p => p.RegionSegments, "s1")
                && q.Term(p => p.RegionSegments, "s2")
                 && q.Term(p => p.RegionSegments, "s3")
            ));

than I wanted to count how many items are with RegionSegments = s1.
As I understand I should use Aggregations but cant find good example how solve this issue.Any ideas?
Answer: If you simply need a count of each of s1, s2 and s3 RegionSegment documents, then you can do a multi_search for this, specifying a count search_type for all
var multiSearchResponse = client.MultiSearch(ms => ms
    // this is the default index for multi_search. Can override
    // on each Search call if needed
    .Index<TestMenuItem>()
    // this is the default type for mulit_search. Can override
    // on each search call if needed
    .Type<TestMenuItem>()
    // this is the default search_type. Can override on
    // each search call if needed
    .SearchType(SearchType.Count)
    .Search<TestMenuItem>("s1", s => s
        .Query(q => +q.Term(p => p.RegionSegments, "s1"))
    )
    .Search<TestMenuItem>("s2", s => s
        .Query(q => +q.Term(p => p.RegionSegments, "s2"))
    )
    .Search<TestMenuItem>("s3", s => s
        .Query(q => +q.Term(p => p.RegionSegments, "s3"))
    )
);

This produces the following request
POST http://localhost:9200/testmenuitem-index/testmenuitem/_msearch?search_type=count
{}
{"query":{"bool":{"filter":[{"term":{"regionSegments":{"value":"s1"}}}]}}}
{}
{"query":{"bool":{"filter":[{"term":{"regionSegments":{"value":"s2"}}}]}}}
{}
{"query":{"bool":{"filter":[{"term":{"regionSegments":{"value":"s3"}}}]}}}

The to get the total for each search result is similar to the following
var s1Total = multiSearchResponse.GetResponse<TestMenuItem>("s1").Total;

Comment: @user1541069 another way would be to use `.Search()` with [multiple filter aggregations](https://www.elastic.co/guide/en/elasticsearch/client/net-api/1.x/filter-aggregation.html) for each regionsegment you want a count over.
Comment: not exactly. First I need to get some query result and then do calculation based on this query result.
Comment: RegionSegments is a string like this 's1 s2 s3' or 's3 s2'
Comment: is `RegionSegments` analyzed? Do you need to match *exactly* on `s1` or `s2` or `s3`?
Comment: Russ Cam, you are right, first match than do calculation based on this query result.
Comment: OK, I would map `RegionSegments` as a collection of `not_analyzed` strings. The query above will then give you a count as requested for each of each of the documents that have a `RegionSegments` value containing `s1`, `s2` and `s3`.


Get value from many2one relationship in openerp?

Question: My codes :
<code>class name(osv.osv):
        _name='name.model'
        _columns={
                  'name':fields.char('Name',size=32),
                  'ten':fields.char('Ten',size=40),
                  'so':fields.integer('So luong'),
                  'cost':fields.integer('Cost'),
                  }
name()

class first_model(osv.osv):
        _name='first.model'
        _columns={
                  'name':fields.char('Name',size=32),
                  'name1':fields.many2one('name.model','Relationship'),
                  'number':fields.integer('Number'),
                  }
first_model()

class second_model(osv.osv):
        _name='second.model'
        _columns={
                  'name':fields.char('Name',size=50),
                  'name2':fields.many2one('first.model','Choose'),
                  'cost':fields.integer('Cost')
                  }
        def onchange_cost(self,cr,uid,ids,name2,context=None):
            value={}
            if name2:
                record=self.pool.get('first.model').browse(cr,uid,name2,context=context)
                if record:
                    print record.name1
                    recor_id=self.pool.get('name.model').search(cr,uid,[('name','=',record.name1)],context=context)
                    if recor_id:
                        rec=self.pool.get('name.model').browse(cr,uid,recor_id,context=context)
                        print rec.cost

second_model()
</code>
My problem is when i try to get cost from name.model it always return empty .I check value of record.name1 and its look like : name.model(3,) or name.model(5,) .How can i get cost from name.model .Please help me to solve this .Thank you :))
Sorry for bad english :((
Answer: Try this:-
record=self.pool.get('first.model').browse(cr,uid,name2.id,context=context)


Dividir Projecto QML em Sub-Directorias

Question: Tenho a seguinte dúvida:
Dividi um projecto de QML, em diferentes sub-directorias.
Ao fazer build, o IDE não consegue localizar os ficheiros implementados, devolvendo o seguinte erro:
Starting /Users/macbook/workspace/build-UI_UX_Framework-          Desktop_Qt_5_7_0_clang_64bit-    Debug/UI_UX_Framework.app/Contents/MacOS/UI_UX_Framework...
QML debugging is enabled. Only use this in a safe environment.
QQmlApplicationEngine failed to load component
qrc:/_files_qml/instantiationTest.qml:17 Button1 is not a type

/Users/macbook/workspace/build-UI_UX_Framework-  Desktop_Qt_5_7_0_clang_64bit-   Debug/UI_UX_Framework.app/Contents/MacOS/UI_UX_Framework exited with code 0

Tentei mudar opções no ficheiro .Framework.pro, mas não consegui resolver a questão. agradeço o feedback
Fica aqui uma imagem do projecto.

https://i.stack.imgur.com/lwPLV.jpg
Comment: no meu caso, esqueci-me de fazer include dos ficheiros, nas respectivas sub-directorias. fica algo desse género:
Comment: import QtQuick 2.0
import QtQuick.Window 2.0
import "_Buttons/"
import "_MIDIKeyboards/"
import "_StochasticSelectors/"
import "_Sliders/"
import "_imgButtons/"
Answer: esqueci-me de fazer include dos ficheiros, nas respectivas sub-directorias. foi algo do género:
import QtQuick 2.0
import QtQuick.Window 2.0
import "_Buttons/"
import "_MIDIKeyboards/"
import "_StochasticSelectors/"
import "_Sliders/"
import "_imgButtons/"

Dividir Projecto QML em Sub-Directorias


Solving a Derivative Equation Faster

Question: How can I solve this problem as fast as possible just using a piece of paper and a pen:
$f(x)=(3x+4)^4\\f''(x)=?\\$

Please show me how to do that.
Answer: $$\begin{align*}
f'(x)&=4(3x+4)^3\cdot 3\\
&=12(3x+4)^3\\
f''(x)&=12\cdot 3(3x+4)^2\cdot 3\\
&=108(3x+4)^2
\end{align*}$$
Comment: I am assuming you know chain rule and exponentiation rules. I.e., $(f^n)'=nf^{n-1}f'$
Comment: "Chain rule", right... I remember it, yes. I also tried this simple, basic rule: (U^n)'=U'.n.U^(n-1) . I like this form and I've encountered this kind of problems very much recently... Thank you, Daniel.
Answer: Induction generalizes these sorts of problems; if you can intuitively remember these two formulas:
$$\frac{d^k}{dx^k} f(ax+b)=a^k \frac{d^kf}{dx^k}(ax+b);$$
$$\frac{d^k}{dx^k} x^n=n(n-1)\cdots\big(n-(k-1)\big) x^{n-k},$$
then you're golden. The first just says that in order to interchange differentiation and $x\mapsto ax+b$ transformations, you just have to bring the scale factor outside to the appropriate power. The second says that the power is reduced by $k$, and you put a "falling factorial" in front of it that stops just before $n-k$.
Comment: Thank you very much, anon. I think this might work also... :)

Solving a Derivative Equation Faster


Soma parcial de elementos de um vetor em O(n) ou O(log n)

Question: Tenho um vetor A de tamanho n.
Tenho que calcular a soma parcial de cada elemento e escrever na matriz B[i,j].
O pseudo-código mostra uma solução O(n^2);
  For i = 1, 2, . . . , n
    For j = i + 1, i + 2, . . . , n
      B[i, j] <- A[i] + A[i+1] + ... +  A[j];
   Endfor
  Endfor

Existe uma solução O(n) ou O(log n)? Como seria?
Answer: Da forma que está escrito, o seu algoritmo é O(N3). Tem um terceiro loop implícito na parte que você soma os A[i]s.
Na forma atual do problema, não tem como ter um algoritmo melhor que O(N2). Você tem N*(N-1)/2 elementos para preencher na matriz B então só a parte de escrever a saída já vai ser O(N2).
Se você mudar a definição de B para ser um vetor unidimensional onde B[i] significa a soma de A[1] até A[n], ai dá pra fazer em O(N). O truque é reaproveitar os valores já calculados de B nas suas contas. (tente fazer isso sem perguntar antes - é um ótimo exercício)
O(log N) não dá porque no mínimo você vai ter que percorrer o vetor A uma vez para ler os seus elementos e isso já vai dar O(N).


L() notation in linear algebra

Question: This might be a really simple question, but I just didn't find an answer from anywhere.
I'm teaching linear algebra to myself and in my study material I came upon notation that I just don't understand. I can't find an explanation for it from my material and it is hard to find on the internet as well it seems.
Example:
$U = L((3,2,-6,4),(0,4,1,-5))$
What does the L() notation mean? U itself should be a subspace for ℝ⁴. I would assume that those are vectors within the L().
Comment: It could be what is in other places called "span", i.e. the set (space) of all linear combinations of those two vectors. But I don't actually know.
Comment: Well, I must say that without context on what $L$ is, I don't really know. Given that $U$ is a subspace, the thing that comes to mind is that span of the vectors in $L$, but I have not seen this notation before.
Comment: I have never seen that notation, but my guess is $L()$ the subspace spanned by the vectors within the parentheses; that is the subspace of all linear combinations of those
Comment: My best guess is what was already mentioned: "linear span". Also denoed by "Span( - )" or $\langle \dots \rangle$
Comment: I have seen the notation before, and it meant the span of the vectors inside the parentheses. So it's very likely that it's the meaning here too.
Comment: I'm quite confident that @DanielFischer is correct (as are many others of you as well), that would make very much sense. I knew it was something very simple like this. Thank you all!
Answer: I agree with the commenters: it's most likely the linear span ($L$ for linear) of the vectors in parenthesis.  But that is from context rather than from convention.
In general, the best place to look for the answer to a question like this is the materials you are studying from.
When you take a course, you get a textbook and/or lecture notes.  Those texts are designed to be coherent and consistent.  The definitions and notations may vary from text to text.  Notation is calculus has pretty much been standardized, but less so in linear algebra.
When you're self-studying, I think you need to work in the same way. Concentrate on your one source.  If there is a definition or notation you don't understand, work backwards until its first usage.  There you'll find its meaning.
Comment: I agree, that is the meaning, it makes sense. Therefore it is equivalent to U = span((3,2,−6,4),(0,4,1,−5)). Also, thank you for the tips. I did go through all the material I have been using and it used this notation only twice without explaining it. Still, now that I think of it, I should have been able to guess it.

L() notation in linear algebra


Parse xml with lxml - extract element value

Question: Let's suppose we have the XML file with the structure as follows.
<?xml version="1.0" ?>
<searchRetrieveResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/zing/srw/ http://www.loc.gov/standards/sru/sru1-1archive/xml-files/srw-types.xsd" xmlns="http://www.loc.gov/zing/srw/">
  <records xmlns:ns1="http://www.loc.gov/zing/srw/">
    <record>
      <recordData>
        <record xmlns="">
          <datafield tag="000">
            <subfield code="a">123</subfield>
            <subfield code="b">456</subfield>
          </datafield>
          <datafield tag="001">
            <subfield code="a">789</subfield>
            <subfield code="b">987</subfield>
          </datafield>
        </record>
      </recordData>
    </record>
    <record>
      <recordData>
        <record xmlns="">
          <datafield tag="000">
            <subfield code="a">123</subfield>
            <subfield code="b">456</subfield>
          </datafield>
          <datafield tag="001">
            <subfield code="a">789</subfield>
            <subfield code="b">987</subfield>
          </datafield>
        </record>
      </recordData>
    </record>
  </records>
</searchRetrieveResponse>

I need to parse out:

The content of the "subfield" (e.g. 123 in the example above) and
Attribute values (e.g. 000 or 001)

I wonder how to do that using lxml and XPath. Pasted below is my initial code and I kindly ask someone to explain me, how to parse out values.
import urllib, urllib2
from lxml import etree

url = "https://dl.dropbox.com/u/540963/short_test.xml"
fp = urllib2.urlopen(url)
doc = etree.parse(fp)
fp.close()

ns = {'xsi':'http://www.loc.gov/zing/srw/'}

for record in doc.xpath('//xsi:record', namespaces=ns):
    print record.xpath("xsi:recordData/record/datafield[@tag='000']", namespaces=ns)

Comment: You are using the prefix `xsi` for the namespace `http://www.loc.gov/zing/srw/` - this is valid, but usually `xsi` is used as a prefix for the standard namespace `http://www.w3.org/2001/XMLSchema-instance`.
Answer: I would be more direct in your XPath: go straight for the elements you want, in this case datafield.
>>> for df in doc.xpath('//datafield'):
        # Iterate over attributes of datafield
        for attrib_name in df.attrib:
                print '@' + attrib_name + '=' + df.attrib[attrib_name]

        # subfield is a child of datafield, and iterate
        subfields = df.getchildren()
        for subfield in subfields:
                print 'subfield=' + subfield.text

Also, lxml appears to let you ignore the namespace, maybe because your example only uses one namespace?
Comment: Yes, I have only one namespace.
Answer: Try the following working code :
import urllib2
from lxml import etree

url = "https://dl.dropbox.com/u/540963/short_test.xml"
fp = urllib2.urlopen(url)
doc = etree.parse(fp)
fp.close()

for record in doc.xpath('//datafield'):
    print record.xpath("./@tag")[0]
    for x in record.xpath("./subfield/text()"):
        print "\t", x

Answer: I would just go with
for df in doc.xpath('//datafield'):
    print df.attrib
    for sf in df.getchildren():
        print sf.text

Also you don't need urllib, you can directly parse XML with HTTP
url = "http://dl.dropbox.com/u/540963/short_test.xml"  #doesn't work with https though
doc = etree.parse(url)


What is the specific normalization chi2 in seqdist?

Question: In the documentation for the seqdist() function it is noted that there is "...a specific normalization for"CHI2" and "EUCLID". See the Details section." (p.60). But in the details section there is no additional information about what normalization is applied for either of these distance measures. Thanks
Answer: This looks like an error in the documentation. Currently (TraMineR v 2.0-11.1)  normalization has no effect for CHI2 and EUCLID distances. For example, you can observe with the following code that non-normalized and normalized distances are the same for a sample of 50 randomly generated sequences.
<code>library(TraMineR)
dat <- seqgen(50,12,1:3,c(.1,.5,.4))
seq <- seqdef(dat)
d <- seqdist(seq, method="EUCLID", norm="none", step=4)
d.n <- seqdist(seq, method="EUCLID", norm="auto", step=4)
sum(d - d.n != 0)

## [1] 0
</code>
May be the normalization affected the outcome before the bug fixes in version 2.0-10.
Comment: Thanks for clarifying - I found the same thing with my data (no effect when switching norm from "auto" to "none") but thought it best to check.


What happens if you try to receive from a Timer channel again after it has expired

Question: I'm playing around with one of the examples from the Tour of Go tutorial. I've edited the code as follows:
package main

import (
    "fmt"
    "time"
)

func main() {
    tick := time.Tick(100 * time.Millisecond)
    boom := time.After(500 * time.Millisecond)
    for {
        select {
        case <-tick:
            fmt.Println("tick.")
        case <-boom:
            fmt.Println("BOOM!")
            c, ok := <-boom
            fmt.Println(c)
            fmt.Println(ok)
        default:
            fmt.Println("    .")
            time.Sleep(50 * time.Millisecond)
        }
    }
    fmt.Println("Finished")
}

However, the output of the code is as follows:
    .
    .
tick.
    .
    .
tick.
    .
    .
tick.
    .
    .
tick.
    .
    .
tick.
BOOM!

c and ok are never printed, and the very last "Finished" is never printed either. Can someone help me understand what exactly happens when I try to receive from the boom channel the second time?
Comment: `c` and `ok` are never printed, because nothing else is ever sent over the `boom` channel. It's pretty straight forward. Did you expect otherwise? If you want to reuse it, you must [Reset](https://golang.org/pkg/time/#Timer.Reset) it.
Comment: @Flimzy but in that case wouldn't receive block forever? How does the program terminate?
Comment: I don't understand your question. As it is, your receive blocks forever, because nothing is ever sent.
Answer: Consider what time.After does (quote from go docs):

After waits for the duration to elapse and then sends the current time
  on the returned channel.

So boom := time.After(500 * time.Millisecond) will return a channel and send a single message to that channel after 500ms. Now lets consider your code:
case <-boom:
   fmt.Println("BOOM!")
   c, ok := <-boom
   fmt.Println(c)
   fmt.Println(ok)

When something is received on the boom channel your code prints "boom" and then waits for something else on the boom channel. However only one thing is ever sent to the boom channel so the statement c, ok := <-boom will never complete (and your application will never terminate). If you changed boom from a time.After to a time.Tick then you might see something more like what you were expecting (the application will still run for ever).
The original code is a bit different:
case <-boom:
            fmt.Println("BOOM!")
            return

It receives the message, prints boom and then returns (ending the program). If you want your code to get to the bit where it outputs 'finnished' then you need something like the code below. Note that the label loop is needed because break:

terminates execution of the innermost "for", "switch", or "select"

so without the label break would exit the select but the for loop would continue.
package main

import (
    "fmt"
    "time"
)

func main() {
    tick := time.Tick(100 * time.Millisecond)
    boom := time.After(500 * time.Millisecond)
loop:
    for {
        select {
        case <-tick:
            fmt.Println("tick.")
        case <-boom:
            fmt.Println("BOOM!")
            break loop
        default:
            fmt.Println("    .")
            time.Sleep(50 * time.Millisecond)
        }
    }
    fmt.Println("Finished")
}

Comment: In the go playground it exits with "Program exited: process took too long.". This is because the go playground runs applications within a sandbox which limits execution time (amoungst other things). Without this someone would be using it to mine bitcoin :-). Try running it on your computer and it will not exit.
Comment: I copied/pasted your code into the playground at https://play.golang.org/p/dJE9LE1eMNP running that gives me "Program exited: process took too long."
Comment: The thing that is confusing me is that the program *does* terminate. Or at least it does when I run it in the go playground (you can copy/paste my code and try it for yourself?). As far as I understand it shouldn't terminate, which is why I'm confused
Comment: Really? For me it exits without any error in the go playground :/


Variable Baudrate for serial port possible?

Question: The baudrate is normally set to one of the specified values, like 9600, 56k and so on.
Is it possible to select another value, like 123456 Baud? Its an numerical parameter, so why not?
Comment: You should probably add what operating system and platforms you are targeting, as a correct answer depends on both of these.
Answer: The clock of the communication module is usually derived from the system clock.
this system clock can be devided by specific numbers , like 2,4,8..
that's why you can reach only to specific baudrates.
Because you are talking on asynchronous protocol , clock is not transmitted on lines.
all of the above , cause the industry to decide on list of acceptable baudrates
BUT , if your two communication modules support special baudrate like 17800 you can work with it.
Comment: Actually, it's fairly normal to use a rate register and a countdown register.  The rate is programed as a clock count into the register, and the countdown register starts with the value in the rate register and counts down to zero.  Generally this will produce a value that's 2 to 16 times the target baud rate, and further division produces the actual rate.
Answer: Generally a serial adapter is designed to only operate at certain "standard" bit rates -- 50, 110, 150, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, etc.  In practice many adapters are implemented partially in software and can run any rate (within the range of their counters), but the (de-facto) standard doesn't require that you can specify such arbitrary rates.
Answer: Under Windows you set the baud rate of a serial port using SetCommState which takes a device control block structure as a parameter.  The BaudRate element of this structure is used to set the baud rate and can either be a constant value,e.g. CBR_4800, or your own specified value, e.g. 4801.  Whether any value works is hardware dependent, i.e. whether or not the UART or SIO in use allows your specific baud rate.  It's a while since I've worked with these things, but it is possible the baud rate must be a multiple of an input clock rate provided by some other piece of hardware, such that certain rates may not work.  Note that my experience relates to RS232, as opposed to RS485, but I believe the same SDKs are used.


Let $p$ be a prime number and let $G$ be a $p$-group. Then $G$ contains a normal subgroup of order $p^k$ for every nonnegative $k\le r$

Question: Let $p$ be a prime number, and let $G$ be a $p$-group: $|G|=p^r$ . Then $G$ contains a normal subgroup of order $p^k$ for every nonnegative $k\le r$
But are there any normal subgroup of order $p^n$ such that $n>r$ ?
How can we show that, I couldn't show.
Comment: I mean, the order of $G$ is already $p^r$, so how do you want to define such a subgroup with more elements than $G$?
Comment: After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark $\checkmark$ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/), [What should I do if someone answers my question?](https://math.stackexchange.com/help/someone-answers).
Comment: Yes my bad i thought $p^n$ as $n$ sorry. Thank you for your comment
Answer: No, since Lagrange's Theorem ensures that the order of any subgroup of a group divides the order of the group; $p^n\nmid p^r$ for $n>r$.


Comparison of medians

Question: I`m currently an Intern and one of my tasks is to asses whether certain variables were optimal for a control system. In total there are four variables which can vary, and to avoid a complicated analysis I decided to, from the default settings (as a control), only vary one of these variables at a time and see how it impacted the stabilization time of the system. Each of these sample consists of 2500 tests and the time it takes to converge for each test. Just to clarify, my values are discrete as time is the number of cycles it takes to converge.
This approach seemed simple enough, however after preliminary analysis it became apparent that the distributions were not normal and that one of the parameters played heavily with the skew and shape of the PDF. Non-parametric tests seemed most-appropriate and I felt the median would be most representative of the time it took to settle, due to the heavy skew. The Mann-Whitney test seemed perfect, but the assumptions it required to be valid to compare the medians were too restrictive (My data is discrete and the distributions do not appear to just be shifted). The next test I thought of using was a permutation test to compare the medians of our two distributions, however I have no Idea how to conclude from the distribution of the medians. I though about just noting the percentage of the time that one settled faster than the other, but have no idea how to prove if that is statistically significant.
If additional information is required, please do not hesitate to ask. Thank you ahead of time!
Edit:
Ok, minutes after having posted something clicked and now everything seems clear. My question now is rather does it make sense or is there a better approach?
Histograms
The first histogram is that of my control settings (epsilon = 0.1) and the other is when epsilon = 0.4. As epsilon grows the data's skew tends to become (from what I can see) more and more to the right. Due to my lack of reputation points I can only post two images, but the trends persists for all the values of epsilon I have tested thus far.
Comment: What do you intend by "non-parametric distribution" here?
Comment: *Comparison of medians* (if you really want a comparison of medians) or some similar terminology if you actually want to compare something else.
Comment: Even if you did fit a known distribution to your sample, it didn't actually come from that distribution; if the word "nonparametric" is simply to indicate we don't know what distribution(s) the data are from,  it seems that it's not performing a useful role. We can almost never know that.
Comment: I meant that I didn't manage to fit it to a known distribution. I'll include some pictures, I think it will answer your question better than I can.
Comment: Ok, how would you say that instead? My exposure to statistics has been rather limited thus far, so any help would be greatly appreciated!
Comment: Thanks for the help! I decided to change the title as result.
Answer: The description of the data would suggest that you have time-to-event data and that analysis with Cox's model could be employed to help resolve some of the distributional issues you describe. The issue here is not so much identifying a perfect distribution for your data as deciding what type of data you actually have. Based on the ability to perform 2500 repetitions of the experiment, please comment on whether your data are generated from a deterministic or stochastic process, which are less well-suited to statistical inference.
In order of preference, the negative binomial, Poisson or normal distributions are candidate distributions given your data. To use the normal distribution, consider a data transformation to reduce the skew. For each distribution, fit statistics are available to test the fit to the respective distribution.
Analysis of ranks can also be used, as you suggest in the original post. Note that ranks are being compared and not medians. For this sample size, non-parametric analysis would like perform as well as methods based on the normal distribution. The skew is not important for nonparametric analysis, as all values are ranked and analyzed.
Very generally, I would recommend a regression technique given the need to evaluate multiple independent variables. I would generally prefer a time-to-event analysis given the natural time to convergence you describe as the dependent variable. Cox's model or a parametric Weibull model (fit statistics available for both) may allow you to nicely evaluate your parameters using one test instead of multiple tests for values of each parameter, suggested in a previous version of the post.
Comment: I hadn't thought of using a regression technique, I'll look into doing that! As far as using rank tests, I don't see the advantage of evaluating the ranks. From my understanding the only information that would give me is if my populations are different or not. As far as fiiting distributions, pretty much non of the samples have the same 'shape' if you will. Is it legit to use different statistical models for a hypothesis test?
Comment: I would focus on the regression method and not worry choosing models based soley on the shape of the data you obtained. In brief and as hinted at by @Glen_b, the test we use to evaluate the data obtained is often best determined by the data generating process, not the shape of the results generated from that process. You can only test a hypothesis using one model/test of the data if you are being strictly scientific in your approach. Reconciling two or more tests is not possible.
Comment: After reading up a bit and thinking about it, I have somethings I'm unclear about using regression. I can't use each of my trials (one simulation) as a point in the regression due to the probabilistic nature of the system. The solution I came up with was using the medians of each series of tests with certain parameters. I was wondering if this seems valid? I'm also not sure that regression is exactly what I need. Although I'm interested in seeing the impact of my variables on my system, I really just need a way to compare the different results which I get after a series of trials.

Comparison of medians


How do I create a Many to Many Relationship in CRM 2013 using Web Services

Question: I have a many to many custom relationship company_a_c between Accounts and Contacts in CRM 2013.  I am now trying to add a relationship via the oData (REST) web services, but have run into some difficulties.  I created a standard c# proxy class to the oData web services.
Attempt 1 (create relationship object):
var crmRelationship = new company_a_c();
crmRelationship.accountid = account.AccountId;
crmRelationship.contactid = contact.ContactId;
crmService.AddTocompany_a_cSet(crmRelationship);
crmService.SaveChanges();

Result: Error "The 'Create' method does not support entities of type CRM 2013 'company_a_c'
Attempt 2 (create via objects):
account.company_A_C.Add(contact);
crmService.UpdateObject(account);
crmService.SaveChanges();

Result: No error thrown, but relationship not created
I'm sure I'm going about this the wrong way (new to oData) so any help as to the right way to setup these type of relationships would be appreciated.
Answer: try the following:
EntityReferenceCollection entityCollection = new EntityReferenceCollection();
entityCollection.Add(new EntityReference(Contact.EntityLogicalName, contact.ContactId));
Relationship crmRelationship = new Relationship(company_a_c.EntityLogicalName);
crmService.Associate(Account.EntityLogicalName, account.AccountId, crmRelationship, entityCollection);

Comment: I don't seem to have EntityRefenceCollection as a type (was looking under CrmServiceReference) and Account, Contact, etc... do not have .EntityLogicalName as a property.  I'm using the oData REST proxy classes generated.
Answer: Looks like SetLink was the wrong one, but AddLink was what I should have been after.
crmService.AddLink(account, "company_a_c", contact);
crmService.SaveChanges();

Comment: Not sure why this was flagged as the correct answer. You cannot add many-to-many links using AddLink.


Purchasing Godaddy SSL Exchange 2010 Server

Question: I have created a CSR for our Microsoft Exchange 2010 Server (domain: mail.domain.com (example). We have a hosting account with Godady (DNS Hosting only as well). We do not have  SSL Cert and need to purchase one. However, which SSL to purchase? https://www.godaddy.com/ssl/ssl-certificates.aspx?ci=9039
We only need a SSL cert for mail.domain.com (https://mail.domain.com) Would the "Protect one website option work?) Godaddy is suggesting we use the multiple domain or even wild card package. However due to only needed a cert for one subdomain/domain (https://mail.domain.com) this is why I this the basic options would be our best option. Do you agree?
Comment: Purchase a *not-GoDaddy-SSL-cert*, for starters ... go with someone good.
Comment: That does not help. Say I go with someone else? Who? Should I get a SSL Cert for subdomains? Wildcard?
Comment: www. certificatesforexchange. com is what I always use and recommend. Simple, easy, done.  (not a plug for them just a recommendation, so I've messed with the URL a little).  You'll need multiple SANs for Autodiscover, external, internal, netbios name even.
Comment: @TheCleaner
Internal and netbios names are no longer available.
https://www.digicert.com/internal-names.htm
Comment: Correct, I'm just rambling from years of it.  It's best to use proper FQDNs on the internal Exchange URLs.
Answer: You should get the UCC SAN certificate as GoDaddy suggests. You need AT LEAST two FQDNs - autodiscover.domain.com and mail.domain.com.
Never had an issue with Godaddy certs.


find the derivative of the function g(x)

Question: Find the derivative of
$$g(x)= \int_1^{\cos x} \sqrt[3]{1-t^2} \ dt$$
I am having trouble finding the integral. I thought you would set u as 1-t^2 but it doesn't work
Answer: Hint: Use the Fundamental Theorem of Calculus. If $h(t)$ is the antiderivative of $\sqrt[3]{1-t^2}$, i.e., $h'(t) = \sqrt[3]{1-t^2}$ then
$$g(x) = h(\cos x) - h(1)$$
Hence $g'(x) = ...$ what?
Comment: I'm sorry I'm not following you
Comment: By the FTCalculus, $\int_a^b f(t) \ dt = h(b) - h(b)$ where $h$ is the function that has derivative $f$, i.e., $h'(t) = f(t)$. So instead of trying to calculate the expression of $g(x)$ in your question explicitly--which is very difficult--use the FTC. Between my answer and Raúl's below, I hope you can piece it together.
Comment: okay I don't know if I'm not understanding the process but how would you solve it if the integral was from sq.rt. x to x of e^t/t
Answer: If $F(x) = \int_1^x \sqrt[3]{1-t^2}\,\mathrm{d}t$, you should know that $F'(x)=\sqrt[3]{1-x^2}$.
Here $g(x) = F(\cos x)$, thus:

$$g'(x) = F'(\cos x)\cdot(-\sin x) = \sqrt[3]{1-(\cos x)^2}\cdot(-\sin x) = -(\sin x)^{5/3}$$
Answer: You are trying to find the derivative of
\begin{align*}
g\left(x\right)=\int_1^{\cos\left(x\right)}\sqrt[3]{1-t^2}\:dt.
\end{align*}
Notice that we are integrating, and if you look up Leibniz's Rule, you'll find the following "formula" based on the fundamental theorem of calculus:
\begin{align*}
F\left(x\right)& =\int_{g\left(x\right)}^{y\left(x\right)}h\left(\tau\right)\:d\tau, \\
\frac{d F\left(x\right)}{dx} & =h\left(y\left(x\right)\right)\cdot y'\left(x\right)-h\left(g\left(x\right)\right)\cdot g'\left(x\right).
\end{align*}
Hence, applied to your problem here we would get
\begin{align*}
\frac{d g\left(x\right)}{dx}& = \sqrt[3]{1-\left(cos\left(x\right)\right)^2}\cdot\left(-\sin\left(x\right)\right)-\sqrt[3]{1-1}\cdot{0}=-\sin\left(x\right)\cdot\sqrt[3]{\sin\left(x\right)}=-\sin^{\frac{4}{3}}\left(x\right).
\end{align*}
Answer: Let us make it more general. You first look for the derivative of a function $g(x)$ defined as $$g(x)=\int_{a(x)}^{b(x)} F(t) \, dt$$ Application of the fundamental theorem of calculus leads to  $$g'(x)=F\big(b(x)\big) b'(x)-F\big(a(x)\big) a'(x)$$ In your case, since $a(x)$ is a constant, the second term in the rhs is $0$ and what is left is then $$g'(x)=F\big(\cos(x)\big) \frac{d\big(cos(x)\big)}{dx}$$
I am sure that you can take from here.