Função de validação customizada html5

Question: Gostaria de saber se há alguma forma de sobrescrever a função que faz a validação de um campo no html5, noto que os browser's implementam de forma elegante um alerta flutuante, eu desejo ter um teste customizado no qual eu verifique CPF e outros dados não simples.
Basicamente quero usar os meios do browser mas com javascript implementar uma validação diferente sobrescrevendo a validação que o browser usa naquele tipo e até implementar novos tipos.
Gostaria sim de implementar algo que me permitisse criar um campo de input que valide CPF, CNPJ, url diferente do que o browser implementa, e até email, porem sem perder a forma de exibição que os browser's hoje nos dá que é bem elegante a meu ver.
Comment: [Como validar formulário antes de enviar](https://pt.stackoverflow.com/questions/221066/validar-formul%C3%A1rio-antes-de-enviar)
Comment: Desculpe amigo, gostaria sim de implementar algo que me permitisse criar um campo de input que valide CPF, CNPJ, url diferente do que o browser implementa, e até email, porem sem perder a forma de exibição que os browser's hoje nos dá que é bem elegante a meu ver.
Answer: Já viu algo sobre o jquery validate e jquery validate unobtrusive? Eles adicionam uma camada de validação e permitem que você utilize a forma padrão de notificação dos browsers

Função de validação customizada html5


Managing user accounts on remote drupal website? (Dev team all needs access)

Question: My company makes lots of Drupal websites and the biggest annoyance I've seen is having to add each other as a user to each site whenever someone else wants to work on it. We all have the same email address domains as we use google docs.
We currently use openId and login with our google accounts but we have to make everyone a user on each site and they have to activate it.
Is there some type of module that would allow us to all have access to any site if said module was installed? Or that it would allow us to create an admin account because we have and can verify our domain in our email through google apps?
Thanks!
Comment: Are you talking about SSO(Single Sign On) ?
Comment: I would rather have us each use our own email addresses and be able to have unique accounts on all the sites, but not have to add everybody manually to each site
Answer: maybe User Import and keep a running cvs file of users to add to new sites on an as needed basis (?)


Using walk to recursively aggregate resources in a terraform state with rego

Question: I'm using Open Policy Agent to write policy against the JSON output of my terraform state.
Here is the structure of the state file:
{
  "format_version": "0.1",
  "terraform_version": "0.12.28",
  "values": {
    "root_module": {
      "resources": [],
      "child_modules": [
        {
          "resources": [],
          "address": "",
          "child_modules": [
            {
              "resources": [],
              "address": "",
              "child_modules": [
                {}
              ]
            }
          ]
        }
      ]
    }
  }
}

I have this nasty rule defined that achieves what I want, but it is obviously not an ideal way to be aggregating these resources.
resources[resource_type] = all {
    some resource_type
    resource_types[resource_type]
    rm := tfstate.values.root_module

    # I think the below can be simplified with the built in "walk" function TODO: do that.
    root_resources := [name |
        name := rm.resources[_]
        name.type == resource_type
    ]

    cmone_resources = [name |
        name := rm.child_modules[_].resources[_]
        name.type == resource_type
    ]

    cmtwo_resources = [name |
        name := rm.child_modules[_].child_modules[_].resources[_]
        name.type == resource_type
    ]

    cm := array.concat(cmone_resources, cmtwo_resources)

    all := array.concat(cm, root_resources)
}

I have read the documentation of the built-in function walk(x, [path, value]). Docs here. I believe this function does what I want it to do, but based on the documentation given and admittedly sparse examples I've found elsewhere, I cannot figure out how to get it to work how I'm expecting.
I've included a playground with a very basic setup and the current rule I have defined. Any help at all would be greatly appreciated.
Answer: You're on the right track, and using walk would definitely be a good approach for collecting arbitrarily nested child resources.
To get started we'll want to explore what walk does. It is going to essentially iterate over all nodes in the object we're walking over, and for each one it gives the "path" and current node value. The path is going to be an array of keys, so like for object:
{"a": {"b": {"c": 123}}}

if we do a walk over (example below using the opa run REPL:
> [path, value] = walk({"a": {"b": {"c": 123}}})
+---------------+-----------------------+
|     path      |         value         |
+---------------+-----------------------+
| []            | {"a":{"b":{"c":123}}} |
| ["a"]         | {"b":{"c":123}}       |
| ["a","b"]     | {"c":123}             |
| ["a","b","c"] | 123                   |
+---------------+-----------------------+

We see that we have every path and value combination for the values of path and value. You can capture any of these values while iterating in a partial rule (like your resources rule), or in a comprehension.
So.. taking this over to the terraform stuff. If we modify the playground example to walk over the example input (which is slightly modified to give some unique names to things) we get:
walk_example[path] = value {
    [path, value] := walk(tfstate)
}

https://play.openpolicyagent.org/p/2u5shGbrV2
If you look at the resulting value for walk_example we can see all the paths and values we'd expect to have to handle.
From there it is a matter of doing the filtering, similar to what you've done in the resources rule, for the resource_types. Instead of doing iteration over the set we will use it as a lookup to check on each type that is OK, and we will build a full set of all resources first (without grouping them by type). The reasoning being that it is very expensive to walk over all nodes of the input json so we want to only do that a single time. We can subsequently walk over the full list of every resource faster with a second pass to group by type (as needed).
An updated version would look something like:
walk_resources[resource] {
    [path, value] := walk(tfstate)

    # Attempt to iterate over "resources" of the value, if the key doesn't
    # exist its OK, this iteration for walk will be undefined, and excluded
    # from the results.
    # Note: If you needed to be sure it was a "real" resource, and not some
    # key you can perform additional validation on the path here!
    resource := value.resources[_]

    # check if the resource type was contained in the set of desired resource types
    resource_types[resource.type]
}

https://play.openpolicyagent.org/p/TyqMKDyWyh
^ The playground input was updated to include another level of nesting and types on the examples. You can see that the original resources output is missing that depth 3 resource, but the walk_resources set contains all of the expected ones.
The last part, if you wanted to group them by type, add a complete rule like:
# list of all resources of a given type. given type must be defined in the resource_types variable above
resources = { resource_type: resources |
    some resource_type
    resource_types[resource_type]
    resources := { resource |
        walk_resources[resource]
        resource.type == resource_type
    }
}

https://play.openpolicyagent.org/p/RlRZwibij9
Which replaces the original resources rule with a comprehension that is going to iterate over each resource type, and then collect resources matching the type.
One extra pointer, which I've seen be a problem in these terraform resource helper rules, is that you will want to reference that "complete" rule, see https://www.openpolicyagent.org/docs/latest/policy-language/#complete-definitions for some details on what that means, rather than the "partial" rule (in this case the ones building a set of resources versus assigning the value to the comprehension result). The problem being that internally, as of writing this, OPA will cache values for the "complete" rules whereas the partial rules are not. So if you then go and write a bunch of rules like:
deny[msg] {
    r := resources["foo"]
    # enforce something for resources of type "foo"...
    ...
}

deny[msg] {
    r := resources["bar"]
    # enforce something for resources of type "bar"...
    ...
}

You want to ensure that it is using a cached value for resources each time and not recalculating the set. The original version of your resources rule would suffer from that issue, along with using the walk_resources rule I've shown in those examples. Something to keep an eye on as it can have a pretty dramatic performance impact if you had a large input tfplan.
Answer: I just had a lot of use for the above, excellent answer. I wanted to validate that certain controlled resources only be created from the designated module. The resulting rule looks like this:
has_key(x, k) { _ = x[k] }

controlled_resources[resource] {
  # Recursively walk the module hierarchy
  [path, module_ref] := walk(tfplan["configuration"])

  # Filter out only objects that are modules, i.e. have a source property
  source := module_ref["source"]

  # Get all resources created in the module and their types
  resources := module_ref["module"]["resources"]
  resource_type := resources[_]["type"]

  # Filter out resources that are considered controlled
  has_key(controlled_resource_types, resource_type)

  # Create an object with the module and the resource type,
  # this is a set so duplicates will be removed based on this object
  resource := {
    "module": source,
    "type": resource_type
  }
}

default resources_valid := false
resources_valid {
  # Iterate over resource types in the controlled set
  some resource_type
  has_key(controlled_resource_types, resource_type)

  # Get the allowed modules for each resource type
  expected_modules := controlled_resource_types[resource_type]

  # For each instance of a controlled resource type, make sure its
  # module is listed in the expected modules
  every resource_instance in controlled_resources {
    startswith(resource_instance.module, expected_modules[_])
  }
}

controlled_resource_types is an object mapping types such as aws_iam_role to accepted modules. I hope it helps someone.


What would be the best way to sum all the credit values from this JSON output?

Question: refer to the link below for the image, I want to know how can we add all the credit values what would be the best way to implement this.
[1]: https://i.stack.imgur.com/raA5x.png
Answer: You need to iterate over the Ledger list using a for statement. Take a look at the example below:
<code>final data = {
  "Ledger": [
    {"Credit Amount": 1000},
    {"Credit Amount": 1000},
    {"Credit Amount": 1000},
    {"Credit Amount": 1000},
    {"Credit Amount": 1000},
  ],
};

var sum = 0;
for (final item in data['Ledger']) {
  sum += item['Credit Amount'];
}
</code>
Comment: This was really helpful. I am using a different method to implement this. I am using fold to use this.                    num credit = stmt.fold(0, (a, b) => a + b["Credit Amount"]);
Comment: You're welcome. Yeah, you can do it like that too. If it was useful please accept and vote up ;)


Views News slider

Question: I have this design:

E.G. Click "Structure" header, open contents and come img.
Created content type and installed Views. Seperate image, header, content fields via block.

Like our design but site now static. I want dynamic structure but i don't know. Well, how can i do it?
Answer: You can able to do it using "Views Module" and "Views Slideshow Module" . Below Steps may help you.

Create a Content Type.
Add all necessary fields.
Create content
Create a view that lists all above content and use views field option to display above content type fields.
Select the Views Style as "Views Slideshow".
Configure settings and select pager as title field.
That's it ! With little bit of CSS and Positioning you are good to go :-)

Views News slider


How to find out what sub command that fails with ninja?

Question: I am trying to build glib with meson. The reason meson is used is simply because this is what glib supports, but I do not have much experience with it yet. The glib project is also using ninja for the build. So I downloaded https://download.gnome.org/sources/glib/ and tried to build the project (was also forced to download pcre and build separately, due to firewall issues). The latest version 2.78.0 was missing some files, so the meson setup step failed. Thus I downloaded 2.77.3 (and later 2.76.5) and ran
meson setup _build
meson compile -v -C _build

but this fails on
...
[127/1441] cc  -o glib/libglib-2.0.so.0.7600.5 glib/libglib-2.0.so.0.7600.5.p/deprecated_gallocator.c.o glib/libglib-2.0.so.0.7600.5.p/deprecated_gcache.c.o glib/libglib-2.0.so.0.7600.5.p/deprecated_gcompletion.c.o glib/libglib-2.0.so.0.7600.5.p/deprecated_grel.c.o glib/libglib-2.0.so.0.7600.5.p/deprecated_gthread-deprecated.c.o glib/libglib-2.0.so.0.7600.5.p/garcbox.c.o glib/libglib-2.0.so.0.7600.5.p/garray.c.o glib/libglib-2.0.so.0.7600.5.p/gasyncqueue.c.o glib/libglib-2.0.so.0.7600.5.p/gatomic.c.o glib/libglib-2.0.so.0.7600.5.p/gbacktrace.c.o glib/libglib-2.0.so.0.7600.5.p/gbase64.c.o glib/libglib-2.0.so.0.7600.5.p/gbitlock.c.o glib/libglib-2.0.so.0.7600.5.p/gbookmarkfile.c.o glib/libglib-2.0.so.0.7600.5.p/gbytes.c.o glib/libglib-2.0.so.0.7600.5.p/gcharset.c.o glib/libglib-2.0.so.0.7600.5.p/gchecksum.c.o glib/libglib-2.0.so.0.7600.5.p/gconvert.c.o glib/libglib-2.0.so.0.7600.5.p/gdataset.c.o glib/libglib-2.0.so.0.7600.5.p/gdate.c.o glib/libglib-2.0.so.0.7600.5.p/gdatetime.c.o glib/libglib-2.0.so.0.7600.5.p/gdir.c.o glib/libglib-2.0.so.0.7600.5.p/genviron.c.o glib/libglib-2.0.so.0.7600.5.p/gerror.c.o glib/libglib-2.0.so.0.7600.5.p/gfileutils.c.o glib/libglib-2.0.so.0.7600.5.p/ggettext.c.o glib/libglib-2.0.so.0.7600.5.p/ghash.c.o glib/libglib-2.0.so.0.7600.5.p/ghmac.c.o glib/libglib-2.0.so.0.7600.5.p/ghook.c.o glib/libglib-2.0.so.0.7600.5.p/ghostutils.c.o glib/libglib-2.0.so.0.7600.5.p/giochannel.c.o glib/libglib-2.0.so.0.7600.5.p/gkeyfile.c.o glib/libglib-2.0.so.0.7600.5.p/glib-init.c.o glib/libglib-2.0.so.0.7600.5.p/glib-private.c.o glib/libglib-2.0.so.0.7600.5.p/glist.c.o glib/libglib-2.0.so.0.7600.5.p/gmain.c.o glib/libglib-2.0.so.0.7600.5.p/gmappedfile.c.o glib/libglib-2.0.so.0.7600.5.p/gmarkup.c.o glib/libglib-2.0.so.0.7600.5.p/gmem.c.o glib/libglib-2.0.so.0.7600.5.p/gmessages.c.o glib/libglib-2.0.so.0.7600.5.p/gnode.c.o glib/libglib-2.0.so.0.7600.5.p/goption.c.o glib/libglib-2.0.so.0.7600.5.p/gpathbuf.c.o glib/libglib-2.0.so.0.7600.5.p/gpattern.c.o glib/libglib-2.0.so.0.7600.5.p/gpoll.c.o glib/libglib-2.0.so.0.7600.5.p/gprimes.c.o glib/libglib-2.0.so.0.7600.5.p/gqsort.c.o glib/libglib-2.0.so.0.7600.5.p/gquark.c.o glib/libglib-2.0.so.0.7600.5.p/gqueue.c.o glib/libglib-2.0.so.0.7600.5.p/grand.c.o glib/libglib-2.0.so.0.7600.5.p/grcbox.c.o glib/libglib-2.0.so.0.7600.5.p/grefcount.c.o glib/libglib-2.0.so.0.7600.5.p/grefstring.c.o glib/libglib-2.0.so.0.7600.5.p/gregex.c.o glib/libglib-2.0.so.0.7600.5.p/gscanner.c.o glib/libglib-2.0.so.0.7600.5.p/gsequence.c.o glib/libglib-2.0.so.0.7600.5.p/gshell.c.o glib/libglib-2.0.so.0.7600.5.p/gslice.c.o glib/libglib-2.0.so.0.7600.5.p/gslist.c.o glib/libglib-2.0.so.0.7600.5.p/gstdio.c.o glib/libglib-2.0.so.0.7600.5.p/gstrfuncs.c.o glib/libglib-2.0.so.0.7600.5.p/gstring.c.o glib/libglib-2.0.so.0.7600.5.p/gstringchunk.c.o glib/libglib-2.0.so.0.7600.5.p/gstrvbuilder.c.o glib/libglib-2.0.so.0.7600.5.p/gtestutils.c.o glib/libglib-2.0.so.0.7600.5.p/gthread.c.o glib/libglib-2.0.so.0.7600.5.p/gthreadpool.c.o glib/libglib-2.0.so.0.7600.5.p/gtimer.c.o glib/libglib-2.0.so.0.7600.5.p/gtimezone.c.o glib/libglib-2.0.so.0.7600.5.p/gtrace.c.o glib/libglib-2.0.so.0.7600.5.p/gtranslit.c.o glib/libglib-2.0.so.0.7600.5.p/gtrashstack.c.o glib/libglib-2.0.so.0.7600.5.p/gtree.c.o glib/libglib-2.0.so.0.7600.5.p/guniprop.c.o glib/libglib-2.0.so.0.7600.5.p/gutf8.c.o glib/libglib-2.0.so.0.7600.5.p/gunibreak.c.o glib/libglib-2.0.so.0.7600.5.p/gunicollate.c.o glib/libglib-2.0.so.0.7600.5.p/gunidecomp.c.o glib/libglib-2.0.so.0.7600.5.p/guri.c.o glib/libglib-2.0.so.0.7600.5.p/gutils.c.o glib/libglib-2.0.so.0.7600.5.p/guuid.c.o glib/libglib-2.0.so.0.7600.5.p/gvariant.c.o glib/libglib-2.0.so.0.7600.5.p/gvariant-core.c.o glib/libglib-2.0.so.0.7600.5.p/gvariant-parser.c.o glib/libglib-2.0.so.0.7600.5.p/gvariant-serialiser.c.o glib/libglib-2.0.so.0.7600.5.p/gvarianttypeinfo.c.o glib/libglib-2.0.so.0.7600.5.p/gvarianttype.c.o glib/libglib-2.0.so.0.7600.5.p/gversion.c.o glib/libglib-2.0.so.0.7600.5.p/gwakeup.c.o glib/libglib-2.0.so.0.7600.5.p/gprintf.c.o glib/libglib-2.0.so.0.7600.5.p/glib-unix.c.o glib/libglib-2.0.so.0.7600.5.p/gspawn.c.o glib/libglib-2.0.so.0.7600.5.p/giounix.c.o glib/libglib-2.0.so.0.7600.5.p/gjournal-private.c.o glib/libglib-2.0.so.0.7600.5.p/gthread-posix.c.o -Wl,--as-needed -Wl,--no-undefined -shared -fPIC -Wl,--start-group -Wl,-soname,libglib-2.0.so.0 -Wl,-rpath,/proj/wcdmaiov/epatrek/babeltrace/glib/pcre2-10.42-bin/lib -Wl,-rpath-link,/proj/wcdmaiov/epatrek/babeltrace/glib/pcre2-10.42-bin/lib glib/libcharset/libcharset.a -Wl,-z,nodelete -Wl,-Bsymbolic-functions -lm -lrt /proj/wcdmaiov/epatrek/babeltrace/glib/pcre2-10.42-bin/lib/libpcre2-8.so -Wl,--end-group -pthread
[128/1441] cc -Iglib/tests/cache.p -Iglib/tests -I../glib/tests -I. -I.. -Iglib -I../glib -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wextra -pedantic -std=gnu99 -O2 -g -D_GNU_SOURCE -fno-strict-aliasing -DG_DISABLE_CAST_CHECKS -Wmissing-field-initializers -Wnonnull -Wunused -Wno-unused-parameter -Wno-format-zero-length -Wno-variadic-macros -Werror=format=2 -Werror=init-self -Werror=missing-include-dirs -Werror=pointer-arith -Wstrict-prototypes -Wno-bad-function-cast -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=pointer-sign -pthread '-DG_LOG_DOMAIN="GLib"' -UG_DISABLE_ASSERT -MD -MQ glib/tests/cache.p/cache.c.o -MF glib/tests/cache.p/cache.c.o.d -o glib/tests/cache.p/cache.c.o -c ../glib/tests/cache.c
[129/1441] cc -Iglib/tests/bytes.p -Iglib/tests -I../glib/tests -I. -I.. -Iglib -I../glib -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wextra -pedantic -std=gnu99 -O2 -g -D_GNU_SOURCE -fno-strict-aliasing -DG_DISABLE_CAST_CHECKS -Wmissing-field-initializers -Wnonnull -Wunused -Wno-unused-parameter -Wno-format-zero-length -Wno-variadic-macros -Werror=format=2 -Werror=init-self -Werror=missing-include-dirs -Werror=pointer-arith -Wstrict-prototypes -Wno-bad-function-cast -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=pointer-sign -pthread '-DG_LOG_DOMAIN="GLib"' -UG_DISABLE_ASSERT -MD -MQ glib/tests/bytes.p/bytes.c.o -MF glib/tests/bytes.p/bytes.c.o.d -o glib/tests/bytes.p/bytes.c.o -c ../glib/tests/bytes.c
[130/1441] cc -Iglib/tests/bookmarkfile.p -Iglib/tests -I../glib/tests -I. -I.. -Iglib -I../glib -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wextra -pedantic -std=gnu99 -O2 -g -D_GNU_SOURCE -fno-strict-aliasing -DG_DISABLE_CAST_CHECKS -Wmissing-field-initializers -Wnonnull -Wunused -Wno-unused-parameter -Wno-format-zero-length -Wno-variadic-macros -Werror=format=2 -Werror=init-self -Werror=missing-include-dirs -Werror=pointer-arith -Wstrict-prototypes -Wno-bad-function-cast -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=pointer-sign -pthread '-DG_LOG_DOMAIN="GLib"' -UG_DISABLE_ASSERT -MD -MQ glib/tests/bookmarkfile.p/bookmarkfile.c.o -MF glib/tests/bookmarkfile.p/bookmarkfile.c.o.d -o glib/tests/bookmarkfile.p/bookmarkfile.c.o -c ../glib/tests/bookmarkfile.c
[131/1441] cc -Iglib/tests/array-test.p -Iglib/tests -I../glib/tests -I. -I.. -Iglib -I../glib -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wextra -pedantic -std=gnu99 -O2 -g -D_GNU_SOURCE -fno-strict-aliasing -DG_DISABLE_CAST_CHECKS -Wmissing-field-initializers -Wnonnull -Wunused -Wno-unused-parameter -Wno-format-zero-length -Wno-variadic-macros -Werror=format=2 -Werror=init-self -Werror=missing-include-dirs -Werror=pointer-arith -Wstrict-prototypes -Wno-bad-function-cast -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=pointer-sign -pthread '-DG_LOG_DOMAIN="GLib"' -UG_DISABLE_ASSERT -MD -MQ glib/tests/array-test.p/array-test.c.o -MF glib/tests/array-test.p/array-test.c.o.d -o glib/tests/array-test.p/array-test.c.o -c ../glib/tests/array-test.c
ninja: build stopped: subcommand failed.
patrik[babeltrace/glib/glib-2.76.5]$

However, this tells very little on what error that caused ninja to fail. Any idea how to find the defacto error that caused ninja to fail?
I am using ninja 1.9.0 and meson 1.2.1.
BR
Patrik
Answer: The error should be printed. Note that if you're running several concurrent jobs, which Ninja does by default, the error may have already scrolled off your terminal due to the commands of other compilation steps being printed after it.
If no error is printed, that might mean that the subcommand failed without printing any error. In that case, you can use -j1 to only run one command at a time. That way, it will be clear which command failed.


Interpreting binomial test results

Question: I'm relatively new to stats and any help would be appreciated.
My experiment has two boxes one baited with food and the other non-baited. I am trying to test whether the probability of the animal successfully choosing the baited box is only by chance, i.e. 50% of the time.
Therefore my
Alternative Hypothesis= success at choosing the box= 50%
Null Hypothesis= success < 50%  / success > 50%
I have used a binomial test
binom.test(42, 74, p=0.5, alternative = "two.sided", conf.level = 0.95)

Output:
data:  42 and 74
number of successes = 42, number of trials = 74, p-value = 0.2954
alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
 0.4472142 0.6823437
sample estimates:
probability of success
             0.5675676

My questions

Would the binomial test be the best test to run?
How do I interpret the output?
Since the p-value is 0.29 I fail to reject the null hypothesis which means that the success of choosing the baited box is not happening by chance? However given that these are experiments and I'm never going to get an exact 50% success, how should I frame my question?

Also the probability of success is only 56% which isn't vastly different from 50%- therefore how can I interpret this?
Comment: Your null and alternative hypotheses look as if they may be the wrong way round
Comment: You are testing $H_0: p = .5$ against $H_a: p \ne .5$ Your fraction of Successes $42/74 = 0.567567$ is different from $0.5,$ but not sufficiently different to Reject $H_0$ at the 5% level because P-value $0.2954 > 0.05 = 5\%.$ Alternatively, you cannot say there is a significant difference from $0.5$ because the 95% confidence interval $(.447, .682)$ contains $0.5.$ // [(+1) to both Comment and Answer of @cdalitz.]
Comment: By contrast, if you had **46** successes out of 74, then you would reject $H_0.$ Notice that R code `binom.test(46,74)$p.val` returns P-value $0.04739298 < 0.05.$
Comment: Thank you so much for your comments. Just to clarify if I am assuming that the animal cannot smell the food in the baited box then should I not be testing Ha : p = .5? That both the baited and unbaited box will have a 50% chance of being selected?
Answer: In hypothesis testing, the null hypthesis $H_0$ is usually the opposite of what you want to demonstrate. In your case, this means that $H_0$ is that the probability is 0.5.
binom.text is the correct way to test this, and the resulting p-value shows that your observation is not very unlikely under the null hypothesis. There is thus no significant deviation from $p=0.5$ whatever confidence level you might choose.
To actually achieve a significant difference, you must collect more data.
Note that binom.test also yields a confidence interval, which might be of more interest to you: it says in what range the probability presumably lies and you thus obtain a measurement of the strength of the effect.
Comment: Thank you so much for your advice! It helps clarify things

Interpreting binomial test results


Tiling a rectangular checkerboard with one arbitrary square removed

Question: Assume that there's a rectangular board of dimension $ab$, and one square is arbitrarily removed. Assume that $d | (ab -1)$. Does this imply that there exists some tiling of the rectangle -- with the square removed -- using some combination of the various polyominos of size $d$? It feels intuitive that this should be true, as it hits very close to what division "means" (visually), but not obvious as regards proof.
Comment: Another counterexample: a 5 x 3 rectangle with its middle square removed -- coordinate (2,3) -- missing. It cannot be tiled by 2-ominoes. Indeed, this appears to happen more generally, whenever the prime factorization of (ab -1) = 2*p.
Comment: Try induction on d.
Comment: Ah, I'm not taking *ab* to be fixed. The question is whether the result obtains for all *ab* such that *d | ab*. It seems like induction would require fixing the value of *ab*, in order to interrelate the *d = n* and *d = n+1* cases.
Comment: Maybe the best way towards a proof is some kind of constructive algorithm... a really obvious result, it seems, that nonetheless is elusive to show directly.
Comment: A $3{\times}1$ rectangle with the middle tile removed can't be tiled with tiles of area $2$. Assuming $a,b$ are both greater than $1$, it's clear that a valid tiling is possible, but a proof will likely not be elegant.
Comment: A helpful counterexample. In fact, the family of $ a $ x $ 1 $ produces lots of them. Let's set $ a, b > 1$.
Answer: Here is a solution when at least one of $a$ and $b$ is even (and both are $>1$).
In this case, it is possible to draw a closed path through the $a \times b$ rectangle that visits each square once. Deleting a square means we're left with an open path. Just take the squares in order along this path, $d$ at a time, to get a tiling with size-$d$ polyominoes. Here's an illustration when $a=b=8$ and $d=9$:

Here is a solution when $a$ and $b$ are both odd, $a,b>1$, and $d \ne 2$.
In this case, we take a closed path that visits each square once and almost always goes from a square to an adjacent square, except in one case where it takes a step from square $(1,1)$ to square $(2,2)$. Such a path always exists (exercise) by generalizing the $7\times 7$ solution below.

If necessary, rotate the board so that the deleted square is not one of the squares $\{(1,1),(1,2),(2,1),(2,2)\}$ in the top left corner. This is possible except when $a=b=3$, but we can solve the $3 \times 3$ case easily :)
Now, once again, the deleted square splits the closed path into an open path, and we try to take squares along that path, $d$ at a time, to be our polyominoes.
Earlier, $d$ consecutive squares of the path would always form a polyomino because any two consecutive squares of the path are adjacent. Here, that's not true in one place, because $(1,1)$ is not adjacent to $(2,2)$. However, when $d\ne 2$, if we are taking $d$ consecutive squares of the path including $(1,1)$ and $(2,2)$, we also take either $(1,2)$ or $(2,1)$, which makes a connected shape again. So we're still fine.

As already mentioned in comments, there might not be a solution in the following cases:

when $a=1$ or $b=1$ (because the deleted square might split the rectangle into two parts, neither of which has area divisible by $d$)
when $a$ and $b$ are both odd and $d=2$ (because, if we take a checkerboard coloring of the rectangle, the deleted square might leave more white squares than black squares, but a domino always covers one square of each color).

So we've covered all the cases in which a solution is guaranteed to exist.
Comment: That makes sense: in that case, if we look at the checkerboard coloring, it's possible to remove a square so that there are two more white squares than black squares. But every domino covers one square of each color. (Note that $\frac{ab-1}{2}$ doesn't have to be prime for this to happen.)
Comment: When *a* and *b* are both odd, it actually appears the result isn't always true. When *ab* - 1 = 2*p, for instance, two-size tiles do not tile the region if the center square of the rectangle is removed.
Comment: Ah, a great insight! Thanks.
Comment: @GabrielHorn I've edited my answer to deal with the case where $a,b$ are odd and $d \ne 2$.


