Mixing two data sources

Question: I'm working on my master thesis using the gravity equation. I have to choose a data source for the trade flows of Iran with it's trade partners. I have a panel data and for the intended period (over 20 years) there is a data source from  Iran's Custom Administration. My problem is, for some of the years, this data source contains no information about the trade transactions. My question: Could I get help from another data source for the missing Datas, and when yes, how can I check the robustness? Thank you guys!
Comment: estimating the gravity equation intelligently taking into account the missing data could be cool too!
Comment: What about other data sources wrt international trade? For instance, the World Input-Output Database (http://www.wiod.org/home), the World Bank Open Data (https://data.worldbank.org/) or Quandl.com? Can't vouch that any of them will have the info you need but it can't hurt to poke around for other corroborating sources...
Answer: The easiest check you can make is to compare that the data that is present in both datasets is the same. If it differs, you can study where the differences come from and whether you need to apply some transformation on the data from the second set to reuse it in the context of the first dataset.
A common assumption that is made, and verified by the above test, is that the two datasets represent the same phenomenon. If this is the case, they should have similar distributions. This should hold for both the overall data and for data filtered according to any features (e.g. not only global exports, but also exports to one particular country, and exports of one particular commodity). So comparing the distributions of the two datasets is one strong robustness check you could make.
Another assumption that you could add is continuity over time. In this case you can use the present for the values missing in the first dataset, you can compare the extrapolation see if the second dataset is within certain vicinity from the extrapolation of the first.
Generally, discrepancies are not impossible/improbable, but you should try to have explanations of where they come from. This would give you a way to reason about the quality of the data and whether it could be used for your purposes.

Mixing two data sources


How to show the product "add to cart" button on a product kit?

Question: I would like to add a "add to cart" button on a product kit, for each product in the product kit. How may I achieve that? I have been searching for a while now. Ubercart 3.
This would be similar to iTunes when viewing an album, the user may buy a single song of the album. Currently with product kit, the user has to click the product link to get to the song then be able to buy it.
Answer: Drupal has a number of modules that make "add to cart" and other similar features of Drupal commerce work, by simply enabling those modules.Check out the following links:

Commerce Line Item Cart Form
This link may also help- Cart Modules
Comment: Drupal Commerce != Ubercart...
Comment: @Rakhi, I'm using Ubercart 3 not Drupal Commerce.


Implementing jQuery-UI tabs

Question: I have all my js files in a folder under my custom theme:
htdocs/themes/<mytheme>/js

I load all these js files in 'mytheme.info' in this way:
scripts[] = js/

Implementing jQuery-UI tabs


About can't export the performance problems

Question: At first,let me describe my environment
My VirtualCenter is install on window 2008 ,and theDataBase that VC used is SQL 2008
I really want to ask is .....
When I use vsphere clinet to connect VC.....I got a problem.
the performance chart only can show "realtime "......
whatever I only want to view the chart , or I want to export the performance log .
when i manually want to export performance, and I select the time to 1 hour ,1 day ,1 month, or from a to b.
it showed "No performance data to report for selected objects"
only select realtime can export data normally.
Before I install Vsphere 4 , I install the SQL 2008 , used the schema in the install CD(I follow the step to create SQL DB for vSphere)
Could anybody help me how to solve this problem?
And if need any information ,just tell me to provide.
Thanks a lot.
Answer: In VCenter, go to Administration, vCenter Server Settings, choose statistics and change the statistics level


What happened to byte and packet counters in conntrack?

Question: Netfilter's conntrack docs show an example output of conntrack -L that contains bytes= and packets= counters, but when I run it I only see IP and port information.
I'm aware that the docs are really out of date, and specifically mention ip_conntrack, which has since been replaced with nf_conntrack, but I'm hoping there's some way to enable the counters again.
Is there a way to get that information, or have these counters been removed?
I'm using ubuntu 14.04, with kernel 3.13
Comment: The counters you guys mention are per interface, but I'm interested in counters per *connection*.
Comment: Try iptables -vnL
Comment: Will ifconfig give you the trackers you want?
Answer: Turns out I just needed to enable accounting by doing (as root):
/bin/echo "1" > /proc/sys/net/netfilter/nf_conntrack_acct

After this, byte and packet counts appear in the conntrack output.
Comment: I wonder why they are not enable per default... memory contraints? performance impacts?


add step to checkitout

Question: My company have just baught Ivan's CheckItOut extension, and I'm trying to add a step in it.
Actually, I did have this step integrated into "regular" OPC.
Looking at the extension's code, I see that there is a addCheckoutStepToLayout method used in the layout checkitout.xml file. If I had this line into checkout.layout block:
<action method="addCheckoutStepToLayout"><layout>right-bottom</layout><step>points</step></action>

the step is added, but I'm trying to add it via my extension layout .xml file.
So I've tried updating the checkitout handle:
<ecomdev_checkitout_layout>
    <reference name="content">
        <reference name="checkout.layout">
            <action method="addCheckoutStepToLayout"><layout>right-bottom</layout><step>points</step></action>
        </reference>
    </reference>
</ecomdev_checkitout_layout>

updating the block through regular checkout_onepage_index handle:
<checkout_onepage_index>
    <reference name="content">
        <reference name="checkout.layout">
            <action method="addCheckoutStepToLayout"><layout>right-bottom</layout><step>points</step></action>
        </reference>
    </reference>
</checkout_onepage_index>

with and without <reference name="content">, but no luck until now.
I'd be glad reading your suggestions, thx
Answer: Eventually I asked the author directly, and the solution was quite simple.
The block wasn't created yet when I was trying to update it through my module's layout file: I've made it depends on Ecomdev_Checkitout and everything is working fine now.

add step to checkitout


Can I choose specific nodes to show in a view?

Question: I have a Drupal 9 site with a view that shows products, but I do not want to show all products, I only want to show a select few of them.
Is it possible to filter like this? Instead of showing all the products?
Ideally I'd like a UI where I can manage the products manually. E.g. if I have 5 products but only want to display Product 1 and Product 4, I can select those 2 products.
Comment: You should be able to create an entity queue (https://www.drupal.org/project/entityqueue), and filter the results by that queue. I haven't done it since D7 with the Node queue module, but this module appears to be the successor, so you should be able to do it.
Answer: If you want to manage the products manually, i.e. not base the filter on a product field value, the Entityqueue module offers an easy solution.

Install the module if you don't already have it
Create a queue for the products at /admin/structure/entityqueue/add
Choose the appropriate entity type and bundle under Entity settings
Save and add some products to it
In your View, add a relationship to the entityqueue

Once you've done that, only the products in the queue will be in the View's results.
As a bonus, you can also control the sort order with the entity queue if needed. Just add a sort criteria for Content Queue Position to the View.


AWS OpenSearch OpenIdConnect as Authentication Method

Question: I am trying to add an authentication method to AWS OpenSearch.
By default it comes with basic auth with internal db,

I would like to configure Security Plugin with a second authentication mechanism OpenId Connect
Documentation says to use Update Security Configuration , which doesn't seem to be allowed by AWS.
tried PUT _plugins/_security/api/securityconfig and PUT _plugins/_security/api/securityconfig/authc both seems to be failing with {"Message":"Your request: '/_plugins/_security/api/securityconfig/authc' is not allowed."}
Is there an alternative, all I want to do is , use JWT Token(from OpenID Connect Cognito) to run OpenSearch _search API, rather than using internal database basic auth or IAM Role from Federated Pool.
Answer: AWS Opensearch has blocked apis for updating security configuration which is why you see the error. The documentation you have linked is applicable when using opensearch security plugin for your self hosted opensearch service and not AWS hosted solution.
I am not sure if this will be helpful to you but this blog does talk about using OpenId Connect along with AWS Cognito for opensearch auth: https://aws.amazon.com/blogs/apn/use-amazon-opensearch-service-with-kibana-for-identity-federation-auth0/


How many ways to choose teams

Question: $30$ people want to play capture the flag. There are two teams. Each team has ten people. How many ways to choose the teams? I figure there are $30\choose 10$$20\choose 10$ ways to choose members for the team. I am told that this is "double counting", and the answer should be half of $30\choose 10$$20\choose 10$Why is this so?
Comment: Choosing the first ten to be on one team and the second ten to be on the other team is the same as choosing the second ten to be on one team and the first ten to be on the other.
Comment: Are there two teams or three?
Comment: Alternatively, avoiding the "division" issue, first pick which ten people are waiting on the bench and not playing.  Then among the twenty people who are going to be playing, one of them will be the youngest.  Pick who the nine people are who will be on his team.  This gives an answer of $\binom{30}{10}\binom{19}{9}$.
Comment: Sometimes I find it easier to reduce the counting required to make it easier to "see" an answer.  You have three people and you must pick 2 teams, one person per team (it's a chess tournament).  If you pick person number 1 for the first team, and person 2 for the second team, that's the same as picking 2 and then 1, because it's still the same two people facing off against each other.  Makes sense? Hence that's "double counting."  (It's been ages since I've done these, let's see if I get corrected.)
Answer: The question is not 100% clearly phrased. You could also consider your answer correct.
Say there is a red and a blue team. Then you correctly figured that there are $\binom{30}{10}\binom{20}{10}$ ways to pick 10 players for 10 red and 10 players for the blue team.
But now you can argue that swapping the team colors does not change anything. So if you do not care which team is red and which is blue but only which players play together the number of possibilities is reduced in half.
Answer: Actually, there are two types of situations

The teams are labelled (distinguishable), e.g. Lions and Tigers
Here you would not divide by $2$,
as being on the Lions team is not the same as being on the Tigers team.
The teams are unlabelled (indistinguishable)
Here you would divide by $2$, as explained in the various comments.

In the absence of any explicit mention of teams being labelled, we presume that they are unlabelled.
As a safeguard, you could add the above remark to your answer, if remarks are permitted.
Comment: @wonce: I can't understand why your answer wasn't showing when I was typing mine. Anyway, I'll let it stand with credit to you !

How many ways to choose teams


The least common multiple of $n$-bit numbers

Question: Two $n$-bit numbers (i.e. $2^{n-1} \le x_i \le 2^n - 1$) are chosen uniformly randomly. What is their least common multiple?
I know the minimum is $x_1=x_2$ when they collide and the maximum is $x_1*x_2$ when they are coprime. However, I would like to know:

The expected value.
The minimum when $x_1 \neq x_2$.
The bounds in terms of $n$ (when distinct).

If there is no answer in general, the approximation for $n \to \infty$ would be great.
Comment: In this question the expected value of the LCM of two numbers seems to be $\zeta(3)/\zeta(2)$ times the product.  http://math.stackexchange.com/questions/1363950/average-lcma-b-1-le-a-le-b-le-n-and-asymptotic-behavior
Comment: @Michael, the range is different there, so I don't know if it applies.
Answer: The exact expected value will probably be very hard to compute because it depends in part on how many primes there are between $2^{n-1}$ and $2^n - 1$, and the values of those primes. It may be possible to get asymptotics, e.g. if $f(n)$ is the expected value you may be able to find a function $g(n)$ such that $\lim_{n \to \infty} f(n)/g(n) = 1$. I don't see how to do that off the top of my head though
The minimum possible value you can get for $x_1 \neq x_2$ is when $x_1 = 2^{n-1}$ and $x_2 = 3*2^{n-2}$, and in this case the LCM is $3*2^{n-1}$.
Comment: Thanks for the partial answer.


mysql query to select one specific row and another random row

Question: I want to display two records.
For eg
select * FROM users WHERE user_id = 5.
Now i want another row randomly selected from users table but with user_id != 5
Is it possible to do in a single query. I tried using union all but i dnt get two distinct rows.
Thanks
Answer: This works fine for me. The first result is always the record with ID 5, the second row is a random one. Note that if no record with the ID 5 exists, both rows will be random.
SELECT * FROM users ORDER BY (user_id = 5) DESC, RAND() LIMIT 0,2

Comment: THanks pekka. I tried your query. It works great. +1. What if i have a condition. Can i use it in there. say eg SELECT * FROM users ORDER BY (now() BETWEEN start_date and end_date) DESC, RAND() LIMIT 0,2 ??
Comment: @noobcode sure, depending on what you want to do. The random row won't be covered by the condition this way
Comment: Simply entering the condition did not work.So i put a subquery. This is how the query looks."" SELECT * FROM users ORDER BY (user_id = (select user_id FROM users WHERE the_condition)) DESC, RAND() LIMIT 0,2 "" This works perfect. Thanks a lot. Appreciate.
Answer: Try this
SELECT * FROM users WHERE user_id = 5 || user_id != 5 ORDER BY RAND() LIMIT 2

Comment: Won't work: Will not necessarily give user ID 5 as the first result
Answer: Union should do the trick. You probably forgot LIMIT.
(SELECT * FROM users WHERE user_id = 5 LIMIT 1)
UNION
(SELECT * FROM users WHERE user_id != 5 LIMIT 1)

Answer: Try this:
SELECT * FROM users WHERE user_id=5
union all (
  SELECT * FROM  users WHERE user_id!=5
  ORDER BY RAND() LIMIT 0,1)


Difference between optimizing single polynomial neuron vs multiple perceptron?

Question: Is there any specific reason why we usually prefer to use a neural network with, let's say, 6 hidden neurons rather than one single neuron representing the following function?
$$ax^3+bx^2+cx+d$$
Is it harder to optimize the latter one?
Comment: What is x and what are a, b, c, and d?
Answer: It's mainly convention to think of a neuron as a nonlinear activation applied on a linear input, e.g. $f(ax_1+bx_2+c)$. The point is that after a few layers of connections, you'll have reasonable approximations to stuff like $x^2,x^3$ if necessary. The allowed modifications to this become whether you wanna use ReLu, tanh, etc. activations.  It's also "minimal" in that linear combinations are fairly cheap to compute, followed by nonlinear activation. This speeds up individual neuron forward and backward passes (but can arguably require a slightly deeper network). Overall, speed is still an active research area.
It also makes input normalization less of a headache. $x^3$ can grow out of control with a large input, or look abnormally small for a small input. Whereas with a linear input, you can always control for the magnitude and range of $ax_1+bx_2+c$ via a constant shift. You could definitely get this to work for $x^3$ as well, but then it becomes more annoying to to debug unless all your neurons follow the same conventional form of input.
Comment: Thanks Alex, Would you please elaborate further about your second paragraph? Or refers me to a website or article which talks about it?
Comment: For BatchNormalization: https://towardsdatascience.com/batch-normalization-in-neural-networks-1ac91516821c

For Xavier normalization: http://andyljones.tumblr.com/post/110998971763/an-explanation-of-xavier-initialization
Comment: Thanks, and was about the optimization? Is it more difficult to optimize a single polynomial rathe than bunt of connected neurons?


Anscombe's quartet - Using just descriptive statistics, can I determine if two sets of values represents the same phenomenon?

Question: Given two sets, lets say:

Can I say that they are related to the same phenomenon, given their mean and correlation?
P.S.: Both sets have same correlation (x1 and y1; x2 and y2)
P.S.2: x1 and x2 have the same mean, so as y1 and y2
This question was related with Anscombe's quartet. More info about it here: https://en.wikipedia.org/wiki/Anscombe%27s_quartet
But I'm still looking for some details. Descriptive statistics alone is not enough here, so what must we use? Plot data? Some advanced regression models? I know we should go further, but to where?
Comment: Can you add the data as text rather than images please
? (so that others can use them for examples more easily)
Comment: @baxx I would like to add data as table, but I can't so I posted it as image.
Comment: You can - worse case you could just put the raw output of a csv file there and someone would be able to edit that quite easily
Answer: You need an underlying model or metric by which one can describe 'sameness'. The quantitive description of data depends on the origin of the data.
In this case it seems like (meaningless) fabricated data. The y2 values look like following a smooth curve without much noise. You can see this also in a plot of the 2nd order derivative (computed by taking the difference of the difference).
Whether this is relevant to you and whether measures like just correlation are meaningful or not, depends on your viewpoint and interpretation of the data.
But, if you have fabricated data then anything will be meaningless. So not much can be said about this particular case without context.
See more about the philosophy behind these graphs here:  https://www.jstor.org/stable/2682899


How do I prevent Lilypond from hiding "empty" staves?

Question: Preamble: I read music to only a very basic level. As a small project to combine my (amateur) singing hobby with my (also amateur) interest in coding, I am trying to use Lilypond to reproduce as closely as possible the existing score of one of the songs we are currently learning, namely an arrangement of "Let the river run" (pdf available here). Another reason for using Lilypond is that I'm familiar with TeX and its derivatives so this approach appeals to me.
Through this project I hope to learn about musical theory and notation in a gentle and unstructured fashion. Obviously, if the goal were to learn as much as possible in as short a time as possible I would take a course, but that is not the aim.
I have hit a problem whereby staves are being hidden during the staggered start. For the first bar only the basses are singing, joined at the end of the second by the altos, then tenors in bar 3 and finally sopranos in bar 4. In the original score you can see that there are what I think are semibreve rests that "placemark" in the soprano score.
Original

My attempt

P.235 of the notation manual states "A staff is considered empty when it contains only multi-measure rests, rests, skips, or a combination of these elements." I suppose by this benchmark the soprano staff is empty and is not being displayed? I note Keep_alive_together_engraver but that doesn't seem to do what I want.
\version "2.24.1"
\header {
  title = "A Test"
  composer = "A Composer"
}

SopranoMusic = \relative {
    \key fis \minor
    r1 |
    r1 fis'4
 }
SopranoLyrics = \lyricmode {   }
AltoMusic = \relative {
    \key fis \minor
    r1 |
    r1. fis'4
}
AltoLyrics = \lyricmode {  Oh | }

TenorMusic = \relative { a4 a a a }
TenorLyrics = \lyricmode { Te -- nor ly -- rics }

BassMusic = \relative {
    \clef "bass"
    \key fis \minor
    \time 4/4
    g16 g g g g16 r16 g16 g g16 g g8 r4 |
    g16 g g g g16 r16 g16 g g16 g g8 r4 |
}

BassLyrics = \lyricmode {
    Let16 the riv16-er run16 let16 the riv16-er16 run8 |
    Let16 the riv16-er run16 let16 the riv16-er16 run8
    }
\include "satb.ly"

Questions

How can I keep the soprano part displayed when it contains only rests?

Out of interest, is there a way to use "4/4" instead of the "big C" as the time signature?

Is there a straightforward want to shorten the stem of notes? I can see that in the original score the stems for the bass part extend down two notes whereas in my score they go down to the bottom of the stave.

Why is the natural symbol appearing before the first note of the bass part, and can I suppress it?

I'm also grappling with lyric alignment but that may be better dealt with separately. Some of the problems I face are likely caused by my lack of understanding of musical notation as well as my lack of familiarity with Lilypond, so any suggestions or pointers on either would be much appreciated!
Comment: This question seems to focus on showing staves. The other three assorted questions should be asked separately so they can be focused on(e.g., searched for in the future), no matter how small.
Comment: Aren't the notes in the original supposed to be A's in the bass part, and an E to start the alto part?  You have them as G's and F#'s respectively.  Was that intentional?
Answer: You are including satb.ly which resides in [lilypond-installation/ly/satb.ly]. Here you've got the lines
\layout {
  \context {
    \Staff
    \override VerticalAxisGroup.remove-empty = ##t
    \override VerticalAxisGroup.remove-first = ##t
  }
}

which tells Lilypond to remove all empty Staves (including the first one). If you do not want this behaviour you could make a copy of that file and remove these lines. If you do not want to do so you can still override this change by doing
\override Staff.VerticalAxisGroup.remove-empty = ##f
\override Staff.VerticalAxisGroup.remove-first = ##f

at the begin of the voice definitions in question, e.g.
SopranoMusic = \relative {
    \override Staff.VerticalAxisGroup.remove-empty = ##f
    \override Staff.VerticalAxisGroup.remove-first = ##f
    \key fis \minor
    R1 |
    R1
 }

For more information on that mechanism read this part of the manual:
https://lilypond.org/doc/v2.25/Documentation/notation/hiding-staves.html
Comment: `satb.ly` supports setting a `Layout` variable to override the layout, so you could also just write `Layout = \layout { }` once at the top level (anywhere before the `\include`). That overrides anything else that might be in `satb.ly`'s default layout, but currently there is nothing else there.
Comment: Ah, that's it; easier than I thought.  I was trying to put those overrides is another layout block (which obviously doesn't make much sense).
Answer:
a) Full measure rests (of any value) should be typed in with capital R's.  This make them centred in the bar.  (So change all r1's to R1's)
b) Where you have r1. fis'4 in the alto part, the rest is actually suppose to be a dotted mimim and not a dotted semibreve (notice how in the original, it sits on the barline below, rather than hanging from the bar line above), so change that to: r2. fis'4, or perhaps r2 r4 fis'4.
c) You're missing the key signature (and a few rests) in the tenor part. Also, the notes are not right.

