text:
Q: Extracting value from nested list The JSON I want to parse looks like this:
{
  "results": [
    [
      {
        "field": "@logStream",
        "value": "i-0d41c4f2b294fae88-messages"
      },
      {
        "field": "@ptr",
        "value": "CmEKJgoiMTI1NzEwNTIwMzE3OkRhdGFJbmdlc3QtZW50ZXJwcmlzZRAHEjUaGAIGPjW1igAAAACsKl4NAAY/k4KwAAAAoiABKIzAjqzoMDC5+ZGs6DA4D0DrEEi4C1DlBxgAEA4YAQ=="
      }
    ]
  ],
  "statistics": {
    "recordsMatched": 94761,
    "recordsScanned": 94761,
    "bytesScanned": 13659575
  },
  "status": "Complete"
}

From each sublist in the results list, I want the value of value for every field that equals @logStream.
How can this be achieved?
The closest I've been able to come to even getting anything that distinguishes field values is this:
results[].[field==`@logStream`]

But that only gives booleans:
[
  [
    true
  ],
  [
    false
  ]
]

What I'd like to get is this, or something like it:
[
  [
    {
      "value": "i-0d41c4f2b294fae88-messages"
    }
  ]
]

I also tried
results[].[field==`@logStream`].value

and
results[].[field==`@logStream`].[value]

but those only gave me [ null ] and null.

A: The biggest issue in your query is the fact that you forgot the question mark ? in order to make a proper filter projection [?someCondition], and not a multiselect .[someAttributeProjectedInAnArray].
The other issue is that you are using a flatten projection [] on your results array without stopping it, which makes it impossible to do the subsequent filter projection you need on the field attribute, where you could have used a [*].
Then, to achieve the selection of the value attribute, you can use a multiselect hash, this time: .{value: value}.
Knowing all this, if you want to achieve exactly the output stated your question, you can use this query:
results[*][?field ==`@logStream`].{value: value}

Wich would yield:
[
  [
    {
      "value": "i-0d41c4f2b294fae88-messages"
    }
  ]
]

You can even go further and flatten the list of lists:
results[*][?field ==`@logStream`][].{value: value}

Would yield:
[
  {
    "value": "i-0d41c4f2b294fae88-messages"
  }
]

Or simplify the multiselect hash in a list projection:
results[*][?field ==`@logStream`][].value

Would yield:
[
  "i-0d41c4f2b294fae88-messages"
]

Or use alternative syntaxes, by keeping your first flatten projection, stop it with a pipe expression, then apply your query:
results[]|[?field ==`@logStream`].{value: value}

Would yield:
[
  {
    "value": "i-0d41c4f2b294fae88-messages"
  }
]

And
results[]|[?field ==`@logStream`].value

Would yield:
[
  "i-0d41c4f2b294fae88-messages"
]


text:
Q: Run C program in Xcode 4 using makefile I have created an 'External Build Project' in Xcode 4 using a makefile. The project builds perfectly, except the only way I know how to get it to run is in Terminal.
Is there a way I can run the program in Xcode 4 or is Terminal it ?

A: Yes, you can!
Product -> Edit scheme
Select "Run" from the left panel, select "Info" from top and specify "Executable" drop list
Select next pane "Arguments" and add "Arguments Passed On Launch" (to "Executable" you select before)

A: Yes, you need to create a Custom Executable, so that Xcode knows where your built executable resides and how to run it. In Xcode 3 it's Project -> New Custom Executable....
This will allow you to to run your executable and even do source level debugging if you have added the source code to the project. The only minor hassle is that you have to manually select which custom executable is "active" when you switch between e.g. debug and release builds.

Note re Xcode 4: I don't use Xcode 4 but looking at the online help the nearest equivalent to Xcode 3's "custom executable" seems to be:
Customize Executables in the Scheme Editor
To customize the environment in which a product is launched in Xcode 3, you click the executable in the Groups & Files list and then open the Info window. In Xcode 4, choose Edit Active Scheme from the Scheme pop-up and choose the product you want to run (Figure 3-10). Note that you can choose to display the running product at a higher UI resolution to simulate running at a different display resolution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Protecting associations with Protector I want to use Protector to control the fields that unauthorized users can see on my models but I'm having trouble using it to hide associations.
I have a project model and a post model. They partially look like this.
class Project < ActiveRecord::Base
  has_many :posts
  protect do
    can :read, %w(title)
    cannot :read, %w(posts)
  end

end

class Post < ActiveRecord::Base
  belongs_to :project
  protect do
    cannot :read
  end
end

Now let's say I create some records that look like this
Project.create(title: 'project one')
User.create(email: 'example@user.com')
Post.create(project_id: Project.first.id, title: 'post one')
Post.create(project_id: Project.first.id, title: 'post two')

When I ask for Project.first.restrict!(User.first).posts I get a non-empty ActiveRecord relation. I can't access the titles of the objects in the relation, but I can see their IDs and how many posts there are. I'd rather be able to restrict access to the Project object so that no posts are returned at all. Is this possible with Protector or should I look for another solution?

A: The thing here is that you misuse it :). You shouldn't try to make your association unreadable since it's not realy a value in terms of ActiveRecord. It's a Relation.
So to make things work – you have to use scopes. Add proper scope {} to your Post model. Then when you call .posts on Project it will give you a Relation of Posts restricted by the same user. And the described scope {} of Post model will apply as well.
Again: don't try to describe associated models – use their own protection block to define their independent behavior. This is how encapsulation works for Protector.


text:
Q: static files not found in django 1.11 I am getting "Not Found" when accessing any page on localhost.
I have read all related posts but still cannot understand why.
I have included 'django.contrib.staticfiles' in INSTALLED_APPS.
I have DEBUG = TRUE in my settings.py
my project layout and code is as the following.
Thank you in advance.
repo_root
├── manage.py
│
├── project_root
│   │
│   ├── accounts
│   │   ├── migrations
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── models.py
│   │   ├── tests.py
│   │   ├── views.py
│   │   └── urls.py
│   │
│   ├── templates
│   │   └── index.html
│   │
│   └── static
│       └── assets
│           ├── bootstrap
│           ├── css
│           ├── fonts
│           ├── img
│           └── js
│
├── config_root
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
│

settings.py
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(
        BASE_DIR,
        'project_root/static/assets')
]

STATIC_ROOT = os.path.join(
    BASE_DIR,
    'project_root/staticfiles')

index.html
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>index</title>
    <meta name="description" content="sample_content">
    <link rel="stylesheet" href="'static/assets/bootstrap/css/bootstrap.min.css'">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,400i,700,700i,600,600i">
    <link rel="stylesheet" href="'static/assets/fonts/simple-line-icons.min.css'">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.css">
    <link rel="stylesheet" href="'static/assets/css/smoothproducts.css'">
</head>

urls.py
url(r'^index/$', IndexView.as_view())

views.py
class IndexView(TemplateView):
    template_name = "index.html"

A: I didn't have,
{% load static %}
and
href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}"
adding these solved the problem.
Thank you!

A: Your STATICFILES_DIRS isn't defined properly. Your BASE_DIR is most probably defined as your project_root folder, since this is the default Django setting. You should leave out project_root in your definition.
STATICFILES_DIRS = [
    os.path.join(
        BASE_DIR,
        '/static/')
]
You should also include static files urls to your urlpatterns.
Check Django docs for further info https://docs.djangoproject.com/en/2.1/howto/static-files/


text:
Q: Live updates in website? (streamerapi) I was in http://finance.yahoo.com/ and checked the europe tab ( markets are open here atm) you ll see trades updating live, I went to firebug to the Net tab and there was no updates... so I wonder how are they doing that?
I can see there is a streamerapi.finance.yahoo.com that actually makes fiddler throw an error.
Anyone knows anything else about this live update?
Really interested in this, would really like to know if they are constantly polling , the updates seem to happen at irregular intervals
found some info here
Please note my interest is on the seeminly push aspect of it ( ie view is updated when there is new information)
Cheers

A: It is called Comet.
http://en.wikipedia.org/wiki/Comet_(programming)

A: It is a comet system using a hidden iframe technique.  A step by step description of what is going on with streamerapi as well as a simple debug HTA to consume the feed is available on my site: AJAX Push – Comet.


text:
Q: Cannot get SD Card formatted as ext2 to work on MX Linux laptop Summary
I formatted a 64Ggb micro SD Card with an ext2 filesystem. After
mounting and copying files to it, many files were corrupted; almost 400 out of 10,500 files.
I also tried ext3 and ext4. And I see, here, a number of people have successfully formatted SD Cards with ext file systems.
Details

*

*I used fdisk to delete the partition and recreate it as a Linux partition

    fdisk /dev/mmcblk0
        d, 1
        n, p, 1, 2048, max
        w

    Command (m for help): p
    Disk /dev/mmcblk0: 59.46 GiB, 63847792640 bytes, 124702720 sectors
    Units: sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disklabel type: dos
    Disk identifier: 0x1fdb5227

    Device           Boot Start       End   Sectors  Size Id Type
    /dev/mmcblk0p1         2048 124702719 124700672 59.5G 83 Linux

*

*Create the filesystem

    mkfs -t ext2 -m 1 -b 2048  /dev/mmcblk0p1
    tune2fs -L microsd /dev/mmcblk0p1

*

*I mounted with this /etc/fstab entry:

    LABEL=microsd /mnt/data1 ext2 auto,async,rw,exec,noatime,nosuid,nodev 0 2

*

*I copied about 10,500 files to /mnt/data1/

I did a diff between the source and the copied files. Almost
400 files were different
Hardware and OS

*

*Dell Inspiron 11-3180 laptop

https://www.dell.com/support/home/en-us/product-support/product/inspiron-11-3180-laptop/docs

*

*SD Card: SanDisk Extreme, 64GB, MicroSD, V30, XC1, [3] A2
plugged it into the microSD slot

*OS: MX-21.2.1_KDE_x64 Wildflower April 9, 2022

*Kernel: 5.10.0-20-amd64 #1 SMP Debian 5.10.158-2 (2022-12-13) x86_64 GNU/Linux
Update 1

*

*Tried using f2fs filesystem

mkfs -t f2fs -f /dev/mmcblk0p1

        F2FS-tools: mkfs.f2fs Ver: 1.14.0 (2020-08-24)

Info: Disable heap-based policy
Info: Debug level = 0
Info: Trim is enabled
Info: Segments per section = 1
Info: Sections per zone = 1
Info: sector size = 512
Info: total sectors = 124733440 (60905 MB)
Info: zone aligned segment0 blkaddr: 512
Info: format version with
  "Linux version 5.10.0-20-amd64
  (debian-kernel@lists.debian.org)
  (gcc-10 (Debian 10.2.1-6) 10.2.1 20210110, GNU ld
  (GNU Binutils for Debian) 2.35.2) #1 SMP Debian 5.10.158-2 (2022-12-13)"
Info: [/dev/mmcblk0p1] Discarding device
Info: This device doesn't support BLKSECDISCARD
Info: Discarded 60905 MB
Info: Overprovision ratio = 0.810%
Info: Overprovision segments = 497 (GC reserved = 254)

*

*mounted with this /etc/fstab entry:

    /dev/mmcblk0p1 /mnt/mxtrance.data1 f2fs auto,async,rw,exec,noatime,nosuid,nodev 0 0

*

*After copying 10,500 files, 35 files were shown to be "different"