On hypersurfaces of the projective space

Question: Let $\pi : \mathbb{S}^{n+1}  \to \mathbb{R}P^{n+1}$ the projection from the round sphere os radius $1$ to the projective space, and endow $\mathbb{R}P^{n+1}$ with a riemannian metric so that $\pi$ is a local isometry. Let $M^n \subset \mathbb{R}P^{n+1}$ be a hypersurface (orientable or not) and consider $\tilde{M} = \pi^{-1}(M)$. Since $\pi$ is a submersion, it is transverse to $M$, so that $\tilde{M}$ is indeed a hypersurface of $\mathbb{S}^{n+1}$. Is it always orientable? And connected?
I read that, whenever $n$ is odd, $\mathbb{S}^{n+1}$ is the oriented double cover of $\mathbb{R}P^{n+1}$ via $\pi$, and since the sphere is connected, it follows that the even-dimensional projective spaces are non-orientable. I wonder if the same holds for $\pi|_{\tilde{M}} : \tilde{M} \to M$: is it true that $M$ is non-orientable iff $\tilde{M}$ is connected?
Another question, now related to distances. The projective space has diameter of $\pi/2$, half of the diameter of the sphere. Suppose that the smallest (geodesic) ball of $\mathbb{S}^{n+1}$ that contains $\tilde{M}$ is $r$. Is it true, by analogy, that the radius of the smallest geodesic ball of $\mathbb{R}P^{n+1}$ that contains $M$ is $r/2$?
Answer: I will give a partial answer. Assume that $\pi :S^{n+1}\rightarrow \mathbb{R}P^{n+1}$ is a
quotient map by $\mathbb{Z}_2$-free
isometric action.
If $M$ is a closed $n$-dimensional manifold, then let $\widetilde{M}:=\pi^{-1} (M)$. Since $\pi$ is
   locally isometric, so $\widetilde{M}$ is a closed $n$-manifold.