I'm not sure what you mean by this point, the soprano part is displaying, (please clarify what you mean here).*

To display the time signatures as "4/4" instead of "C", use the command \numericTimeSignature at the start of any one of the music blocks (say, after the key signature).

Stems inside the staff "should be" this long (3½ stave spaces); they start an octave away from where they end.  Yes you can override this (with \override Stem.details.beamed-lengths = #'(2)), but I wouldn't.

The natural symbol is there because you have g's where the key signature is expecting g#'s, so change g16 g g g ... in the bass staff to  gis16 gis gis gis ..., (or gis16 16 16 16 ... which is simpler to type.)
EDIT: as pointed out in a comment, they are actually supposed to
be a's not g's or g#'s, so a16 16 16 16 ....

If you're lyrics are supposed to line up with the music you shouldn't have to specify the value of each word/syllable.  To type in hyphenated words use -- between syllable, i.e. Let the riv -- er run let the riv -- er run |.

EDIT 2:
* Okay, so I've put in all these fixes, and you're right the empty staves for the soprano part etc. aren't being displayed.  This is because the file satb.ly is hiding them for you.  I don't use the provided templates (I make my own) and I don't really know how to override them (I tried a few things, but they didn't work).  Since that is your main question in this post, if you want to keep using that template, you might have to wait for another answer.
Comment: Thank, very useful pointers


