text:
Q: Knowage autogenerated query understanding I'm using knowage software for data analysis, I'm facing performance issues, now I'm watching 'dataset audit' log to see what queries does the system perform. I found this one that, to me, is a nonsense:
SELECT COUNT(*)
FROM

(select TOP(100) PERCENT "ATC_1" AS "ATC_1"
from

    (SELECT [ID_AFo]
          ,[ATC]
          ,[ATC_1]
          ,[ATC_3]
          ,[ATC_4]
          ,[ATC_5]

      FROM [AFO]

        ) T  order by "ATC_1" ASC
) u

inner T query is the dataset definition query I entered that basically is a select * from [AFO] on my table, outer wrap are made by knowage (I never wrote them)
doesn't a select count (*) from T have performed the same calculation but avoiding a cexpensive order by?
EDIT:
Backend (data source) is MSSQL, cache server is MYSQL so frequent queries are on mysql

A: This query is equivalent to:
SELECT COUNT(*)
FROM [AFO];

The only reason that I can think of for constructing such a query is if the "100" could be set to another value.  I'm not sure if SQL Server's optimizer is good enough to eliminate the ORDER BY in the subquery.


text:
Q: PlotLegends won't generate automatically more than 15 labels in v10 Update: NOT fixed in V10.0 - 12.0.0

While testing the examples from this recent post, i've noticed a problem in V.10 with PlotLegends when it has to automatically generate more than 15 labels (i.e. when there are more then 15 functions to plot). There's no problem with V.9.
The problem concerns the option values : Automatic and "Expressions". For example :
Plot[Evaluate[Range[20] + x], {x, -5, 5}, PlotLegends -> "Expressions"]

Plot[Evaluate[Range[20] + x], {x, -5, 5}, PlotLegends -> Automatic]

No problem however when you specify explicitly the labels in the legend :
Plot[Evaluate[Range[20] + x], {x, -5, 5}, PlotLegends -> Range[20]]

A: You can use indexed colors as color function to generate as many distinct colors as you like. For example, although
Length @ ColorData[97, "ColorList"]

15

we can generate 100 distinct colors mapping ColorData[97] on Range[100]
ColorData[97] /@ Range[100] // CountDistinct

100

ColorData[97, "Range"]

{1, ∞, 1}

ColorData[97, "ColorFunction"]

ColorData[97, "ColorFunction"] // InputForm

A nice illustration suggested by @Mr.Wizard in comments:
ArrayPlot[Partition[ColorData[97] /@ Range[500], 21],
 Mesh -> All, MeshStyle -> White, ImageSize -> 1 -> 30]

So ... if we use PlotStyle -> (ColorData[97]/@Range[20]) the issue goes away:
Plot[Evaluate[Range[20] + x], {x, -5, 5},
 PlotStyle -> (ColorData[97] /@ Range[20]),
 PlotLegends -> "Expressions"]

and with PlotLegends -> Automatic we get

Note that removing the PlotStyle option or the setting PlotStyle -> 97 or PlotStyle -> ColorData[97] we get only 15 distinct colors:
colorswithdefaultplotstyle =  Cases[Plot[Evaluate[Range[20] + x], {x, -5, 5},
    PlotLegends -> "Expressions"], {Directive[_, col_, ___],
   _Line} :>  col, All];