Assume that $M_1$ is a connected component in $\widetilde{M}$.
(1) $M_1$ is in some open hemisphere iff $M$ is in some
$B(x,r)$ where $r<\frac{\pi}{2}$
In this case $\widetilde{M}$ is disconnected and $M_1,\ M$ are
  orientable (cf. Proof of (2.2)).
(2) By (1) we have that there is a point $\widetilde{x}\in
M_1$ with $-\widetilde{x} \in M_1$ iff $M$ is not in any geodesic
ball $B(x,r)$ where $r<\frac{\pi}{2}$.
(2.1) In this case, prove that $\widetilde{M}$ is connected.
Proof : If not, then let $M_2$ to be another connected component.
Then $\widetilde{x},\ -\widetilde{x}\in
M_1$ and $\widetilde{y},\ -\widetilde{y}\in M_2$.
Note that $\pi\ (\widetilde{x})$ is not in $\pi\ (M_2)=M$. It is a
contradiction.
(2.2) In this case, consider orientability of $M,\
\widetilde{M}$
Proof : $\widetilde{M}$ is in $S^{n+1}-\{ \widetilde{x}\}$
for some point $\widetilde{x}$ so that $\widetilde{M}$ is
orientable.
If $M=\mathbb{R}P^n$, then it is orientable where $n$ is odd. And it
is non-orientable where $n$ is even.
Comment: I didn't understand your proof of (2.2), it seems to me you did nothing..