How to select records from a Postgres table using an ORDER BY statement on a jsonb column that points to another table

Question: I have two tables, characteristics and students.
characteristics
 id      name          value
----    ------        -------
 1      country       england
 2      country       brazil
 3      games         football
 4      games         baseball
 5      country       india
 .        .             .
 .        .             .

students
 first_name      age       character_values
------------    -----     ------------------
  Jason          12         [1,4]
  Mark           14         [1,3]
  Kunal          10         [5,3]
   .              .           .
   .              .           .
   .              .           .

The characteristics table has three columns where the id column is an auto-increment field. The name denotes the name of a specific characteristic and the value indicates the respective information about the characteristic.
The students table contains detail about each student. The character_value field in the students table is a jsonb field. Each element in the jsonb array is an ID that points to the appropriate characteristic ID in the characteristics table.
(for example, if a student is from the country of india then the ID 5 is appended to character_values jsonb array against the respective student's name)
Assuming that each student can only belong to one country, how do I select a list of students while ordering the result by the name of the country they belong to?
Answer: You can join the tables with jsonb_array_elements:
select c.*, s.first_name from characteristics c join students s on exists
  (select 1 from jsonb_array_elements(s.character_values) v where v.value::int = c.id)

Output:

id
name
value
first_name

1
country
england
Jason

1
country
england
Mark

3
games
football
Mark

3
games
football
Kunal

4
games
baseball
Jason

5
country
india
Kunal
Comment: @Vinay `select 1` is convention for `exists` subqueries.
Comment: Why did you use a SELECT 1 instead of SELECT *? Any specific reason?


Can javascript run through browser as some plugin

Question: I am very confused on this one but can javascript run through browser without pasting it into console?
The meaning of this is that I like watching movies online but websites that let us see movies for free are showing lot of ads some of them cant be blocked by adblockers etc so I open developer tools and find elements that are used for ads and by javascript remove them.
And I may be using 30 sites and I made one code for each and one big code for all but my question is can I make some web browser plugin that will when being active at the time when I open some website, run code and if the site is in my code find for ads and remove it?
The main idea is that can I make plugin that will do all job for me instead me doing it every time I want to watch something?
Comment: Can make a  `userscript` that runs in browser extensions like Tampermonkey or Greasemonkey and will run on domains you define
Comment: @charlietfl Since I was just thinking about that, I'll need to research for that first and thank you :)
Answer: Most browsers support extensions. Take a look at chrome extensions development https://developer.chrome.com/extensions/content_scripts. It allows to run content scripts for a specific websites. This is primarily a chrome API but Firefox and Mircosoft Edge also partially support it. And they definitely support content scripts API
Comment: Thank you too I will check it all!


Elasticsearch Query for field with multiple values

Question: Is it possible to write an Elasticsearch query that will return only documents that have multiple values in a given field? I don't care what those values are, only that a field has multiple, instead of 1.
I'd like the query to match:
{
  "color": ["red", "blue"]
},
{
  "color": ["green", "yellow", "orange"]
}

but not
{
  "color": "red"
}

Ideally, I'd prefer to avoid using scripts in my query; they are disabled on my cluster.
Answer: I'm not aware of a solution approach that works without using a script. But you have choice:
Preparation: Index some sample documents
POST my_index/_bulk
{"index": {"_id": 1}}
{"color": ["red", "blue"]}
{"index": {"_id": 2}}
{"color": ["green", "yellow", "orange"]}
{"index": {"_id": 3}}
{"color": ["grey"]}

Option 1: Using a script at query time ("expensive")
GET my_index/_search
{
  "query": {
    "script": {
      "script": "doc.color.size() > 1"
    }
  }
}

Option 2: Using a script at indexing time ("cheap")
(preferred approach, as the script only gets executed once per document write)
PUT _ingest/pipeline/set_number_of_colors
{
  "processors": [
    {
      "script": {
        "lang": "painless",
        "source": "ctx.number_of_colors = ctx.color.size()"
      }
    }
  ]
}

POST my_index/_update_by_query?pipeline=set_number_of_colors

GET my_index/_search
{
  "query": {
    "range": {
      "number_of_colors": {"gt": 1}
    }
  }
}

You can also configure the pipeline as default pipeline for your index, so you don't need to change anything in your indexing application logic.
Comment: I wouldn't say that I'm "happy" with it, since I cannot use scripts in my cluster, but it does appear to be correct. :P


Surprising behaviour when using functools.partial in default argument inside a class

Question: class A:

    def _add(a, b):
        return a + b

    def f_add():
        return _add

    def lambda_add():
        return lambda x, y: _add(x, y)

    def lambda_arg_add(l=lambda x, y: _add(x, y)):
        return l

    def partial_add():
        return partial(_add)

    def partail_arg_add(f=partial(_add)):
        return f

A.f_add()(1, 2)

A.lambda_add()(1, 2)

A.lambda_arg_add()(1, 2)

A.partial_add()(1, 2)

A.partail_arg_add()(1, 2)

All the function calls except the last one raise an error saying _add is not defined but the call to partail_arg_add executes successfully. What is the logic behind this? Why does the interpreter know where to look for _add when creating the partial function but only when it's done as a default argument?
Answer: functools.partial is not involved in this behavior.
This is because the default arg is created at the function definition, during the class definition, which occur in the scope of the class, so you don't need any "self.".
This is why this works :
class Example:
    def A(self):
        pass

    def B(self, x=print(A, 1)):
        print(self.A, 2)

    print(A, 3)

Output:
<function Example.A at 0x7fcf8ebc5950> 1
<function Example.A at 0x7fcf8ebc5950> 3

Even without calling any Example.B(), it should print the <function Example.A at 0x7fcf8ebc5950> 1 and 3 when the class is defined.
But you can't create a partial with a method of a non-yet created class
Or, maybe you can, but I am not aware of any way to do it.
I tried to fix you class:
class A:
    @staticmethod
    def _add(a, b):
        return a + b

    @classmethod
    def f_add(cls):  # valid
        return cls._add

    @classmethod
    def lambda_add(cls):  # valid
        return lambda x, y: cls._add(x, y)

    @staticmethod
    def lambda_arg_add(l=lambda x, y: A._add(x, y)):  # valid
        return l

    @classmethod
    def partial_add(cls):  # valid
        return partial(cls._add)

    @staticmethod
    def partial_arg_add(f=partial(_add)):  # TypeError: 'staticmethod' object is not callable
        return f

But partial_arg_add will fail because _add is not callable yet when the partial is created :
class A:
    @staticmethod
    def _add(a, b):
        return a + b

    print(_add(1, 3))  # TypeError: 'staticmethod' object is not callable

class A:
    @staticmethod
    def _add(a, b):
        return a + b

print(A._add(1, 3))  # 4

Comment: Thanks, that's a nice explanation. I take it the contents of the lambda are not evaluated until later and that's why that doesn't work?
Comment: Exactly, the code of the lambda is evaluated when you do `A.lambda_arg_add()(1, 2)`.


Python JSON only get keys in first level in same order passed from Angular js

Question: How can I get keys in the first level in JSON in the same order as it is passed from angular js? Let's say bellow example.
my_dict = {
            'key1': {...},
            'key2': {...},
            'key3': {...}
          }

Now when I fetch first level keys in python, it is not giving me in the same order as passed. But for some reason, I want to fetch it in the same order as passed.
for item in my_dict:
     print item

This gives bellow result.
key3
key2
key1

Q1 - Why python change it's order?
Q2 - For some reason i want it in the same order like ['key1','key2','key3']. How can I fetch it?
I tried lots of thing on internet but not getting the solution. Downvoters give the reason, so I can improve my question.
Comment: Possible duplicate of [Can internal dictionary order change?](http://stackoverflow.com/questions/38975722/can-internal-dictionary-order-change)
Answer: Because python's dicts are hashed tables. The nature of hashed tables is that they do not keep the initial ordering. Check this link to learn more.
In order to keep your dict in certain order consider using OrderedDict
Example from python docs on this:
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

Answer: Dictionary is a key-value map. It does not guarantee order. Use OrderedDict


Como colocar elementos de uma lista em outra lista

Question: Tenho o seguinte código:
a = list()
b = list()
c = list()

a = (1,2,3)
b = (2,4,6)

c = a + b[1]

print(c)

Como eu faço pra adicionar um elemento de uma lista em outra lista?
Answer: Use o método extend para adicionar os itens da lista a e o append para adicionar o segundo item da lista b:
a = [1, 2, 3]
b = [2, 4, 6]
c = []

c.extend(a)
c.append(b[1])

print(c)

# [1, 2, 3, 4]


Valid Transitive Closure?

Question: Is the relation $D_r\cup\{(x,z)\in\mathbf{R}\times\mathbf{R}|\exists y\in\mathbf{R}(\|x-y\|+\|y-z\|<r)\}$ the transitive closure to the relation $D_r = \{(x,y)\in\mathbf{R}\times\mathbf{R}|\land\|x-y\|<r\}$ where $r\in\mathbf{R}$ and $r>0$ ?
Comment: No, for two reasons. Firstly the condition should be "$\|x-y\|<r$ and $\|y-z\|<r$" rather than "$\|x-y\|+\|y-z\|<r$. Secondly you have added $(x,z)$ whenever $(x,y),(y,z)\in D_r$, but you also need to add $(x,w)$ whenever $(x,y),(y,z),(z,w)\in D_r$, and so on. See also https://math.stackexchange.com/q/1251670/197161
Answer: No, because the relation $\mathbb R$ is not transitive:
$$\mathbb R = \{(x,z)\in\mathbf{R}\times\mathbf{R} | \exists y\in\mathbf{R} (|x-y|+|y-z|<r)\}$$
An intuitive example to show that is below. Let's assume that $r = 2.5$, $a = 1$, $b = 3$ and $c = 5$.
The $(a, b) \in \mathbb R$, cause you can find a (middle) point $m_1 = 2$ between points $a$ and $b$, such that:
$$|a-m_1| + |m_1-b| < r$$
The $(b, c) \in \mathbb R$ as well, cause you can find a (middle) point $m_2 = 4$ between points $b$ and $c$, such that:
$$|b-m_2| + |m_2-c| < r$$
However, $(a, c) \notin \mathbb R$, because the distance between points $a$ and $c$ is $4$, so it'll be impossible to find a (middle) point $m_3$, such that:
$$|a-m_3| + |m_3-c| < r$$
QED

Valid Transitive Closure?


Simple AM-GM Inequality Proof

Question: I am trying to prove the inequality $a<\sqrt{ab} < \frac{a+b}{2}<b$, given that $0<a<b$, by using simple algebra. I proved that $a<\sqrt{ab}<b$ and $a<\frac{a+b}{2}<b$ fairly easy. For $\sqrt{ab} < \frac{a+b}{2}$, I did the following:
$a<\sqrt{ab}$
$0<\sqrt{ab}-a$
$0^2<(\sqrt{ab}-a)^2$
$0<-2a\sqrt{ab}+a(b+a)$
$2a\sqrt{ab}<a(b+a)$
Since $0<2a$,
$\sqrt{ab} < \frac{a+b}{2}$.
However, I am aware that there are probably more concise and elegant proofs. I stumbled on this proof by luck so I would appreciate it if someone would explain how they arrived at each step. Thanks.
Comment: I'm not sure what is your question. Are you asking for an alternative (simpler) proof? Or do you need some clarification about this one?
Comment: I am asking for a simpler proof. Also, I just want to know how you would approach this problem without using the generalized version.
Answer: Hint
$$(\sqrt{b}-\sqrt{a})^2 >0$$
Just open and see what you get.
Your proof is similar, you just multiplied both sides of the above inequality by $a= (\sqrt{a})^2$.
Comment: Interesting! Thanks. The main reason I asked this question was because I am trying to improve my proof skills a little by arriving at an elegant (or relatively simple proof) quicker. How did you arrive at this proof?
Comment: @PreciselyT Reverse engeneering: $$\sqrt{ab} < \frac{a+b}{2} \Leftrightarrow 2\sqrt{ab} < a+b \Leftrightarrow 0 <a-2\sqrt{ab}+b$$ Now all you need is to recognize the RHS as $(\sqrt{a})^2- 2(\sqrt{a})(\sqrt{b})+(\sqrt{b})^2$.
Answer: A way of finding this kind of proofs is starting with the desired inequality and operate with it to reduce it to some inequality that you know is true. But (be careful!), this only works if you can reverse the implication steps (that is, if the implications are "if and only if").
In this case, I'd try this:
$$ \sqrt{ab} < \frac{a+b}{2}$$
$$ ab < \frac{(a+b)^2}{4}$$
$$ ab < \frac{a^2 + 2ab +b^2}{4}$$
$$ 0 < \frac{a^2}{4} - \frac{ab}{2}+\frac{b^2}{4}$$
$$ 0 < \frac{(a-b)^2}{4}$$
which is true. But this proves nothing (I must start with the assumed-as-true proposition and build the correct chain of implications). That is doable, thus:
$$ a<b\implies (b-a)>0\implies (a-b)^2>0 \implies\\
\implies a^2 - 2 ab +b^2 >0 \implies a^2 + 2 ab +b^2 > 4 ab \implies\\
\implies \frac{(a+b)^2}{4} > ab \implies \frac{a+b}{2} > \sqrt{ab}
$$
Comment: Thanks for the help.

Simple AM-GM Inequality Proof


Is 12(mod 13) the same as -1(mod 13)?

Question: I'm in the process of studying for an exam and this just popped into my head. Sorry if it's a dumb question
Comment: I am not sure you understand the "concept" of "$a\equiv b \pmod n$" or what this means: "$a\bmod n$". To answer your question, yes because $12\equiv-1\pmod{13}.$
Comment: $a\equiv a\pm n\pmod{n}$
Comment: Yes, because -1 + 1 = 0 = 0 mod 13; 12 + 1 = 13 = 0 mod 13
Comment: Boom... Here is an upvote too.
Answer: Yes, they are the same. Note that $(-1)+13=12$, so their difference is exactly the thing that is ignored by mod $13$!
Comment: Thank you for your explanation. It seems so clear now, I'm not sure why that confused me before
Answer: Indeed they are the same, although I'd write them either without brackets or with brackets around the whole expression.
I really wanted to add that that using the $(-1 \bmod 13)$ representation can be very useful, especially when try to find the result of a multiplication. For a simple example, $12\times 7 \bmod 13$ is easily converted to $12\times 7 \equiv -1\times 7  \equiv -7 \equiv 4 \bmod 13$

Is 12(mod 13) the same as -1(mod 13)?


How can I show a hidden DIV for a selection included with others?

Question: I have a javascript file that when called, checks to see if a particular option is selected on a form.  The form allows for multiple selections before being submitted.  When a particular item is selected within the given choices it shows a hidden menu.  In this case with "audits" I am able to show the hidden menu fine when just "audits" is selected from the list.  However, I'm having much difficulty in figuring out how to get the menu to show when "audits" would be selected/highlighted with others.  Eg: I had audits, services, someotheroption
Below you can see the code I'm currently using and that's working only when the single item is selected.  Any guidance would be much appreciated.
function toggleFields(){
    function toggleFields(){
        if ($("#installations").val() == "audits"){
            $("#dbcredentialsfield").show();
        }
        else
            $("#dbcredentialsfield").hide();
}

Comment: Could you create a jsfiddle or code snippet with your entire project? Welcome to Stackoverflow.
Comment: Possible duplicate of [How to get multiple select box values using jquery?](http://stackoverflow.com/questions/3243476/how-to-get-multiple-select-box-values-using-jquery)
Comment: I would be more than happy to help out if you have a JSfiddle of your code!
Comment: You can use [`$.inArray()`](https://api.jquery.com/jQuery.inArray/). ie. `if(isArray($("#installations").val()) && $.inArray("audits", $("#installations").val()){ ...`
Comment: Here is the link to the jsfiddle.  Also, I had to remove the following out of the body in the html code section.  I was having trouble figuring out a workaround.            https://jsfiddle.net/b3ojbghm/
Answer: Using the code you have so far, I assume you probably want something like this:
$('#installations').on('change', function(){
   $("#dbcredentialsfield").toggle($(this).val() == 'audits');
});

This says; when the select element (assuming your dropdown has the id of installations) changes, toggle the visibility of the element with id dbcredentialsfield depending on if the value of the select is audits or not.
Comment: Tried this option including it in the code but wasn't able to get it to work.  I've attached a jsfiddle up above since others were asking.  Thank you for the explanation.  Definitely new at this and actually being described to the process of things is a tremendous help.


Resize XFS Partition (Increase)

Question: I'm new to xfs and was wondering how to increase the size of /var and /home, I'm guessing xfs does not simply increase in size as needed...
Filesystem    Type     Size   Used  Avail Use% Mounted on
/dev/sda1     ext3     4.0G   418M   3.6G  11% /
none      devtmpfs     4.2G   205k   4.2G   1% /dev
none         tmpfs     4.2G      0   4.2G   0% /dev/shm
none         tmpfs     4.2G      0   4.2G   0% /tmp
none         tmpfs     4.2G    58k   4.2G   1% /var/run
none         tmpfs     4.2G      0   4.2G   0% /var/lock
none         tmpfs     4.2G      0   4.2G   0% /lib/init/rw
/dev/mapper/vg00-usr
               xfs     4.3G   640M   3.7G  15% /usr
/dev/mapper/vg00-var
               xfs     4.3G   657M   3.7G  16% /var
/dev/mapper/vg00-home
               xfs

4.3G   1.9G   2.5G  44% /home

also:
# parted
 /dev/sda
GNU Parted 2.2
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print
Model: Areca ARC-1110-VOL#00 (scsi)
Disk /dev/sda: 1000GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system     Flags
 1      32.3kB  4006MB  4006MB  primary  ext3
 2      4006MB  6013MB  2007MB  primary  linux-swap(v1)
 3      6013MB  1000GB  994GB   primary                  lvm

Answer: You're using LVM, which is good.
As long as the logical volume within which /var and /home reside is bigger than they are now, you can do the resize with xfs_growfs.
First make sure the logical volume you're using for the two partitions is bigger than 3.7G (for /dev/mapper/vg00-var) and 2.5G (for /dev/mapper/vg00-home):
bash$ lvdisplay <partition> | grep 'LV Size'
If the logical partition is bigger (so your FS has room to grow), you're all set.
If it's not, then you need to look at the physical volume group which contains the above logical volume, and make sure there is enough space in there to grow the logical volume first.
Comment: I just saw your comment about 30 seconds after I found this link (took me a while to find it): http://tldp.org/HOWTO/LVM-HOWTO/extendlv.html Thanks though :)
Comment: No problem :) It's a fun concept to get your head around.

Resize XFS Partition (Increase)


Advanced forum: How to modify template of forum list page?

Question: Here's the normal template for Advanced Forum:

I'd like to modify the template of advanced forum so that I can

Remove the elements in red
Rearrange the elements in blue
Edit the elements in green
Display the topic starter's profile2 picture

so that I can achieve the result below:

So far, I've tried editing advanced-forum.naked.topic-list.tpl.php but it doesn't change anything. I've managed to remove some of the content with Panels but I cannot modify what's left over here.
Answer: When I had to do this I found there are lots of template files and it's not obvious what controls what. I ended up putting die() in each one to find out which template file was used for each view, and then a case of trial and error to make the changes I wanted.
When you have worked out which files need editing then you should copy them from:
<code>/sites/all/modules/advanced_forum/styles/naked/advanced-forum.naked.TEMPLATE_NAME.tpl.php
</code>
to your theme at:
<code>/sites/all/themes/YOUR_THEME/templates/advanced-forum.naked.TEMPLATE_NAME.tpl.php
</code>
Any files here will override the ones in the advanced forum themes folder.
Comment: Thanks :)  Now I've found the template file and I notice that they are printing things like $header and $rows. How do I modify the content of these variables? I ran global $rows; dsm($rows); with devel and nothing appears, but when I remove that line, it's clear that $rows contain information. running dsm($user) prints $user correctly so devel is working properly.
Comment: Oh wait, I think I've found what I need here admin/structure/views/view/advanced_forum_topic_list
Comment: Sounds like you've found it - it will be in another template file somewhere.
Comment: ah actually I didn't need to edit the template. I used views to acheive what I needed :)
Comment: Sounds like a good solution - those templates are tricky!
Answer: I achieved what I wanted (rearrange, add and remove fields, and set the display format for the time format) just by using views here : admin/structure/views/view/advanced_forum_topic_list
Answer: Just to update the answer from @Felix Eve - if doing it in your own theme in Drupal 7 (which is recommended) then save the "naked" file here, ie with a hyphen and no "naked":
<code>/sites/all/themes/YOUR_THEME/templates/advanced-forum-TEMPLATE_NAME.tpl.php
</code>
Comment: Thank you so much for this. This `naked` suffix is really weird.


People rejects edit without any reason where question edit is meaningful?

Question: I know this question is asked many time but I need to draw an attention of moderators.
I have made one change. Question was about exporting Magneto 2 orders.
But title of that question was "Script for export products"
And I checked answer as well answer is about to export orders in magneto  2.
So I made a change in question title you can review that here.
https://magento.stackexchange.com/review/suggested-edits/118729
Still, some people have rejected the edit.
So  I don't know what is mean by the user one who rejects such changes which is truly acceptable!!
Answer: You are right that this edit made the title more clear and the majority of the reviewers agreed, so don't worry.
The one reviewer who disagreed might have not looked closely enough because on first sight it doesn't look like a very useful edit: only minor change, redundant adding of "Magento 2" in the title (this is what tags are for) and it's an old question with few views. There are different opinions if the latter actually matters (see Is the date of the question relevant when reviewing suggested edits?) but I tend to approve minor edits more likely if the question is fresh (or still popular).


Terminology for handling probabilities with partial knowledge

Question: Consider a situation where a person has partial knowledge, but we have a more complete picture. For example, suppose that we want to know the probability that a fish is red. Suppose that the person with partial information knows 1/3 of all fish are red, but we know that the particular species is actually red 2/3 of the time. Do these two separate probabilities have special names? If they don't have any standard names, what would you call them?
Comment: They are called "personal probabilities" in the literature on Bayesian statistics, which is the field where the possibility of different probability assessments among different observers is considered.
Comment: When you say "the person might know that 1/3 of fish are red," is this for *all* fish, or for the same species as "we" know about? Maybe your question could be more clear if you name the people and the fish.
Comment: @Kaestur: Updated question. @whuber: I think that is the answer. Do you want to post it as an answer?
Comment: So, one guy knows that at least 1/3 are red, the other guy knows that exactly 2/3 are red? These are just different probabilities. The first one isn't fully specified. All the guy really knows it that the chance of a fish being red is $\ge 1/3 $, which doesn't uniquely determine a probability measure...
Comment: @Casebash: I apologize for circumventing the usual procedure; you're right, it does constitute an answer, so I'll post it as one.
Comment: Is the request for terminology to express only the fact that persons A (p=1/3) and B (p=2/3) hold *different* beliefs, or the distinction between A's partially-informed belief and B's having the true probability and knowing it to be the true one (e.g., because he is a superbeing, or runs the fish farm and genetically engineers the fish colors, or the "fish" are objects in a computer game B has written).  As a third possibility, are you looking for language that expresses degrees of belief/confidence/information/evidence, which A and B happen to possess in different amounts?
Comment: @T: I was asking for terminology to make it clear that a certain probability was based on the knowledge that a particular individual posessed, rather than the complete knowledge available from the question. I am using simply "probability" to refer to the probability from our perspective
Comment: @Casebash: it seems there are several different concepts expressed in the question: (1) states of knowledge, levels of information, degrees of evidence, etc together with a (partial) ordering where some states are "more complete" than others, (2) assignment of probability models based on states of knowledge (and possibly also based on other things that are assigner-dependent), and (3) a "true" probability model that the assignments might converge to as the state of knowledge becomes increasingly complete.  Concepts and setting of statistics (esp. inference) are highly relevant here.
Answer: I would call the second of these a conditional probability when trying to emphasise the difference:
The probability of a chosen fish being red is 1/3.
The conditional probability of a fish being red, given that it is species X, is 2/3.
Comment: That doesn't seem to capture the distinction the OP appears to be trying to draw. I got the impression that both guys knew it was a fish of species X, but differed in their state of knowledge vis-a-vis colours of that species...
Comment: That isn't quite it
Answer: They are called "personal probabilities" in the literature on Bayesian statistics, which is the field where the possibility of different probability assessments among different observers is considered.  You could check out the Wikipedia article on Bayesian probability, for instance.
Comment: There are certainly interpretations (arguably, the standard ones) where the concept of absolutely certain complete information on model parameters makes sense, i.e., classical statistics and statistical inference.  Whether or not Bayesianism uses that concept has no bearing on whether the OP is allowed to use it or ask for terms expressing it.  If you want only to to express the idea that persons A and B have two different values of $p$, or two different priors, there is already a standard term: "different".  Anyway, the poster should clarify his question.
Comment: I don't think that answers the question.  If persons A and B assign different values to a probability, calling both assignments "personal" gives both values equal status. In the question, B knows that 2/3 is the true parameter ("actually red 2/3 of the time") and one wants a term that distinguishes the true model parameters from assumed, estimated, or Bayesian-priored parameters that are not necessarily the true ones.  The question as written seeks a term expressing the difference between the 1/3 might-be, partially informed probability and the certainly-is, full information, value of 2/3.
Comment: I interpreted the question slightly differently, T.  It appears to ask for the terminology, if it exists, in which a probability "we" have can be distinguished from a probability "you" have.  According to the Bayesian/personalist/subjective philosophy, there is no such thing as a "certainly-is, full information," probability.  Regardless of our different interpretations, I don't think you can validly dispute that my response actually answers the question; the point of difference appears to be whether the response is full or correct.  If you believe not, then what alternative are you proposing?
Comment: @T: I won't disagree.  In the back of my mind, though, is the thought that a search on "personal probability" would be much more fruitful than a search on "different" or even "different probability" ;-).


Distance with matrices

Question: Im not sure if the way i solve this problem is right.
Let
$$
A = \begin{bmatrix} 1&-1 \\ 1&4\end{bmatrix}, W = Sp \{ \begin{bmatrix} 0&-1 \\ 1&2\end{bmatrix}, \begin{bmatrix} 1&0 \\ 0&2\end{bmatrix} \}
$$
Find the distance between $A$ and $W$.
My attempt
So what i did was to find the orthogonal projection of $A$ on $W$, call it $u_0$.
After that i calculated the distance using norms: $||A-u_0||$.
Firstly, using inner product i calculated the coefficients of the vectors for the linear combination for $u_0$:
$a_1 = (A,w_1) = 1*0 + (-1)(-1) + 1*1 + 4*2 = 10$
$a_2 = (A,w_2) = 1*1 + (-1)*0 + 1*0 + 4*2 = 9$
Therefore,  $u_0 = 10w_1 + 9w_2 = \begin{bmatrix} 9&-10 \\ 10&38\end{bmatrix}$
Now, calculate the distance from $A$ to $u_0$:
$$
||A-u_0|| = ||\begin{bmatrix} -8&-11 \\ -9&-34\end{bmatrix}|| = \sqrt{8^2+11^2+9^2+34^2}
$$
And its a very big number - did i do something wrong?
Thank you.
Comment: Isn't $A=w_1+w_2$? In other words $A \in W$, which makes the distance $0$.
Comment: Good point, so why didnt i get $0$ ?
Answer: Since $A=w_1+w_2$, $A\in W$ which means the distance is $0$. Note that using inner product like you did doesn't help to find the distance. Try to visualize these as vector additions and projections in 2D to understand what I mean.
In general, finding the distance can be reduced to least squares problem. Let us write the equation in vectorized form as
$$\begin{bmatrix}1 \\ 1 \\ -1 \\ 4\end{bmatrix}=\begin{bmatrix}0&1 \\ 1&0 \\ -1&0 \\ 2&2\end{bmatrix}\begin{bmatrix}a_1 \\ a_2\end{bmatrix}$$
Mutiply from the left with $W^T$ you get
$$\begin{bmatrix}10 \\ 9\end{bmatrix}=\begin{bmatrix}6&4 \\ 4&5\end{bmatrix}\begin{bmatrix}a_1 \\ a_2\end{bmatrix}$$
which gives the solution $a_1=a_2=1$ and consequently $A=u_0$ as expected.
Notice how the inner product result you found appears on the left side. This inner product doesn't immediately gives the coefficients unless the base is orthonormal.

Distance with matrices


Why does a margin appears when the div size is changed by translate3d?

Question: When I change the div size, an indent appears between the blocks.

test2

hello

hello

Help me how to remove it?

.container {
    perspective: 600px;
    transform-style: preserve-3d;
}
.test2 {
    /* more to fiddle */
    transform: rotateX(45deg);
    transform-origin: center top;
}
.test3 {
    /* more to fiddle */
    transform: translate3d(0,-34px,0) rotate3d(1,0,0,-45deg);
    transform-origin: center bottom;
}

test1

test2

test3

Without margin:
With margin:
https://jsfiddle.net/gipahs/ved2q3vd/9/
P.S. I see CSS transform 3d cube offsets, but I think that's different problem.
Comment: which size you mean ?
Comment: @TemaniAfif The OP means when adding content to .test2 class container.
Comment: I got the fix for when extra items are added for the bottom two divs but the top div doesn't align then which has no transformation.
Answer: what you have is not margin but a logical space added due to the transfomation you are using. You may notice that you added a translation to fix this issue at the first try.
Imagine you have a closed window and when you open both sides you will be able to see space between both side which is logical as you applied a rotation to both sides :

So the rotation of your div will create the same effect :

So to fix it you can apply a translation like you did with the first one but you will notice that both side won't have the same width because both div doesn't have the same height and a rotation with same angle will make width different (this is perspective, a close object look bigger that a far one)

So to fix this you have to also add translation on the Z-axis to make the second div more closer and have this :

Full code :

.container
{
    perspective: 600px;
    transform-style: preserve-3d;
}

.test1
{
    background-color: #fff;
    border: 1px solid #ccc;
    width: 50%;
    padding: 1em;
    margin: auto;
}

.test2
{
    background-color: #fff;
    border: 1px solid #ccc;
    position: relative;
    width: 50%;
    padding: 1em;
    margin: auto;

    transform: rotateX(45deg);
    transform-origin: center top;
    outline: 1px solid transparent;

}

.test3
{
    background-color: #fff;
    border: 1px solid #ccc;
    position: relative;
    width: 50%;
    padding: 1em;
    margin: auto;

    transform: translate3d(0,-57px,57px) rotate3d(1,0,0,-45deg);
    transform-origin: center bottom;
}

test1

test2

hello

hello

test3

Comment: @TemaniAfif  This is the best example with windows that I have ever seen. Thank you so much. Now I understand where I go next
Comment: But that doesn't fix the width difference.
Comment: @Highdef yes as it's not an issue ... this is a logic effect of the transformation used with two different width ... i think we need to understand that what's happening is not an issue but the normal behavior
Comment: But, I actually got the fix for the bottom two divs to maintain their view with no additonal transformation whatsoever, but the top div is a seperate issue.
Comment: @Highdef *got the fix*, am not sure a fix for what :) but show me so i can see
Answer: Here's one solution (partial) to achieve the fixed view and no seperation whatsoever between the rotated divs.

We're making use of transform-origin:center bottom; for the test2 and transform-origin: center top; for test3. This ensures that those two common edges stay at the fixed width of 50%.
The issue with this approach is if we try to align the test1 which is the topmost div with no rotating or transformation whatsoever, we need to manually adjust its width and margin to make it stick to the top of test2.

Without test1:

.container
{
   perspective:600px;
    transform-style: preserve-3d;
}

.test2
{
    background-color: #fff;
    border: 1px solid #ccc;
    position: relative;
    width: 50%;
    padding: 1em;
    margin: auto;
    transform: rotateX(45deg);
    transform-origin: center bottom;
    outline: 1px solid transparent;

}

.test3
{
    background-color: #fff;
    border: 1px solid #ccc;
    position: relative;
    max-width: 50%;
    padding: 1em;
    margin: auto;

    transform: rotate3d(1,0,0,-45deg);
    transform-origin: center top;
}

test2

hello

hello

hello

hello

test3

With test1: (without adjustments)

.container
{
   perspective:600px;
    transform-style: preserve-3d;
}

.test1
{
    background-color: #fff;
    border: 1px solid #ccc;
    width: 50%;
    padding: 1em;
    margin: auto;
}

.test2
{
    background-color: #fff;
    border: 1px solid #ccc;
    position: relative;
    width: 50%;
    padding: 1em;
    margin: auto;
    transform: rotateX(45deg);
    transform-origin: center bottom;
    outline: 1px solid transparent;

}

.test3
{
    background-color: #fff;
    border: 1px solid #ccc;
    position: relative;
    max-width: 50%;
    padding: 1em;
    margin: auto;

    transform: rotate3d(1,0,0,-45deg);
    transform-origin: center top;
}

test1

test2

hello

hello

hello

hello

test3

Comment: as you can see you changed the origin of rotation and thus you made the rotation on another axis which is the one between both of them :) .. so it's not a fix but another way to rotate with its own logic and you see that you will have the same *issue*(which is also logic) with the first div
Comment: @TemaniAfif Like I said, one is going to suffer for the others but it fixes the specific problem that OP was facing adjusting the two rotated divs.
Comment: that's why i said there is no issue but we simply need to understand the logic :) i know you got it ... but i think the OP is not understanding this
Comment: @TemaniAfif Yeah, well I hope these 2 solutions might make him understand :)
Comment: i added more details to my answer and another idea on how to keep both divs stay close ;)
Comment: @TemaniAfif And adding another item will mess the layout again. http://prntscr.com/hruibv So readjustments after every other item is added.
Comment: yes for sure, but i think it's clear since we are using fixed value in all the transformation,  there is no generic solution .. it's like building a castle of cards, you change one size of one card and all the castle fall :)
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161910/discussion-between-highdef-and-temani-afif).
Comment: @Highdef Thank you for your help and sample code. I to do it.