{Length @ #, CountDistinct @ #} & @ colorswithdefaultplotstyle

{20, 15}

This works for all 113 indexed colors.
$Version

11.3 .0 for Microsoft Windows (64 - bit) (March 7, 2018)

A: We may observe that the automatically generated legend limits the number of legend items to the number of available colors in the given color scheme.  Using this utility function:
plot[scheme_] := Plot[Evaluate[Range[20] + x], {x, -5, 5},
   PlotLegends -> "Expressions", PlotStyle -> scheme]

Observe the result for indexed color scheme #42 which has only four colors:
plot[42]

There are eight in #26:
plot[26]

As since there are 21 in #60 all your lines have a legend:
plot[60]

And if you specify a gradient color scheme:
Plot[Evaluate[Range[50] + x], {x, -5, 5}, PlotLegends -> "Expressions",
 PlotStyle -> "Rainbow"]

redpajama_set_name: RedPajamaStackExchange


text:
Q: java.net.MalformedURLException: unknown protocol: f I am trying to get histogram of an image using this code Displaying a histogram of image data. Normally it works fine when input image given by url. But while I give image from local directory
private BufferedImage getImage() {
    try {
        return ImageIO.read(new URL(
            "F:/test.jpg"));
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return null;
}

it gives exception,
 java.net.MalformedURLException: unknown protocol: f

How to resolve this exception and get Histogram of an image

A: F:/test.jpg is not a valid URL. For files the URL is file://F:/test.jpg
where file is the protocol

A: The protocol is not valid.
If you need to load a file from the filesystem you need to use the file URI scheme

A file URI takes the form of file://host/path
where host is the fully qualified domain name of the system on which the path is accessible, and path is a hierarchical directory path of the form directory/directory/.../name. If host is omitted, it is taken to be "localhost", the machine from which the URL is being interpreted.

So the url should be:
file://F:/test.jpg

A: While the other answers will technically solve your problem, you shouldn't be using a URL for this. There are other signatures for the read function, one which takes a File and one which takes an InputStream instead, so you can use either of the following:
return ImageIO.read(new File("F:/test.jpg"));
// or
return ImageIO.read(new FileInputStream("F:/test.jpg"));


text:
Q: Regex for groups of type 1.2-1.4 or 1.2.3.4-1.3.4.5 or 1.2.3.4.5.6-1.2.3.4.5.7 and so on I want to use this for an ASP.NET validator but the regex expression is what I can't write without first studying a book.
As in the title I want to match something that is of the following format:
1.2-4.394

1.33.321.213-2.324.23.545

The number of dots (.) increases but it must not be divisible by 2

A: That's kind of tricky because it involves balancing groups:
^
(?<nb>                       # First series of numbers
  (?:^|(?<=[0-9])\.)         # BOL or dot
  (?>[0-9]+)\.(?>[0-9]+)     # Number pair
)+
-
(?<-nb>                      # Second series of numbers
  (?>[0-9]+)\.(?>[0-9]+)     # Number pair
  (?:$|\.(?=[0-9]))          # EOL or dot
)+
$
(?(nb)(?!))                  # Make sure the second series has the same digit count

Demo
Used with IgnorePatternWhitespace for readability, you could also write:
^(?<nb>(?:^|(?<=[0-9])\.)(?>[0-9]+)\.(?>[0-9]+))+-(?<-nb>(?>[0-9]+)\.(?>[0-9]+)(?:$|\.(?=[0-9])))+$(?(nb)(?!))

This won't be usable from JavaScript though, as JavaScript has very limited regex features. You should set EnableClientScript on your RegularExpressionValidator to false.

A: And when it's not possible to use ASP.NET magical Regex, and with dots not be divisible by 2 You can do that:
^(?:\d+\.\d+-\d+\.\d+|(?:\d+\.){2}\d+\.\d+-(?:\d+\.){2}\d+\.\d+|(?:\d+\.){4}\d+\.\d+-(?:\d+\.){4}\d+\.\d+|(?:\d+\.){6}\d+\.\d+-(?:\d+\.){6}\d+\.\d+|(?:\d+\.){8}\d+\.\d+-(?:\d+\.){8}\d+\.\d+)$

But that work only for 1, 3, 5, 7, 9 dots (before and after the -)...
Test: here


text:
Q: Elasticsearch query returning far less number of records I am running following elasticsearch query from groovy script. There are thousands of records which meet this criteria, but I get only 10 records in return.
{
"query":{
  "bool":{
     "must":[
        {
           "match_all":{

           }
        },
        {
           "range":{
              "@Timestamp":{
                 "gte":1417511269270,
                 "lte":1575277669270,
                 "format":"epoch_millis"
              }
           }
        },
        {
           "match_phrase":{
              "field1.keyword":{
                 "query":"value1"
              }
           }
        },
        {
           "match_phrase":{
              "field2.keyword":{
                 "query":"value2"
              }
           }
        },
        {
           "range":{
              "@Timestamp":{
                 "gte":"2001-03-01",
                 "lt":"2019-10-30"
              }
           }
        }
     ],
     "filter":[

     ],
     "should":[

     ],
     "must_not":[

     ]
  }
 }
}

What am I missing in my query?

A: You are missing a size parameter, which means it defaults to 10 results.
e.g. add this to your query object:
"size": 100


text:
Q: WinXP - Having trouble sharing internet with 3G USB modem via ICS all! I've been banging my head against a wall with this issue for a few days now and am hoping someone can help out.
I recently signed up for T-Mobile's webConnect 3G/4G service to replace the faltering (and slow) DSL connection in my apartment. The goal was to put the SIM in one of my old phones and use its built-in WLAN tethering feature to share Internet out to rest of my computers. I quickly found out that webConnect-provisioned SIMs do not work with regular smartphones, so I was forced to either buy a 4G-compatible router or tether one of my old laptops to my wireless router and share out that way. I chose the latter, and it's sharpening my inner masochistic self by the day.
Here's the setup:
*
*GSM USB modem (via hub), ICS host ->
*10/100 Mbps Ethernet NIC, ICS "guest" ->
*WAN port of my SMC WGBR14N wireless router in bridged mode (i.e. wireless access point). Ideally, this would make my laptop the DHCP server and internet gateway with the WAP giving everyone wireless coverage. I can browse internet on the host laptop fine.
However, when clients try to connect, they get a DHCP-assigned IP from the laptop and are able to use the Internet for a few minutes before completely dying. After that happens, they are able to re-associate with the WAP and get IP addresses, but are unable to use Internet or resolve IP addresses until the laptop and router are restarted. If they do get access, it's very, very slow. After running Wireshark on the host machine, it turns out that this is because every TCP connection keeps getting RST. DNS seems to work.
I would normally think the firewall is the culprit here, but when it drops packets, it drops them completely. The fact that TCP connections are being ACK'ed by the destination rules that out. Of course, none of the event Log isn't saying anything about what's going on. I also tried disabling power management on the NIC, since that's caused problems in the past; that didn't help either. I finally disabled receive-side scaling as per a Microsoft KB (that applied to Windows Server 2003, SP2) to no avail. I'm thinking of trying it with a different NIC (will be tough; don't have a spare Ethernet NIC around for the laptop), but I'm getting the impression that this simply doesn't work.
Can anyone please advise? I apologise for the length of this post; all contributions are much appreciated!
-Carlos.

A: It sucks that this didn't get a lot of attention, but then again, normal folks have some sort of dedicated connection instead of this setup.
After playing around with it for a good while, I'm finally convinced that ICS is fundamentally broken. It seems that its biggest problem is with the stability of the built-in ICS DHCP server. Sometimes, DHCP will try to work but will route DHCP requests to the hosting NIC instead of serving DHCP requests on its own. I would get link-local addresses when this happens. Other times, the DHCP server will quit working entirely by letting DHCP requests go completely unanswered. I think these two problems happen in succession, but not too sure.
I have no idea why the TCP connections start RSTing after a while. I noticed some errors from Tcpip in event viewer, so I think it has something to do with winsock getting corrupted. Now that I think about it, perhaps the DHCP issues are related to that as well.
The only way I was able to get this to work with some stability is by doing the following:

*

*Stopping ICS by unsharing my connection from the modem,

*Disabling both NICS,

*Resetting winsock by using netsh (netsh winsock reset). I don't reboot.

*Re-enabling both NICs, and finally

*Re-enabling ICS by sharing the modem connection again.

With this in mind, is there any way to enable winsock logging to see whether the underlying issue presents itself there?
Combined with everything else I did, I have no idea how long this will work for. Hopefully, it'll work long enough to set me over until I get the Cradlepoint modem I bought.
Hope this helps someone!

A: ICS uses a fixed IP range, 192.168.1.0/24 if I'm not mistaken (I could be).  Make sure this does not conflict with the IP/subnet on your SMC WGBR14N.
It is also possible your 4G modem may be detecting the TTL of outgoing traffic and eventually terminating connections or dropping its PPP session if the TTL isn't what it suspects, this is a way to discover if traffic is originating from the connected system or one "behind" it.


text:
Q: How to resolve the CSS warning in Firefox 71 version I got the CSS warning in console window when load the my page in Firefox's latest version (71.0). Please find the list of warning on below.
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped. material.css:3943:11
Unknown pseudo-class or pseudo-element '-ms-clear'.  Ruleset ignored due to bad selector. material.css:3958:15
Unknown pseudo-class or pseudo-element '-ms-input-placeholder'.  Ruleset ignored due to bad selector. material.css:3988:15
Unknown pseudo-class or pseudo-element '-ms-input-placeholder'.  Ruleset ignored due to bad selector.

Unknown pseudo-class or pseudo-element '-webkit-autofill'.  Ruleset ignored due to bad selector. material.css:5611:40
Unknown pseudo-class or pseudo-element '-ms-textarea-placeholder'.  Ruleset ignored due to bad selector.

Keyframe rule ignored due to bad selector. material.css:540:13
Error in parsing value for 'margin-right'.  Declaration dropped.

Can you please provide a solution to resolve the warning from the Firefox browser.
Thanks
Gobala

A: The warning is just that - a warning, not an error.
In effect, it is saying
"I don't know what this -ms-input-placeholder is, so I'm going to ignore it."
That's exactly what you want to happen, you want this specific browser to ignore any styling that is defined for a specific other browser.


text:
Q: chi square test for independence I am going to use Chi-squre test to see if two categorical variable are independent or not and I just realized the number of observation can affect the result of test:
Data set 1:
    Group 1      Group 2
A    10              20
B    30              40

Date Set2:
    Group 1      Group 2
A    100              200
B    300              400

The result of test for the second data set is 10 times bigger than the first data set and it affect the result rejecting/accepting null hypothesis.
As the ration of groups in both data set are the same it does not make sens to me to get two different result...Could you please help me to understand what sort of data I nee to use for chi test?
Thanks,
Amir

A:
As the ration of groups in both data set are the same it does not make sens to me to get two different result

Consider what a $p$-value is supposed to do: to quantify evidence against the null hypothesis, which in this case states that the categories are independent. Under the null hypothesis, you're much less likely to find a joint empirical distribution this far from independence when the sample size is 1,000 than when it's 100. Sure enough, you get a lower $p$-value with the larger sample. This is an example of the rule of thumb that as a sample size increases while the sample effect size stays fixed, the $p$-value decreases. Any good significance test is more powerful with larger samples.

A: This is also a good example to see the difference between p-value and effect size.  As you noted, the p-values for the two tables you present are quite different, but if you calculate a measure of association, such as phi, it will be the same for the two tables.
The examples in R:
if(!require(psych)){install.packages("psych")}

Input =("
Letter  Group.1  Group.2
A       10       20
B       30       40
")

Matrix1 = as.matrix(read.table(textConnection(Input),
                    header=TRUE,
                    row.names=1))

Matrix1

chisq.test(Matrix1)

library(psych)

phi(Matrix1, digits=4)

Input =("
Letter  Group.1  Group.2
A       100       200
B       300       400
")

Matrix2 = as.matrix(read.table(textConnection(Input),
                    header=TRUE,
                    row.names=1))

Matrix2

chisq.test(Matrix2)

library(psych)

phi(Matrix2, digits=4)


text:
Q: Clarification on Some Definition of Inner Product Space Suppose $V$ is finite-dimensional Real vector space and $T\in \mathcal{L}(V)$. Suppose that $V$ has a basis $(e_1,e_2,\ldots, e_n)$ of eigenvectors of $T$, every element of $V$ can be written as a linear combination of $(e_1,\ldots, e_n)$. Thus we define an inner product of $V$ by
$$\langle a_1e_1+\cdots + a_ne_n,b_1e_1+\cdots + b_ne_n\rangle=a_1b_1+\cdots + a_nb_n$$
Verify that this is an inner product on $V$,and that $(e_1,\ldots, e_n)$ is orthonormal basis of $V$ with respect to this inner product.

To verify that this is an inner product, we need to show that four inner product properties hold for it. This part is easy.
My confusion is the meaning of "$(e_1,\ldots, e_n)$ is orthonormal basis of $V$ with respect to this inner product."  I don't understand the meaning of "with respect to" here. Does it imply that, with different basis will give different inner product ? How to verify that $(e_1,\ldots, e_n)$ is orthonormal basis of $V$ with respect to this inner product?

A: Two vectors can be orthogonal according to one inner product, but not to other.
Example: in $\Bbb R^2$ consider:
$$\langle (x_1,y_1), (x_2, y_2)\rangle_1 = x_1x_2 + y_1y_2 \qquad \langle (x_1, y_1), ( x_2, y_2)\rangle_2 = x_1x_2 + 2 y_1y_2$$
Then $(1,1)$ and $(1,-1)$ are $\langle \cdot , \cdot \rangle_1-$orthogonal, but not $\langle \cdot, \cdot \rangle_2-$orthogonal.
In general, if you have a non-degenerate (and symmetric, for avoiding technical problems) billinear form $g$, you can say that two vectors $u$ and $v$ are $g-$orthogonal if $g(u,v) = 0 $.

A: Here "with respect to" just means "using" (and emphasizes that whether this will not in general hold for other inner products).
To show that a basis $(e_a)$ is orthonormal, we just apply the definition, that is, we check that
$\langle e_a, e_a \rangle = 1$ for all indices $a$, and
$\langle e_a, e_b \rangle = 0$ for all indices $a, b$ such that $a \neq b$.


text:
Q: If $\operatorname{supp}\mu\subseteq \{x_1,\dots, x_n\}$, then $\mu=\sum_{i=1}^na_i\delta_{x_i}$ for some $a_1,\dots, a_n\geq 0$ First, we begin with a definition:

Let $\mu$ be a Radon measure on a Hausdorff space $X$. Let $\{G_i\}_{i\in I}$ be the family of open $\mu$-null sets, and put $G:=\bigcup_{i\in I}G_i$. Then $G$ is the biggest largest open $\mu$-null set. By the support of $\mu$, we understand it the set $\operatorname{supp}\mu:=X\setminus G$.

The question is, how to show that,

If $\operatorname{supp}\mu\subseteq \{x_1,\dots, x_n\}$, then $\mu=\sum_{i=1}^na_i\delta_{x_i}$ for some $a_1,\dots, a_n\geq 0$, (where $\delta_x$ is the Dirac measure concentrated at $x\in X$).

Okay, we begin with an easy case, we look at $\operatorname{supp}\mu\subseteq \{0\}$. I try to show that it implies $\mu=a\delta_0$ for some $a\geq 0$. But I do not know how to do that directly, unless it is done by contrapositive, I think.

A: Given supp $\mu \subseteq \{x_1, \ldots, x_n\}$. Define
$$a_i = \mu(\{x_i\}) .$$
Now, take any measurable set $A$. If $A \cap \text{supp}~\mu = \emptyset$, then $$\mu(A) = 0.$$
Suppose $A \cap \text{supp}~\mu \neq \emptyset$, let $J = \{j | x_j \in A \cap \text{supp}~\mu\}$
$$\mu(A) = \mu(A \cap \text{supp} ~ \mu) = \sum_{i \in J} \mu(\{x_i\}) = \sum_{i \in J} a_i = \sum_{i=1}^n a_i \delta_{x_i}(A).$$


text:
Q: Is $\omega\mapsto\int f\;d\delta_\omega$ measurable? Let $(\Omega,\mathcal A)$ be a measurable space, $f:\Omega\to[0,\infty]$ be $\mathcal A$-measurable. Is $$\kappa:\Omega\to[0,\infty]\;,\;\;\;\omega\mapsto\int f\;d\delta_\omega$$ $\mathcal A$-measurable? ($\delta_\omega$ denotes the Dirac measure on $(\Omega,\mathcal A)$)
I've no idea how I could start. I suppose it's an easy conclusion from one or two basic results.

A: To elaborate on @Daniel Fischer's comment, for $A\in\mathcal A$, $$\delta_\omega(A)=\begin{cases}1,& \omega\in A\\ 0,& \omega\notin A,\end{cases}$$ it follows that
$$\kappa(\omega) = \int_\Omega f\ \mathsf d\delta_\omega = f(\omega), $$
since trivially $\omega\in\Omega$. As $f$ was assumed to be $\mathcal A$-measurable, so too is $\kappa$.


text:
Q: What's the difference between a "surrogate metric" and a "proxy metric"? Is there a difference between a "surrogate metric" a "proxy metric" or a "correlated metric"? Is "surrogate" simply unnecessary jargon, or is there a meaning that makes it more specific than when saying "proxy" or "correlated"?

A: In most contexts I can think of surrogate and proxy are mutually interchangeable. These terms are widely used in cases when the original phenomenon is difficult to measure, and thus refer to a (claimed to be) very close, but easier to measure substitute that is used instead.
In limited contexts correlated can be used as well, but there's a difference in the intention. A correlated measure could be used as a proxy/surrogate, but if it is not, then it is just (possibly one of many) correlated measures.
I wouldn't say that surrogate is "less necessary jargon" than proxy, it's just that the different vocabulary originate from different scientific communities that might have adopted the approach independently of each-other.


text:
Q: How do I connect my external hard drive to Ubuntu? I'm going to be straight and to the point.
I have a WD My Book 25ee External Hard Drive.  It works fine on Windows 10 but does not work on Ubuntu 18.04.
Terminal commands I have tried and their outputs:
Input01: sudo lshw -C disk
Output01:

*

*description: SCSI Disk

*product: My Book 25 EE

*vendor: WD

*physical id: 0.0.0

*bus info: scsi@1:0.0.0

*logical name: /dev/sda

*version: 4004

*serial: (not going to put that online)

*size: 3TB

*configuration:
ansiversion=6 logicalsectorsize=512 sectorsize=4096

Input02: sudo fdisk -l
Output02: it does not show up in the list of drives.
I tried formatting the drive with Disks but I got "Error wiping device: failed to probe the device '/dev/sda' (udisks-error-quark, 0)" and I tried doing an ntfsfix command but that did not work either.  Additionally I have now tried shutting off the "fast startup" option from Windows 10 but I still have the same errors.
Every time I get a read/write error but I have found no solutions online.

A: Update:
The partitions are NTFS, the disk is shown as /dev/sda, the drive is an external drive connected by USB, and it cannot be seen in gParted.
I went into Windows 10 and reformatted the drive from exFAT to NTFS and then when I went back into Ubuntu it was magically working...I'm not sure why but it does.
I hope someone can explain this because I can't.


text:
Q: Add normal String or Integer In a aggregate I have a group-clause:
      {  $group: {
                _id: { town_id: "$_id.town" },
                houses_data: { $push:

                     { house_id: "$_id.house_id",
                       price: {
                           $divide: ["$sum", "$total"]
                             }
                      }
                }
             }
       }

Like this everthing works fine
But then I tried to add an extra field description in the houses_data:
    { house_id: "$_id.house_id",
      price: {
         $divide: ["$sum", "$total"]
      },
      description: "thats a house"
     }

Now I get an error:
FieldPath '2' doesn't start with $"

But Description is not a Field.
I want to add Description as a static String Value.
So in each house_data-array, there should be the same description.
The output should look like:
{town_id: 13, houses_data: [
   {house_id: 5, price: 32, description: "thats a house"},
   {house_id: 2, price: 12, description: "thats a house"}
   ]
 }

What do I wrong? Thanks!

A: Use the $literal operator, in your group clause, as in:
{.. description: {$literal:"thats a house"} ..}

FieldPath '2' doesn't start with $

indicates that the value is parsed as an expression. The $literal operator tells mongoDB - to not parse the content as an expression.

Returns a value without parsing. Use for values that the aggregation
  pipeline may interpret as an expression.

Note: That the syntax for the $group stage operator, is as follows:
{ $group: { _id: <expression>,
            <field1>: { <accumulator1> : <expression1> }, ... } }

$literal is not one of the accumulators and cannot be used in place of an accumulator, but needs to be a part of the expression.

A: $literal is what you are looking for. However I don't believe it's  valid for the group stage of aggregation. I've just tried it and couldn't get it to work.
So instead I would suggest adding in the description field prior to the group operation of the pipeline and then retaining it in the group stage using $first expression:
 { $project: {
              _id: 1,
              sum: 1,
              total: 1,
              description: { $literal: "thats a house" }
              }
 },
 {  $group: {
            _id: { town_id: "$_id.town" },
            houses_data: { $push:

                 { house_id: "$_id.house_id",
                   price: {
                       $divide: ["$sum", "$total"]
                         },
                   description: { $first: "$description" }
                  }
            }
         }
   }

I've tested something similar and it works.


text:
Q: How do I set dynamic transformTo values in a Polymer neon-animation? I want to use neon-animation in Polymer to animate an element from wherever it is (it is draggable and movable) to the middle of the screen. And to do that I think I need to dynamically set transformTo depending on where the element is on the screen and where it should move to.
However, it seems that animationConfig gets evaluated only once.
Is there a way to dynamically set or evaluate 1px, 2px and 3px in the example below?
properties: {
  animationConfig: {
    value: function() {
      return {
        name: 'transform-animation',
        node: this,
        transformFrom: 'translate3d(0,0,0)',
        transformTo: 'translate3d(1px,2px,3px)',
      }
    }
  }
}

A: I have not found a good way to do it, but instead found a workaround.
I override the getAnimationConfig(type) method, which is called by neon-animation each time an animation is performed.
Note that the result from getAnimationConfig must be an array!
getAnimationConfig: function() {
  var x = 1;
  var y = 2;
  var z = 3;
  return [{
    name: 'transform-animation',
    node: this,
    transformFrom: 'translate3d('+x+'px,'+y+'px,'+z+'px)',
    transformTo: 'translate3d(0,0,0)'
  }]
}


text:
Q: Is there a way to provide a sort order to an mdfind query? In trying to get a list of all music files from a particular album using mdfind I see that the files aren't necessarily returned in any order.  I'd prefer album/track order if possible, but can't find a way to provide the sort order on the command line.  The current invocation is something like:
mdfind -onlyin "$MUSICROOT" -literal "$MDQUERY"

where:
$MUSICROOT is ~/Music/iTunes
$MDQUERY is "kMDItemContentTypeTree == 'public.audio' && kMDItemAlbum == '*$1*'c"

Ideally I'd want to add something like the following to the query:
ORDER BY kMDItemAlbum, kMDItemAudioTrackNumber

A: I used the following shell function to provide the sort:
function sort_file()
{
    TMPFILE=`mktemp /tmp/sortable.XXXXXX` || exit 1
    export MDLS="mdls -raw -name kMDItemAlbum -name kMDItemAudioTrackNumber"
    export TR="tr \"\0\" \"\;\""
    awk '{system( "$MDLS \"" $0 "\" | $TR" ); print "\;"$0; }' $1 > $TMPFILE
    sort -t\; -k 2n -k 1f $TMPFILE | awk -F";" '{ print $3; }' > $1
}

META NOTE: I would have put this in a comment in the above answer, but couldn't get it to format correctly.

A: At the risk of stating the obvious, 'sort'.
e.g. mdfind -onlyin "$MUSICROOT" -literal "$MDQUERY" | sort
will sort the output alphabetically, giving you Artist, Title, Track.
(it won't do the cool iTunes trick of ignoring 'The').
The sort command has lots of options, including sorting on particular fields if you want more control.
Edit:  The below shell script function will provide the desired sort in the specific case mentioned:
function sort_file()
{
    TMPFILE=`mktemp /tmp/sortable.XXXXXX` || exit 1
    export MDLS="mdls -raw -name kMDItemAlbum -name kMDItemAudioTrackNumber"
    export TR="tr \"\0\" \"\;\""
    awk '{system( "$MDLS \"" $0 "\" | $TR" ); print "\;"$0; }' $1 > $TMPFILE
    sort -t\; -k 2n -k 1f $TMPFILE | awk -F";" '{ print $3; }' > $1
}


text:
Q: Стоит ли делать составной первичный ключ? Изучаю вот этот вопрос, там такая фраза в ответе

Composite primary keys typically arise
  when mapping from legacy databases
  when the database key is comprised of
  several columns.

Я правильно понимаю, что legacy это практически синоним слову "устаревший"?
Если так, то стоит ли, при разработке нового приложения и новой базы данных, делать составные ключи? Или просто добавить ещё один столбец, который по сути ничего не будет делать, ведь всю работу с бд обычно выполняют фреймворки?

A: Существует несколько устаревший подход в проектировании БД, иногда ошибочно называемый "академическим", когда первичный ключ отношения выбирается как один из естественных ключей отношения. Обычно таким ключом становится имя записи.
В приведенном вами вопросе именно такой подход и используется. Но этот подход устарел по многим причинам. Первая: первичный ключ записи - это то, что используется для ссылок на запись как в самой БД, так и за ее пределами. Желательно делать его как можно меньше - все же большинство естественных ключей строковые.
Причина вторая - многие вещи, выглядящие на первый взгляд как естественные ключи, на самом деле не являются такими. К примеру, среди людей бывают полные тезки (да еще и родившиеся в один день). В магазине может быть два товара с одним и тем же названием в разных отделах...
Причина третья - естественный ключ еще и может изменяться, что так же ведет к проблемам. Так, для человека естественным ключом мог бы быть номер паспорта или свидетельства о рождении - но эти документы могут быть заменены при достижении определенного возраста или в случае утери.
Поэтому хорошей практикой является введение суррогатного ключа - это новое поле, не имеющее никакого отношения к предметной области. Обычно его тип -  автоинкрементное 32х-разрядное целое, реже - 64х-разрядное. Еще это может быть UUID.
Как правило, при наличии такого поля нет никакого смысла в составных ключах.

Тем не менее, иногда составные ключи бывают полезны. Вот эти случаи:

*

*Таблицы-связки для отношений "много ко многим". Обычно такие таблицы создаются и управляются библиотеками ORM самостоятельно - но иногда приходится создавать их отдельно. В таких таблицах естественным ключом является вся запись целиком - и нет никаких причин создавать отдельный суррогатный ключ.

*Некоторые дочерние подобъекты, не имеющие смысла в отрыве от родительского. Если мы делаем систему для тестирования учащихся - то иногда имеет смысл обращаться к ответу на вопрос как к 5му ответу на 147й вопрос - а не к 3423му ответу вообще. А иногда наоборот.

*Использование отношений в БД для дополнительной проверки целостности. Существует так называемая доменно-ключевая нормальная форма, в которой любые ограничения на данные реализуются в формате внешних ключей. В таком случае иногда имеет смысл включать дополнительные поля в первичный ключ.

A: Полагаю, перевод по смыслу: "Составные первичные ключи обычно возникают при сопоставлении с существующими таблицами базы данных, когда ключ таблицы состоит из нескольких столбцов."
legacy здесь это практически синоним слову "существующий".
При разработке новой таблицы теоретически не следует создавать избыточность информации новым ключевым полем если существующая в ней комбинация внешних ключей(или других полей) уже является уникальным ключом.
Но практически поиск по дополнительному полю уникального ключа может быть быстрее или субъективно проще для разработчика и таким образом иметь смысл для достижения необходимого результата :)

A: Это довольно холиварный вопрос, и единственно верного ответа тут нет. Но чаще всего мнения сходятся к тому, что ключи должны быть не составными, и в них не должно храниться какой-либо информации о сущности. То есть это должно быть какое-то (обычно целочисленное автоматически инкрементируемое) поле, обеспечивающее уникальность записи


text:
Q: Binding value as html in stenciljs I am having trouble rendering a value with custom html inside into an element.
ex:
this.title = 'Hello  stencil '; << response value from an API

Binding:

{this.title}

I am expecting something same as innerHtml behavior in JavaScript.

A: You can use

A: This is not a good practice in JSX, it is against the idea of virtual DOM and it's not creating virtual nodes.
You should try like this
this.salute = 'Hello';
this.name='stencil';

Binding

{this.salute} {this.name}

Or if it is a more complex situation, build another smaller component.
However using innerHTML will work, but should be used in different situations more details here(at the bottom of the page).


text:
Q: How to prevent website being grabbed by IDM( or anyother webstie grabber)?Is there any way to prevent it? Using website grabbers whole website with folder structure can be downloaded.
Is there any way to prevent this?
If so,how?

A: The only way to protect a websites markup is not to publish it. If you want your users to see something they need to get the HTML markup and the images, that should be displayed. And therefore the files need to be accessible. And if your files are accessible every user/bot/crawler/grabber can save these files.

A: The best way is to put a few files like the index page in the main directory and call the other sub pages in it. If using php then you may do the following.
Say keep the index.php in the main folder and keep the homepage.php in a directory called includes and use the homepage in the index.php via include function in php.
Now add a .htaccess file to the includes folder which must contain
"deny from all"
This way users can use the page but will not have direct access to the files. So will be for the grabber.


text:
Q: Observer doesn't save order I've build an observer which listens on the sales_convert_quote_to_order event. The event is triggered and I just want to add a value to an attribute of the order. The attribute is set - as printed in the log - but magento doesn't save the order. What I'm doing wrong?
Observer.php
public function addLangToOrder($observer){
        Mage::log('catching convert_quote_to_order_after');
        $order = $observer->getEvent()->getOrder();
        $order->setCustomerLanguage(Mage::app()->getStore()->getCode());
        $order->save();
        Mage::log($order->getCustomerLanguage());
    }

config.xml
<events>
    <sales_convert_quote_to_order>
        <observers>
            <accustomer>
                <type>singleton</type>
                <class>Ac_Customer_Model_Observer</class>
                <method>addLangToOrder</method>
            </accustomer>
        </observers>
    </sales_convert_quote_to_order>
</events>

I've added the attribute customer_language through an install script
$customer_lang = 'customer_language';
$installer->addAttribute('order', $customer_lang, array('type'=>'varchar'));

The customer_language column is present in my sales_flat_order table. But it doesn't get saved.
I'm using Magento 1.4.1.1

A: You need to add your attribute to both - quote and sales model - to make this work.
As Magento will copy a defined <fieldset>* from quote to order, you need to extend the config.xml of your overriding class accordingly, too:
<config>
    <!-- : -->
    <global>
        <fieldsets>
            <sales_convert_quote>
                <customer_language><to_order>*</to_order></customer_language>
            </sales_convert_quote>
        </fieldsets>
    </global>
    <!-- : -->
</config>

*see the config.xml of Mages_Sales

A: is there a transaction occurring before this? its been my experience that trying to save a model when a transaction is still in progress doesn't work. I had to move the observer to another event after the transaction like "sales_model_service_quote_submit_after" instead.


text:
Q: Optimizing SCP over network I have a shell script which sends a file using scp over the network. The script works in an event driven fashion i.e. every time the file is modified,it is sent over the network using scp. I would like to optimize the script such that instead of every time sending the file, I only send the "new appended/new write data" and that gets appended to the file at the other endpoint
The script is as follows
while true
do
inotifywait -e close_write,moved_to,create  . |
while read -r directory events filename; do
  if [ "$filename" = "keylog.txt" ]; then
     sshpass -p "password" scp -o StrictHostKeyChecking=no keylog.txt machine@192.168.151.19:/home/machine/keylog.txt
  fi
done
sleep 0.00001
done

A: I suggest to take a look at rsync.
It's designed exactly for this kind of purposes.
Quoting from man rsync:

   Rsync is a fast and extraordinarily versatile file copying tool.   It  can
   copy  locally,  to/from  another  host over any remote shell, or to/from a
   remote rsync daemon.  It offers a large number  of  options  that  control
   every aspect of its behavior and permit very flexible specification of the
   set of files to be copied.  It is famous for its delta-transfer algorithm,
   which reduces the amount of data sent over the network by sending only the
   differences between the source files and the existing files in the  desti-
   nation.  Rsync is widely used for backups and mirroring and as an improved
   copy command for everyday use.

On a server that supports scp,
typically rsync works too.
Try this:
sshpass -p "password" rsync keylog.txt machine@192.168.151.19:/home/machine/keylog.txt

Even without tuning the parameters,
rsync will try to minimize the amount of data transferred.
When the destination file already exists,
it will transfer only the necessary difference.


text:
Q: Method of expanding list of dictionaries into list of formatted strings I've run across a need to call out to an external executable using the subprocess module. Everything is working fine, however I'd like to improve how I'm generating the commandline arguments.
The executable's command line options require formatting as follows:
    --argname=argvalue
I currently have a list of dictionaries as follows:
    [{arg1:value1},{arg2:value2}]
What is the best method of expanding these dictionaries into their proper string format?  I'm currently iterating over the list, appending to a different list, however it feels there's a more pythonic method I should utilize.

A: Use items() as in http://docs.quantifiedcode.com/python-code-patterns/readability/not_using_items_to_iterate_over_a_dictionary.html
for key,val in d.items():
    print("{} = {}".format(key, val))

A: ' '.join('--{key}={value}'.format(key = k, value = v) for d in arg_list for k, v in d.items())

Essentially, this iterates over each dictionary in the list (for d in arg_list) and then iterates over the items in each dictionary (for k, v in d.items()). Each item is formatted into the proper form, and then all of those key-value pairs are combined.
It is equivalent to:
arg_list = [{arg1:value1},{arg2:value2}]
formatted_args = []

for d in arg_list:
    for k, v in d.items():
        # Format each item per dictionary
        formatted_args.append('--{key}={value}'.format(key = k, value = v))

# Combine the arguments into one string
args_string = ' '.join(formatted_args)

A: Try this
 ','.join('{}={}'.format(k, v) for d in arg_list for k, v in d.items())

A: How about
def format_dict(d):
    key = d.keys()[0]
    return '--%s=%s' % (key, d[key])

ex = [{'a':'3'}, {'b':'4'}]
print ' '.join(map(format_dict, ex)) # --a=3 --b=4


text:
Q: End selector with several classes My HTML code fragment:

test

CSS:
div[class$='ss2'] {
  background-color: red
}

It works well, but for:
div[class$='ss1'] {
  background-color: red
}

Didn't work.
How can I use CSS for end class which is not last class in DIV without adjusting order?

A: I'd go with something like
div[class$="ss1"], div[class*="ss1 "] {

That will handle any class attribute ending in ss1 (the final class in the list) or containing a class ending in ss1, potentially followed by other classes.


text:
Q: iptables allow certain ports and disable the rest I have the following scenario:
I only want to allow access to 22, 80 and 443 ports and everything else permit.
My iptables -L looks like this:
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere             state RELATED,ESTABLISHED
DROP       all  --  anywhere             anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

But I can't get the desired effect, and even from my server I can't ping anything anymore ( can't get on the internet anymore ).
Also, I looked at option to set INPUT policy to DROP and manually open the desired ports but that didn't take the desired effect either.
Is there any difference in putting the DROP policy on INPUT chain and manually open the desired ports and the way I did it by dropping all traffic as the last rule.
Thanks a bunch,
Best regards.

A: Your current setup for INPUT chain allows clients to connect to your server on tcp 22, 80 and 443 and the tcp connections you initiate to be replied. That's it! No icmp (for ping), no udp (DNS lookups).
Having your ESTABLISHED, RELATED rule ALLOW all protocols, instead of just tcp, should fix the above.
Regarding dropping everything using a rule versus DROP policy:
iptables -P INPUT DROP

Is the same thing as having:
iptables -A INPUT -j DROP

As your last rule.
Also, unless you know exactly what you're doing, you should fully allow loopback traffic.


text:
Q: Laravel Migration Type Year become undefined Method I have a problem with my migration on laravel 5.8. I am tring to make Year Column as mentioned in documentation. But I keep on getting this error "[Symfony\Component\Debug\Exception\FatalThrowableError]  Call to undefined method Illuminate\Database\Schema\Blueprint::year()".
This is my migration file :
Schema::create('pengajuan_arsip', function(Blueprint $table) {
        $table->increments('id');
        $table->uuid('uuid');
        $table->integer('id_pegawai_pengaju');
        $table->string('nip_pengaju',50);
        $table->string('nik_pengaju',50);
        $table->string('nama_pengaju',200);
        $table->string('bidang',100);
        $table->string('sub_bidang',100);
        $table->string('tingkat',50);
        $table->integer('status');
        $table->boolean('is_setuju');
        $table->integer('setuju_kasi_by');
        $table->year('tahun_mulai');
        $table->year('tahun_akhir');
        $table->timestamps();
        $table->softDeletes();
    });

    Schema::create('detail_histori_arsip', function(Blueprint $table) {
        $table->increments('id');
        $table->uuid('uuid');
        $table->integer('id_pengajuan_arsip');
        $table->integer('status');
        $table->integer('status_by');
        $table->integer('diambil_by');
        $table->date('tanggal_diambil');
        $table->integer('id_ruang_arsip');
        $table->date('tanggal_pindah');
        $table->timestamps();
    });

    Schema::create('detail_arsip', function(Blueprint $table) {
        $table->increments('id');
        $table->uuid('uuid');
        $table->integer('id_pengajuan_arsip');
        $table->string('nama_dokumen',200);
        $table->year('tahun_dokumen');
        $table->timestamps();
    });

A: I would suggest utilizing an unsigned small integer instead. There is nothing truly remarkable about a year value that would require its own special database column type:
$table->unsignedSmallInteger('tahun_mulai');
$table->unsignedSmallInteger('tahun_akhir');

This will allow you to save values from 0  to 65535.
If for whatever reason you need B.C. times represented by a negative number, then try with a signed small integer:
$table->smallInteger('tahun_mulai');
$table->smallInteger('tahun_akhir');

This will allow you to save values from -32768 to 32767


text:
Q: Hibernate : Table doesn't get updated I'm having trouble with my hibernate transaction. After execution , table has no values in it and is not updated at all. All my other updates work properly.
Here's the mapping
 <class name="LastDownloadedMessage" table="t_imap_lastmsguid">
    <id name="id" column="id" ><generator class="increment"/></id>
    <property name="lastDownloadedMessageUid"><column name="last_msg_uid" /></property>
    <property name="lastUidNext"><column name="next_msg_uid" /></property>
    <property name="folder"><column name="folder_name" /></property>
     <property name="cred"><column name="credential" /></property>
 </class>

This is the POJO object :
public class LastDownloadedMessage {
    Integer id;
    private String lastDownloadedMessageUid;
    private String lastUidNext;
    private String folder;
    private String cred;

    //GETTERS AND SETTERS HERE

    public LastDownloadedMessage() {
        super();
    }
    public LastDownloadedMessage(String lastDownloadedMessageUid,
            String lastUidNext) {
        super();
        this.lastDownloadedMessageUid = lastDownloadedMessageUid;
        this.lastUidNext = lastUidNext;
    }
}

and this is the function which is doing the update.
    Session ssn=HibernateSessionFactory.openSession();
    Transaction txn = ssn.beginTransaction();
    Query query = ssn.createQuery("update LastDownloadedMessage e set e.lastDownloadedMessageUid = :luid , e.lastUidNext = :nextUid where e.folder =:folder and e.cred = :cred");
    query.setParameter("luid",last_downloaded_msg_uid);
    query.setParameter("nextUid", uid_next);
    query.setParameter("folder", folder);
    query.setParameter("cred", credential);
    int result = query.executeUpate();
    txn.commit();
    ssn.flush();
    ssn.close();

The function appears to execute properly with no errors . What could be the issue ?

A: Based on the comments, it seems to me you are confusing UPDATE with INSERT.
If result is zero, it means your WHERE clause didn't match anything, so there's nothing to update.
Also, why are you trying to issue an UPDATE/INSERT on a known (mapped) entity? All you have to do is set your values on your object (LastDownloadedMessage) and then execute a persist on your EntityManager. Browse around the web for EntityManager.persist.


text:
Q: R ggplot - calculate intercept of multiple plotted curves and geom_hline I'm wanting to calculate interpolated x-intercepts for lines like these with geom_hline:

library(dplyr)
library(ggplot2)

g1=data.frame(grp="1", x=seq(1,50,1), y=rnorm(50,5,1))
g2=data.frame(grp="2", x=seq(1,30,1), y=rnorm(30,8,2))
g3=data.frame(grp="3", x=seq(1,45,1), y=rnorm(45,10,1))
comb.dat=rbind(g1,g2,g3)
plot.dat=comb.dat %>% group_by(grp) %>% mutate(cum=cumsum(y)/sum(y))

p1=ggplot(plot.dat, aes(x = x, y = cum, color=grp)) +geom_line()+ geom_hline(yintercept=.5, linetype="dashed", color = "black")

print(p1)

hline=data.frame(plot.dat %>% group_by(grp) %>% mutate(test=cum>0.49 & cum<0.51))#
print(hline[hline$test==T,])# only works when an exact value in the range exists

F1=approxfun(plot.dat$cum,plot.dat$x,ties=mean)
#data.frame(plot.dat %>% group_by(grp) %>% mutate(F1(0.50)))#works only on first group

g1b=plot.dat[plot.dat$grp=="1",]
F2=approxfun(g1b$cum,g1b$x)
F2(0.5)#works but inefficient

I have a lot of these plots and I am looking for the most efficient way to find the x-intercepts with the horizontal line for each factor level so the intercept values can be compared to each other and annotated to the plot. I thought there was a logic approach but then I realized I need interpolation, probably using approxfun. I have not found a way to do this without breaking the groups out of the data frame and doing it one by one...Thanks for setting me straight.

A: Here's a dplyr approach using base::approx.
x_seq = seq(1, 50, by = 0.01)
intersections <- plot.dat %>%
  group_by(grp) %>%
  summarise(interpolated = approx(x = x, y = cum, xout = x_seq)$y) %>%
  mutate(x_seq = x_seq) %>%
  slice_min(abs(interpolated - 0.5))

ggplot(plot.dat, aes(x = x, y = cum, color=grp)) +
  geom_line() +
  geom_hline(yintercept=.5, linetype="dashed", color = "black") +
  geom_point(data = intersections, aes(x_seq, interpolated), size = 3) +
  geom_text(data = intersections, aes(x_seq, interpolated, label = x_seq), vjust = -1)


text:
Q: python sort dictionary by value array I have a dictionary with an array as elements.
Say:
masterListShort = {'a': [5, 2, 1, 2], 'b': [7, 2, 4, 1], 'c': [2, 0, 1, 1]}

I would like to reverse sort this dictionary by the first element of the values.
I would then like to write my output to a tab delimited file like this:
<key>    <value1>    <value2>    <value3>    etc.

My current code where I write my dictionary to file looks like this:
# write the masterListShort to file
outFile2 = open('../masterListShort.tsv', 'w')
for item in sorted(masterListShort):
    tempStr = '\t'.join(map(str, masterListShort[item]))
    outFile2.write(str(item) + '\t' + tempStr + '\n')

outFile2.close()

This code works fine, it just does not sort the list.
I want my output to be written in a tab delimited file format.
So:
b    7    2    4    1
c    5    2    1    2
a    2    0    1    1

I have found the following commands so far, and was wondering if i could apply them to my code:
import operator
sorted(myDict, key=operator.itemgetter(1))

A: You'll need to sort the values then, on the first index (so 0 for zero-based indexing), and tell sorted() to reverse the order:
import operator

sorted(myDict.values(), key=operator.itemgetter(0), reverse=True)

Without the dict.values() call you are trying to sort the keys instead.
Demo:
>>> import operator
>>> myDict = {'a': [5, 2, 1, 2], 'b': [7, 2, 4, 1], 'c': [2, 0, 1, 1]}
>>> sorted(myDict.values(), key=operator.itemgetter(0), reverse=True)
[[7, 2, 4, 1], [5, 2, 1, 2], [2, 0, 1, 1]]

If you wanted to output key-value pairs, then use dict.items() and use lambda to access the first index on just the value:
sorted(myDict.items(), key=lambda i: i[1][0], reverse=True)

Demo:
>>> sorted(myDict.items(), key=lambda i: i[1][0], reverse=True)
[('b', [7, 2, 4, 1]), ('a', [5, 2, 1, 2]), ('c', [2, 0, 1, 1])]

In both cases, there is actually not that much point on sorting just by the first element; you can just leave the lists to sort naturally:
sorted(myDict.values(), reverse=True)  # sort just the values
sorted(myDict.items(), key=operator.itemgetter(1), reverse=True)  # sort items

as a list of lists is sorted in lexicographical ordering; if the first elements are equal, then two lists are ordered based on the second element, etc.
To write this out to a tab-delimited file, use the csv module; it'll take care of converting values to strings, writing the tab delimiters and handle newlines:
import csv

with open('../masterListShort.tsv', 'wb') as outfh:
    writer = csv.writer(outfh, delimiter='\t')
    for key, values in sorted(myDict.items(), key=operator.itemgetter(1), reverse=True):
        writer.writerow([key] + values)

A: You can sort the list of tuples that dict.items() gives;
myDict = {'a': [5, 2, 1, 2], 'b': [7, 2, 4, 1], 'c': [2, 0, 1, 1]}

print myDict.items()
#[('a', [5, 2, 1, 2]), ('c', [2, 0, 1, 1]), ('b', [7, 2, 4, 1])]

print sorted(myDict.items(), key=lambda x: x[1][0], reverse=True))
#[('c', [2, 0, 1, 1]), ('a', [5, 2, 1, 2]), ('b', [7, 2, 4, 1])]

the key keyword argument of sorted is a function you provide it with, which returns something the function can use to sort each element of the list you give it to be sorted on.
lambda x: x[1][0] is just a quick way of making a function which you could have used instead;
i.e.
print sorted(myDict.items(), key=lambda x: x[1][0])

is the same as
def sortFunction(x):
  return x[1][0]

print sorted(myDict.items(), key=sortFunction)

The reason it's giving x[1][0] is because the list myDict.items() is a 2D list; each element is a tuple, where the first element is the key, and the second element is the value. so x[1] is the value (i.e. the lists assigned to each key). And you want to sort on their first values, so we sort on x[1][0].
Now it's just a case of printing them in the format you want;
for key, value in sorted(myDict.items(), key=sortFunction, reverse=True):
  print key + "\t" + "\t".join([str(v) for v in value])

That will give:
b   7   2   4   1
a   5   2   1   2
c   2   0   1   1


text:
Q: How can I play a Sonos playlist using Python soco? I am trying to load a sonos playlist from Python soco so that I can control music from my PC.
Thanks to the developers of soco.  It's been very handy playing individual tracks from my music library, and streaming internet audio.  I just haven't figured out how to use the sonos playlist.
Let zone be a SoCo object representing a Sonos speaker or speaker pair.  Each zone has a current queue stored in its zone.contentDirectory.  I think I need to replace this queue with the tracks from the playlist, but I haven't found how to enumerate the tracks on the playlist.  Also, playing the playlist URI does not work.
The list of sonos playlists is available with
import soco

zone = soco.Soco('192.168.1.249')
zone.get_playlists()

A specific playlist is available by its title with
pl = zone.get_sonos_playlist_by_attr('title', 'Dance').

When I look at the details of the playlist, the only track information
seems to be a uri on the Sonos device.
>>> pprint(pl.to_dict())
{u'desc': None,
 u'item_id': u'SQ:28',
 u'parent_id': u'SQ:',
 u'resources': [{u'bitrate': None,
                 u'bits_per_sample': None,
                 u'color_depth': None,
                 u'duration': None,
                 u'import_uri': None,
                 u'nr_audio_channels': None,
                 u'protection': None,
                 u'protocol_info': 'file:*:audio/mpegurl:*',
                 u'resolution': None,
                 u'sample_frequency': None,
                 u'size': None,
                 u'uri': 'file:///jffs/settings/savedqueues.rsq#28'}],
 u'restricted': True,
 u'title': u'Dance'}

But this uri cannot be played with zone.play_uri().
>>> zone.play_uri('file:///jffs/settings/savedqueues.rsq#28')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/soco/core.py", line 104, in inner_function
    return function(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/soco/core.py", line 483, in play_uri
    ('CurrentURIMetaData', meta)
  File "/usr/local/lib/python2.7/dist-packages/soco/services.py", line 181, in _dispatcher
    return self.send_command(action, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/soco/services.py", line 408, in send_command
    self.handle_upnp_error(response.text)
  File "/usr/local/lib/python2.7/dist-packages/soco/services.py", line 469, in handle_upnp_error
    error_xml=xml_error
soco.exceptions.SoCoUPnPException: UPnP Error 714 received: Illegal MIME-Type from 192.168.1.249

I think I need to replace the queue with the tracks from the playlist uri, but how do I get them?

A: You've to use a different method. At first you have to clear the queue (if you want to remove old tracks), then you can use add_uri_to_queue to add the playlist tracks to Sonos queue, finally you can use play.
import soco

sonos = soco.SoCo("192.168.1.249")

uri = "file:///jffs/settings/savedqueues.rsq#28"
sonos.clear_queue()
sonos.add_uri_to_queue(uri=uri)
sonos.play_from_queue(index=0)


text:
Q: Detect Heap Corruption only no developement computer I use VS 2012 for write an MFC application in C++
In my computer I have no problem but when I lauch in other computer I have heap corruption detected problem.
Do you have some idea how I could solve it knowledge that the error does not produce in my computer so I could not lauch debugger to access my code.
Thank you

A: You can use the remote debugging feature of VS. See https://msdn.microsoft.com/en-us/library/vstudio/bt727f1t(v=vs.110).aspx
Normaly this kind of bug arises from not init member variables.


text:
Q: I have installed TeXStudio and when I compile a file an error occurs I have installed TeXStudio and when I compile a file this error occurs.
What should I do?
Process started: pdflatex.exe -synctex=1 -interaction=nonstopmode "naveed_thesis".tex


text:
Q: Какой самый эффективный способ реализовать закрепление статьи в связке php+mysqli Вот есть таблица статей, id, date, title, description, view. Как вы думаете, какой самый гуманный и правильный (проверенный вашим личным опытом) способ реализовать закрепление статьи при выборке на странице.
Допустим добавим поле [position INT(10) NOT NULL default '1'] и оно будет фигурировать в выборке под ORDER BY position ASC/DESC. Но возможны совпадения значений и путаница.
Или добавим поле [status INT(10) NOT NULL default '5'] и расписать реакцию при выборке по условиям от 1-5, где 5 это дефолтные статьи (можно и 2, это так для примера).
А вы как думаете?

A: Допустим, есть таблица с полями id, date, title, description, view.
Для закрепления записи в топе можно добавить еще одно boolean поле is_top, которое будет указывать на признак размещения в топе. Допустим, что посты сортируются по дате, а is_top = 1 означает размещение в топе. Тогда ORDER BY будет таким:
ORDER BY is_top desc, date

В результате в выборке первыми будут закрепленные посты, отсортированные по дате, а после пойдут обычные посты, так же отсортированные по дате.

A: Конечно, для осмысленного ответа желательно бы точно знать, что имеется в виду под термином "закрепление статьи при выборке на странице".
Согласен, что вариант дополнительного поля "is_top" - самый гуманный и наиболее употребительный.
Если же хочется обойтись без дополнительного поля, можно просто сделать поле ID знаковым. И для закрепления/открепления статьи менять знак, не меняя значения (UPDATE table SET id = -id). Тогда при сортировке по возрастанию ID закреплённые будут самыми первыми. Само собой способ неприменим, если имеются FK на ID таблицы.


text:
Q: Close pop up window c# html I'm trying to make a pop up that closes after a certain time,but I still need to use the button to close it, this is the code for the button and what i'm trying to use to close it:
            [HttpPost]
            public ActionResult Msgbox(int btnACCION = 0)
            {
                switch (btnACCION)
                {
                    case 1: return RedirectToAction("Inicio");
                    case 2:
                        try
                        {
                            Response.ClearHeaders();
                            Response.ContentType = "application/pdf";
                            Response.AddHeader("Content-Disposition", "attachment; filename=pdffile.pdf");
                            Response.TransmitFile(Server.MapPath("~/Files/20220418_MAN0001 Anteproyecto.pdf"));
                            Response.End();
                        }
                        catch { TempData["MsjError"] = "Error!"; }
                        break;
                }

                return RedirectToAction("MsgboxIndex");
            }

    [HttpPost]
    public ActionResult Msgbox(int sleepTime = 0)
    {
         // in mills
        Task.Delay(sleepTime).Wait();
        return RedirectToAction("Inicio");
    }


text:
Q: join using linq getting error Getting error while joining two tables using linq , the error is The name 'u' does not exist in the current context
Here is my Code
from t in Teams
join u in Users on t.TeamId equals u.TeamId  into g
where (t.TeamName.Contains("Pr"))  && (t.Deleted != true) ||(u.FirstName.Contains("Ch"))
select new { t.TeamId,t.TeamName, t.Description,UserId=g.Count()}

A: I have changed it to do the join first, then filter on where and then group. Hopefully this works:
from t in Teams
join u in Users on t.TeamId equals u.TeamId
where (t.TeamName.Contains("Pr")) && (t.Deleted != true) || (u.FirstName.Contains("Ch"))
group new { t.TeamId, t.TeamName, t.Description } by new { t.TeamId, t.TeamName, t.Description } into g
select new { g.Key.TeamId, g.Key.TeamName, g.Key.Description, UserId = g.Count() };


text:
Q: Unlock the Android Lockscreen
Possible Duplicate:
How can I unlock the screen programmatically in Android?

I have a running android Service. It runs even on the lockscreen, and I want it to somehow Unlock the lockscreen.
How can I interface with the lockscreen activity or whatever the lockscreen is?
I want my service to Unlock the lockscreen, just like if the user slided the unlock thing.
How might I do this?

A: got it and here are some suggestions you can try:
First
Second
Third and probably most reliable


text:
Q: Displaying Calendar Dates in Swift Im trying to build a weekly calendar for IOS.

The problem with that sample is code is: the usage of an dates array
let dates = ["7/10/2017", "7/11/2017", "7/12/2017", "7/13/2017", "7/14/2017", "7/15/2017", "7/16/2017"]

func spreadsheetView(_ spreadsheetView: SpreadsheetView, cellForItemAt indexPath: IndexPath) -> Cell? {
    if case (1...(dates.count + 1), 0) = (indexPath.column, indexPath.row) {
        let cell = spreadsheetView.dequeueReusableCell(withReuseIdentifier: String(describing: DateCell.self), for: indexPath) as! DateCell

        cell.label.text = dates[indexPath.column - 1]

        return cell

Filling that array with real dates from 01.01.2000 - 31.12.2099 e.g. leads to really bad performance of the app.
Does anyone know how to display the current Dates in an more elegant way?

A: You could do so by using the following extension:
See here : Swift: Print all dates between two NSDate()
extension Date{

func generateDatesArrayBetweenTwoDates(startDate: Date , endDate:Date) ->[Date]
{
    var datesArray: [Date] =  [Date]()
    var startDate = startDate
    let calendar = Calendar.current

    let fmt = DateFormatter()
    fmt.dateFormat = "yyyy-MM-dd"

    while startDate <= endDate {
        datesArray.append(startDate)
        startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!

    }
    return datesArray
}
}

Usage:
let dates = Date().generateDatesArrayBetweenTwoDates(startDate: Your Start Date Object , endDate: Your End Date Object)

A: Here's one solution using Calendar enumerateDates:
// 01.01.2000
let startComps = DateComponents(year: 2000, month: 1, day: 1)
let startDate = Calendar.current.date(from: startComps)!
// 31.12.2099
let endComps = DateComponents(year: 2099, month: 12, day: 31)
let endDate = Calendar.current.date(from: endComps)!

let components = DateComponents(hour: 0, minute: 0, second: 0) // midnight
var dates = [startDate]
Calendar.current.enumerateDates(startingAfter: startDate, matching: components, matchingPolicy: .nextTime) { (date, strict, stop) in
    if let date = date {
        if date <= endDate {
            dates.append(date)
        } else {
            stop = true
        }
    }
}


text:
Q: "Connection Refused erno 111" while connecting to GrapheneDB using PythonAnywhere I'm trying to establish a connection to GrapheneDB.
I'm running this code on Spyder and its working perfectly fine.
from neo4j.v1 import GraphDatabase, basic_auth
from flask import Flask
#from py2neo import Graph, Node, Relationship

app = Flask(__name__)

@app.route('/',methods=['POST','GET'])
def hello_world():
    driver = GraphDatabase.driver("bolt://hobby-dobhfgnijmdigbkelfmgifdl.dbs.graphenedb.com:24787", auth=basic_auth("username", "password"))
    session = driver.session()

#   session.run("CREATE (n:Object {name:'Mat'})")
    result = session.run("MATCH (n:Object) RETURN n.name AS name")

As soon as I run this code on Server (Pythonanywhere)

Error appears: connect raise ServiceUnavailable("Failed to establish
  connection to {!r} (reason {})".format(resolved_address, error))
  neobolt.exceptions.ServiceUnavailable: Failed to establish connection
  to ('54.234.36.208', 24787) (reason [Errno 111] Connection refused)

I'm not sure what is wrong. GrapheneDB is also on the whitelist of python anywhere.


text:
Q: Remove the close option on a batch file with a command, is it possible? I was just wondering if there is a code that can remove the "close" button on a batch file. (The minimize and expand buttons isn't important so it is ok if they will be disabled or will stay enabled) That is all. I can't seem to find any answer anywhere.
Thanks.

A: A batch file is nothing more that a script that another program must execute.
When you double-click a .bat file in Explorer, cmd.exe launches and "opens" the file, running the script. So your question is: can you remove the close button from cmd.exe? Good luck.
You don't want to be doing that. You should make your script NOT show a window to begin with.
If the window is shown, a user can always Ctrl + C to stop the script mid-stream.
There is a number of ways you can make the window hidden (also called "running a script silently"). See the following links:

*

*Run a completely hidden batch file

*Solved: HowTo run a batch file without it showing

*Eric Helps
Or just google for "batch file silent" or "batch file hide console".
Just a side note: if you have seen this behavior before, chances are that it is not a batch file, but another programming language, and probably not using cmd.exe. C# can let you make a console program app which you can manipulate the title, but even still you cannot change the control buttons on the window. It is simply not within c# or a batch file's scope.


text:
Q: How to send one ngModel new string but send the already existing another string to db? Hello i want to change the title with ngModel (mediaData) and keep the description string (mediaDetails) or vice versa.
Right now it changes the one BUT doesn't keep the value i dont want it to change.
.html

<ion-input placeholder="{{mediaDetails.description}}" [(ngModel)]="mediaData.description" [ngClass]="mediaDetails.description"></ion-input>

.ts
export class EditPage {
  mediaDetails: any = {};
  mediaData: any = {};

  this.mediaDetails = this.navParams.get('mediaDetails');

A: this is two way binding
 [(ngModel)]="mediaData.description"

use regular expression for one way binding
  {{mediaData.description}}

for ion-input use like this :
  <ion-input placeholder="{{mediaDetails.description}}" value="{{ mediaDetails.description }}" [ngClass]="mediaDetails.description"></ion-input>

A: the answer is
    <ion-input placeholder="{{mediaDetails.title}}" value="{{mediaDetails.title}}" [(ngModel)]="mediaData.title" [ngClass]="mediaData.title ? '' : 'required'"></ion-input>


text:
Q: Read binary file into struct (translating instructions) Reading binary files and structs are a new area for me.
I understand how to read in the file and attempted various methods to read the raw data but seems I need to use struct.
I am trying to translate these instructions to python code:

The beginning of the Binary Merge file contains an array of GWI_file_header_struct structs (defined in file INET_INT.H) for the various channels, followed by the interlaced 32bit floating point data. The 1st 4 bytes in the header is the length of the header for 1 channel in bytes (i.e. 516 = 0x0204). To read the # of channels stored in the file, read the 'channelsPerFile' field of the 1st struct (e.g. to see how many headers are there). After the header, the data is saved in an interlaced form, where points are stored in the order that they are acquired in time.

The main confusion is how do I translate this to:
struct.unpack(...)

INET_INT.H struct:
typedef struct GWI_file_header_struct{  //  This struct is at the beginning of GWI iNet BINARY files that contain waves.
                                    //
                                    //  Macintosh:
                                    //
                                    //      file type:      'GWID'
                                    //      creator type:   'ioNe'      NETWORK_DATA_CREATOR

                                    //  ----------------------------------
                                    //  HEADER INFORMATION

iNetINT32 headerSizeInBytes;        //  contains length, in bytes, of this header (this does not include any data) { bytes 0..3, base 0 }

                                    //  ----------------------------------
                                    //  FILE INFORMATION

iNetINT32 int32key;                 //  32bit key that should contain 0x12345678 (this will help you make sure your byte lanes are ok).
                                    //  { bytes 4..7, base 0 }

iNetINT32 file_endian;              //  endian mode of stored data on disk: 0 = bigEndian_ion, 1 = littleEndian_ion
                                    //  { bytes 8..11, base 0 }

iNetINT16 int16key;                 //  16bit key that should contain 0x55b4; (this field should consume 2 bytes
                                    //   in the struct -- no padding) (i.e. INET_INT16_KEY = 0x55b4)
                                    //  { bytes 12..13, base 0 }

iNetINT16 zero;                     //  set to 0 (this field should consume 2 bytes in the struct -- no padding)
                                    //  { bytes 14..15, base 0 }

                                    //  # of seconds since Jan 1, Midnight, 1904 that the acquisition started (this is used to compute the
                                    //  date of acquisition). This overflows in 2030.
                                    //  Strip Chart: 1st digitized point in entire stream (i.e. 1st pt of 1st scan)
                                    //  Osc Mode:    1st point in current scan, secsSince1904_Int64 units
                                    //  { bytes 16..19, base 0 }
iNetUINT32 acquisition_SecsSince1904_FixedUint32_OverflowIn2030;

                                    //  ----------------------------------
                                    //  # OF POINTS STORED
                                    //
                                    //  This file contains a set of scans.  Each scan is 1 to .5billion points long.  For example,
                                    //  we might have 100 scans, each 1000 points long. In this example:
                                    //
                                    //      pointsPerScanThisChannel_LSW = 1000
                                    //      pointsPerScanThisChannel_MSW = 0
                                    //
                                    //      numScansStoredBeforeLastScan = 99
                                    //
                                    //      numPointsInLastPartialScan_LSW = 1000
                                    //      numPointsInLastPartialScan_MSW = 0
                                    //
                                    //  Each channel can have a different number of points per scan due to the sampleRateChanMULTiplier

iNetUINT32 pointsPerScanThisChannel_LSW;
iNetUINT32 pointsPerScanThisChannel_MSW;
                                    //  # points per scan =  (pointsPerScanThisChannel_MSW * 2^32) + pointsPerScanThisChannel_LSW
                                    //  { bytes 20..23, base 0 }
                                    //  { bytes 24..27, base 0 }

iNetUINT32 numScansStoredBeforeLastScan_LSW;
                                    //  # of complete scans stored in file
                                    //  { bytes 28..31, base 0 }

//  iNetUINT32 numScansStoredBeforeLastScan_MSW;
                                    //  this is defined below, at the end of the struct

iNetUINT32 numPointsInLastPartialScan_LSW;
iNetUINT32 numPointsInLastPartialScan_MSW;
                                    //  # points stored in last scan if it is partially complete = (numPointsInLastPartialScan_MSW * 2^32) + numPointsInLastPartialScan_LSW
                                    //  { bytes 32..35, base 0 }
                                    //  { bytes 36..39, base 0 }

                                    //  ----------------------------------
                                    //  TIME INFORMATION

iNetFLT32 firstPoint_Time_Secs;     //  time of 1st point, units are seconds
                                    //  { bytes 40..43, base 0 }

iNetFLT32 endUser_channel_samplePeriod_Secs;
                                    //  time between points for this channel,
                                    //  units are seconds.  Notice that channels
                                    //  can have different sample rates, which
                                    //  is the master_endUser_SampleRate / sampleRate_Divider,
                                    //  where 'sampleRate_Divider' is an integer.
                                    //  { bytes 44..47, base 0 }

                                    //  ----------------------------------
                                    //  TYPE OF DATA STORED

iNetINT32 arrayDataType;            //  Type of src array data. iNetDataType:
                                    //
                                    //  0   iNetDT_INT16:   16bit integer, signed
                                    //  2   iNetDT_UINT16:  16bit integer, unsigned
                                    //  3   iNetDT_INT32:   32bit integer, signed
                                    //  4   iNetDT_UINT32:  32bit integer, unsigned
                                    //  5   iNetDT_FLT32:   32bit float (IEEE flt32 format)
                                    //  6   iNetDT_Double:  'double', as determined by the compiler
                                    //                      (e.g. flt64, flt80, flt96, flt128)
                                    //                      see 'bytesPerDataPoint' field to see
                                    //                      how many bytes
                                    //  { bytes 48..51, base 0 }

iNetINT32 bytesPerDataPoint;        //  # of bytes for each datapoint (e.g. 4 for 32bit signed integer)
                                    //  { bytes 52..55, base 0 }

iNetStr31 verticalUnitsLabel;       //  pascal string of vertical units label (e.g. "Volts")
                                    //  { bytes 56..87, base 0 }

iNetStr31 horizontalUnitsLabel;     //  horizontal units label, e.g. "Secs", pascal string (0th char is the # of valid chars)
                                    //  { bytes 88..119, base 0 }

iNetStr31 userName;                 //  user named set by user, e.g. "Pressure 1" , pascal string (0th char is the # of valid chars)
                                    //  { bytes 120..151, base 0 }

iNetStr31 chanName;                 //  name of channel, e.g. "Ch1 Vin+", pascal string (0th char is the # of valid chars)
                                    //  { bytes 152..183, base 0 }

                                    //  ----------------------------------
                                    //  DATA MAPPING
                                    //
iNetINT32 minCode;                  //  if data is stored in integer format, this contains the mapping from integer
iNetINT32 maxCode;                  //  to engineering units (e.g. +/-2048 A/D data is mapped to +/- 10V, minCode = -2048,
iNetFLT32 minEU;                    //  maxCode = +2047, minEU = -10.000, maxEU = +9.995.
iNetFLT32 maxEU;                    //
                                    //  { bytes 184..187, base 0 }
                                    //  { bytes 188..191, base 0 }
                                    //  { bytes 192..195, base 0 }
                                    //  { bytes 196..199, base 0 }

                                    //  ----------------------------------
                                    //  iNet NETWORK ADDRESS (this does not need
                                    //  to be filled in, 0L's are ok)

iNetINT32 netNum;                   //  channel network # (this pertains to iNet only; use 0 otherwise)
                                    //  { bytes 200..203, base 0 }

iNetINT32 devNum;                   //  channel device # (this pertains to iNet only; use 0 otherwise)
                                    //  { bytes 204..207, base 0 }

iNetINT32 modNum;                   //  channel module # (this pertains to iNet only; use 0 otherwise)
                                    //  { bytes 208..211, base 0 }

iNetINT32 chNum;                    //  channel channel # (this pertains to iNet only; use 0 otherwise)
                                    //  { bytes 212..215, base 0 }

                                    //  ----------------------------------
                                    //  END USER NOTES

iNetStr255 notes;                   //  pascal string that contains notes about the data stored.
                                    //  { bytes 216..471, base 0 }

                                    //  ----------------------------------
                                    //  MAPPING

iNetFLT32 /* must remain flt32 */ internal1;    //  Mapping from internal engineering units (e.g. Volts) to external engineering
iNetFLT32 /* must remain flt32 */ external1;    //  units (e.g. mmHg).  This is used for 2 point linear mapping/calibration to
iNetFLT32 /* must remain flt32 */ internal2;    //  a new, user defined, coordinate system.  instruNet World does not read these values
iNetFLT32 /* must remain flt32 */ external2;    //  from the wave files, yet instead reads them from the instrNet.prf file -- they
                                    //  are only stored for the benefit of other software that might read this file. gsw 12/1/96
                                    //  { bytes 472..475, base 0 }
                                    //  { bytes 476..479, base 0 }
                                    //  { bytes 480..483, base 0 }
                                    //  { bytes 484..487, base 0 }

iNetFLT32 flt32key;                 //  flt32 key set to 1234.56 (i.e. INET_FLT32_KEY), Used to test floating point code. gsw 12/1/96
                                    //  { bytes 488..491, base 0 }

iNetINT32 sampleRate_Divider;       //  this channel is digitized at the master_endUser_SampleRate divided
                                    //  this 'sampleRate_Divider' (i.e. sampleRateChanMULT_integerRatio_N_int64)
                                    //  (helpful with FileType Binary Merge), gsw 1/29/97. Note: This field was introduced 1/29/97 and
                                    //  files saved before that time set it to 0.
                                    //  { bytes 492..495, base 0 }

iNetINT32 channelsPerFile;          //  # of channels per file (i.e. interlaced after array of headers) (helpful with FileType Binary Merge), gsw 1/29/97
                                    //  Note: This field was introduced 1/29/97 and files saved before that time set it to 0.
                                    //  { bytes 496..499, base 0 }

                                    //  ----------------------------------
                                    //  EXPANSION FIELDS

                                    #if 1   //  gsw 12/23/09

                                    //  # of complete scans stored in file, MS 32bits
                                    //  { bytes 500..503, base 0 }
iNetUINT32 numScansStoredBeforeLastScan_MSW;

                                    #else
                                    iNetINT32 expansion8;               //  expansion fields that are preset to
                                    #endif

iNetINT32 expansion9;               //  0 and then ignored
iNetINT32 expansion10;              //  { bytes 500..503, base 0 }
                                    //  { bytes 504..507, base 0 }
                                    //  { bytes 508..511, base 0 }

                                    //  ----------------------------------
                                    //  KEY TO TEST STRUCT PACKING

iNetINT32 int32key_StructTest;      //  32bit key that should contain 0x12345678; (i.e. INET_INT32_KEY)
                                    //  { bytes 512..515, base 0 }

                                    //  ----------------------------------
                                    //  ACTUAL DATA

/* iNetFLT32 *data[1]; */           //  contains array of data of type 'arrayDataType'

} GWI_file_header_struct;

Final Code and Results:
Code
from struct import *
# Current 3 channels: Ch11 Vin+, Ch13 Vin+ and Ch15 Vin+
# Header info extracted using provided header struct (INET_INT.H)
# After the header, the data is saved in an interlaced form,
# where points are stored in the order that they are acquired in time.
# 3 channels: A[0], B[0], C[0], A[1], B[1], C[1]...
# After header = 516 header size x 3 channels = 1,548 bytes
# Start of data at 1,548 bytes?
with open(file, "rb") as f:
    byte = f.read(12)
    header_size, int32key, file_endian = unpack('<3i', byte)
    # channel name 1
    f.seek(152)
    chan = f.read(183-152)
    chan = struct.unpack("<31s", chan)[0].rstrip(b'\x00').lstrip(b'\t')
    # channel name 2
    f.seek(152+header_size)
    chan2 = f.read(183-152)
    chan2 = struct.unpack("<31s", chan2)[0].rstrip(b'\x00').lstrip(b'\t')
print(header_size, int32key, file_endian)
print("channel 1: {}".format(chan))
print("channel 2: {}".format(chan2))

Results
516 305419896 1
channel 1: b'Ch11 Vin+'
channel 2: b'Ch13 Vin+'

A: Ok, this is not a full answer but I feel comments would be really unreadable here.
The first step is reading the first 12 bytes (three 4-bytes integers), and unpack them so we can check the endianness. Let's try big-endian first
from struct import *
with open(file, "rb") as f:
    byte = f.read(12)
header_size, int32key, file_endian = unpack('>3i', byte)

We expect to have int32key set at 305419896 (= \x12345678). If we get another value then let's switch to little-endian, i.e. change our unpack format string to <3i.
At this point we can read the rest of the header, with the same logic, and get all the info we need to read data for the first channel. I hope this can be a good start for you.


text:
Q: very simple anova model - compare variables with factors vs different vectors I think my question is best understood with a little  code:
#Load data
b <- structure(list(s1 = c(18.5, 24, 17.2, 19.9, 18), s2 = c(26.3,
     25.3, 24, 21.2, 24.5), s3 = c(20.6, 25.2, 20.8, 24.7, 22.9),
     s4 = c(25.5, 19.9, 22.6, 17.5, 20.4)), .Names = c("s1", "s2",
     "s3", "s4"), row.names = c(NA, -5L), class = "data.frame")

# Model A
# One way (the wrong way) to test wether s1,s2,s3,s4 differs:
summary(aov(s1~s2+s3+s4, data=b))
# R does not complain here - but I don't know what I am doing. I guess I am trying
# to explain the variance in s1, with the variable s2,s3 and s4.
# I am not sure how this actually is different from a proper anova (see below).
# Also I dont understand why the Sum of Squares for s3 is much larger than the sum of
# squares for s2 and s4.

# Model B
# The correct way to do it (requires reshape)
# install.packages('reshape')
# library(reshape)

summary(aov(value ~variable, data=melt(b)))
# This is correct - I am here testing variation within the factors of 'variable',
# to explain variation in 'value'.
# Doing
TukeyHSD(aov(value ~variable, data=melt(b)))
# shows me that s1 is significantly different from s2.
# My way of thinking is that this result should be evident from "model A"
# What does Sum of Squares in model A mean? - why is it so big for s3?

So as from the comments in the code above: I am asking for an explanation of how and why Model A is wrong.

A: Model A is not ANOVA. You are modelling one response variable (s1) using s2, s3 and s4 as predictors; this is analysis of covariance here. The reason why it is so big for s3 will become apparent if you plot a correlation matrix; cor( b ) will show you
            s1          s2         s3         s4
s1  1.00000000  0.08009315  0.7929146 -0.4200527
s2  0.08009315  1.00000000 -0.4433499  0.7846037
s3  0.79291464 -0.44334985  1.0000000 -0.8725241
s4 -0.42005268  0.78460371 -0.8725241  1.0000000

You cannot compare it with the model B, where you treat s1 as predictor rather than response variable, and your response variable is the class (s1, s2, s3 or s4).


text:
Q: tableView property causes loop I've got a subclass of a UITableViewController and when I call self.tableView in viewDidLoad it crashes and keeps calling the same method. I've transferred it from using storyboards (which was working fine) to just code and now it comes up with this bug. I have a xib file with the UITableViewCell subclass in though.
- (void)viewDidLoad
{
[super viewDidLoad];

UINib *nib = [UINib nibWithNibName:@"AddCell" bundle:nil];

//here
    [self.tableView registerNib:nib forCellReuseIdentifier:@"AddCell"];

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel:)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)];

// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

Wondering if anybody has the same problem or if there is a solution.
Thanks in advance

A: It almost seems like the class that contains the above -viewDidLoad implementation already owns the nib. This means every time it wakes, it proceeds to wake itself...
...which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, which then wakes itself, ... ... ... ... ...
Could this be your problem?


text:
Q: TextBox in Matlab Plot Please help me here. I am trying to include a small textbox with boundaries in  matlab plot, that says certain important things about the plot. I did come across this link,
http://www.mathworks.in/matlabcentral/newsreader/view_thread/154660
But I want to know if there's any other inbuilt plot function that can do this directly. I am really sorry, if this question is rudimentary, But I will be thankful for your help.
Moreover, am not actually clear what this link is exactly saying. How will the mtext place the textbox in plot? How do I actually code it? These are my confusions. Please help me here.

A: The function you are looking for is called annotation.
For example, annotation('textbox',[x y w h]) creates an editable text box annotation with its lower left corner at the point x,y, a width w, and a height h, specified in normalized figure units. Specify x, y, w, and h in a single vector.
Here a demonstration with some bells and whistles...
x=0:0.1:10;
var=1.85;
y=x.^(var);
plot(x,y);

annotation('textbox',...
    [0.15 0.65 0.3 0.15],...
    'String',{'plotting y=x^{var} ,',['with var =' num2str(var)]},...
    'FontSize',14,...
    'FontName','Arial',...
    'LineStyle','--',...
    'EdgeColor',[1 1 0],...
    'LineWidth',2,...
    'BackgroundColor',[0.9  0.9 0.9],...
    'Color',[0.84 0.16 0]);

For a full list of the annotation textbox properties is found here.

A: alldatacursors = findall(gcf,'type','hggroup')
set(alldatacursors,'FontSize',11)
set(alldatacursors,'FontName','Times')
set(alldatacursors,'BackgroundColor','w');


text:
Q: python xpath in xml.etree.ElementTree I use xml.etree.ElementTree with the function root.findall(xpath)
How can I find all roots' children which have 'Status' child with text 'Pass'?
<Root>
    <Some_Element> <!-- I want only this element -->
        <Status>Pass</Status>
    </Some_Element>
    <Some_Element>
        <Status>Fail</Status>
    </Some_Element>
</Root>

Thanks

A: Try something like
elements = [x for x in root.findall("Some_Element") if x.find("Status").text == "Pass"]


text:
Q: Initialization of MQQueueManager hangs in .NET core 2.2 We are having issues when initializing the Constructor for MQQueueManager. Our service is a Cron Job hosted on Kubernetes (AWS) which is scheduled to run every minute. This Cron Job connects to IBM MQ Server and reads the messages by looping through a list of queues. We are using "IBM MQ Client for .NET Core(9.2.0)" for connecting to MQ server.
Service was working fine for couple of months in Production , but one fine day the service stopped working, when checking the logs we could see Service was stuck while initializing MQQueueManager and Cron Job status in the POD was still showing running. Since the Cron Job was in running status , new jobs couldn't be created and finally we had to kill the POD on K8s to get the service up and running.
We have tried replicating the issue on our dev and test env's , but not succeeded yet. Not sure if the issue is while initializing
MQQueueManager constructor or the thread that is running is in deadlock. Below is the piece of code we are using... Any help would be appreciated....
Also there is no exception thrown...
private void InitialiseMQProperties()
        {
            try
            {
                _mqProperties = new Hashtable();
                _mqProperties.Add(MQC.HOST_NAME_PROPERTY, _hostName);
                _mqProperties.Add(MQC.PORT_PROPERTY, _port);
                _mqProperties.Add(MQC.CHANNEL_PROPERTY, _channelName);
                _mqProperties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
                _mqProperties.Add(MQC.USER_ID_PROPERTY, _userId);
            }
            catch (Exception ex)
            {
                Logger.Error("ConfigurationError: Initialising properties for Queue {Message}", ex.Message);
            }
        }

**This function gets called by the Cron Job every minute**

public async Task GetMessagesFromQueue()
        {
            try
            {
                InitialiseMQProperties();
                var queTaskList = new List<Task>();
                var _queues = _queueList.Split(',');
                foreach (var queue in _queues)
                {
                    queTaskList.Add(GetMessasgesByQueue(queue));
                }
                await Task.WhenAll(queTaskList).ConfigureAwait(false);
                Logger.Information("Messages successfully processed from the Queues");
            }
            catch (Exception ex)
            {
                Logger.Error("GeneralError: Reading messages from Queue error {Message}", ex.Message);
            }
        }

private async Task GetMessasgesByQueue(string queueName)
        {
            Logger.Information("Initialising queuemanager properties");
            var queueManager = new MQQueueManager("", _mqProperties);
            **From the logs it gets Stuck here**
            MQQueue queue = null;
            MQMessage message;
            MQGetMessageOptions getMessageOptions;

            try
            {
                getMessageOptions = new MQGetMessageOptions();
                getMessageOptions.Options |= MQC.MQGMO_SYNCPOINT + MQC.MQGMO_FAIL_IF_QUIESCING;
                Logger.Information("Accessing queue {queueName}", queueName);
                queue = queueManager.AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
                Logger.Information("Connection to queue succeeded");

                while (true)
                {
                    var commitTrans = true;
                    message = new MQMessage();
                    queue.Get(message, getMessageOptions);
                    var queMessage = message.ReadString(message.MessageLength);

                    Logger.Debug("Message read from MQ {0}", queMessage); //sensitive

                    if (queMessage.Length > 0)
                    {
                        var data = await _dataSerializer.DeserializePayload<Response>(queMessage);
                        if (data != null)
                        {
                           **Internal logic**
                        }
                    }

            }
            catch (MQException mqe)
            {
                switch (mqe.ReasonCode)
                {
                    case MQC.MQRC_NO_MSG_AVAILABLE:
                        Logger.Information("MQInfo: No message available in the queue {queueName}", queueName);
                        CloseQueue(queue);
                        break;

                    case MQC.MQRC_Q_MGR_QUIESCING:
                    case MQC.MQRC_Q_MGR_STOPPING:
                        CloseQueue(queue);
                        queueManager.Backout();
                        Logger.Error("MQError: Queue Manager Stopping error {Message}", mqe.Message);
                        break;

                    case MQC.MQRC_Q_MGR_NOT_ACTIVE:
                    case MQC.MQRC_Q_MGR_NOT_AVAILABLE:
                        CloseQueue(queue);
                        queueManager.Backout();
                        Logger.Error("MQError: Queue Manager not available error {Message}", mqe.Message);
                        break;

                    default:
                        Logger.Error("MQError: Error reading queue {queueName} error {Message}", queueName, mqe.Message);
                        CloseQueue(queue);
                        queueManager.Backout();
                        break;
                }
            }
            Logger.Information("Closing queue {queueName}", queueName);
            CloseQueue(queue);
            CloseQueueManager(queueManager);
            Logger.Information("Closing Queue manager for queue {queueName}", queueName);
        }

A: I have a very similar setup, I am using aks and XMS client for .net core 3.1,  running the CronJob every second, I saw a couple of crashes in Prod without understanding why even checking the POD logs, I had a conversation with the MQ team and their advice was to recycle the connection, it looks like the amount of connection exhaust the communication and crash the app but we couldn't see that in DEV or Test because of the amount of messages processed per environment.
What I ended doing was to spin up the container, create the connection with MQ and leave it open for the life cycle of the POD instead of each CronJob Cycle and destroying it only if the POD crashes or stops.
Something that worth evaluating?