Get position and visibility of translucent Android navigation bar

Question: I'm working on a cross-platform app which has been ported to Android. Due to its non-Android heritage it doesn't make extensive use of Android UI elements – the main app window is one single View.
I would like to implement translucent system (status and navigation) bars, as supported from KitKat onwards, while ensuring that UI elements inside the main View are not obstructed by them.
This answer shows how to get the default height for these bars (there is also navigation_bar_height_landscape for navigation bar height in landscape mode, and navigation_bar_width for the width of a vertical navigation bar). But these are only the system's default sizes and contain no information if the navigation bar is currently being shown, and whether it is showing at the right or on the bottom edge of the screen.
The other answers I have found so far probably work fine for non-translucent system bars: they simply compare total screen size to the size of the main app view, and the difference is the space occupied by the system bars. However, with translucent system bars, the size difference is zero and this approach won't work.
How can I reliably determine if the navigation bar is being displayed, and in which position?
Answer: Looking around a bit, including this part of the AOSP code, I came up with the following:
        // determine if navigation bar is going to be shown
        boolean isNavShowing;
        if (Build.VERSION.SDK_INT >= 13) {
            isNavShowing = ViewConfiguration.get(activity.getApplication()).hasPermanentMenuKey();
        }

        // determine where the navigation bar would be displayed
        boolean isNavAtBottom;
        if (Build.VERSION.SDK_INT >= 13) {
            isNavAtBottom = (activity.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
                    || (activity.getResources().getConfiguration().smallestScreenWidthDp >= 600);
        }

You can then calculate the following insets:

Left: 0
Top: value of status_bar_height
Right: 0 if navigation bar is not at bottom, else navigation_bar_width
Bottom: 0 if navigation bar is not at bottom, else: if orientation is landscape (see code above), navigation_bar_height_landscape; else navigation_bar_height.

Defaults, as per dimens.xml, are:

status_bar_height: 24 dp
navigation_bar_height: 48 dp
navigation_bar_height_landscape: 48 dp
navigation_bar_width: 48 dp

(you might want to fall back to these if somehow you fail to get the actual values.)
The logic for isNavShowing is a variation on something I implemented a while ago. It reliably detects the presence of a physical Menu button even on a OnePlusOne running CyanogenMod (where the user can switch between a navigation bar and hardware buttons via Settings). Even when adding a software Menu button to the navigation bar (which seems to be a CM addition), the navigation bar is still detected correctly.
The logic for isNavAtBottom is mostly taken from the findNavigationBar() function in the source file I linked above and should work unless you are using a heavily customized build of Android.


Terrible electric guitar resonance

Question:

My guitar started giving me some serious whine recently (never before). It seems to mostly happen when I play the 'D' chord. I have contacted Schecter, and they seem to think, after watching my video (above), that it is NOT the PUs, but that the sound is resonating. This is very frustrating to me, and I would like any advice to fix it. I can't use any of my overdrive/distortion pedals anymore, and my onboard amp distortion isn't any better. I can have my Gain nearly at zero and it still whines. This doesn't happen at all on clean.
Things I have already tried:
switch cables
change strings
lowered PUs
changed PU battery
tried multiple amps
Comment: I'm voting to close this question because it links to a private video, and so is of no use.
Comment: does this happen at all when not amplified? I thought it might be a analog (spring) reverb or loose component problem, but you say you tried different amps. Try and identify the exact note (not chord) that makes this happen, and then work from there. If something in the guitar is resonating, it will happen without amplification. I note that there is a preamp in that guitar, so if it isn't the pickups, its the preamp.
Comment: @Kaz Although the video is dead, I think the question still works without it.
Comment: yes it does make this sound when not plugged into anything, thanks for that new evidence! if I do happen to find a specific note, not chord, then what?
Comment: If you can narrow down the note it will help you reproduce it more reliably. Put your ear close while unplugged and localize the sound. This can be the pickup covers, loose wires, the nut on the tension rod. I had an acoustic where a 1 inch section of the binding kerf was vibrating with A and the paper label had a bubble in it that vibrated like a drum at certain odd resonances
Comment: If there is an actual preamp in this, it might still be an electric squeak. Also if there is a spring in the toggle switch, you might try and mechanically dampen it. It really does sound like a sort of reverb, unless that is a plate echo from the recording
Comment: What happens if you put some felt or some thing to damp the string areas above the nut and behind the bridge? Also, if you mute the strings in a different place in the neck the ringing sound doesn't change?
Comment: yes, yours and DrMayhem below have solved my problem.. nothing happened when dampening the nut area, but all was solved with the bridge! thanks!
Comment: @Aaron I see that OP basically acknowledged that Dr Mayhem's answer worked for him, without accepting the answer.
Comment: @Kaz, I did accept the answer.. I see the green check next to the answer. Also, the video was made "Private" by YouTube as some sort of security update. I have made it 'Unlisted' again, so hopefully it shows back up.
Answer: I think @Todd's comment is right. This sounds a lot to me like the symptom I have on my twin neck SG. Whatever I play I get the same nasty squeak/ringing noise. I researched it, and found wolf tones on acoustic instruments - especially cellos so thought I'd do some checking.
It turns out the structure of the bridge and tail seemed to encourage resonance at this frequency, in two of the short tails of strings behind the bridge.
The solution for me was to add a rubber damper to the strings behind the bridge. Instant, and very cheap as we had the rubber bands in the house anyway.
Comment: what exactly did you do with the rubber bands?
Comment: Intertwined them between the strings behind the bridge. I'll get a picture and update my answer
Comment: WOW.. your suggestion worked! I put a sock in that spot behind the bridge, and BOOM, no scream.. You just saved me packing up and sending my baby to Schecter for warranty work.. thanks again!
Comment: Brilliant! I am glad - I honestly was baffled when it happened to me, until I tracked down that wolf tone article. This is simple and effectively free (my daughter plaited the rubber bands)

Terrible electric guitar resonance


PHP SQL Get Date Time from Username and compare to todays date

Question: I want to get Date Time from specified Username and compare to todays date. I'm using a database.
  $con = mysqli_connect("server", "name", "pass", "db");
  if(!$con) {
    die("noconn");
  }

  $HWID = "";
  if(isset($_POST['HWID']) && !empty($_POST['HWID'])) {
    $HWID = mysqli_real_escape_string($con, $_POST['HWID']);
    $HWID = ($HWID);
  }
  elseif(isset($_GET['HWID']) && !empty($_GET['HWID'])) {
    $HWID = mysqli_real_escape_string($con, $_GET['HWID']);
    $HWID = ($HWID);
  } else {
    die("nodata");
  }

  $rows= "";
  if(isset($_GET['Expire_Date'])){
      $id=$_GET['Expire_Date'];
      $sql="SELECT HWID FROM users WHERE Expire_Date='$id'";
      $result=mysql_query($sql);
      $rows=mysql_fetch_array($result);
  }

  if (strtotime((new DateTime())->format("Y-m-d H:i:s")) > strtotime($rows)) {
    die("valid");
  } else {
    die("invalid");
  }

The code works together with C#
    dataToSend["HWID"] = HWID();
    string GetData = Encoding.UTF8.GetString(wc.UploadValues(@"http://127.0.0.1/test.php", dataToSend));

    if (GetData == "valid")
    {
        MessageBox.Show("date is valid", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    else if (GetData == "invalid")
    {
        MessageBox.Show("date is not valid", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

Let's say HWID (Hardware ID) is an username 18585B53C213CA86DE91BE1E2772D66C6EC3F32F in a database and there's a date specified 2021-07-01. So when the date will run out, it will tell invalid, otherwise if it's not out, it'll tell valid. Every time I try this code it gives me valid. I'm not sure if I specified the username correctly or didn't compare correctly.
Comment: `strtotime($rows)` - you're attempting to create a timestamp from an array containing data of the whole row. You need to select just one column, the one containing the actual date.
Comment: **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187)
Comment: You are mixing APIs in PHP. `mysql_query` doesn't exist
Comment: `strtotime((new DateTime())->format("Y-m-d H:i:s")` looks way too overcomplicated. Why not just use `time()` instead?
Comment: `$HWID = ($HWID);` doesn't make much sense either.
Answer: First of all, you should be using prepared statements. If you want to use mysqli then I show you how to do it below, but I would strongly recommend learning PDO instead.
You can check DateTime objects against themselves. No need to use the old strtotime() function. You just need to select the single value from the database.
<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect("server", "name", "pass", "db");

$HWID = "";
if (!empty($_POST['HWID'])) {
    $HWID = $_POST['HWID'];
} elseif (!empty($_GET['HWID'])) {
    $HWID = $_GET['HWID'];
} else {
    die("nodata");
}

$stmt = $con->prepare("SELECT Expire_Date FROM users WHERE HWID=?");
$stmt->bind_param('s', $HWID);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_object();
$Expire_Date = $row->Expire_Date;

if (new DateTime() > new DateTime($Expire_Date)) {
    die("valid");
} else {
    die("invalid");
}

Comment: I noticed that it gives a HWID to compare and not the database time from a specified HWID.
Comment: @MattThhh Yeah, I didn't really know where you were getting the date from
Comment: I want to get the database time from a specified HWID in database. [This is how the database are looking](https://prnt.sc/13o2t59)
Comment: I removed the GET input and swapped around the SELECT statement. Is this what you meant?
Comment: It says undefined variable Expire_Date on line 23
Comment: @MattThhh It's defined two lines above
Comment: I get blank as output so I did like that
[Link](https://hastebin.com/zinasoqoma.php)
Comment: If `$_GET['Expire_Date']` is not set then `$Expire_Date` won't be set either. I removed that line from my answer as I have no idea what you were trying to do there
Answer: As El_Vanja say, your problem is the strtotime($rows). When you fetch your rows with $rows=mysql_fetch_array($result); you get an array with all selected columns(see doc here, you should take care it's depreciated since PHP 5.5 and remove from PHP 7.0 and above).
When you read the doc of strtotime your first argument must be a string.
To fix your error you just have to replace $rows=mysql_fetch_array($result); by $rows=mysql_fetch_array($result[0]); or $rows=mysql_fetch_array($result["HWID"]);. Personnaly I prefer the second one is more readable.


How to download video with JavaScript

Question: I am working on video downloader extension for Google Chrome, and it is my first project (I am making Chrome extension for the first time). As I know you should use JavaScript for functionality of extension.
I want to do following: I am on some website where is some video player and i want to let user to download that video. I think Video Downloader Plus is related to my purpose. So how can I let user do functional above?
Comment: Please specify your problem to a single concise question and show us what you tried so far.
Comment: @SebastianSpeitel As I said i have no idea about how can i donwload video with javascript from any website, so i want hint or example
Comment: It's a very broad topic, quite possibly very complicated as well. Start by inspecting the code of other extensions which you can do easily in devtools. Also learn how to use devtools to facilitate debugging various contexts of extensions.
Comment: yes but how can i inspect it?
Answer: Use JavaScript to look through the user's DOM.
Take anything that's <embed> on the page...
document.getElementsByTagName("embed")

That's usually a video player. The embed tag has a URL, use JavaScript to parse the URL that's written in the embed tag, you have your video URL.
if you use JavaScript to navigate to a page, you can effectively download it.
For instance if you used
window.location.href = 'VIDEO URL';

you would download the video. Example embedded code:
   <embed width="420" height="315"
    src="https://www.youtube.com/embed/tgbNymZ7vqY">

Please note: usually people are using iframes now to plop a video onto the page:

So maybe your code should be able to parse things like YouTube URLs within iframes, as well as embedded videos.
Comment: Yeah I know it sound board but all i wanted was a hint. Thank You. BTW i am js developer but chrome extensions are new challenges for me
Answer: <button onclick="downloadImage()">Download Image</button>

function downloadImage() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://via.placeholder.com/150', true);
  xhr.responseType = 'blob';
  xhr.onload = function() {
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL(this.response);
    var tag = document.createElement('a');
    tag.href = imageUrl;
    tag.target = '_blank';
    tag.download = 'sample.png';
    document.body.appendChild(tag);
    tag.click();
    document.body.removeChild(tag);
  };
  xhr.onerror = err => {
    alert('Failed to download picture');
  };
  xhr.send();
}

If you see cors problem then adds
It will works only download with image and video
Comment: tested with `mp4` and `flv` files of +120Mb, this absolutely works for video as well.
Answer: Here's how to use it with the Fetch API using a Promise:
export async function download(url) {
    return new Promise((res, rej) => {
        fetch(url).then(res => res.blob()).then(file => {
            const tempUrl = URL.createObjectURL(file);
            const aTag = document.createElement("a");
            aTag.href = tempUrl;
            aTag.download = url.replace(/^.*[\\\/]/, '');
            document.body.appendChild(aTag);
            aTag.click();
            URL.revokeObjectURL(tempUrl);
            aTag.remove();
            res();
        }).catch(err => {
            rej(err);
        });
    });
}

Source: https://www.codingnepalweb.com/download-file-from-url-with-javascript/

How to download video with JavaScript


How to get timed metadata updates in an iOS app with Google Cast support

Question: I'm working on an iOS app with Google Cast support. One of the key features is playing radio live streams and with the native player (I'm using AVPlayer) I'm able to get timed metadata from the stream, so I can update the currently playing content while the live stream is being played. This is a very common feature you can find in almost every media app. To accomplish this, I just observe using KVO the timedMetadata property of the current item of the AVPlayer instance, and then filter the info of the keys that interest me.
When I load the same stream in the default receiver app of the Google Cast, I only get updates of the status, volume... but the metadata info is just the one I created the item with before loading it, and I can't find how to get this timed metadata.
Is there a way to implement this?
Answer: If you need more metadata beyond what is provided by the default receiver, then you need to implement your own custom receiver. You can start with our reference receiver: https://github.com/googlecast/CastReferencePlayer
Additional information can be passed to the senders as part of the media update messages or you can use your own custom namespace.
Comment: Thanks! That means that it's doable using a custom receiver, right? Does that implementation support it already? I've checked it and I couldn't find it.
Comment: You will need to add custom logic to send the additional data to the senders.
Comment: Great, I can try that. I have a couple of more questions. a) Should I add another listener to the media element to get timed metadata updates or does your media player library already provide a callback for that? b) I've used a listener in the sender iOS app where I get status updates, I guess I should use the custom data property for this additional data. How can I send this custom data from the receiver?
Comment: For both it depends on your need and timing. There are callbacks on both the receiver and sender that you could hook into. If you add your metadata to the media status updates as a custom payload then you can use the media status updates otherwise use your own custom channel.


Fisher's Exact Test, Relative Risk or Odds Ratio?

Question: A clinical trial is being planned, in which the primary outcome is binary (success/failure). There are two treatment groups (treatment/control). The aim of the trial is to show that the treatment is better. The outcome is bad, meaning that in the treatment group, we wish to have a smaller proportion.
The events of interest are rare, and assumed to be around 7% in the control group and 5% in the treatment group.
I did a lot of reading, and some people say that with low rate of events it's better to use the risk ratio (relative risk) over the proportion difference (with normal approximation). It's not clear to me why.
I wanted to ask, under the conditions described above, what is best: Fisher's Exact Test, Odds Ratio (with a CI or hypothesis testing of OR=1), or Relative Risk (with CI or hypothesis testing of RR=1)? Will I get similar results in all? Should sample size be roughly the same?
Thank you !
Answer: Such guidelines exist, but either the odds ratio (OR) or the relative risk (RR) is fine. You only have to be sure that you interpret either one correctly. This is the advice given by Schmidt & Kohlmann (See below). Given that the relative risk is more intuitive, then it may be more advisable to use it. At least, this is the advice given by Deeks (See below). Deeks recommends the odds ratio only when it is obtained from case-control studies and logistic regression analysis.
Additionally, the CI would be much better at communicating the uncertainty about the effect than using a p-value. Both are analogous either way.
An additional outcome of interest for you could be the Number Needed to Treat, which is calculated from the absolute risk. In your situation using the 5% and 7% values you posted, one would need to treat ~50 people to reduce incidence by 1 person.
This tool calculates all 4 metrics given the 2x2 contingency table, and returns confidence intervals using a variety of methods. It makes use of the epitools R package. I'd be glad to answer any questions.
Schmidt, C. O., & Kohlmann, T. (2008). When to use the odds ratio or the relative risk? International Journal of Public Health, 53(3), 165–167. https://doi.org/10.1007/s00038-008-7068-3
Deeks, J. (1998). When can odds ratios mislead? Odds ratios should be used only in case-control studies and logistic regression analyses. BMJ (Clinical Research Ed.), 317(7166), 1155-6-7. Retrieved from http://www.ncbi.nlm.nih.gov/pubmed/9784470
Comment: Firstly, thank you for the wise comment. I have two questions. 1. Should the conclusion of all methods be identical (i.e., if one test shows a difference between groups, so will the others). 2. Should the required sample size for all methods be roughly identical ? i.e., is using OR instead of Fisher's exact test reduces the sample size significantly? I am trying to figure out why people recommended using the OR and RR when the proportions are low.
Comment: No, the methods are not identical as the different methods for calculating the confidence intervals can lead to different inference. The point estimates will have the same direction though. Unless it is a theoretical question, the solution when one comes up with issues like this is to perform all the valid options, then attempt to understand any reasons for differences in results if there are. If there are not, then it increases confidence. For your second question, I do not understand how a test reduces sample size. And can you provide a reference for that recommendation?
Comment: I ran a calculation using a sample size software, and for an OR test I got a much smaller sample size than for the exact test. I think it has something to do with the fact that the OR test or CI uses a normal approximation ?
Comment: Are you talking about a "power" analysis?
Comment: Yes ! Also about the analysis, but thinking about both aspects. I just ran a simulation in SAS, and the power came out identical to OR (95% CI) and Fisher.
Comment: For the actual analysis, try out the different methods and see if they converge. Expect that the estimates can be widely different for OR and RR (with good reason), but always same direction. For power analysis, I would like the most conservative (i.e. method producing largest sample size) unless recruitment is expensive. I would also try to stick with using the effect size I am most likely to report, so for an intervention, RR. Note that the CI calculation for the OR could be using Fisher's exact test by default in SAS.
Comment: Thank you. I used the default output of PROC LOGISTIC. The output said Wald confidence interval. Yes, recruitment is expensive indeed.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/60649/discussion-between-user162986-and-user3275222).
Answer: It may depend on the sample size but keep in mind that Fisher's Exact test is very conservative is based on the assumption that both sets of marginals are fixed (number in each group and number of each type of outcome). Logistic regression and Pearson Chi Square are both possibilities. If you have a browser that works with unsigned applets, you can investigate the performance of the Chi Square test with different sample sizes here.
Comment: Hi David. Since the effect is very small, the sample size is expected to be very large, hundreds if not thousands of subjects.
Comment: I would say Pearson Chi Square and logistic regression are equally good choices. Choose one a priori and stick with it. Don't try both.


What are concrete categories with the property that its morphisms that have (functional) inverses are isomorphisms called?

Question: In the category of topological spaces, a morphism (continuous map) which has an inverse (as a function of sets) is not necessarily an isomorphism (homeomorphism), but in the category of groups, or any other algebraic category I can think of, every homomorphisms which has an inverse (as a function of sets) is an isomorphism. What is this property (that the category of groups has and the category of topological spaces does not have) called? And how important is it in Category Theory? Is it a nice property for a category to have?
Answer: It means that the forgetful functor $U : \mathsf{C} \to \mathsf{Set}$ is conservative. I don't believe this property has a particular name.
Here you can find some info about how to characterize concrete categories with a conservative functor.


Problema no replace usando for

Question: Quero fazer uma sentença dançante a partir de uma frase dada pelo usuário, mas pela forma q eu fiz a saída está dando diferente e eu não consigo entender
<code>    frase: str = input("Digite a sentença que deseja transformar: ")
frase: str = frase.lower()

cont: int = len(frase)

for x in range(cont):
    if x % 2 == 0:
        frase = frase.replace(frase[x], frase[x].upper())

print(frase)
</code>
Por algum motivo resultou em:
Digite a sentença que deseja transformar: Alo galera
Saída: ALO GALeRA
Comment: Não sei se entendi o que é pra fazer, mas enfim, segue meu chute: `frase = ''.join(c.upper() if i % 2 == 0 else c for i, c in enumerate(frase))`
Answer: O replace vai substituir todas as ocorrências desse caratér na frase. Para substituir pelo índice tem que ser da seguinte forma:
<code>for x in range(cont):
    if x % 2 == 0:
        frase = frase[:x] + frase[x].upper() + frase[x + 1:]
</code>

Problema no replace usando for


Programmatically select/use ItemTemplate or AlternatingItemTemplate

Question: I have a ASP.NET repeater, and i want to make use of it's ItemTemplate and AlternatingItemTemplate slightly different as how they are supposed to be used. Instead of having ASP.NET to switch between the 2 for every odd/even item, i want to choose the right template in the ItemDataBound event.
Does anyone know whether this is possible?
I saw that which template is being applied, comes from which ItemType the row/item has. So if anyone knows how to manipulate that value, that would be great as well.
Answer: Turns out that this is really not possible. The only option you have here, is to write your own version that inherits from ASP.NET repeater. Then, of course, you can do/overrule whatever you like to do with your templates.


Criar procedure no phpmyadmin

Question: Estou tentando criar um procedure que altera entre insert e update no phpmyadmin mas me retorna um erro na linha do if EXISTS, depois tentei criar pelo painel grafico e me retorna erro na ultima linha sempre... Alguém sabe oque está errado?
Erro quando tento pelo painel(Sem sql)

Erro quando tento por sql

Query
CREATE PROCEDURE SEND_ITEMS(
  IN i_item_id int(11),
  IN i_customer_id VARCHAR(11),
  IN i_quantity SMALLINT)
  AS
  BEGIN
  IF(EXISTS(SELECT item_id,customer_id FROM wpcheap_items_selected WHERE (item_id = i_item_id AND customer_id = i_customer_id)))
 THEN Update wpcheap_items_selected SET quantity = i_quantity WHERE (item_id = i_item_id AND customer_id = i_customer_id)
 ELSE
   INSERT INTO wpcheap_items_selected(item_id,customer_id,quantity) VALUES (i_item_id, i_customer_id, i_quantity)
END

Answer: Você possui vários erros de sintaxe nessa procedure, segue o código correto:
Faltavam alguns ;
DROP PROCEDURE IF EXISTS SEND_ITEMS;
DELIMITER |
CREATE PROCEDURE SEND_ITEMS(
        IN i_item_id int(11),
        IN i_customer_id VARCHAR(11),
        IN i_quantity SMALLINT
)
BEGIN
    IF(EXISTS(SELECT item_id,customer_id FROM wpcheap_items_selected WHERE (item_id = i_item_id AND customer_id = i_customer_id))) THEN

        UPDATE wpcheap_items_selected
            SET quantity = i_quantity
        WHERE (item_id = i_item_id
            AND customer_id = i_customer_id);

     ELSE

         INSERT INTO wpcheap_items_selected(
                item_id,
                customer_id,
                quantity)
        VALUES (
                i_item_id,
                i_customer_id,
                i_quantity);

    END IF;
END
|
DELIMITER ;

Comment: Muito Obrigado Funcionou

Criar procedure no phpmyadmin


How to calculate the distance between two points in C

Question: I'm stuck on a problem where I'm suppose to create a function to calculate the distance between two points. This is the code we were given in class:
typedef struct Point3D {
double x;
double y;
double z;
} point3d_t;

 // Structure for a triangle in 3d
 typedef struct Triangle3D {
point3d_t pts[3];   // Lines between points implicit
 } triangle3d_t;

 // Distance between two points
 double distance(point3d_t *p1, point3d_t *p2){

 }

Initially I thought that the code in double distance was going to be the following, but I couldn't compile:
distance = (sqrt((p2-p1)*(p2-p1)));

Anyone what should be in double distance?
Comment: `(sqrt((p2-p1)*(p2-p1))` has 4  `(` but only 3 `)`
Comment: `p1` and `p2` are *pointers*. While subtracting pointers can sometimes be valid, this is not one of those cases. They both *point to* something that has `x` `y` and `z` coordinates. You are supposed to extract these coordinates, manipulate them,  and use them to calculate the distance.
Comment: you always need to balance parenthesis
Comment: Well this is a very inefficient way to learn. If you cannot keep up with lectures, use a book at your own pace.
Comment: @GarrGodfrey what do you mean?
Comment: @GarrGodfrey Aha, yeah I fixed it now. It still doesn't compile the code tho
Comment: @n.1.8e9-where's-my-sharem. aha okey! Should i use p1[x] then to point at the coordinates ?
Comment: Did they actually teach you to work with pointers before giving you this assignment?
Comment: @Cheatah I have issues with concentration so I have a hard time understanding lectures, so I try to do the assignments we get instead and search online for solutions
Answer: Getting a distance in 3D space is not much different than in 2D space:
you have 3 vectors, dx, dy, dz. The distance is sqrt(dx^2 + dy^2 + dz^2)
Your code didn't compile because it doesn't balance parenthesis, but it is also incorrect as it only accounts for 2 dimensions and multiplies instead of adds.
For you code, you need to do a simple calculation to get dx, dy, dz:
double distance(point3d_t *p1, point3d_t *p2){

    double dx,dy,dz;
    dx = p2->x - p1->x;
    dy = p2->y - p1->y;
    dz = p2->z - p1->z;

    return sqrt(dx*dx + dy*dy + dz*dz);
}

Note, sign doesn't matter on our deltas, since they get squared and will always be positive.
For a quick proof of the distance formula, you start with Pythagorean theorem, and then realize that any two vectors (say, dx and dy) form a right triangle, with sqrt(dx^2 + dy^2) as the length of hypotenuse. The hypotenuse forms another right triangle with dz, so applying pythagorean theorem again, we get:
sqrt(sqrt(dx^2 + dy^2) ^ 2  + dz^2)
which simplifies to:
sqrt( dx^2 + dy^2 + dz^2 )
Comment: @meaning-matters These types of problems aren't usually very hard but I've struggled to understand how to use points in these scenarios ._.
Comment: Thanks man! Just another question then, to access the x1 and x2 should it be as p2[x+1] and p1[x] to access these coordinates?
Comment: In C, use -> to access members of a struct or class when derefencing a pointer. Use `.` if you have a reference to the struct rather than a pointer.  So, pt->x   or t.x.   Could also use (*pt).x to really annoy people
Comment: And it's not much different in 1D space either: sqrt(dx^2)  :-)
Comment: @relaxedbroccoli I understand, been there.  I hope you Understand why the distance is calculated in this way.  Once you understand something it's easy to rethink it later in case you've half forgotten it over time.


Distinction between Mode and Key

Question: I am a little confused on the distinction between mode and key. If I see a lot of F#s (not in the key signature) and Cs, is it correct to say I am in C lydian mode but still in C major key? Moreover, what if the key signature actually has F# but instead of G being the tonic, C is emphasized?
Is a mode a certain type of key, just as using the C major scale puts you in the C major key? I have not heard anyone say C lydian key before, so I assume that is incorrect.
Help appreciated!
Answer: The "key" in many cases can be determined by the tonic note of the piece, and the tonic's position in the diatonic pattern.
It often happens that a modal music's key signature is written in a parallel major/minor key, and adjusted into the modal pattern by adding or removing accidentals.
I believe this is done so as not to confuse musicians that have learned only Major/Minor as key signatures and scale. Musicians that learn Major-centric theory are expecting only one of two tonics in a key signature, the Major tonic and the Minor tonic.
For example, you will see a Dorian tune (d-ef-g-a-bc-d) written in D minor key (one flat, the Bb in the key signature), and every single Bb in the piece will have a natural sign in front of it.  The same is true for Mixolydian pieces, (g-a-bc-d-ef-g) where the F# is in the key signature indicating G Major, but all the #s are removed in the piece with accidentals.
In some method and instructional books, you will also see the key of C major, but the piece is actually G major, and the F#s are added in as accidentals. I believe this is usually because the method book hasn't advanced to explaining key signatures yet.
To answer your example, if your key signature is the same as C major and you see the Fs turned into F#s, if the tonic is C then you would say you are in the key of C Lydian, even if the key signature indicates otherwise. You would not say that you are playing C Lydian mode in the key of C Major (except to describe how the piece was written out in the transcription). If the key signature shows C, but the Tonic is G and F#s are added, then the diatonic pattern you are playing is G major.
Modal music will be described by its actual key, so you will hear "E Dorian", meaning the tonic is E and the scale pattern is Dorian. The key signature in this case should have two sharps in it.
Each Key signature contains the notes for all seven natural modes. The mode is determined on which tone in the pattern the melody or piece is focusing on (the tonic). Of the seven, Ionian is the same as Major Scale, Aeolean is the same as Minor Scale
Answer: The term mode is often the subject of confusion, but it's really quite
 simple:
Mode in the musical sense means a 'manner' or 'fashion' of playing a scale. There is no absolute difference between a mode and a scale: Every scale has a given key signature and one can play any ordered collection of 7 notes using that key signature - start on any note in the chromatic octave (which has no accidentals) and play a conventional 7 note scale,  following the key signature -  you now have a what's called a scale or mode.
Mode is a relative term: when you decide, for whatever reason, to make one particular note your root, that pattern is called the scale, and becomes a 'parent scale', as it were, to its other modes: Building a scale with the same key signature but using a different root than the 'parent' root becomes a mode: A different fashion/manner of playing the parent scale.
So using the example of C Ionian - which we call the C Major Scale, the 6th mode of that scale - a scale that starts on the 6th degree of the parent scale, (whose key signature has no sharps and no flats) in this case A - becomes the Aeolian mode, commonly known as the A Minor Scale. But note that C major also has a modal name: Ionian. In fact, if we  decide that A Aeolian is the parent scale, C Ionian would then be considered the third mode of A Minor. And so it goes with all modes and scales.
Because today we tend to think  of the C Major and A Minor Scales as the basis for our tonal system, everything else we refer to as "modes", but it's by no means so clear-cut, and in truth it's simpler than one might think.

Distinction between Mode and Key


Webpack can't resolve non-js `require`s from within node_modules

Question: I've got a Next.js project configured to resolve imports that end in .web.js. This works outside of my node_modules directory. I did this by setting resolve.extensions = ['.web.js, '.js', '.jsx'] in my webpack config. I understand that this setting is responsible for resolving imports that don't have an extension, e.g. import _ from './component', when ./component.web.js exists.
I also have some node_modules that make use of this .web.js extension. They're private modules, but the idea stands. Let's say our node_modules looks like this. It may be worth noting that these modules have already been transpiled and as such use require rather than import.
- node_modules
  - @foo
    - bar.js
    - baz.web.js
    - baz.native.js

Now let's say that we have the following:
// bar.js
require("./baz");

If I try to import @foo/bar, the app will throw a module not found error on the line require("./baz"); saying that it can't be found. If I change it to require("./baz.web.js") or remove the line altogether then the app runs fine.
Why can webpack make these kind of resolutions outside of node_modules, but not within the directory? And how can I tell webpack to resolve those imports, too?
Answer: Depending on your module resolution strategy, you'll either find some files or not. Node.js resolves modules as outlined here. This means for you that require('./baz') is resolved to requesting /path/to/module/baz.js. Since your file is not actually named, it is not found. You can use require('./baz.web') instead.
As to whether Webpack can "automatically" handle which import to use, it probably comes down to using a plugin or having some sort of logic in bar.js to choose between baz.web and baz.native.


How to compute the Gaussian measure of a ball centered at the origin?

Question: The Gaussian measure is the probability measure on $\mathbb{R}^d$ with density
$$\frac{e^{-\|x\|^2/2}}{(2\pi)^{d/2}}.$$
The ball is defined as
$$B_r = \{x\in\mathbb{R}^d: \|x\| \le r\}.$$
How to compute
$$\mathbb{P}(B_r) = \int_{x\in B_r}\frac{e^{-\|x\|^2/2}}{(2\pi)^{d/2}}dx?$$
Comment: What have you tried? Spherical coordinates lead to an evaluation in terms of the incomplete gamma function. ($r^2$ is chi-squared distributed.)
Comment: @spaceisdarkgreen I have no idea how to solve this. Could you please elaborate it?
Answer: The integrand is radially symmetric so we can use spherical coordinates and not have to worry about the angular coordinates. $d^dx\propto \rho^{d-1}d\rho,$ so $$ P(B_r) \propto\int_0^re^{-\rho^2/2}\rho^{d-1}d\rho \propto\int_0^{r^2/2} e^{-u}u^{d/2-1}du = \gamma(d/2,r^2/2)$$ where $\gamma$ is the lower incomplete Gamma function. The proportionality constant can be found by normalization.


E/launcher - unknown error: Chrome failed to start: exited abnormally, Protractor

Question: I am new to protractor ,as well as automation testing. I ran my conf.js file but the process terminate with below error related to chorme

error message

$$> protractor conf.js
[08:38:14] I/launcher - Running 1 instances of WebDriver
[08:38:14] I/direct - Using ChromeDriver directly...
**

[08:39:14] E/launcher - unknown error: Chrome failed to start: exited
  abnormally   (Driver info: chromedriver=2.37.544315
  (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Linux
  3.10.0-1062.1.1.el7.x86_64 x86_64) [08:39:14] E/launcher - WebDriverError: unknown error: Chrome failed to start: exited
  abnormally   (Driver info: chromedriver=2.37.544315
  (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Linux
  3.10.0-1062.1.1.el7.x86_64 x86_64)

**
    at Object.checkLegacyResponse (/usr/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:546:15)
    at parseHttpResponse (/usr/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/http.js:509:13)
    at doSend.then.response (/usr/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/http.js:441:30)
    at process._tickCallback (internal/process/next_tick.js:68:7)
From: Task: WebDriver.createSession()
    at Function.createSession (/usr/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:769:24)
    at Function.createSession (/usr/lib/node_modules/protractor/node_modules/selenium-webdriver/chrome.js:761:15)
    at Direct.getNewDriver (/usr/lib/node_modules/protractor/built/driverProviders/direct.js:77:33)
    at Runner.createBrowser (/usr/lib/node_modules/protractor/built/runner.js:195:43)
    at q.then.then (/usr/lib/node_modules/protractor/built/runner.js:339:29)
    at _fulfilled (/usr/lib/node_modules/protractor/node_modules/q/q.js:834:54)
    at /usr/lib/node_modules/protractor/node_modules/q/q.js:863:30
    at Promise.promise.promiseDispatch (/usr/lib/node_modules/protractor/node_modules/q/q.js:796:13)
    at /usr/lib/node_modules/protractor/node_modules/q/q.js:556:49
    at runSingle (/usr/lib/node_modules/protractor/node_modules/q/q.js:137:13)

[08:39:14] E/launcher - Process exited with error code 199

I have tried all possible solutions ,
From upgrading chrome to 59x version to downgrading it to 2.37 version
adding extras like below to conf.js file
directConnect: true,
 useAllAngular2AppRoots:true,
 capabilities: {
    browserName: 'chrome',
    chromeOptions: {
    'args':['--no-sandbox']
    }
  }

 conf.js

exports.config = {

  directConnect: true,
  framework: 'jasmine',
  //  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec.js'],
  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      'args': ['--no-sandbox']
    }
  },
  useAllAngular2AppRoots: true
}

could someone please help me make this work.
Thank you
(new to post questions on stackoverflow as well :b)
Comment: Please check the chrome version installed and the chrome-driver being downloaded when you run webdriver-manager update command. There might be difference in chrome and driver versions.
Answer: The main error here is that your chrome is failing to start a session. This happens if the chrome version being downloaded is the latest beta version. This is a bug in the latest protractor package which is being looked into for the protractor 6 release with backwards compatibility with webdriver-manager. For this you will have to fix the version of the chromedriver.
How are you running your webdriver manager update? Do not use the globally installed protractor to run your tests, use the protractor from node modules. Do the same thing when using webdriver manager update. Use a fix version like ./node_modules/protractor/bin/webdriver-manager update --standalone --versions.standalone=3.8.0 --chrome --versions.chrome=78.0.3904.97
Add this to your scripts in package.json.
Add jasmine options in your configuration file:
jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 260000,
        isVerbose: true,
        includeStackTrace: true,
    }