Search by typing and show in GridView without reloading page?

Question: how can I search in the database by typing in the txtbox and show the result in GridView without reloading the page every time, I use function getdate(string searchtearm).but not answer....i think my URL in ajax is incorrect.please help me.
My CodeBehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class search : System.Web.UI.Page
{
    string m;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

        }
    }

    [System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod()]
   public  void getdata(string searchtearm)
    {

        if (searchtearm != "")
        {
            DataSet.usersDataTable ouserD1 = new DataSet.usersDataTable();
            DataSetTableAdapters.usersTableAdapter ouserT1 = new DataSetTableAdapters.usersTableAdapter();
            ouserT1.FillBy_dhearchPeople(ouserD1,searchtearm);

            GridView1.DataSource = ouserD1;
            GridView1.DataBind();

        }

    }

My Aspx Page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="search.aspx.cs" Inherits="search" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

searching your friends

        <input type="search" id="txtsearch" name="txtsearch"    placeholder="Type to start searching ..."  runat="server" autocomplete="off"/>

         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  >
                                <Columns>
                                    <asp:TemplateField>
                                        <ItemTemplate>

                                            <asp:Image ID="Image1" runat="server" Width="50px" Height="50px" ImageUrl='<%# Eval("picture") %>' />
                                            <asp:Label ID="lblsearch" runat="server" Text='<%# Eval("username") %>'></asp:Label>
                                            <asp:Button ID="btnFollow" runat="server" Text="follow" BackColor="White" OnClick="Button1_Click" />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>

    </form>

    <form id="form1" runat="server">