I then recopied just those 35 files and diff reported no differences.
But 5 minutes later it showed 20 files had problems: "Input/output
error"

*

*I'm giving up on this SD Card

It could be this particular SD Card just does not work with being
re-formatted.  I'm going to buy another SD Card "type" and then try again.
Update 2

*

*Tried a different new MicroSD card.

    SD Card: SanDisk Ultra, 64gb, MicroSD, [1], XC 1, (10) A1
             140MB/s transfer speed

*

*I used fdisk to delete the partition and recreate it as a Linux partition

Before:
    /dev/mmcblk0p1      32768 124735487 124702720 59.5G  7 HPFS/NTFS/exFAT

    fdisk /dev/mmcblk0
        d
        n, p, 1, 2048, 124735487
        w

After:
    /dev/mmcblk0p1       2048 124735487 124733440 59.5G 83 Linux

Reboot

*

*Create the f2fs filesystem

Along with man pages, this was useful:
https://docs.kernel.org/filesystems/f2fs.html
    mkfs -t f2fs -l microsd -f /dev/mmcblk0p1

    F2FS-tools: mkfs.f2fs Ver: 1.14.0 (2020-08-24)
    Info: Disable heap-based policy
    Info: Debug level = 0
    Info: Label = microsd
    Info: Trim is enabled
    Info: Segments per section = 1
    Info: Sections per zone = 1
    Info: sector size = 512
    Info: total sectors = 124733440 (60905 MB)
    Info: zone aligned segment0 blkaddr: 512
    Info: format version with
      "Linux version 5.10.0-20-amd64 (debian-kernel@lists.debian.org)
      (gcc-10 (Debian 10.2.1-6) 10.2.1 20210110, GNU ld (GNU Binutils
      for Debian) 2.35.2) #1 SMP Debian 5.10.158-2 (2022-12-13)"
    Info: [/dev/mmcblk0p1] Discarding device
    Info: This device doesn't support BLKSECDISCARD
    Info: Discarded 60905 MB
    Info: Overprovision ratio = 0.810%
    Info: Overprovision segments = 497 (GC reserved = 254)
    Info: format successful

*

*Mount with /etc/fstab

    LABEL=microsd   /mnt/mxtrance.data1 f2fs auto,async,rw,exec,gc_merge,discard,data_flush,noatime,nosuid,nodev 0 0

*

*Copied 10,519 files to /mnt/mxtrance.data1, then did a diff between the source and destination. There were no differences.

*About an hour later, after deleting 2 files, the diff showed 50 files
were different, i.e. damaged. I should have only seen 2
differences. It looks like only binary files are getting damaged (but only some).

*Result: still unusable.


text:
Q: What is the difference between "$a" and $a in unix For example:
#!/bin/sh
a=0
while [ "$a" -lt 10 ]
   b="$a"
   while [ "$b" -ge 0 ] do
      echo -n "$b "
     b=`expr $b - 1`
   done
   echo
   a=`expr $a + 1`
done*

The above mentioned script gives the answer in triangle while with out the double quotes, it falls one after the other on diff lines.

A: Here the difference is how the argument is passed to echo function. Effectively " " will preserve whitespaces.
This:
echo -n "$b "

Is translated to:
echo -n "<number><space>"

While this:
echo -n $b<space>

Will ignore the trailing space and will just output the number:
echo -n <number>

Therefore removing all the spaces that are needed for output to look "triangular".

A: After a variable is expanded to its value, word splitting (i.e. separating the value into tokens at whitespace) and filename wildcard expansion takes place unless the variable is inside double quotes.
Example:
var='foo   bar'
echo No quotes: $var
echo With quotes: "$var"

will output:
No quotes: foo bar
With quotes: foo   bar

A: There are errors in your script:

*

*no do after 1st while

*no ; before do after 2nd while

*why asterisk on done* at the end?

Now to answer your question.
If used as a paramenter:

*

*"$a" is one argument.

*$a (without quotes) is possibly multiple arguments:

Compare:
v='a b';  set $v; echo "\$#=$#, \$1=\"$1\",  \$2=\"$2\""
$#=2, $1="a",  $2="b"

v='a b'; set "$v"; echo "\$#=$#, \$1=\"$1\",  \$2=\"$2\""
$#=1, $1="a b",  $2=""


text:
Q: C#-Roslyn :How do I Use strings to define fields? For example, I want to define a field:
int i;

If I use SyntaxFactory:
SyntaxFactory.FieldDeclaration(
    SyntaxFactory.VariableDeclaration(
        SyntaxFactory.PredefinedType(
            SyntaxFactory.Token(SyntaxKind.IntKeyword)))
    .WithVariables(
        SyntaxFactory.SingletonSeparatedList<VariableDeclaratorSyntax>(
            SyntaxFactory.VariableDeclarator(
                SyntaxFactory.Identifier("i")))))
.NormalizeWhitespace()

It so loooooooong~
How do I define a field by using string?
EX:
string str = "int i = 0;";
{Api}.CreateField(str);


text:
Q: Nginx reverse proxy for elasticsearch - inserting filters I've got an elasticsearch instance, with an Nginx reverse proxy sat in front of it, implementing a URL level access control mechanism - approximately as described in this article
This is giving me per-index granularity, which is handy.
What I'm trying to figure out next though is - can I enforce a blanket filter criteria that excludes results from searches and direct document retrievals?
I'm thinking a 'group' model, where docs in my indices are tagged by group, and users can only see results and docs for their group.
Now, I know I could do a per-group index, and apply URL level controls.  That may be my workaround if I can't do this.
I have had a look at aliasing - this seems to do 90% of what I want, in that I can restrict a search to an alias. But what I can't then do is inhibit a direct 'GET' request with an (unauthorised) document ID.
Is there a way of doing this, or am I just on a road to nowhere?
Note - part of my reasons for this, is I'm trying to use a fairly standard kibana setup, and I have overlapping groups of users.

A: While I can't directly answer your question (+1), I wanted to point out that the people working at elastic finally listened to all the requests made by people demanding access control for Elasticsearch and introduced Shield. Quoting the website:

With the rapid adoption of Elasticsearch, it is easier than ever to store, search, and analyze your data. Shield allows you to easily protect this data with a username and password, while simplifying your architecture. Advanced security features like encryption, role-based access control, IP filtering, and auditing are also available when you need them.
Your data is increasingly your most valuable asset. Password protect it with Shield.

Maybe having a look at least to check if this fulfills your requirements would be worth.

A: While starting a new project today at work with Elasticsearch I did some research and found Search Guard - Elasticsearch security for free. Obviously I can't judge (yet) how good this works but wanted to leave a pointer here in case you or others are still searching for (a) solution(s), and in case Shield can't be used, for whatever reasons.
Quoting the website, these are the features:

*

*Flexible REST layer access control (User/Role based; on aliases, indices and types)

*Flexible transport layer access control (User/Role based; on aliases, indices and types)

*Document level security (DLS): Retrieve only documents matching criterias

*Field level security (FLS): Filter out fields/sourceparts from a search response

*HTTP authentication (Basic, Proxy header, SPNEGO/Kerberos, Mutual SSL/CLIENT-CERT)

*HTTP session support through cookies

*Flexible authentication backends (LDAP(s)/Active Directory, File based, Proxy header, Native Windows through WAFFLE)

*Flexible authorization backends (LDAP(s)/Active Directory, File based, Native Windows through WAFFLE)

*Node-to-node encryption through SSL/TLS (Transport layer)

*Secure REST layer through HTTPS (SSL/TLS)

*X-Forwarded-For (XFF) support

*Audit logging

*Anonymous login/unauthenticated access

*Works with Kibana 4 and logstash

But, there are limitations as well:

*

*When using DLS or FLS you can still search in all documents/fields but not all documents/fields are returned

*Transport layer access control only with simple username/password login

*No automatic multi index filters (see below)

*Currently monitoring of the cluster needs no authentication and is allowed always (this may change in the future)

Maybe this is helpful and of value for you or someone else, who comes across this post.


text:
Q: Assumptions of linear models and what to do if the residuals are not normally distributed I am a little bit confused on what the assumptions of linear regression are.
So far I checked whether:

*

*all of the explanatory variables correlated linearly with the response variable. (This was the case)

*there was any collinearity among the explanatory variables. (there was little collinearity).

*the Cook's distances of the datapoints of my model are below 1 (this is the case, all distances are below 0.4, so no influence points).

*the residuals are normally distributed. (this may not be the case)

But I then read the following:

violations of normality often arise either because (a) the
distributions of the dependent and/or independent variables are
themselves significantly non-normal, and/or (b) the linearity
assumption is violated.

Question 1
This makes it sound as if the independent and depend variables need to be normally distributed, but as far as I know this is not the case. My dependent variable as well as one of my independent variables are not normally distributed. Should they be?
Question 2
My QQnormal plot of the residuals look like this:

That slightly differs from a normal distribution and the shapiro.test also rejects the null hypothesis that the residuals are from a normal distribution:
> shapiro.test(residuals(lmresult))
W = 0.9171, p-value = 3.618e-06

The residuals vs fitted values look like:

What can I do if my residuals are not normally distributed? Does it mean the linear model is entirely useless?

A: First off, I would get yourself a copy of this classic and approachable article and read it: Anscombe FJ. (1973) Graphs in statistical analysis. The American Statistician. 27:17–21.
On to your questions:
Answer 1: Neither the dependent nor independent variable needs to be normally distributed. In fact they can have all kinds of loopy distributions. The normality assumption applies to the distribution of the errors ($Y_{i} - \widehat{Y}_{i}$).
Answer 2: You are actually asking about two separate assumptions of ordinary least squares (OLS) regression:

*

*One is the assumption of linearity. This means that the trend in $\overline{Y}$ across $X$ is expressed by a straight line (Right? Straight back to algebra: $y = a +bx$, where $a$ is the $y$-intercept, and $b$ is the slope of the line.) A violation of this assumption simply means that the relationship is not well described by a straight line (e.g., $\overline{Y}$ is a sinusoidal function of $X$, or a quadratic function, or even a straight line that changes slope at some point). My own preferred two-step approach to address non-linearity is to (1) perform some kind of non-parametric smoothing regression to suggest specific nonlinear functional relationships between $Y$ and $X$ (e.g., using LOWESS, or GAMs, etc.), and (2) to specify a functional relationship using either a multiple regression that includes nonlinearities in $X$, (e.g., $Y \sim X + X^{2}$), or a nonlinear least squares regression model that includes nonlinearities in parameters of $X$ (e.g., $Y \sim X + \max{(X-\theta,0)}$, where $\theta$ represents the point where the regression line of $\overline{Y}$ on $X$ changes slope).

*Another is the assumption of normally distributed residuals. Sometimes one can validly get away with non-normal residuals in an OLS context; see for example, Lumley T, Emerson S. (2002) The Importance of the Normality Assumption in Large Public Health Data Sets. Annual Review of Public Health. 23:151–69. Sometimes, one cannot (again, see the Anscombe article).
However, I would recommend thinking about the assumptions in OLS not so much as desired properties of your data, but rather as interesting points of departure for describing nature. After all, most of what we care about in the world is more interesting than $y$-intercept and slope. Creatively violating OLS assumptions (with the appropriate methods) allows us to ask and answer more interesting questions.

A: In addition to the previous answer, I would like to add some points to improve your model:

*

*Sometimes non-normality of residuals indicates the presence of outliers. If this is the case, handle the outliers first.