I don't think the latter would help but try updating the webdriver manager with the fix version and let me know how that goes.


Fetch multiple rows with LIKE operator?

Question: Dealing with a unnormalized database, I have to fetch rows from two tables with a LIKE operator.
TblRequests                             TblDetails
ReqID      ReqName                      DetailID    ReqID         DetailDesc
  1        Ledgers                         1          1           Accounting
  2        Inventory                       2          1           Finance
                                           3          1           Finance Audit
                                           4          2           Misc

I have to fetch all rows from TblDetails whom have DetailDesc like 'finance' with their detail id. Something like
ReqID   ReqName         HasMatch        MatchedDetailsID
  1      Ledgers           Yes            2,3

Update
I tried to use an inner join but that would return me multiple rows in result.
Answer: DB2 (and most relational databases) is not well suited to returning a comma separated list instead of individual rows.
See DB2 comma separated output for details of transforming the multiple rows into a list.

Fetch multiple rows with LIKE operator?


Raspberry Pi MAX31865 Python to Java conversion

Question: I'm trying to convert a piece of Python code reading MAX13865 sensor into Java. The Python code works well and return an expected number (1238), while the Java version always returns 32767. To simplify the reading I reduced the Python code and the Java code to the smallest. The Python code below still works very well. What am I missing? It seems to be very simple, but still doesn't work...
#!/usr/bin/python -tt