searching your friends

        <input type="search" id="txtsearch" name="txtsearch"   placeholder="Type to start searching ..."  runat="server" autocomplete="off"/>

         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  >
                                <Columns>
                                    <asp:TemplateField>
                                        <ItemTemplate>

                                            <asp:Image ID="Image1" runat="server" Width="50px" Height="50px" ImageUrl='<%# Eval("picture") %>' />
                                            <asp:Label ID="lblsearch" runat="server" Text='<%# Eval("username") %>'></asp:Label>
                                            <asp:Button ID="btnFollow" runat="server" Text="follow" BackColor="White" OnClick="Button1_Click" />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>

    </form>

Answer: Webmethod needs to be static. So change your function accordingly:
 [System.Web.Script.Services.ScriptMethod()]
 [System.Web.Services.WebMethod()]
 public static void getdata(string searchtearm)
 {
 }

Please check WebMethod needs to be static
To bind Gridview using Ajax and WebMethod, you need to change your code as below:
         var gridView = '<%= GridView1.ClientID %>';
         $.ajax({
                type: "GET",
                url: "search.aspx/getdata",
                data: { mysearch: $("txtsearch").html() },
                success: function (response) {

                 $("#" + gridView).empty();
                 //if response contains data , create table using for loop
                }

            });

Please check Bind GridView using Ajax
Comment: if use static ...error is for '     GridView1.DataSource = ouserD1;
            GridView1.DataBind();'