*Maybe using some transformations solve the purpose however, it has consequences. Like the interpretation of coefficients changes if we transform variables.

*Additionally, to deal with multi-colinearity, you can refer https://www.researchgate.net/post/My_data_has_the_problem_of_multicolinearity_Removing_unique_variables_using_variance_inflation_factor_VIF_didnt_work_Any_solution

A: The most accessible exploration of the impact of non-normal errors that I have found is this paper by Schmidt and Finan.
Here is the summary of the results in the abstract:

Although outcome transformations bias point estimates, violations of the normality assumption in linear regression analyses do not. The normality assumption is necessary to unbiasedly estimate standard errors, and hence confidence intervals and P-values. However, in large sample sizes (e.g., where the number of observations per variable is >10) violations of this normality assumption often do not noticeably impact results. Contrary to this, assumptions on, the parametric model, absence of extreme observations, homoscedasticity, and independency of the errors, remain influential even in large sample size settings.

A: I wouldn't say the linear model is completely useless. However, this means that your model doesn't correctly/fully explain your data. There is a part where you have to decide whether the model is "good enough" or not.
For your first question, I don't think that a linear regression model assumes that your dependent and independent variables have to be normal. However, there is an assumption about the normality of the residuals.
For your second question, there is two different things you could consider :

*

*Check different kind of models. Another model might be better to explain your data (for example, non-linear regression, etc). You would still have to check that the assumptions of this "new model" are not violated.

*Your data may not contain enough covariates (dependent variables) to explain the response (outcome). In this case, you cannot do anything else. Sometimes, we may accept to check if the residuals follow a different distributions (e.g. t-distribution) but it doesn't seem to be the case for you.

In addition to your question, I see that your QQPlot is not "normalized". Usually it is easier to look at the plot when your residuals are standardised, see stdres.
stdres(lmobject)

I hope it helps you, maybe someone else will explain this better than me.

A: Your first problems are

*

*in spite of your assurances, the residual plot shows that the conditional expected response isn't linear in the fitted values; the model for the mean is wrong.

*you don't have constant variance. The model for the variance is wrong.
you can't even assess normality with those problems there.

A: For your second question,
Something that happened to me in practice was that I was overfitting my response with many independent variables. In the overfitted model I had non normal residuals. Even though, the results stablished that there wasn´t enought evidence to discart the posibility that some coeficients were zero (with p-values grater than 0.2). So in a second model, dismissing variables following a backward selection procedure I got normal residuals validated both graphically with a qqplot and by hypotesis testing with a Shapiro-Wilk test. Check if this could be your case.


text:
Q: How do I get variables from a returned value within a function of a function? I would like to put the returned player who sent the message !player1 or !player2 into a short list so that I can them for later, but I can't seem to find out how to get returned variables from functions inside of functions. I saw something about Closure which I think this is but even following the example I can't seem to get the returned values so I can assign them.
    def players(sender, event):

    def getplayer():

        msg = event.parsed[0]['msg']

        if msg == '!player1':
            BotBasicFunction.sendmsg(msgg='{} has joined the game!'.format(hasplayer()))
            hasplayer()

        if msg == '!player2':
            BotBasicFunction.sendmsg(msgg='{} has joined the game!'.format(hasplayer()))
            hasplayer()

    def hasplayer():
        invoker = event.parsed[0]['invokername']
        return invoker

    parsedmsg = event.parsed[0]['msg']

    players = [getplayer(), getplayer(), getplayer(), getplayer()]

    if parsedmsg == '!players':
        BotBasicFunction.sendmsg(msgg='{}'.format(players))


text:
Q: Using equal operators in C# In a If Statement When should I use =, == operators. Is there a === operator ?
What is the difference between these operators ?

A: = is assignment, like in
var i = 5;

Do not use this operator in the if statement.
== is for comparison
like in
if(i == 6){...}

there is no === operator in C#

A: a single = is for assignment like:
String myString = "Hi There";

A double equal is for comparison
if (5 == 5)
{
    do something
}

triple equals in some languages mean exactly equal.
C# does not utilize that operator.

A: In addition to the other answers, ReferenceEquals(x,y) is probably the closest thing to ===.

A: (The following is somewhat of a "comment" but is too long to be in a comment and would be lost with the other comments in this post.)
In C# == (like all operators in C#) is non-polymorphic. That is, the "version" of == that is called is always based on the static type at compile-time.
For instance:
object a = Guid.NewGuid();
object b = new Guid(""+a);
a == b // false -- uses object.== -- an *identity* compare

The Equals virtual method, on the other hand, is defined on object and is thus polymorphic across all sub-types.
object a = Guid.NewGuid();
object b = new Guid(""+a);
a.Equals(b) // true -- uses Guid.Equals

The choice of which one to use (== or Equals) is sometimes subtle -- but important. Most collection types will use Equals for tasks like Contains, etc. (This is pretty much required for all generic containers as there is no T.== for an arbitrary type T.)
// compile-time error: Operator '==' cannot be applied to operands of type 'T' and 'T'
bool equals<T> (T a, T b) { return a == b; }

// fair-game, because object defines Equals and it's polymorphic to subtypes
bool equals<T> (T a, T b) { return a.Equals(b); }

See When should I use == and when should I use Equals? and Guidelines for Implementing Equals and the Equality Operator (==), etc. Personally, I use == over Equals for statically-resolvable concrete types for which == is well-defined and I will not (by contract or convention) deal with a subtype -- examples are string and (most) structure types (e.g. int, Guid).
Happy coding.
Edit: There is no C# === operator (as people have said, duh!). If talking about the JavaScript variant, it would be approximately:
bool trippleEquals (object a, object b) {
  return a.GetType() == b.GetType() && a.Equals(b);
}

(It is strict equality in JavaScript -- but not object identity).
If talking about object identity then it should be the same as (object)a == (object)b which has the same semantics as object.ReferenceEquals(a,b).

A: In if statement you usually check for equality using ==, the = operator is the assignemt operator, and for my knowledge there is no === in c# I have never heard of it but it does exists in other languages I think in javascript it does.

A: This is to long for a comment so I decided to add another post.
I set var variables to an object list this and performed a comparison on the two vars that always failed comparison logic:
   object Object1;
   object Object2;
   var v1 = Object1;
   var v2 = Object2;
   if (v1 != v2)
   {
     // Do something
   }

Thanks to the posts here in this thread, I changed the logic as follows and now it works perfectly:
   object Object1;
   object Object2;
   var v1 = Object1;
   var v2 = Object2;
   if (!v1.Equals(v2))
   {
     // Do something
   }

A: = and == means fundamentally different things in the C# programming language. = is the assignment operator. It is used to assign values to variables.
The variable being the bucket in the computer memory and the assignment operator being the sign used to tell the computer to put some data in the bucket.
== is the equality operator it is used to determine if variable is equal to another variable. === is the operator for strict equality, this checks not only that what is in the bucket is the same, but that the type of variable is also the same, so for instance...
if you have a integer variable that is equal to 6 and a string that is equal to 6 if you check equality with ==, then the check will give a Boolean value of true, if you do it with === it will give a false.
This is useful in weakly typed programming languages, like JavaScript where implicit type conversions are common and you sometimes need to check for types and values during equality checks.
Seeing as C# you declare types when you declare your variables there is no way you would not, not know what a variables type is. Also, the CLR for C# is very strict in what type-conversion it allows and for such a type casting to happen you have to explicitly convert it. All of which makes a strict equality operator redundant to a large degree.
In decision structures, like loops, you will not use the assignment operator. Typically you will have your variables already defined and populated with data when you do these checks, you would use equality operator (Among others).

A: One equal sign is only used to assign a variable a value, the assignment will also return the same value so i could be used in a if statement but should never (almost...) be used in a if statement. Double equal signs are used to test if two values are equal and is what you use most of the time. I don't know of a === operator.
/Viktor

A: = is an assignment operator while
==is an comparision operator
Example:
int a=2;
int b=3;
int c=a=b; // a, b, c is equal to 3 as b=3

while
int a=2;
int b=3;

bool c= a==b // c = false since result of a==b is false

A: For extra info, the Not Equal operator is !=.
More info on C# Operators: http://msdn.microsoft.com/en-us/library/6a71f45d%28v=VS.100%29.aspx

A: I came across === only in javascript yet. It's the strict equal operator in there.
I used it several times as this if(obj === undefined){ alert("obj has sublimed");}

A: The question has since been answered, but I wanted to go into a little further detail between the uses.
"=" is an assignment operator. This is used to assign a value (or values) to a variable or object. An example of this would be:
int abc;
abc = 5;
Console.WriteLine("Print: " + abc);
*Console Output* Print: 5

You can't use a single equal sign in an if statement as the code would see you trying to assign a value to the object instead of comparing two values.
"==" is a comparison operator. This is the way you would compare values in an if statement. An example would be:
int abc = 5;
int xyz = 10; //Notice the use of a single equal sign to assign the values
if (abc == xyz)
{
    Console.WriteLine("The values are equal");
}
else
{
    Console.WriteLine("The values are not equal");
}
*Console Output* The values are not equal

"===" would technically be called an identical comparison operator. As the other answers have stated, C# does not allow for this sort of comparison. The reason it won't is because the identical comparison operator is checking whether the two object types are equal as well as their value. Essentially, it would check whether:
double abc = 5;
int xyz = 5;
if (abc === xyz)
{
    Console.WriteLine("The values and variable types are equal");
}
*Console Output* Error

The reason you can't use the "===" operator is because C# is smart enough to know before a build that the two variables are not the same type and if statements require you to compare the same variable types. IF you wanted to compare an int vs. double, you would need to cast (or parse) one of the variables to be the same type as the other. After casting, you would then compare with the regular "==" operator.
There are many languages that do allow you to compare with the identical comparison operators. JavaScript is an excellent example of a language that does allow for it. Since so many variables in JavaScript can be declared as a "var" type, it is beneficial to check whether a decimal value is equal to an integer value. C# however, will see the types being compared incorrectly during a build or even while coding (depending on your IDE) and will throw an error or exception when it reaches that piece of code


text:
Q: Create a page tracker in react-pdf I am creating a pdf viewer using react-pdf, I want to implement a page tracker in the pdf viewer, so that user can navigate to any page typed in the input box. And the page number should also update when the user reaches any page with that specific page number.
I am not able to implement this. Here is the image of the page tracker -

Please help me solve this problem.

A: I think you can use this if you can get the page number from change event.
import {useState} from 'react'

function Component(){
  const [pageNumber, setPageNumber] = useState(1)

  const onChangeHandler = (data) => {
    setPageNumber(data.pdfPageNumber)
  }
  return(
      <>
        <PdfViewer onStateUpdate={onChangeHandler}/>
        <pageNumber>{pageNumber}</PageNumber>
      </>

  )
}

Or you can use the useRef hook or useEffect hook.
Thank you.