import RPi.GPIO as GPIO
import time
import datetime
import math

class MAX31865(object):

    def __init__(self, cs_pin, clock_pin, data_in_pin, data_out_pin, board = GPIO.BCM):

        self.cs_pin = cs_pin
        self.clock_pin = clock_pin
        self.data_in_pin = data_in_pin
        self.data_out_pin = data_out_pin
        self.board = board

        # Initialize needed GPIO
        GPIO.setmode(self.board)
        GPIO.setup(self.cs_pin, GPIO.OUT)
        GPIO.setup(self.clock_pin, GPIO.OUT)
        GPIO.setup(self.data_in_pin, GPIO.IN)
        GPIO.setup(self.data_out_pin, GPIO.OUT)

        # Pull chip select high to make chip inactive
        GPIO.output(self.cs_pin, GPIO.HIGH)

    def get_data(self):
        '''Acqures raw RDT data.'''
        self.address = int(0x01)    #RTD MSBs
        MSB = self.read()
        self.address = int(0x02)    #RTD LSBs
        LSB = self.read()
        MSB = MSB<<8
        raw = MSB+LSB
        raw = raw>>1
        return raw

    def read(self):
        '''Reads 16 bits of the SPI bus from a self.address register & stores as an integer in self.data.'''
        bytesin = 0

        # Select the chip
        GPIO.output(self.cs_pin, GPIO.LOW)
        # Assert clock bit
        GPIO.output(self.clock_pin, GPIO.LOW)

        # Write to address
        for i in range(8):
            bit  = self.address>>(7 - i)
            bit = bit & 1
            GPIO.output(self.data_out_pin, bit)
            GPIO.output(self.clock_pin, GPIO.HIGH)
            GPIO.output(self.clock_pin, GPIO.LOW)

        # Read in 8 bits
        for i in range(8):
            GPIO.output(self.clock_pin, GPIO.HIGH)
            bytesin = bytesin << 1
            if (GPIO.input(self.data_in_pin)):
                bytesin = bytesin | 1
            GPIO.output(self.clock_pin, GPIO.LOW)
        # Dsable clock
        GPIO.output(self.clock_pin, GPIO.HIGH)
        # Unselect the chip
        GPIO.output(self.cs_pin, GPIO.HIGH)

        # Save data
        self.data = bytesin
        return self.data