Comment: @yasin, what you are trying to do is not possible, as WebMethod is stateless. If you want to bind Gridview using Ajax and WebMethod, you need to modify your html side code.Please check https://www.codeproject.com/Tips/775585/Bind-Gridview-using-AJAX. I will update answer too
Comment: i want to bind data by    '

'


How do I solve a least square regression equation (see description)?

Question:
For instance, how do I solve this for Delta13Cleaf = -23? The plusminus signs dont represent standard error, because for a given Delta13Cleaf, multiple values (or an interval, not sure) for MAP are computed. The author furthermore doesn't give a much more information than this, but another clue is that he gives three calculated MAPs: Mininum, maximum, and mean, with the mean not being the mean of the minimum and maximum value.
If someone would explain how to solve this, that would be great.
Source equation: Amiot et al, Environment and ecology of East Asian dinosaurs during the Early Cretaceous inferred from stable oxygen and carbon isotopes in apatite (2015)
Comment: The equations you write have no apparent connection to the contents of the image; nothing is explained; no background or context is given.  There isn't anything to be "solved."
Comment: How does the equation you give relate to a regression model and its least square solution?
Comment: Thank you.  Still, there is nothing to "solve" here: this is announcing the result of fitting a line to data pairs of the form $(\Delta^{13}C_\text{leaf},\log(\text{MAP}))$. The "$\pm$" are probably some kind of standard errors or confidence intervals for the coefficients that should be explained somewhere in the paper: their meaning cannot be determined just from this excerpt.
Comment: @MichaelChernick Are you referring to the equation on the picture or on my a, b, c, d example?
Comment: @whuber what is unclear about this question?
Comment: @whuber I just gave an example on how to I thought normally to deal with the plusminus stuff. Anyway, i deleted it. Thanks for the correction and making the image visible.
Comment: @whuber He doesnt mention anything like that unfortunately. He does, however, calculate a mean, max, and min MAP, that's all I know, and this mean is not calculated als the average of the min of max. So that seems very weird.
Answer: Read it like this:
(0.082 +/- 0.0102) * delta13C + (1.3726 +/- 0.1875)
In other words, to calculate the mean you/I only need to do:
0.082 * delta13C + 1.3726


Footballers with most free kicks scored