text:
Q: Redis get command unpredictable result in runtime I have a small program which establishes web socket connection with crypto exchange, receive data and save it with set Redis command.
Code
//get Redis connection
    RedisAsyncCommands<String, String> redis = TRedis.getRedis();
    String symbol = "AGIETH";
    Session session = null;
    try {
        //Open websocket connection.
        session = (new
  BinanceApi()).websocketTrades(BinanceSymbol.valueOf(symbol), new BinanceWebSocketAdapterAggTrades() {
            @Override
            public void onMessage(BinanceEventAggTrade message) {
                double closeOrderBuy = 0;
                double closeOrderSell = 0;
                //check if we  saved order information before and if yes get data from Redis
                try {
                    if(redis.get(symbol+"Buy").get()!=null )
                    {
                        closeOrderBuy = Double.valueOf(redis.get(symbol+"Buy").get());
                    }
                    if( redis.get(symbol+"Sell").get()!=null)
                    {
                        closeOrderSell = Double.valueOf(redis.get(symbol+"Sell").get());
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                // get current value from exchange
                double currentCloseOrder = message.getPrice().multiply(message.getQuantity()).doubleValue();

                // rewrite data in Redis
                if(message.isMaker()) {
                    closeOrderBuy = currentCloseOrder + closeOrderBuy;
                    redis.set(symbol + "Buy",String.valueOf(closeOrderBuy));
                }
                else {
                    closeOrderSell = currentCloseOrder + closeOrderSell;
                    redis.set(symbol + "Sell",String.valueOf(closeOrderSell));
                }
            }
        });
    } catch (BinanceApiException e) {
        e.printStackTrace();
    }
    try {
        Thread.sleep(10000);
        session.close();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
//check what we write
    try {
        System.out.println(symbol + redis.get(symbol + "Buy").get() + "  " + redis.get(symbol + "Sell").get());
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

This is part of console output for AGIETH pair:
18:01:00.197 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.CommandHandler - [channel=0x6893917d, /127.0.0.1:64152 -> localhost/127.0.0.1:6379, chid=0x1] write(ctx, AsyncCommand [type=GET, output=ValueOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command], promise)
18:01:00.197 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.CommandEncoder - [channel=0x6893917d, /127.0.0.1:64152 -> localhost/127.0.0.1:6379] writing command AsyncCommand [type=GET, output=ValueOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command]
18:01:00.197 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.CommandHandler - [channel=0x6893917d, /127.0.0.1:64152 -> localhost/127.0.0.1:6379, chid=0x1] Received: 5 bytes, 1 commands in the stack
18:01:00.197 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.CommandHandler - [channel=0x6893917d, /127.0.0.1:64152 -> localhost/127.0.0.1:6379, chid=0x1] Stack contains: 1 commands
18:01:00.197 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.RedisStateMachine - Decode AsyncCommand [type=GET, output=ValueOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command]
18:01:00.197 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.RedisStateMachine - Decoded AsyncCommand [type=GET, output=ValueOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command], empty stack: true
***AGIETH 0.045027  null***

Output for AGIBTC pair
13:51:02.646 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.CommandHandler - [channel=0xc565134b, /127.0.0.1:54361 -> localhost/127.0.0.1:6379, chid=0x1] write(ctx, AsyncCommand [type=GET, output=ValueOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command], promise)
13:51:02.646 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.CommandEncoder - [channel=0xc565134b, /127.0.0.1:54361 -> localhost/127.0.0.1:6379] writing command AsyncCommand [type=GET, output=ValueOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command]
13:51:02.646 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.CommandHandler - [channel=0xc565134b, /127.0.0.1:54361 -> localhost/127.0.0.1:6379, chid=0x1] Received: 25 bytes, 1 commands in the stack
13:51:02.646 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.CommandHandler - [channel=0xc565134b, /127.0.0.1:54361 -> localhost/127.0.0.1:6379, chid=0x1] Stack contains: 1 commands
13:51:02.646 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.RedisStateMachine - Decode AsyncCommand [type=GET, output=ValueOutput [output=null, error='null'], commandType=io.lettuce.core.protocol.Command]
13:51:02.646 [lettuce-nioEventLoop-4-1] DEBUG io.lettuce.core.protocol.RedisStateMachine - Decoded AsyncCommand [type=GET, output=ValueOutput [output=0.5475444299999999, error='null'], commandType=io.lettuce.core.protocol.Command], empty stack: true
**AGIBTC 0.20769342999999998  0.5475444299999999**

I receive Null for some pairs, but exchange provides this information. I don't understand if it's a Redis problem, or if the logic of my program is incorrect?

A: I see two problems with your code:

*

*You use Redis async API but do not wait properly for set() operation to complete. RedisAsyncCommands.set returns RedisFuture. Before calling get() you must ensure that future is completed.

*You wait 10 seconds for trade event from BinanceApi. But some currency pairs may have few trades so 10 seconds is just not enough.

I've slightly modified your code by adding proper waiting conditions and all seems to work fine:
//get Redis connection
    RedisClient client = RedisClient.create("redis://localhost");
    StatefulRedisConnection<String, String> connection = client.connect();
    RedisAsyncCommands<String, String> redis = connection.async();
    String symbol = "AGIETH";
    Session session = null;
    CompletableFuture<String> cfBuy = new CompletableFuture<>();
    CompletableFuture<String> cfSell = new CompletableFuture<>();
    try {
        //Open websocket connection.
        session = (new
            BinanceApi()).websocketTrades(BinanceSymbol.valueOf(symbol), new BinanceWebSocketAdapterAggTrades() {
            @Override
            public void onMessage(BinanceEventAggTrade message) {
                double closeOrderBuy = 0;
                double closeOrderSell = 0;
                //check if we  saved order information before and if yes get data from Redis
                try {
                    if(redis.get(symbol+"Buy").get()!=null )
                    {
                        closeOrderBuy = Double.valueOf(redis.get(symbol+"Buy").get());
                    }
                    if( redis.get(symbol+"Sell").get()!=null)
                    {
                        closeOrderSell = Double.valueOf(redis.get(symbol+"Sell").get());
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                // get current value from exchange
                double currentCloseOrder = message.getPrice().multiply(message.getQuantity()).doubleValue();

                // rewrite data in Redis
                if(message.isMaker()) {
                    closeOrderBuy = currentCloseOrder + closeOrderBuy;
                    redis.set(symbol + "Buy",String.valueOf(closeOrderBuy)).thenAccept(cfBuy::complete);
                }
                else {
                    closeOrderSell = currentCloseOrder + closeOrderSell;
                    redis.set(symbol + "Sell",String.valueOf(closeOrderSell)).thenAccept(cfSell::complete);
                }
            }
        });
    } catch (BinanceApiException e) {
        e.printStackTrace();
    }
    try {
        System.out.println("Futures completed: " + cfBuy.get() + " " + cfSell.get());
        session.close();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //check what we write
    try {
        System.out.println(symbol + redis.get(symbol + "Buy").get() + "  " + redis.get(symbol + "Sell").get());
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

Output:
Futures completed: OK OK
AGIETH0.06922798  0.08610368


text:
Q: PHP Firebird API: php_interbase or PDO? We've been using PDO for 2 years in new scripts to connect to our MySQL, PostgreSQL and SQLite databases.
We're now starting a project in which we'll need to read (and maybe a few simple UPDATE's) a Firebird 2.5 database file. I'd like to use PDO since we already use that and it will be less of a transition. However the PDO_FIREBIRD PECL package seems to be last updated in 2006.
So my question is: is it better to use the PDO Firebird driver or the php_interbase API for a new project? I.e. is the PDO Firebird driver production worthy?

A: The PDO Firebird is stable if you use it from main repository of PHP
You should use the the extension that comes with Php not the PECL one
Here is the PDO health status from last Year http://www.firebirdnews.org/?p=6619
Many bugs are fixed from then so you can just try it and abuse it.
The version from PECL is not updated for many years but i will take care of it soon https://bugs.php.net/bug.php?id=58824
Of course the php_ibase api is much older and well tested in production systems for years (from the old times of php3 ~ 1998)


text:
Q: How to split newline from char pointer in Objective-C? I have a buffer, that is char pointer. The content of this is something like:
aaa
bbb
ccc

How can I just get the aaa first line from that char pointer?
I try to convert it into NSString first, but can I split it by \n in Objective-c?
Something like:
arrayString[0] = "aaa", arrayString[1] = "bbb", arrayString[2] = "ccc"

A:   char *buffer = "aaa \n bbb \n ccc \n";
  NSString *str = [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
  NSArray *arr = [str componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
  NSLog(@"arr: %@", arr);


text:
Q: Set of independent sets is a sigma-algebra? I was wondering whether the set $\{E \in \mathscr{E};A,B,E \text{ are independent} \}$ is always a sigma-algebra, when $A,B$ are two independent sets in some probability space? I know that it is a Dynkin-system but is it also true that it is a sigma-algebra?
Somehow I guess the answer is no, but could not find a counterexample so far.

A: Define a probability space $\langle \Omega,\mathscr{F},P\rangle$ where
\begin{eqnarray}
\Omega&=&\mathbf{2}^{3} \\
\mathscr{F}&=&\mathcal{P}\Omega \\
\mu(A)&=&\frac{\vert A\vert}{8}.
\end{eqnarray}
Now, let $A$ and $B$ be defined by
\begin{eqnarray}
A&=&\pi_1^{-1}\{0\}=\big\{\langle 0,x,y\rangle\in\Omega\big\vert x,y\in\{0,1\}\big\}\\
B&=&\pi_2^{-1}\{0\}=\big\{\langle x,0,y\rangle\in\Omega\big\vert x,y\in\{0,1\}\big\}
\end{eqnarray}
so that $A$ and $B$ are independent with $P(A)=P(B)=\frac{1}{2}$, and let $\mathscr{I}$ denote the set of elements of $\mathscr{F}$ which are independent of $A$ and $B$.
Finally, let $E_1$ and $E_2$ be:
\begin{eqnarray}
E_1 &= &\big\{\langle 0,0,0\rangle,\langle 1,1,0\rangle,\langle 1,0,0\rangle,\langle 0,1,0\rangle\big\} \\
E_{2}&=&\big\{\langle 0,0,0\rangle,\langle 1,1,1\rangle,\langle 1,0,1\rangle,\langle 0,1,1\rangle\big\}.
\end{eqnarray}
Then $E_1$ and $E_2$ are both independent of $A$ and $B$ (and $A\cap B$) and are thus elements of $\mathscr{I}$.  But $$E_1\cap E_2=\big\{\langle 0,0,0\rangle\big\}\subseteq A\cap B$$ and so $E_1\cap E_2$cannot be independent of either $A$ or $B$.
It follows that $\mathscr{I}$ is not a $\pi$-system, and hence not a $\sigma$-algebra.


text:
Q: Postman post request to Rails API strong params error I have a controller that uses strong params with require and permit. When I'm testing this endpoint with postman, I keep getting something like:
undefined method `permit' for "{foo: [1,2,3], bar: 1}":String

I know this controller works fine when I make the post request through the UI, but testing with postman gives me this error each time. I'm sending my payload through raw as JSON(application/json) and the header with the corresponding content type too.
This is the body I'm passing thru:
{
    "foos": {"foo":[1,2,3], "bar": 2675}
}

  def foos_params
    params.require(:foos).permit(:foo, :bar)
  end

A: In Headers tab add Content-Type: Application/json

A: In my opinion,
with Postman input params:
key       : value
foos[foo] : [1,2,3] # this is string:  JSON.stringify([1,2,3]) => "[1,2,3]"
foos[bar] : 2675
In controller:
def foos_params
   params.require(:foos).permit(:foo, :bar)
end

But, we need convert string to array for :foo:
ActiveSupport::JSON.decode(foos_params[:foo]) # => [1, 2, 3]


text:
Q: Coherent configurations (example and explanation) A coherent configuration is a
pair $(X, S)$ consisting of a finite set $X $ of size $v$  and a set $S$ of binary relations on $X$ such that
•$ S$ is a partition of $X × X$;
• the diagonal relation $ ∆X$  is the union of some relations in $S$;
• for each $R  \in  S$ it holds that $R^{T}  \in S$;
• there exist integers $p^{R}_{ ST}$ such that
|$\{z ∈ X|(x, z)  \in  S$  and  $(z, y) \in  T \}| = p^{R}_{ ST} \}$
whenever $(x, y) \in  R$, for each $R, S, T ∈ S$.
I am new to this subject, so it is hard for me to understand. I request to explain above four axioms using an example.
I have tried some notes, most of them have not included any example.

A: The canonical examples arise from a group of permutations acting on $X$. Define two ordered pairs $(a,x)$ and $(b,y)$ to be related if there is an element of $G$ that maps $(a,x)$ to $(b,y)$, i.e., some element $g$ in $G$ maps $a$ to $b$ and $x$ to $y$. The set of ordered pairs related to a given pair is an orbit of $G$ acting on $X\times X$, and these orbits form a partition of $X\times X$. Thus the first axiom holds.
For the second axiom, note that all pairs in the orbit of a pair $(a,a)$ have the form $(b,b)$, and so the diagonal of $X\times X$ has a partition as required.
The orbit of $(a,b)$ is the ``transpose'' of the orbit of $(b,a)$.
Finally, if $x$ is $S$-related to $a$ and $T$-related to $b$ and $g\in G$, then $x^g$ is also $S$-related $a^g$ and $T$-related to $b^g$. So, in what I hope is an obvious notation,
\[ p_{S,T}(a,b) = p_{S,T}(a^g,b^g)\]
for all $g$ in $G$. From this it follows that the intersection numbers are well-defined.

A: We also know that if each relation R is represented by a matrix A whose rows and columns are indexed by the elements of X with (x,y) entry 1 if (x,y) belongs to R , otherwise 0.
Then the three conditions become:
1. The sum of the matrices is the all-1 matrix.
2.There is a subset of the matrices which sums to the identity matrix.
3.The set of matrices is closed under transposition.
But what will the fourth condition become ? Please explain in detail.


text:
Q: Nginx + Wordpress + Roots Rewrite URL Parameters I am trying to have Wordpress handle custom parameters from a rewritten URL. Using the below rewrite, I can do a print_r($_REQUEST) and see that a URL such as spots.com/plans/ky/lexington/ actually shows state=ky and city=lexington, but it is on the 404.php, instead of actually posting the values to spots.com/plans/.
For the rewrite, I have tried doing spots.com/?pagename=plans&state=$1&city=$2, but in that case, it just dumps me onto spots.com/plans without anything being populated. I have gotten a URL such as spots.com/plans/41005/ to post correctly (using last rather than break), but the second argument is tripping me up to the tune of 10 or so hours of nginx config and filters in functions.php.
/plans/?state=ky&city=lexington

populates the page correctly, but is ugly and onerous.
Below is the most recent Nginx config I've used, which results in
Array ( [q] => /plans/ [state] => ky [city] => burlington )

being shown on the 404 page I'm redirected to.
# serve static files directly
    location ~* ^.+.(jpg|jpeg|gif|png|ico|html|txt)$ {
    access_log        off;
    expires           max;
    }

    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args; #q=$uri isn't needed, just using it for troubleshooting?
    }

#Pass off php pages to php-fpm
        location ~ \.php$ {
        try_files $uri =404;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include /etc/nginx/fastcgi_params;
        }

rewrite ^/plans/([^.]*)/([^.]*)/$ /plans/?state=$1&city=$2 break;
rewrite ^/plans/([^.]*)/([^.]*)$ /plans/?state=$1&city=$2 break;

Since the values seem to be passing through Nginx, should I be looking more at
 add_filter('query_vars', 'parameter_queryvars' );
    function parameter_queryvars( $qvars )
    {
    $state[] = 'state';
    $city[] = 'city';
    $qvars = $city[] + $state;
    return $qvars;
    }

or am I way out in left field?


text:
Q: NGINX Load Balancer routing to different ip if request fail I have following nginx configuration for my reverse proxy load balancer.
upstream appserver{
    server 192.168.1.101:3800;
    server 192.168.1.102:3800;
    server 192.168.1.103:3800;
    server 192.168.1.104:3800;
}
server {
    location /api {
        proxy_pass         http://appserver;
    }
}

If by any chance or error my one node instance is breaking or getting restart in middle of processing request, my load balancer is redirecting the request to other ip in reverse proxy. I dont want this to happen. I want it should not redirect and respond back with 500 or something else.

A: If I understand your request correctly I think you need proxy_next_upstream off;
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream


text:
Q: Kuenneth-formula for group cohomology with nontrivial action on the coefficient For a trivial action on the coefficient, we have the following Kuenneth formula
for group cohomology:
$$
H^n(G_1 \times G_2; M) \cong
[\oplus_{i= 0}^n H^i(G_1;M) \otimes_M H^{n-i}(G_2;M)]
\oplus [\oplus_{p =0}^{n+1} \text{Tor}^M(H^p(G_1;M),H^{n+1-p}(G_2;M))]
$$
where $G_1$ and $G_2$ are finite groups and/or compact Lie groups --Edit-- and $M$ is a PID such as $Z$?
If the group action on the coefficient $M$ is non-trivial, does the above Kuenneth formula remain valid?

A: I learned this through Ken Brown's textbook "Cohomology of Groups" (and studying under him):  I basically use the beginning of his Chapter 5 and solve the two exercises in that section.
Let $M$ (resp. $M'$) be an arbitrary $G$-module (resp. $G'$-module), let $F$ (resp. $F'$) be a projective resolution of $\mathbb{Z}$ over $\mathbb{Z}G$ (resp. $\mathbb{Z}G'$), and consider the map $(F\otimes_GM)\otimes(F'\otimes_{G'}M')\rightarrow (F\otimes F')\otimes_{G\times G'}(M\otimes M')$ given by $(x\otimes m)\otimes(x'\otimes m')\mapsto(x\otimes x')\otimes(m\otimes m')$.
Note that $(F\otimes_GM)$ $\otimes(F'\otimes_{G'}M')$ = $(F\otimes M)_G \otimes(F'\otimes M')_G$ ,
which is the quotient of $F\otimes M\otimes F'\otimes M'$ by the subgroup generated by elements of the form $gx\otimes gm\otimes g'x'\otimes m'$.  The isomorphism $F\otimes M\stackrel{\cong}{\rightarrow}M\otimes F$ of chain complexes ($M$ in dimension $0$) is given by $x\otimes m\mapsto (-1)^{deg(m)\cdot deg(x)}m\otimes x=m\otimes x$, and so the aforementioned quotient is isomorphic to $F\otimes F'\otimes M\otimes M'$ modulo the subgroup generated by elements of the form $(gx\otimes g'x'\otimes gm\otimes g'm')=(g,g')\cdot(x\otimes x'\otimes m\otimes m')$ where this latter action is the diagonal $(G\times G')$-action.  Now this is precisely
$$(F\otimes F'\otimes M\otimes M')_{G\times G'} = (F\otimes F')\otimes_{G\times G'}(M\otimes M')$$ and hence the considered map is an isomorphism.
Assuming now that either $M$ or $M'$ is $\mathbb{Z}$-free, we have a corresponding Künneth formula $\bigoplus_{p=0}^nH_p(G,M)\otimes H_{n-p}(G',M')\rightarrow H_n(G\times G',M\otimes M')$
$\rightarrow\bigoplus_{p=0}^{n-1}Tor_1^\mathbb{Z}(H_p(G,M),H_{n-p-1}(G',M'))$ by Proposition I.0.8[Brown].  Note that in order to apply the proposition we needed one of the chain complexes (say, $F\otimes_G M$) to be dimension-wise $\mathbb{Z}$-free (and so with a free resolution $F$ this means we needed $M$ to be $\mathbb{Z}$-free).
Actually, the general Künneth theorem has a more relaxed condition and it suffices to choose $M$ (or $M'$) as a $\mathbb{Z}$-torsion-free module}.

Cohomology Künneth Formula (no proofs, just statements/notes)
Let $M$ (resp. $M'$) be an arbitrary $G$-module (resp. $G'$-module), let $F$ (resp. $F'$) be a projective resolution of $\mathbb{Z}$ over $\mathbb{Z}G$ (resp. $\mathbb{Z}G'$), and consider the cochain cross-product $Hom_G(F,M)\otimes Hom_{G'}(F',M')\rightarrow Hom_{G\times G'}(F\otimes F',M\otimes M')$ which maps the cochains $u$ and $u'$ to $u\times u'$ given by $\langle u\times u',x\otimes x'\rangle=(-1)^{deg(u')\cdot deg(x)}\langle u,x\rangle\otimes\langle u',x'\rangle$.  This map is an isomorphism under the hypothesis that either $H_i(G,M)$ or $H_i(G',M')$ is of finite type, that is, the $i$th-homology group is finitely generated for all $i$ (alternatively, we could simply require the projective resolution $F$ or $F'$ to be finitely generated).
For example, if $M=\mathbb{Z}$ then $Hom_G(-,\mathbb{Z})$ commutes with finite direct sums, so we need only consider the case $F=\mathbb{Z}G$.  An inverse to the above map is given by $t\mapsto \varepsilon\otimes \phi$, where $\varepsilon$ is the augmentation map and $\phi:F'\rightarrow M'$ is given by $\phi(f')=t(1\otimes f')$.  Note that this does not hold for infinitely generated $P=\bigoplus^\infty \mathbb{Z}G$ because $Hom_G(P,\mathbb{Z})\cong\prod^\infty \mathbb{Z}$ is not $\mathbb{Z}$-projective (i.e. free abelian).
Assuming now that either $M$ or $M'$ is $\mathbb{Z}$-free, we have a corresponding Künneth formula $\bigoplus_{p=0}^nH^p(G,M)\otimes H^{n-p}(G',M')\rightarrow H^n(G\times G',M\otimes M')\rightarrow$
$\bigoplus_{p=0}^{n+1}Tor_1^\mathbb{Z}(H^p(G,M),H^{n-p+1}(G',M'))$ by Proposition I.0.8[Brown].


text:
Q: drupal 7 - can't restore anonymous user I noticed than my anonymous user was removed by something when i noticed $_SESSION was crashed for anonymous user
After gogling like a panther i take a look in my users sqltable and effectively the uid = 0 was not here.
So i apply the solve given by many guys like him : add this in sql:
insert into users (name, pass, mail, theme, signature, language, init, timezone) values ('', '', '', '', '', '', '', '');
update users set uid = 0 where name = '';
INSERT INTO users_roles VALUES(0,1);

and then flush cache. However even if the row uid = 0 is now with us, the anonymous is still not showed on the user list and the $_SESSION is still crashed.
Does anyone can help me to fix this issue?
(apologies for my english)
EDIT:
as thought I can't figure out to fix this, i give you a nice shot of my row:

Pls need help, i can't replace $_SESSION usage

A: Ok that's weird but it seems that the session is not started for the anonymous user, so adding this code in my module solve my problem:
if(session_id() == '') {
    // session isn't started
    session_start();
}

But if someone know a proper way to fix this, i take it


text:
Q: Laravel request validation (requests with arrays) I am developing an app using Laravel and VueJs. I have used the below form validation rules:
public function rules()
{
  $rules = [
    'id.*'=>'required|integer',
    'job_id.*'=>'required|integer',
    'satisfied.*'=>'nullable',
    'client_comments.*'=>'nullable',
    'improvements.*'=>'nullable',
    'rating.*'=>'integer|max:10|min:0'
  ];
  return $rules;
}

Further, I am sending the below axios request to the Laravel controller. However, the validation is not working. Could somebody can help?
The request comes to the Laravel controller as below:
array:2 [
  0 => array:7 [
    "client_comments" => null
    "id" => 34
    "improvements" => null
    "job_id" => 1
    "quality_cycle_id" => 14
    "rating" => "10"
    "satisfied" => null
  ]
  1 => array:7 [
    "client_comments" => null
    "id" => 35
    "improvements" => null
    "job_id" => 3
    "quality_cycle_id" => 14
    "rating" => "9"
    "satisfied" => null
  ]
]

I just used so many efforts to resolve this problem, but none of these worked. In the same application, I have put so many validations for single request. But this request is coming as an arrays inside array as above.
Appreciate, if somebody help.
Thanks

A: You can try to validate like this:
 $request->validate($request, [
          '*.id'=>'required|integer',
          '*.job_id'=>'required|integer',
          '*.satisfied'=>'nullable',
          '*.client_comments'=>'nullable',
          '*.improvements'=>'nullable',
          '*.rating'=>'integer|max:10|min:0']);

It works fine for me

A: Your field is inside of array not an array. It work for array of  inputs id[], job_id[], etc..
Try this,
public function rules()
{

 $rules = [

          '*.id'=>'required|integer',
          '*.job_id'=>'required|integer',
          '*.satisfied'=>'nullable',
          '*.client_comments'=>'nullable',
          '*.improvements'=>'nullable',
          '*.rating'=>'integer|max:10|min:0'

        ];

        return $rules;

    }

A: The request data should be in a specified filed like items, which you dump it out using
dd($request->input('items'));

That prints an array. So to validate that array you could use these rules:
public function rules()
{
  return [
    'items.*.id'=>'required|integer',
    'items.*.job_id'=>'required|integer',
    'items.*.satisfied'=>'nullable',
    'items.*.client_comments'=>'nullable',
    'items.*.improvements'=>'nullable',
    'items.*.rating'=>'integer|max:10|min:0',
  ];
}


text:
Q: Python: trouble reading number format I am reading from a file where numbers are listed as -4.8416932597054D-04, where D is scientific notation.  I have never seen this notation before.  How can Python read -4.8416932597054*D*-04 as -4.8416932597054*E*-04  I've looked at other question and haven't read anything that addresses this?  (Or I have and didn't recognize it.)  Thanks.

A: def to_float(s):
    return float(s.lower().replace('d', 'e'))

Edit: Can you give an example of an input string that still gives you 'the same error'? Because to_float('-4.8416932597054D-04') works perfectly for me, returning -0.00048416932597054.

A: Do you understand this notation? If so, you can use your knowledge to solve that. Do string formatting with the number, parse it, extract D-04 from the number using regular expressions and translate it into a more numberish string, append to the original string and make Python convert it.
There's not a Python module for every case or every data model in the world, we (you, especially) have to create your own solutions.

Example:
def read_strange_notation(strange_number):
    number, notation = strange_number.split('D-')
    number, notation = int(number), int(notation)
    actual_number = number ** notation # here I don't know what `D-` means,
                                       # so you do something with these parts
    return actual_number


text:
Q: CTreeCtrl state image limited to 15 images I have a CTreeCtrl that uses "state images" to get a second icon next to the normal icon.  From the documentation here http://msdn.microsoft.com/en-us/library/fc4e6etb(v=vs.80).aspx:

If a state image list is specified, a tree control reserves space to the left of each item's icon for a state image. An application can use state images, such as checked and cleared check boxes, to indicate application-defined item states. A nonzero value in bits 12 through 15 specifies the one-based index of a state image (0 indicates no state image).

Since there are only 4 bits and 0 is reserved to indicate no state image, you can only have 15 state images.  This is mentioned here as well: http://www.codeguru.com/cpp/controls/treeview/usingimages/article.php/c669
Question
I've used up all 15 state icons and would like to add more.  What are my options to achieve this?

A: Implement a custom-drawn tree-view or find such an implementation.


text:
Q: CMake per file optimizations Elsewhere the question has been asked, "How do I turn off optimizations on one file?" The answer is usually something like this:
cmake_minimum_required( VERSION 3.8 )

project( Hello )

add_executable( hello hello.c foo.c bar.c )

set( CMAKE_C_FLAGS_RELEASE "" )
set( CMAKE_CXX_FLAGS_RELEASE "" )

set_source_files_properties( hello.c
                PROPERTIES
                COMPILE_FLAGS -O0 )

This works unless you invoke cmake like this:
cmake -GNinja -DCMAKE_BUILD_TYPE=Release ../hello

And you get this in your build.ninja
FLAGS = -O3 -DNDEBUG   -O0

Checking the documentation on COMPILE_FLAGS

Additional flags to be added when compiling this source file.

This makes sense, it is added to the list of COMPILE_FLAGS, it does not override existing compiler flags.
So, within CMake how can you override the optimisation level on a single file and being able to compile the rest of the project in Release? Otherwise you can force the compile to CMAKE_BUILD_TYPE="" which is the default behavior, but that somewhat defeats a selling point of Cmake.

A: You can't overwrite compiler options with the makefile CMake generators on source file level. Options are always appended (see my answer at Is Cmake set variable recursive? for the complete formula).
This is - as far as I know - only supported with the Visual Studio solution/project generators. These generators have flag tables to identify flags that are in the same group/that does overwrite a previous defined flag.
So yours is more like a feature request to also add compiler option tables to CMake's makefile generators.

Alternatives
I just wanted to add some crazy CMake magic I came up with as a workaround. Add the following to your main CMakeLists.txt after the project() command:
if (CMAKE_BUILD_TYPE)
    define_property(
        SOURCE
        PROPERTY COMPILE_FLAGS
        INHERITED
        BRIEF_DOCS "brief-doc"
        FULL_DOCS  "full-doc"
    )
    string(TOUPPER ${CMAKE_BUILD_TYPE} _build_type)
    set_directory_properties(PROPERTIES COMPILE_FLAGS "${CMAKE_CXX_FLAGS_${_build_type}}")
    set(CMAKE_CXX_FLAGS_${_build_type} "")
endif()

This example moves the CMAKE_CXX_FLAGS_<build type> content into an new COMPILE_FLAGS directory property that is then linked to COMPILE_FLAGS source file property via define_property(... INHERITED ...).
Now the build type specific flags are only defined in COMPILE_FLAGS for each source file and you can overwrite/change them e.g. with the code snippet from your example:
set_source_files_properties(
    hello.c
    PROPERTIES
    COMPILE_FLAGS -O0
)

References

*

*Directory properties and subdirectories

*CMake: How do I change properties on subdirectory project targets?


text:
Q: TV connected via HDMI for audio only? Samsung TV has better speakers than my laptop. I want to have audio going through the TV without extra load on my video card. Is such a thing possible?

A: As far as I know, the HDMI standard insists there must be some picture, even if it's just black screen.
If that would be OK, then maybe some type of HDMI breakout box to separate the audio - something like this http://www.amazon.co.uk/Av-Tool-HDMI-AUDIO-BREAKOUT/dp/B00BBE77H8
I've never tested it, so I've no idea how it would work.


text:
Q: How to hide the output message of the curl elasticsearch command? Can not I get the message out of curl elasticsearch command?
ex)
> /usr/bin/curl -s -XPOST localhost:9200/_bulk --data-binary "@/home/1003783/data/20161201.json"
=> {"took":9,"errors":false,"items":[{"index":{"_index":"ctlg_info","_type":"1002154","_id":"20161201","_version":2,"_shards":{"total":3,"successful":3,"failed":0},"status":200}}]}

When I run the curl command against elasticsearch, I do not want to see the above message. It seems to be a message from elasticsearch.
Thank you.

A: You can use the -o switch and send the output to dev/null
> /usr/bin/curl -s -o /dev/null -XPOST localhost:9200/_bulk --data-binary "@/home/1003783/data/20161201.json"


text:
Q: how to show a missing bootloader? I don't have a bootloader. there's just a GRUB terminal-like interface and apparently, linux terminal commands (e.g. exit, shutdown, poweroff) don't work on it so I don't know what to do with it.
I have windows 8 and ubuntu 12.04 (both 64bit) installed on the partitions of my laptop.

A: Boot using a live usb/cd of ubuntu.
Use boot-repair to fix the problem.
After booting with live usb/cd ,Run following command in terminal,
sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
sudo apt-get install -y boot-repair && boot-repair

Use Recomended Repair
More information can be found here- > https://help.ubuntu.com/community/Boot-Repair


text:
Q: Can the same fusion law for foldr be applied to foldlmap? I've read there is no fusion law for foldl alone. If I guess correctly, this is due to foldl awkwardness for implementing map - which is mostly due to (foldl cons nil xs) reversing the list.
If instead we use conc lists, then the function foldlmap is much nicer in this aspect:
(foldlmap list conc nil xs) -> xs

If my guess is correct, then there should be a simple fusion law for foldlmap. Is this correct?

A: We can start with the "natural" fold-build fusion rule for an explicit concatenation list type:
{-# LANGUAGE RankNTypes #-}

data ConcList a = List a | Conc (ConcList a) (ConcList a) | Nil

buildCL :: (forall l . (a -> l) -> (l -> l -> l) -> l -> l) -> ConcList a
buildCL g = g List Conc Nil

foldCL :: (a -> v) -> (v -> v -> v) -> v -> ConcList a -> v
foldCL list conc nil cl = go cl
   where
      go (List a) = list a
      go (Conc cl1 cl2) = conc (go cl1) (go cl2)
      go Nil = nil

{-# RULES "foldCL/buildCL"
      forall list conc nil
             (g :: (forall l . (a -> l) -> (l -> l -> l) -> l -> l))
         . foldCL list conc nil (buildCL g) = g list conc nil #-}

Then in theory this translates to an equivalent over "normal" lists:
buildCL2 :: (forall l . (a -> l) -> (l -> l -> l) -> l -> l) -> [a]
buildCL2 g = g (\a -> [a]) (++) []

{-# RULES "foldl/map/buildCL2"
      forall list conc nil
             (g :: (forall l . (a -> l) -> (l -> l -> l) -> l -> l))
         . foldl conc nil (map list (buildCL2 g)) = g list conc nil #-}

But the beauty of foldr/build on lists is that it applies to quite a lot of things because a lot of functions are "natural producers" (can be rewritten in terms of build) and a lot are natural consumers (can be rewritten in terms of foldr). I think the pattern foldl/map/buildCL2 would be a lot harder to engineer.


text:
Q: POSTing a complex Dictionary to Controller I am attempting to post the following type to my controller.
Model
public class EmailNotificationSettings
{
    public string EmailHost { get; set; }
    public string EmailPassword { get; set; }
    public int EmailPort { get; set; }
    public string EmailSender { get; set; }
    public string EmailUsername { get; set; }
    public bool Enabled { get; set; }
    public bool EnableUserEmailNotifications { get; set; }
    public string RecipientEmail { get; set; }
    public Dictionary<NotificationType, NotificationMessageContent> Message { get; set; }
}

NotificationType
public enum NotificationType
{
    NewRequest,
    Issue,
    RequestAvailable,
    RequestApproved,
    AdminNote,
    Test,
}

NotificationMessageContent
public class NotificationMessageContent
{
    public string Subject { get; set; }
    public string Body { get; set; }
}

Now all of the properties are part of my form except Message.
Here is how I plan to populate Message
View
New Request Subject

    <input type="text" class="form-control form-control-custom " id="newRequestSubject" name="newRequestSubject" value="@Model.Message.FirstOrDefault(x => x.Key == NotificationType.NewRequest).Value.Subject">

New Request Body

    <input type="text" class="form-control form-control-custom " id="newRequestBody" name="newRequestBody" value="@Model.Message.FirstOrDefault(x => x.Key == NotificationType.NewRequest).Value.Body">

Javascript to Post
 $('#save').click(function (e) {
        e.preventDefault();

        var newRequestObj = {
            "Subject": $('#newRequestSubject').val(),
            "Body": $('#newRequestBody').val()
        };
        var message = { 'NewRequest': JSON.stringify(newRequestObj) };

        var $form = $("#mainForm");
        var data = $form.serialize();

        data = data + "&" +JSON.stringify(message);

        $.ajax({
            type: $form.prop("method"),
            data: data,
            url: $form.prop("action"),
            dataType: "json",
            success: function (response) {
               // Do something
            }
        });
    });

Now this is obviously the wrong way to do it as my Message property is not getting populated.
Any idea how I can POST to the controller and it update my model?
Controller if you want to see (Using NancyFX)
private Response SaveEmailNotifications()
{
    var settings = this.Bind<EmailNotificationSettings>();
    // settings.Message doesn't contain the new values
}

A: I cannot think of a way to make it work with pure HTML. The problem is you need to submit a control with the name "Message" that contain the data, then MVC mapping engine will map that control to the "Message" property of your model.
The best way I can think of is to use a JavaScript function (bound to the onsubmit event of the form) which collects the info as an array of objects and assign it to a variable called "Message" then serialize it with the rest of the form data and submit the form.


text:
Q: compare values in different chunks using pandas Say I have in memory a large file, loaded using chunksize in pandas. Now I have to compare every value with the ones ajdacent to it. My problem is that I can't seem to select at the same time the extreme values (in first and last position) of two different chunks.
Example:
print(df)

     a
0  102
1  101
2  104
3  110
4  104
5  105

count = 0
for i in range(len(df)-1):
    if df.iloc[i+1]['a']>df.iloc[i]['a']:
        count+=1

count would be equal to 3 in this example. But say I have loaded df from a .csv with chunksize=1, how would I achieve a similar result, considering that values will be in different chunks? In practice chunksize is 10000 and so the problem would be limited to the first and last value for each chunk.

A: EDIT:
Here is an example where I store the last_chunk_value to update the value when running the next loop.
I've tested a 'brut force' method to compare with the 'chunk script'. The results are the same with both methods.
By the way, I've simplified the 'brut force' method.
import pandas as pd
import numpy as np
import random

# 'data' generation as csv file
file = open("data.csv", 'w')
file.write('rand_int' + '\n')
for i in range(0, 10000):
    file.write(str(random.randint(80,120)) + '\n')
file.close()

# "brute force method"
df = pd.read_csv("data.csv")
length = int( (df.shift(-1) - df > 0).sum() )
print('number=', length)

# chunksize method
chunksize = 33
length = 0
last_chunk_value = np.nan
for chunk in pd.read_csv("data.csv", chunksize=chunksize):
    chunk['shift'] = chunk.shift(1)
    chunk.iloc[0, 1] = last_chunk_value
    length += (chunk['rand_int'] - chunk['shift'] > 0).sum()
    last_chunk_value = chunk.iloc[-1, 0]

print('number=', length)


text:
Q: django run code before model field access? (proxy model fields) I'm trying to proxy the access of some models' fields. A simple example of the usage I want.
@uppercase_fields(['name'])
class Book(models.Model):
   name = models.CharField(max_length=50)
   # .. more fields ..

Given a book instance with name='some_book':
Access to book.name should return 'SOME_BOOK'
I know it looks weird, but I need an access wrapper like this around model fields that will act as if I'd access the model fields normally. So a method is not an option here.
I thought of using __getattr__ but I read it might mess with django internals. Any better way, preferably simple?

A: I think you will have to go with __getattribute__ (not __getattr__, because it is called only if the attribute cannot be found in other ways).
Your implementation should call super().__getattribute__ to access the value and then either modify it if it is in your decorator list or return as is.


text:
Q: Trouble with realization Byte[] operations I use XOR operation for byte[]
public static byte[] XOR(byte[] buffer1, byte[] buffer2)
{
    for (int i = 0; i < buffer1.Length; i++)
        buffer1[i] ^= buffer2[i];
    return buffer1;
}

And realize shift methods for hashing algorithm.
public static byte[] RotHi(byte[] B, int count)
{
    for (int i = 0; i < count; i++)
    {
        byte[] a = ShHi(B);
        byte[] b = B;
        for (int j = (B.Length * 8) - 2; j >=0 ; j--)
        {
            b = ShLo(b);
        }
        B = XOR(a,b);
    }
    return B;
}
public static byte[] ShHi(byte[] B)
{
    return BitConverter.GetBytes(BitConverter.ToUInt64(B, 0) >> 1);
}
public static byte[] ShLo(byte[] B)
{
    return BitConverter.GetBytes(BitConverter.ToUInt64(B, 0) << 1);
}

And when it works individually result is correct
W0 = b194bac80a08f53b.
W1 = e12bdc1ae28257ec.
W2 = e9dee72c8f0c0fa6.
m1 = 8; n1 = 53.

T0 = RotHi(W0, m1); // 3bb194bac80a08f5
W0 = XOR(W0,W1);
W0 = XOR(W0,W2); // b96181fe6786ad71

But next code return wring result^
T1 = XOR(W1,(RotHi(W0, n1))); // ed242f26d7e9da27, but should be CDFB23D652B779DB

What's wrong?

A: Trouble was in byte sequence. Be attentive with BigEndian or LittleEndian.


text:
Q: Symbolic linking in an SMB share? I have read/write access to an SMB share, but I do not have access to the box itself. My end goal is to create a symbolic link of some sort inside the share to another share, so that other devices connected can access the share. My problem is that the devices I have connected to the share have a hard coded reference to the shares and I cannot add anymore ... e.g., they only see this:
\\networkshare1\videos

And I have:
\\networkshare2\videos

I do not have anything besides file system access to networkshare1, but I do have full permissions for the folders.
I'd like to have something like:
\\networkshare1\videos\folderlink

And if you hit that directory the networkshare2 videos folder is exposed.

A: Symbolic links to network shares are not allowed.

A: if you can create a symlink to the actual disk location instead of the share, you can set 'follow symlinks = yes ' in your smb.conf, and it will work. I have my nas set up the same way, so that content from multiple disks can be exposed via a single share.
if you can't acutally create the symlink on the server, then you will have to try Scott Chamberlain's advice above.
http://www.samba.org/samba/docs/man/manpages-3/smb.conf.5.html


text:
Q: Angular, RxJS - How to cancel previous requests using switchMap? I was trying to figure out that for a long time by myself but I stuck.
My case: I have a table with data, when user enters the page the request goes to REST API. Above the table there is a form that specify/filters results of the table. When user clicks a button, new request with query parameters goes to a service.
I'm trying to find a way to stop a previous request when user clicked a button, to search a table with specific parameters
Here is what I have done so far stackblitz. Maybe my approach is wrong and someone could show me how to write it better, or maybe there are just few thing to correct.
Thank you for any help

A: You can use the takeUntil operator inside your pipe, and pass a subject to it, and everytime you apply a new filter you can emit something to that subject to unsubscribe from the previous subscription and subscribe again! let me give you an example on how to use this operator:
regardless if your code was working or not!! I added just the part on how to use the takeUntil operator!
...
 unsubscribe = new Subject<boolean>();

  constructor(private _service: ServiceConnectService) {}

  ngOnInit() {
    this.clickStream
      .pipe(
        map(() => console.log(1)),
        switchMap(() => {
          return this.getMethodServicesInstances();
        }),
        takeUntil(this.unsubscribe) // this will be executed once you call next with a value!! and the subscription will be stopped!
      )
      .subscribe(results => {
        console.log(2);
      });
  }

  applyFilter(){
    this.unsubscribe.next(true);
    /*
      you can then rerun the subscription and reset the unsubscribe subject state to null!
     */
  }
...


text:
Q: The else condition does print anything when printf is used in ternary operator.. why? The else part in ternary operator which is a printf statement is not working in the code, Is the syntax correct??Or some silly mistake??
#include<stdio.h>
#define isNegative(x) x<0 ? 1 : 0
#define isPositive(x) isNegative(x) ? 0 : 1
#define isEven(x) x%2 ? 0 : 1
#define isOdd(x) isEven(x) ? 0 : 1
main(){
 int n,ch;
do{
printf("Enter a number\n");
scanf("%d",&n);
printf("Choose an operation :\n 1.isEven\n 2.isOdd\n 3.isPositive\n 4.isNegative\n");
scanf("%d",&ch);
switch(ch){
case 1 :isEven(n) ? printf("Its even number\n") : printf("Its not an even number\n") ;
        break;
case 2 :isOdd(n) ? printf("Its odd number\n") : printf("Its not an odd number\n") ;
        break;
case 3 :isPositive(n) ? printf("Its a positive number\n") : printf("Its not a positive number\n");
        break;
case 4 :isNegative(n) ? printf("Its a negative number\n") : printf("Its not a negative number\n");
        break;
default : printf("Enter valid option\n");
        break;
}
printf("Press 5 to continue or 6 to exit\n");
scanf("%d",&ch);
}while(ch!=6);
}

Is the logic of the code correct?
  contents of header file

A: The ternary operator isn't like an if-then-else statement; it's an expression in and of itself, which means its value is whatever gets evaluated in the usual fashion. You can't see it in your code because the result of the ternary operator expressions you  used isn't being captured by anyone. It's what in C++ is called an rvalue.
You can actually prove this to yourself by doing this:
size_t i = 1;
(i == 2) ? printf("hello\n") : printf("goodbye\n")

Output:
goodbye

Here again we're just evaluating the predicate and evaluating the "else" expression. The output, not surprisingly, is goodbye. This isn't the whole story though.
A lot of people don't realize printf has a return value. It returns the number of characters written to stdout, or in the case of fprintf to whichever output stream you specify. Like the scanf functions, the printfs will return a negative number on an error. This is why it's important to check the return value of scanf. Unfortunately many people don't realize these functions have return values, so obviously they don't check what they don't know exists.
With this next example though, you can clearly see the return value of the ternary expression.
size_t i = 1;
int result = (i == 2) ? printf("hello\n") : printf("goodbye\n");
printf("Result: %d\n", result);

Output:
goodbye
Result: 8

Going back to the actual ternary operator, I want to stress that's its an expression. You see things like this very often in functional programming languages, albeit not in the same "shape", if you will. The fact that the printf function is printing to stdout is what's known as a side-effect, and the concept of reducing side-effects as much as possible while still having a useful programming language is one of the foundations of functional programming.

To answer your specific question:

Is the logic of the code correct?

I reformatted some of the code and added a signficant amount of parentheses. You have to be really careful when you're working with both macros and ternary operators to get the parentheses right or you'll get errors like that.
#include <stdio.h>

#define isNegative(x) x<0 ? 1 : 0
#define isPositive(x) isNegative(x) ? 0 : 1
#define isEven(x) x%2 ? 0 : 1
#define isOdd(x) isEven(x) ? 0 : 1

int main()
{
    int n, ch;

    do {
        printf("Enter a number\n");
        scanf("%d", &n);

        printf("Choose an operation :\n 1.isEven\n 2.isOdd\n 3.isPositive\n 4.isNegative\n");
        scanf("%d", &ch);

        switch (ch) {
            case (1): ((isEven(n)) ? printf("Its even number\n") : printf("Its not an even number\n"));
                break;
            case (2): ((isOdd(n)) ? printf("Its odd number\n") : printf("Its not an odd number\n"));
                break;
            case (3): ((isPositive(n)) ? printf("Its a positive number\n") : printf("Its not a positive number\n"));
                break;
            case (4): ((isNegative(n)) ? printf("Its a negative number\n") : printf("Its not a negative number\n"));
                break;
            default: printf("Enter valid option\n");
                break;
        }

        printf("Press 5 to continue or 6 to exit\n");
        scanf("%d",&ch);
    } while(ch != 6);

    return EXIT_SUCCESS;
}

Execution:
Enter a number
5
Choose an operation :
 1.isEven
 2.isOdd
 3.isPositive
 4.isNegative
4
Its not a negative number
Press 5 to continue or 6 to exit
5
Enter a number
3
Choose an operation :
 1.isEven
 2.isOdd
 3.isPositive
 4.isNegative
3
Its a positive number
Press 5 to continue or 6 to exit

Hope this helps, man, good luck. Let me know if you have any questions.


text:
Q: Rellenar input text en funcion del valor de otro input text Tengo una tabla producto la cual tiene código, nombre, etc..
entonces al momento de ingresar el código del producto en formulario, automáticamente coloque el nombre de ese producto...
<form  accept-charset="utf-8">

        Código
        <input type="text" class="form-control" required placeholder="Código" id='codigo' name='codigo' autofocus>

        Nombre
        <input type="text" disabled class="form-control" id='nombre' name='nombre'>

 </form>

A: Pues hay una funcion que se llama change() en jquery, en el que capturas el valor de la siguiente manera.
$(document).ready(function(){ // Se ejecuta una vez que el DOM de la pagina este listo
        $( "#codigo" ).change(function() { //Captura cada vez que vea un cambio en el input con id "codigo"
              //Ejecuta la accion a realizar
        });
});

Aquí la pregunta es: ¿Tienes un controlador, que al pasar un parametro (el codigo), te devuelve los parametros que necesitas de vuelta? y ¿Tienes una conexion con la base de datos, y la query que necesita para ello?
Estas preguntas son clave, por que la idea es que cada vez que cambie de dato en este input, se ejecute un ajax el cual hará una llamada asíncrona a buscar tus datos en tiempo real, a el controlador, donde se le pasara el parámetro "código" y este al ejecutar una consulta a la base de datos, devolverá la información que se necesite, y a través del mismo ajax, dejaremos la o las respuestas en sus respectivos inputs. Saludos!

A: <?php

include('Conexion.php');

$codigo = $_POST["codigo"];

if (!$con) {
    echo 'No pudo conectarse a mysql';
    exit;
}

if (!mysql_select_db('BASE DE DATOS', $con)) {
    echo 'No pudo seleccionar la base de datos';
    exit;
}

$sql       = 'SELECT nombre FROM TABLADEDATOS WHERE codigo = '.$codigo; //solo un ejemplo de la consulta
$resultado = mysql_query($sql, $con);

if (!$resultado) {
    echo "Error de BD, no se pudo consultar la base de datos\n";
    echo "Error MySQL: ' . mysql_error();
    exit;
}

$pila = array();
while ($fila = mysql_fetch_assoc($resultado)) {
      array_push($pila, $fila['nombre']);
}

echo json_encode($pila);

mysql_free_result($resultado);

?>

Considera $con como la variable de conexión para conectarse a la clase de esta misma.
Se pasa el include de la conexion, luego capturas por el "POST" el codigo que le has de pasar desde la pagina web a el controlador. Luego haces unas consultas para ver si te puedes conectar con la bbdd y con la tabla que necesitas.
Posterior a eso haces una consulta, lo montas en una variable y haces la consulta a la bbdd con mysql_query donde hará la llamada a la BBDD. Si este tiene problemas, te regresara un error, y si no colocara el resultado en un array como nuevo elemento. Una vez recorrido todos los resultados, te devolverá un json, donde en jquery por medio de ajax lo capturaras.
Avísame cuando tengas estos pasos listos, y perdón por la demora.


text:
Q: Routing with 'if' statement I need my site to be behind a login wall. so far I have done this with an "if" statement:
Route::get('/', function() {
    if (Auth::check()) {
        return view('pages.feed');
    } else {
        return view('auth.login');
    }
});

i also need to call the feedController though. how can i add

'feedController@index'

to the statement?

A: Add your condition in controller not in web.php routing
Route::get('/', 'feedController@index');

and in feedController controller
function index(){
    .........
    if (Auth::check()) {
        return view('pages.feed');
    } else {
        return view('auth.login');
    }
}

Also be sure to use use Illuminate\Support\Facades\Auth;
or just \ as if (\Auth::check()) {


text:
Q: Error in cordova.js for windows 8 app I am porting my cordova hybrid app currently deployed on android platform to Windows 8/8.1.
My App uses Jquery2.0.0 / angularjs /jquery mobile and intel framework. I ported my app using VS2015 and it compiles fine.
But at runtime I am getting an error "prompt: undefinedin cordova.js".
I am new to this and any pointers on how to resolve this would be really helpful.
Thanks in advance.

A: Make sure you have the correct Cordova.js file(s) for windows and that they are in the proper directory (should be your root web folder with your index.html page).
If you are not using the Cordova CLI to build the app, I would highly recommend it.  Adding the windows platform through the CLI gives you all of the cordova.js files you need when you build, you just need to make sure you reference them correctly (not in your scripts/js folder).
Also, make sure you're waiting for the "deviceready" event that cordova fires when it's ready to do work.


text:
Q: Usage of the word "unlike" I want to say to a person that "I am not like him who waste one's time".
How can I say the same thing using the word unlike in my sentence.
Which of the following sentence should I say?

*

*I am unlike you to waste my time

*I am unlike you who waste one's time

Which one is the correct and is there any other, more native, way of saying the same?

A: If you are blaming the person, with whom you're talking, then ustanak is correct...

Unlike you, I don't waste my time.

However, this means that the person with whom you are talking does waste time.
If you want to say a general statement that is less insulting, you can use the following...

I don't like to waste my time, unlike some people.

You still have to be careful when saying this phrase because, if you emphasize the word some, it can still sound insulting to the other person.
It's always more polite to talk about yourself and not speak negatively about  others.  If it were me, I would simply say...

I don't like to waste time.


text:
Q: Банальный вопрос. Минуту вашего времени. Метод GET для получения данных, а метод POST для отправки данных? JS, Request В гугле я нашел что, post это для данных только "секретных", а get для "публичных". Я смотрю туториал. Автор говорит, что если хочется получить данные, надо метод get, а если отправить то метод post. Просто хочется удостовериться, он прав? Вот часть кода:
async createPost(post) {
    try {
        const request = new Request(this.url + "/posts.json", {
            method: "post", // отправка данных?
            body: JSON.stringify(post)

        });
        const response = await fetch(request);
        return await response.json
    } catch (error) {
        console.error(error);
    }

}

async fetchPosts() {
    try {
        const request = new Request(`${this.url}/posts.json`,
            {
                method: "get" // получение данных?
            });
        const response = await fetch(request);
    } catch (error){
        console.log(error);
    }
}

Весь код: https://jsfiddle.net/Lnet1kxq/
Я просто хочу узнать, get только для получения данных, а post для отправки данных?

A: Если погуглить то можно найти полно примеров
вот что пишут
Основная идея запросов. - Вы отправляете запрос методом (post, get, ...) прикрепляя данные каким-то образом (в заголовке, в пути, в теле), в ответ вам высылаются данные.
Основные различия в формировании самого запроса, у кого есть тело у кого нет. И ответ у кого полный у кого нет. А менять данные можно любым способом. Поймите это запрос, а что делать с ним решать вам. У каждого типа запроса есть небольшая философия например у get - то что его можно кешировать.


text:
Q: Parallel Computing In Java How can I make use of parallel in Java? Or do I use normal threads?

A: *

*Read the Java Concurrency Tutorial.

*Make multiple threads to do your work for you.

A: What a big topic!
A typical solution is using multi-threading, you need a class implemented Runnable interface and put your function into its run() method. For details, I suggest you buy a copy of Java Concurrency in Practice.

A: You can use both Java Threads and Java Concurrency framework.
If you are really interested about Java concurrency, Java Concurrency in Practice is a good book to start.


text:
Q: Should .htaccess files be allowed in Git for Rails projects? Does rails 3.1 have any dependencies on .htaccess files (and thus should be included in the git repo)?
I'm from the PHP CodeIgniter world where .htaccess was required for some of the functionality.

A: Rails doesn't care about these server-specific things, so it doesn't care about .htaccess.


text:
Q: Update mongo document filtered by parent and nested Id using C# driver First, sorry for my english ;)
I have the next classes that represents a person which can have many email accounts and each of those accounts have its respective email messages
public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }
    public EmailAccount[] Accounts { get; set; }
}

public class EmailAccount
{
    public string Id { get; set; }
    public string Name { get; set; }
    public Message[] Messages { get; set; }
}

public class Message
{
    public string Date { get; set; }
    public string Content { get; set; }
}

I need to replace the messages of particular email account, but i need first do a select by person id and account id, how can i do this with Mongodb c# driver, I made something like this but without success:
var collection = _mongoDatabase.GetCollection<Person>("Person");
var query = Query.EQ("Person._id", "20");

var bsonMessages = BsonDocumentWrapper.CreateMultiple(new[]
{
    new Message(DateTime.Now.ToString(CultureInfo.InvariantCulture), "Test 55"),
    new Message(DateTime.Now.ToString(CultureInfo.InvariantCulture), "Test 66")
});

var messageArray = new BsonArray(bsonMessages);

var update = Update.Set("Accounts.$.Messages", messageArray);
collection.Update(query, update, UpdateFlags.Upsert);

As you can see, I do the filter the person by its Id but I don't know how to add the second filter to select an account by its Id
I appreciate any help ;)


text:
Q: Cannot execute k8s module My code in tasks/main.yml.
- name: Check Istio services
  k8s_info:
    api_version: v1
    kind: Service
    namespace: istio-system

But it returns;
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ImportError: No module named kubernetes
fatal: [localhost]: FAILED! => {"changed": false, "error": "No module named kubernetes",

"msg": "Failed to import the required Python library (openshift) on Gihu's-MacBook-Pro.local's Python /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python.

Why does this issue happen?

A: Execute command;
sudo pip install --upgrade --user openshift

A: the install of the openshift (and really a whole ansible install) is required on the target host

A: In my case, the error indicates that "ImportError: No module named kubernetes", so I tried with pip install anisble kubernetes, and it works~