if __name__ == "__main__":
    cs_pin = 8
    clock_pin = 11
    data_in_pin = 9
    data_out_pin = 10

    # Configure RTDs
    rtd = MAX31865(cs_pin, clock_pin, data_in_pin, data_out_pin)
    log_string = ''

    # Run main loop
    running = True
    while(running):
        try:
            RTD_code = rtd.get_data()
            print '{:.0f}'.format(RTD_code * 4300 / 32768)
            time.sleep(0.1)
        except KeyboardInterrupt:
            running = False
    GPIO.cleanup()

And my tentative of Java conversion:
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.wiringpi.Gpio;

public class MAX31865 {

  protected Pin cs_pin;
  protected Pin clock_pin;
  protected Pin data_in_pin;
  protected Pin data_out_pin;

  protected GpioPinDigitalOutput cs_pin_out;
  protected GpioPinDigitalOutput clock_pin_out;
  protected GpioPinDigitalInput data_in_pin_in;
  protected GpioPinDigitalOutput data_out_pin_out;

  protected int address;
  protected int data;
  final GpioController gpio = GpioFactory.getInstance();

  public MAX31865(Pin cs_pin, Pin clock_pin, Pin data_in_pin, Pin data_out_pin, int address, int data) {
    this.cs_pin = cs_pin;
    this.clock_pin = clock_pin;
    this.data_in_pin = data_in_pin;
    this.data_out_pin = data_out_pin;
    this.address = address;
    this.data = data;

    // Initialize needed GPIO
    cs_pin_out       = gpio.provisionDigitalOutputPin(cs_pin, "SPI_CS");
    clock_pin_out    = gpio.provisionDigitalOutputPin(clock_pin, "SPI_CLCK");
    data_in_pin_in   = gpio.provisionDigitalInputPin(data_in_pin, "SPI_IN");
    data_out_pin_out = gpio.provisionDigitalOutputPin(data_out_pin, "SPI_OUT");

    // Pull chip select high to make chip inactive
    cs_pin_out.setState(PinState.HIGH);
  }