Question: Who are the footballers with most free kicks scored? We all remember Juninho Pernambucano, but who else?
Comment: From your posts it seems that you are interested in various statistics and trivia. If you find something interesting, feel free to post such stuff also in [Sports News chatroom](https://chat.stackexchange.com/rooms/info/29021/sports-news). See the beginning of the transcript for an explanation [what is the intended purpose of this room](https://chat.stackexchange.com/transcript/29021/2015/9/11), (In chat you can post things which would not be a good fit for a question on the main site, but are still interesting for sports fans.)
Answer:

#
Player
Goals

1
Juninho Pernambucano
77

2
Pelé
70

3
Víctor Legrotaglie
66

3
Ronaldinho Gaúcho
66

5
Lionel Messi
65

5
David Beckham
65

7
Diego Armando Maradona
62

7
Zico
62

9
Cristiano Ronaldo
60

9
Ronald Koeman
60

10
Rogério Ceni
59

10
Marcelinho Carioca
59

13
Kostas Frantzeskos
57

Last update: 8 September 2023
Sources:

Sport (Wayback Machine)
Messi Stats

Footballers with most free kicks scored


QuadTree or Octree templatized implementation in C++

Question: I'm going to write a templatized implementation of a KDTree, which for now should only work as Quadtree or Octree for a BarnesHut implementation.
The crucial point here is the design, I would like to specify the number of dimension where the tree is defined as template parameter and then simply declare some common methods, which automatically behave the correct way (I think some template specialization is needed then).
I would like to specialize the template in order to have 2^2 (quadtree) or 2^3 (octree) nodes.
Do someone have some design ideas? I would like to avoid inheritance because it constrains me to do dynamic memory allocation rather than static allocations.
Here N can be 2 or 3
template<int N>
class NTree
{
public:
    NTree<N>( const std::vector<Mass *> &);
    ~NTree<N>()
    {
       for (int i=0; i<pow(2,N); i++)
          delete nodes[i];
    }
 private:
    void insert<N>( Mass *m );
    NTree *nodes[pow(2,N)]; // is it possible in a templatized way?
};

Another problem is that quadtree has 4 nodes but 2 dimension, octree has 8 nodes, but 3 dimension, i.e. number of nodes is 2^dimension. Can I specify this via template-metaprogramming? I would like to keep the number 4 and 8 so the loop unroller can be faster.
Thank you!
Comment: You are using the term "leaf" incorrectly, the correct term is "node".  A "leaf" is a node without any children.
Comment: You are also mixing kdtrees and quad/octree incorrectly, they're not the same (i.e. a 2D-tree is not equal to a quadtree)..
Comment: Right, I simply want a n-ary tree which behaves like quadtree in 2D and octree in 3D, I'm editing the question.
Answer: You can use 1 << N instead of pow(2, N).  This works because 1 << N is a compile-time constant, whereas pow(2, N) is not a compile time constant (even though it will be evaluated at compile-time anyway).
Comment: Nice idea! thank you! Do you also think a templatized implementation of this kind is feasible or good?
Comment: No.  I think the template code will be more difficult to write and read than two separate implementations: one quadtree and one octree.  It is unlikely that you will encounter N=2 since we have better data structures specialized for one-dimensional data, and N>3 is unlikely due to the exponential growth of the size of each node.
Comment: You're right, but I'm also using a templatized linear algebra library for vector and matrix operations (eigen), it seems is a matter of checking if N==2 or N==3, and then write the code consequently. I wanted to join the two implementations for maintenance purposes. I'll keep you informed
Answer: If you are using a C++11 compiler that supports constexpr you could write yourself a constexpr-version of pow to do the calculation at runtime.
Comment: You can do that in C++03 as well. A simple recursive template meta-function for integral powers is really easy to make. Bud if the base is always 2, you're far better off with bit shifting, as Dietrich Epp suggests.
Comment: Unfortunately I can't have such compiler, and some features of C++11 are still obscure to me :P


Most common C++ project directory structure convention with respect to third-party libraries

Question: I'm kind of new to C++ (learning some game programming stuff) and I want to set up my directory structure using common conventions. My main point of confusion, which I haven't seen a clear recommendation for, is where I put dependencies. For example, I'm going to be looking at FreeGLUT and FreeType. The first thing I've downloaded is the MSVC build of FreeGLUT and it comes with a subdirectory structure like so:
<code>bin/
    freeglut.dll
    x64/
        freeglut.dll
include/
    GL/
        someheaders.h ...
lib/
    freeglut.lib
    x64/
        freeglut.lib
readme.txt
</code>
The C# developer in me wants to create a subdirectory called "Dependencies" within my solution directory, take all of this and put it in its own subdirectory there, and then do the same with any other libraries, similar to the NuGet packages directory, then reference the appropriate locations when building. I'm not 100% sure but I'm guessing this might be messy with regards to referencing header files if they're scattered throughout different subdirectories, given that you don't just "Add References" in C++ like you do in C#.
Should my dependencies be part of my project? Should I break them out into different base folders? What's the standard thing to do?
n.b. I understand that lib or dll is a choice (i.e. you don't use both in your build)
Comment: Hmm, my question is a possible duplicate of http://stackoverflow.com/questions/3605484/where-should-i-put-third-party-libraries
Comment: Wrong focus, consider how you are going to organize your source control.   So that it can still check-out 5 years from and rebuild the exact same binaries.  The C++ compiler and linker won't stop you.  Look at github projects if you need inspiration.
Comment: Libraries are frequently shared between projects, so they rarely fit very well as a subordinate to a single project.
Answer: The more-or-less standard solution is as follows:

In your main source control repository, you store only the source files and the build system files required to compile them. No binary dependencies at all.
If the dependencies are nontrivial to obtain and install, make a secondary repository and put the dependencies there.
If you need to use an external library with some modifications and upstream won't accept them, either put its complete modified source tree into your main source control and integrate its build process into the build process of your application (in-tree fork), or store the modified source in yet another repository (out-of-tree fork). Note that if you use an in-tree fork, most licenses will require you to make your program open source. With others, e.g. LGPL, you can just publish the source code of the out-of-tree fork.

This is what e.g. the Inkscape project does: there is a main repository at https://launchpad.net/inkscape with the complete source code of the project, and there is a separate repository at https://launchpad.net/inkscape-devlibs with the binaries of the dependencies required to build under Windows.
This way you will avoid cluttering up the revision history with dependency changes and storing large binary files in your main tree.


3 relationships within each others for subscription

Question: I have hashtags and users can subscribe them. here is what I did for subscription:
function hashtag(){
    return $this->belongsToMany('App\Hashtag');
}

And also there is user relationship in Subscription Model:
function user(){
    return $this->belongsToMany('App\User');
}

The user Model has subscribes which is supposed to give me the hashtags that the Authed user subscribes. Here it is:
function subscribes(){
    return $this->hasMany('App\Subscription');
}

Now with this code I tried to access the hashtags the Authed user subscribes here is the view code:
@foreach(Auth::user()->subscribes->hashtag as $tags)
    {{ $tags->name }}
@endforeach

What I think is that, laravel expects a relationship table here, called hashtag_subscription or something like that. Now I got a bit confused with these relationships. I highy prefer to get around this withput creating extra table, I feel like I can accomplish it without an extra table.
Tables are as following:user, hashtag, subscription
Models: Hashtag, Subscription, User
Answer: You need to change your relationships first, because as I understood you one Subscription model has One-To-One relationship to both User and Hashtag:
function hashtag() {
    return $this->belongsTo('App\Hashtag');
}

function user() {
    return $this->belongsTo('App\User');
}

Then you can loop through user subscriptions and have access to both Hashtag and user to whom the initial user is subscribed to:
@foreach(Auth::user()->subscribes as $subs)
    {{ $subs->user->firstname }}
    {{ $subs->hashtag->name }}
@endforeach

Comment: I tried that, it expects. Table called hashtag_subscription. But in my opinion there is no need to that.
Comment: One subscription can have one hashtag?
Comment: That is right. Think of it as youtube channels subscription. One user subscribes a channel. The subscription is one to one right?
Comment: I guess I had to put belongsTo instead of belongsToMany right?


Contextual filter to show only nodes of the same type

Question: I am trying to create a View that will be a sidebar block on node pages of various content types. The View is pretty basic, just a linked title. I figured I could use Contextual Filters (what used to be Views Arguments in Drupal 6) so I don't have to set up many Views that will all be the same and just use one for all.
My goal is to get only nodes in the sidebar block View of the same type to show up on a node page. So for example on a single Blog node page, the sidebar View will only show other blog stories. However, that same View on a News content type node page will only show other News stories in the View sidebar block and so on...
I have various content types including "News", "Services" and "Blog".
Here is what I have tried so far.

Set up the basic View, showing linked titles.
Added a contextual filter using Content: Type
"When the filter value is NOT available"

Provide default value >> Content id from URL

"When the filter value IS available or a default is provided"

"Specify validation criteria" >> Validator >> Content >> Checked off the content types I want i.e. Blog, News, Services.

After I save this, no data shows up on any of the node pages.  I also tried playing around with other various options in the Contextual settings but to no avail. My google-foo is also failing as everything I found for something like this deals with Taxonomy and that's not what I am after here.
Comment: Maybe duplicate of http://drupal.stackexchange.com/questions/11979/contextual-filters-and-node-types
Comment: If you were using Panels, you could do this by making your view a Content Pane instead of a Block and setting the argument input for the contextual filter to `context: content type` in the Views UI.
Comment: @MohammadAliAkbari - yes, I think it is a duplicate. Thanks.
Comment: @Patrick Kenny I tried that using panels as well and setting my view to Content Pane but from the Panels itself there is no way I could specify a context to be content type. It gives me all sorts of options but no content type. Or should I select Node ID (of the content type)?
Answer: I don't think you can do it with a contextual filter (without using coding).
Just build a view (with block output) for each of the types and then use a filter criteria "content type = news", etc.
It's pretty easy since you can clone the view, then just override the type and change the block name.
Comment: Yes, easy but not necessarily efficient. The whole point was to find something that I would not have to duplicate over and over.
Answer: Add path aliases by pathauto for each content type.
create a view with block and to show contents or fields of contents , then add the Contextual filter : Content: type.
From WHEN THE FILTERT VALUE IS NOT AVAILABLE section choose provide default value then select "Raw id from the URL" with depth 1 and check the "use path alias" selected. the view block will work fine. you shoud user views3 to get this worked.
Comment: I did the same thing but for some reason it still doesn't work!
Answer: You could provide code like this answer, though PHP is often not available for good security reasons. Ultimately, you'd want to use (or create, if one is not available) a module that provides this functionality to the contextual filters section of the views module.


Working on Drupal and Drush with teammates

Question: I'm currently working on a website using Drupal 8, with 3 other members in my team.
We use git as a versioning system, and we very often work at the same time on different branches.
Here is the problem :

If we all use local databases, then it's a mess when we have to merge our code, because we have to isolate the parts of the database that have changed, and create a patch, or re-create the changes ourselves a second time.
For example if I have created many static pages, I have to create them again, or export the part of the database containing them.
If we choose to share a database to avoid that problem, then every time someone runs the drush cr command, everyone's website gets synched to their last changes, erasing every other changes from other teammate, which can be very confusing and annoying.

What is the right solution here?
Comment: Are you familiar with these docs: https://www.drupal.org/documentation/administer/config and https://www.drupal.org/node/1667894 ?
Comment: @DavidThomas I wasn't familiar with it. Although I'm not sure it will solve my problem. If I work with several people at the same time, we have several dev environment, everyone can export their own configuration and import it on the live environment, but we will still step on each other's toes, won't we? I'll export my configuration, then my coworker will export his, and it will erase mine...
Answer: Checkout configuration management in Drupal 8. Though there are many modules that can help you out but most of them are in active development and not stable for production use yet.
Two most promising modules are Configuration Update module and Features module.
Checkout What are the alternatives to Features module in Drupal 8 for further notes.


Trusted redirect response

Question: I installed version 8.3.7 and today the version 8.4.0 (NOT localhost, multilingual or not), using PHP 7.0.13, MySQL 5.6.22, and made the proper settings apparently. I read about this problem, which generates this error:

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

I took the necessary steps like changing the settings.php file and inserting:
<code>$settings['trusted_host_patterns'] = [
  '^gersonvagner\.com$',
  '^www\.gersonvagner\.com$',
];
</code>
However, the problem persists in all instances, for example when I try to put the site under maintenance or try run cron. I don't know where else I might be going for more than a week of testing and reading. If anyone can help me.
Every time I go to validate any action in the administrative environment it returns me with this message, anyway, the changes are accepted, but always this message is shown to me. Examples: If I run cron for updates, it runs and the message appears successful, but after the screen with the message I mentioned earlier. If I put or remove the site from the maintenance mode, the same occurs, that is, the site enters or leaves the maintenance with success, but I will only know this if I return to the domain and see the status, because the screen that always appears next is with this message: "Redirects to external URLs ...". This is repeated in all changes that are made in the admin environment, such as installing or uninstalling modules or templates. I don't see what I am doing wrong.
Comment: `$settings['trusted_host_patterns']` isn't used for `TrustedRedirectResponse`.  It just validated the 'Host' header in the HTTP request to make sure it is valid.  We need a little more information on how/what is generating your redirect here.
Comment: Are you using a `RedirectResponse` somewhere that is linking to an external site?
Comment: @Kevin, no, I don't do this, only trying to configurate simples things, how as I say.
Comment: @mpdonadio, I was edited the question, but I dont know what more I need to say... if you guide me with your doubts.
Comment: Do you run a multi-lingual site? - https://www.drupal.org/node/2643466
Comment: @rooby, yes. Three languages: Portuguese is primary, and the other two are English and Spanish. But before Im try this patch, Im using PHP 7.0.13, MySQL 5.6.22 and Drupal 8.3.7. This patch was indicated for PHP 5.5 MySQL 5.5 and Drupal 8, that is, by previous versions, and is not a official solution.
Comment: @gersonvagner the patch still applies to Drupal 8.3.7 and I expect it shold also work fine with PHP 7. have you tried the patch? Knowing whether or not it fixes your particular issue would help narrow down your options.
Comment: @rooby, ok, im try this, but the same problem to be continued. Im try too
https://www.drupal.org/node/2863184, but not fix this.
Comment: The same problem occours in 8.4.0... oh God! Will be the server?
Comment: My foolishness! I just needed to uncomment 'RewriteBase /' in '.htacess'. I can not believe it was just that. I feel foolish, but I never forget this small detail. Many thanks for the support!
Answer: For me, I just needed to uncomment 'RewriteBase /' in '.htacess'. Working now. I had forgotten this little detail.

Trusted redirect response


Why does deduction fail for std::set in GCC?

Question: I have a std::set which allows deduction from an iterator range.
#include <iostream>
#include <set>

int main()
{
   std::set s1 = {1,2,3,4};
   std::set s2(s1.begin(), s1.end());
}

The above program failed to compile in GCC.
Why does deduction fail for std::set here?
Comment: @Kevin (and Ron) C++17 added class template argument deduction. The question is why it isn't implemented for the iterators constructor.
Comment: @Ron it is, in the tags :)
Comment: According to the [GCC feature matrix](https://gcc.gnu.org/projects/cxx-status.html) _Template argument deduction for class templates_ should be in version 7.
Comment: @YSC the matrix shows the core feature. It works in gcc7 (s1 initialisation compiles)
Answer: Just take the current GCC version (8.0.0 at this time) and it will build. The template deduction guide for std::set just doesn't seem to be implemented in the older GCC version's stdlib.
Answer: Deduction guides for the iterators constructors of std::set was only recently added to gcc HEAD.
According to gcc-mirror/gcc at GitHub, the deduction guides for std::set's iterators constructor(s) was added and merged to libstdc++-v3 less than two weeks ago,

(Extract from diff for libstdc++-v3/include/bits/stl_set.h)
 +#if __cpp_deduction_guides >= 201606
 +
 +  template<typename _InputIterator,
 +       typename _Compare =
 +         less<typename iterator_traits<_InputIterator>::value_type>,
 +       typename _Allocator =
 +         allocator<typename iterator_traits<_InputIterator>::value_type>,
 +       typename = _RequireInputIter<_InputIterator>,
 +       typename = _RequireAllocator<_Allocator>>
 +    set(_InputIterator, _InputIterator,
 +    _Compare = _Compare(), _Allocator = _Allocator())
 +    -> set<typename iterator_traits<_InputIterator>::value_type,
 +      _Compare, _Allocator>;
 +
 +  template<typename _Key, typename _Compare = less<_Key>,
 +       typename _Allocator = allocator<_Key>,
 +       typename = _RequireAllocator<_Allocator>>
 +    set(initializer_list<_Key>,
 +    _Compare = _Compare(), _Allocator = _Allocator())
 +    -> set<_Key, _Compare, _Allocator>;
 +
 +  template<typename _InputIterator, typename _Allocator,
 +       typename = _RequireInputIter<_InputIterator>,
 +       typename = _RequireAllocator<_Allocator>>
 +    set(_InputIterator, _InputIterator, _Allocator)
 +    -> set<typename iterator_traits<_InputIterator>::value_type,
 +       less<typename iterator_traits<_InputIterator>::value_type>,
 +       _Allocator>;
 +
 +  template<typename _Key, typename _Allocator,
 +       typename = _RequireAllocator<_Allocator>>
 +    set(initializer_list<_Key>, _Allocator)
 +    -> set<_Key, less<_Key>, _Allocator>;
 +
 +#endif

This naturally explains why template argument deduction fails for the templated set by iterator(s) constructors for earlier versions of gcc, e.g. 7.2.0. If using the current gcc trunk (gcc HEAD 8.0.0 20171103 (experimental)) the deduction guides above are available, and the template argument deduction is successful also for the iterator(s) constructors.
As for why the template argument deduction is successful already in gcc 7.2.0 for the std::initializer_list constructors (without deduction guides; guides that was also added in the commit above), as was somewhat explained in @JohnZwinck deleted answer, these constructors are not templated themselves (not parameterized by their own template parameter list), but use set's member type value_type—which is simply a typedef of the set's first template type parameter Key—as template argument to the std::initializer list, which I would assume results in a simple enough deduction path to succeed even without and explicit deduction guide.


Insert valores da tabelaB na tabelaA se os mesmos não existirem

Question: Normalmente, quando trabalhamos com um insert em tabelaA se baseando no select de uma tabelaB, fazemos algo similar a isso:
INSERT INTO tabelaA ( column1, column2, someInt, someVarChar )
SELECT  tabelaB.column1, tabelaB.column2, 8, 'some string etc.'
FROM    tabelaB

Porém, o meu problema é que eu preciso validar se os dados já não existem na tabelaA, pois se existirem, o insert não será feito
Comment: Talvez um `WHERE NOT EXISTS Xyz` ?
Comment: @RafaelWithoeft Poderia por gentileza demonstrar como ficaria a estrutura?
Comment: Achei um exemplo para você, espero que ajude: http://stackoverflow.com/questions/3164505/mysql-insert-record-if-not-exists-in-table
Answer: Fica assim:
INSERT INTO tabelaA ( column1, column2, someInt, someVarChar )
SELECT  tabelaB.column1, tabelaB.column2, 8, 'some string etc.'
FROM    tabelaB
where not exists (select 1
                  from tabelaA a2
                  where a2.column1 = tabelaB.column1
                  and s2.column2 = tabelaB.column2
                  and ...)

Coloquei reticências porque não sei todas as condições, mas basta completar com mais condições (ou simplesmente retirar o and ...).
Answer: Algo assim:
INSERT INTO tabelaA (column1, column2, someInt, someVarChar )
SELECT  tabelaB.column1, tabelaB.column2, 8, 'some string etc.'
FROM    tabelaB
WHERE (SELECT count(Id) FROM tabelaA as valida WHERE valida.column1 = tabelaB.column1) < 1

Answer: Não especificaste qual o SGBD que estas a usar. No entanto, fica aqui uma alternativa para SQL Server que muitas vezes é mais rápida que as respostas que foram já postadas.
MERGE tabelaA AS Target
USING (SELECT column1, column2, someInt, someVarChar FROM tabelaB) AS Source
   ON (Target.column1 = Source.column1 AND Target.column2 = Source.column2 AND (...))
WHEN NOT MATCHED BY TARGET THEN
    INSERT (column1, column2, someInt, someVarChar)
    VALUES (Source.column1, Source.column2, Source.someInt, Source.someVarChar)

Esta forma é também mais flexível caso, no futuro, decidas que precisas de por exemplo, actualizar os registos na tabela de destino caso eles já existam. Isto pode ser feito da seguinte forma:
MERGE tabelaA AS Target
USING (SELECT column1, column2, someInt, someVarChar FROM tabelaB) AS Source
   ON (Target.column1 = Source.column1 AND Target.column2 = Source.column2 AND (...))
WHEN NOT MATCHED BY TARGET THEN
    INSERT (column1, column2, someInt, someVarChar)
    VALUES (Source.column1, Source.column2, Source.someInt, Source.someVarChar)
WHEN MATCHED THEN
    UPDATE SET Target.column1= Source.column1


Can't change add to cart button value

Question: I can't change 'Add to cart' button value (site http://zoo812.ru)
Now it is value="Добавить в корзину", I want to change it to value="buy"
I inserted
function ivanco_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
    $form['submit']['#value'] == t('Buy');
}

in template.php, but it does absolutely nothing.
String overrides also doesn't work.
There is no js code linked with it nor any other mentions about it in theme files.
You see, there is Catalog View, and each item's displayed with Evo.
I can do this with JS of course, but it wont be elegant..
Answer: I've used this code and worked fine:
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit']['#value'] = 'CUSTOM BUTTON VALUE';
    //dpm($form);
  }
}

Can't change add to cart button value


Need to take user inputted string and create several files with user string as part of them

Question: I'm trying to create a number of files in which I define the first part of the filename, then use a user inputted string for the second part.
so if user puts in "filename", I want to create 1TEMPfilename, 1FLUXfilename, 1PRESSUREfilename
so far:
main ()
{

  char filename[64];

  printf("Enter the Runfile ID (e.g. jul0476.a\n");

  fgets(filename,50,stdin);

  //create new files

  FILE *fp;

  fp = fopen('1FINALTEMP'filename,"w");

}

this generates an error, any ideas on how to do this?
Comment: you question is - how do i concatenate strings in c. Use snprintf
Comment: Please show the error message that you receive.
Comment: error is:  warning: multi-character character constant [-Wmultichar]
  fp = fopen('1FINALTEMP'filename,"w");
                   ^
warning: character constant too long for its type
error: expected ')'
  fp = fopen('1FINALTEMP'filename,"w");
                                          ^
note: to match this '('
  fp = fopen('1FINALTEMP'filename,"w");
Comment: use `strcat(str1,filename)` where str1 is `"1FINALTEMP"` before fopen
Comment: if I concatenate the strings won't it change the filename string I'm trying to use? So I'd end up with 1TEMPfilename and 1FLUX1TEMPfilename.... ect?
Comment: using strcat i get an Abort trap 6 error
Comment: Create a 2nd buffer: `char full_name[64]; snprintf(full_name, 64, "1TEMP%s", filename); fp = fopen(full_name, "w");`
Comment: cool that worked! except all my file names end in "?" but I'll sort that out later! Thank you @JohnnyMopp
Comment: More likely, they all end with newline (which you typed when entering the name on stdin, but didn't ever remove).
Comment: BTW, you ought to `#include ` and turn your compiler warnings up a bit - relying on implicit function definitions can cause surprises.
Answer: Don't forget that fgets() would read in the trailing newline (\n) as well. You may want to remove that.
fgets(filename,50,stdin);
filename[strlen(filename)-1]='\0';

After that make the new file names.
char names[3][60];
sprintf(names[0], "1TEMP%s", filename);
sprintf(names[1], "1FLUX%s", filename);
sprintf(names[2], "1PRESSURE%s", filename);

Then use these strings as argument to fopen() like
fopen(names[0], "w");

And check if fopen() succeeded by having a look at its return value. If it's NULL, some error has occurred.
As for fp = fopen('1FINALTEMP'filename,"w"); giving error, '1FINALTEMP' is a string and not a character literal. Single quotes are for character literals. See here.
And only adjacent string literals are concatenated as mentioned here.

Adjacent string literal tokens are concatenated.

ie, in printf("%s", "hello " "world");, the "hello " "world" would become "hello world".
But that's only for string literals.
Edit: snprintf() is preferred over sprintf() as the latter may write out of bounds if the string to be written is too large to be stored in the string to which writing occurs. With snprintf(), you can specify the number of bytes to be written.
char name[60];
snprintf(names, 60, "1TEMP%s", filename);

Comment: This fixed everything! Thanks so much
Answer: Try taking a string variable which store filename from fgets and then use '+' and concatenate what you provide (1Finaltemp) then pass it to file pointer like fp= fopen( myNewFile,w)
Comment: You can 't concat strings with `+` in [tag:C].