  /**
   * Reads 16 bits of the SPI bus from an address register & stores as an integer in data.
   * @return
   * @throws InterruptedException
   */
  public int read() throws InterruptedException {
    int bytesin = 0;

    // Select the chip
    cs_pin_out.setState(PinState.LOW);
    // Assert clock bit
    clock_pin_out.setState(PinState.LOW);

    // Write to address
    for (int i = 0; i < 8; i++) {
      byte bit = (byte) ((address >> (7 - i)) & 1);
      data_out_pin_out.setState(bit == 1);
      clock_pin_out.setState(PinState.HIGH);
      clock_pin_out.setState(PinState.LOW);
    }

    // Read in 8 bits
    for (int i = 0; i < 8; i++) {
      clock_pin_out.setState(PinState.HIGH);
      bytesin = bytesin << 1;
      if (data_in_pin_in.getState() == PinState.HIGH) {
        bytesin = bytesin | 1;
      } else {
        System.out.println("Is low!");
      }
      clock_pin_out.setState(PinState.LOW);
    }

    // Disable Clock
    clock_pin_out.setState(PinState.HIGH);
    // Unselect the chip
    cs_pin_out.setState(PinState.HIGH);
    Thread.sleep(1);

    // Save data
    data = bytesin;
    return data;
  }

  public int getData() throws InterruptedException {
    address = 0x01;
    int msb = read();
    address = 0x02;
    int lsb = read();
    System.out.println(msb + " " + lsb);
    msb = msb << 8;
    int raw = msb + lsb;
    raw = raw >> 1;
    return raw;
  }

  public static void main(String args[]) throws InterruptedException {
    MAX31865 max = new MAX31865(RaspiPin.GPIO_08, RaspiPin.GPIO_11, RaspiPin.GPIO_09, RaspiPin.GPIO_10, (int)0x80, (int)0xC2);
    // max.write();
    while (true) {
      System.out.println(max.getData());
      Thread.sleep(100);
    }
  }
}

Update
Just adding one comment in case it can help others. If you power-off the system (and so the MAX31865) it will stop working back until you WRITE to it.
    # Configure RTDs
    rtds = []
    address = int(0x80)    # RTD control register, see datasheet for details
    data =  int(0xC2)      # RTD condrol register data, see datasheet for details
    for cs_pin in cs_pins:
        rtds.append(MAX31865(cs_pin, clock_pin, data_in_pin, data_out_pin, address, data))
    print rtds
    for rtd in rtds:
        rtd.write()
    print rtd

Comment: Could you please check the values read (`msb`, `lsb`, `MSB`, `LSB`) in `get_data`?
Comment: In the java version, I get 255 for both msb and lsb. In the Python version I get 75 and 69 (For a result being 1264 which is 68.22C)
Comment: Hm, ok. Then please check the value `bit` in each iteration when writing the adress and `bytesin` while you are doing the bit shifting. Is the adress correct?
Comment: In Python:
[code]
0
0
0
0
0
0
0
1
0
0
0
2
6
14
30
60
0
0
0
0
0
0
1
0
0
2
6
14
28
56
[code]
In Java:
[code]
0
0
0
0
0
0
0
1
0
0
0
2
6
14
30
60
0
0
0
0
0
0
1
0
0
2
6
14
28
56
[code]
The addresses seems to be fine, but the reads seems to be wrong...
Comment: when I print GPIO.input(self.data_in_pin) I get this: 0
0
1
1
1
1
0
0
1
1
1
1
0
1
1
1
And for Java:
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
Comment: Could you please try to read from another adress just to see if you can read any zeros at all? I had a look at the datasheet and you could try Configuration (00h) or Fault Status (07h).
Comment: Tried addresses from 0 to 7 (included) and they all return only 1 for every single bit.
Answer: Issue was related to the way Pi4J maps the GPIO pin numbers vs the Python version.
https://www.pi4j.com/1.2/pins/model-3b-rev1.html
The Python version:
MAX31865(8, 11, 9, 10)

And the java equivalent:
MAX31865 max = new MAX31865(RaspiPin.GPIO_10, RaspiPin.GPIO_14, RaspiPin.GPIO_13, RaspiPin.GPIO_12);

Notice that the pin numbers are different. But both give the exact same result now. Everything else works just fine.
RTFM :(
Comment: As usual...You think you did something wrong in the smart stuff you were doing. But it is just some stupid thing you overlooked in the beginning. Been there ;)


C using free correctly

Question: I believe I am doing this right but wanted to make sure. In a program I am using two pointers that point to allocated memory returned by a function. When I finish using that memory I free() it, but then I use those same pointers to point at a new allocated memory space. Here is my program to give an example of what I mean (Commented to show my thought process):
int main(void)
{
    char *data, *url;
        int i = 1;

    while(i)
    {
        printf("Enter URL: ");
        if(!(url = getstr())) return 1;                                  //url now points to allocated memory from getstr();
        if(strlen(url) <= 0) i = 0;
        if(data = readsocket(url, 80, "http")) printf("\n%s\n\n", data); //data now points to allocated memory from readsocket();
        else printf("\n\n");
        free(url);                                                       //free allocated memory that url points to url
        free(data);                                                      //free allocated memory that data points to data
    }
    return 0;
}

Is this correct, or is there a better more generally preffered method of doing this? Or am I just completely doing it wrong?
Comment: A small tip, `strlen` will never return a negative number.
Comment: OK, then you're fine. Freeing `NULL` is perfectly legit.
Comment: What are the semantics of `readsocket`?
Comment: It retrieves data from a socket
Comment: I meant what does it return, how does it fail, etc. I'm worried that `free(data)` may be a problem.
Comment: Ah that's right because it returns a size_t right? (in regards to strlen)
Comment: It returns NULL on any kind of failure otherwise it returns allocated memory space containing data retrieved from the socket.
Answer: Assuming your functions getstr and readsocket malloc the memory internally then this is perfectly fine.
My only suggestion is that it's often helpful to allocate memory in the same scope that you free it, this often helps reason about when things need to be freed.
For example:
url = malloc(URL_MAX_LEN);
if (!url) return 1;
if (!getstr(url)) {
    free(url);
    return 1;
}
/* do something with url */
free(url);

It can be nice to do this using goto, if you have lots of objects and exit points.
object1 = malloc(OBJECT1_SIZE);
/* do work, if there's an error goto exit1 */
object2 = malloc(OBJECT2_SIZE);
/* do work, if there's an error goto exit2 */
object3 = malloc(OBJECT3_SIZE);
/* do work, if there's an error goto exit3 */
exit3:
free(object3);
exit2:
free(object2);
exit1:
free(object1);
return 1;

If your objects get more complex and require a lot of work to create and destroy then you can wrap malloc and free, but it's critical you apply exactly the same rules to your create/destroy functions as you would to malloc/free to avoid leaks. As a matter of good practice you should always have a destroy to match a create, even if it just wraps free. It's much harder to go wrong that way.
struct x *create_x() {
    struct x *p = malloc(10);
    p->val1 = 7;
    return p;
}
void destroy_x(struct x *p) {
    free(p);
}

Comment: As a general guideline, I propose C's *Rule of Three*: `malloc`, `goto` and `free` should always come together, or not at all.
Comment: @AdrianRatnapala: That's true. There's a somewhat transitive gotcha to the rule, I suppose: You *can* leak one surplus `malloc`, but that in turn makes your entire function count as a `malloc`-type function itself, which then becomes subject to the Rule... if that makes any sense :-)
Comment: I this rule is good, but it prevents you from having "factory functions" which create new objects.  If you want to use that pattern, you should do one or both of the following: (a) invent consistently name the factory functions (new_XYZ and create_XYZ are good conventions), so that you get in the habit of free()ing them. (b) define a matching "destroy_XYZ" function for each new_XYZ, which might or might not be a simple wrapper for free().
Comment: @KerrekSB Or you should forget about goto and write an inline function cleanup() which frees all malloc:ed memory. It is perfectly safe to pass a null pointer as parameter to malloc so the clean up function can look the same no matter from where it is called.
Comment: @AdrianRatnapala I very much agree with this. I'm going to update my answer to include a reference to factory functions.
Answer: There is no problem in your code, but you can pre-allocate memory for data and url and pass these as arguments to getstr and readsocket functions. This will be more efficient.
Comment: @JanSpurny, perhaps he will implement this later ;)
Answer: If the functions getstr and readsocket allocates memory using e.g. malloc then it's what you are doing is okay.
Comment: @JoachimPileborg: In soviet Russia, null deletes *you*!
Comment: You don't need to check for `NULL` prior to calling free, [`free`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html) simply does nothing if passed a `NULL`.
Comment: Freeing a NULL pointer is legal C and should have no negative consequences - obviously getting a null back might be a sign of other problems but by itself free(NULL); isn't an error.
Comment: @KerrekSB I still remember when bad stuff happened, and seem to forget that apparently it's okay these days.
Answer: Here's some things I've noticed:

You're using i to control the loop, but when you set i = 0, the program has to go all the way to closing curly bracket. I'd recommend using while (1) and break statements and getting rid of i variable:
while(1) {
    ...
    if (strlen(url) <= 0)
        break;
    ...
}

you are using if (data = readsocket(url, 80, "http")) which is not technically wrong, but it is a bit misleading as someone may mistake it for comparison if (data == readsocket(url, 80, "http"). This is almost a "pattern" in C programming and it's generally a good idea to write just like you did on if (!url = getstr())) line:
if ((data = readsocket(url, 80, "http")) != NULL) ...

or
if (!(data = readsocket(url, 80, "http"))) ...

this is more a "style"-related, but it is better to write separate statements on separate lines, so don't write
if (!(url = getstr())) return 1

but rather
if (!(url = getstr()))
    return 1;

as for free-ing memory, you're doing just fine

C using free correctly


Why there is no number 13 in Formula 1?

Question: Why is number 13 not used in Formula 1? Is it just superstition? Was the number ever used?
Answer: Number 13 isn't in use just from superstition.

The FIA Formula 1 World Championship entry list does not have a number
  13. The number is generally considered to be an unlucky number. It was used in the early years of the sport but in the 1920s it was dropped
  after the Delage factory team suffered two fatal accidents with the
  number in the course of just a few months. The first was Paul Torchy,
  who crashed into a tree during the San Sebastian Grand Prix in
  September 1925 (below).

Source
Answer: Basically, yes it's just superstition. I remember noticing this in the 1990 season where the Osella/Fondmetal team were only running one car (Olivier Grouillard). Logically they should have run car #13 but were allocated #14.
Here is one of a number of sources for the superstition story online.
Note that, after a rule change in 2014 which mandates drivers to make such a decision, Pastor Maldonado opted for the number 13 for the rest of his F1 career. As of 2021, Maldonado has not raced in F1 for more than two seasons, and so the number is available for any new entrant who wishes to use it.

Why there is no number 13 in Formula 1?