text:
Q: Function for writing text file (.obj) data to python list fills list with last element in data file I am trying to save co-ordinate information of a .obj file to a multidimensional python list. Each element of the list "cube" is 8 sets of 3D co-ordinates.
The code was working fine until I made it into a function. The problem seems to be in the for loop I made for parsing the data, but I cannot see what's wrong.
The data file looks like this (only pasted the first two objects (cubes, since they are all cubes)): https://pastebin.com/U7dmCsC3
def read_obj(file, filepath):
    # count number of distinct objects (cubes)
    o = 0
    for line in fyle:
        if line[0] == "o":
            o += 1
    print("number of cubes =", o)

    # generate array with size = number of cubes
    vec = [0.0] * 3
    arr = [vec] * 8
    cube = [arr] * o
    # each element of cube is an array of
    # the 8 co-ordinates that make up the cube
    i = -1
    j = 0
    for line in open(filepath):
        #
        vec_line = line.split(" ")
        if line[0] == "o":
            i += 1
            j = 0
        if line[0] == "v" and line[1] == " ":
            cube[i][j] = [float(vec_line[1]),
            float(vec_line[2]),float(vec_line[3])]
            j += 1

    return cube

To run it,
cube = read_obj(fyle, filepath)

Where filepath is chosen with tkinter, and
fyle = open(filepath,"r")

Every time the letter "o" is read the function should write the following co-ordinates to cube[i] in the for loop, until the next "o" and then it goes on to cube[i+1] and so on. The problem I have is that every row of cube is the same - the co-ordinates of the last object in the data file.


text:
Q: What are the relative geometries of the Google Glass camera and screen? In regards to developing some AR applications for the device, I am wondering if the relative geometries between the virtual screen on the glass and the camera's view are specified and defined anywhere? That is, is the screen in a fixed, known position in relation to the camera's cone of vision?

A: Nope, none of this information is specified as part of the official API surface, but I bet with a little experimentation you could figure it out.

A: The sensor coordinate system for Google Glass is documented here by Google.  Note that the optics-pod part of Google Glass carries the sensors. There is an admonition that since users may adjust the optics-pod the relationship to where the user is looking may not be precise.  Here is the excerpt from this Google Glass documenation
Here's some tips when using sensors on Glass:
The Glass sensor coordinate system is shown below relative to the Glass display. For more information, see sensor coordinate system.

The accelerometer, gyroscope, and magnetometer are located on the optics pod of the Glass device, which users rotate to align the device with their sight. You cannot measure the angle of the optics pod directly, so be aware of this when using angles from these sensors for applications such as compass heading.
To preserve battery life, only listen to sensors when you need them. For example, if your Glassware uses a Service to render a LiveCard and you only need the sensors when the live card is visible, use the LiveCard surface callback methods to start and stop listening to the sensors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Probability of placing $k$ balls in $n$ bins? We have $n$ bins and $k$ balls, with $1 \leq k \leq n$.
The balls are placed in the bins, knowing that the placement of each ball is independent of the others, and that the bins are chosen in an equiprobable way.

*

*Calculate the probability that each bin contains at most one ball.

*Calculate the probability that a bin contains all balls.

*Calculate the probability that a bin contains at least two balls.

My attempt:

*

*The probability that each bin contains at most one ball is the probability that a bin contains at most one ball $n$ times. Now, the probability that a bin contains at most one ball is the probability that it contains exactly one ball plus the probability that it contains no balls.

I think that the probability that it contains exactly one ball is $k/n$.
I cannot continue. Any helps? Thanks.

A: Assuming you have 1., you can immediately get 3.: these are complementary events.
To answer 1., observe that for this even to happen, you first need to place the first ball into any bin; then the second into any of the remaining $n-1$ bins; then the third into any of the remaining $n-2$ bins; etc. So your probability is
$$
\mathbb{P}\{\text{no collision}\} = 1\cdot\frac{n-1}{n}\cdot\frac{n-2}{n}\cdots\cdot\frac{n-(k-1)}{n} = \prod_{\ell=0}^{k-1} \frac{n-\ell}{n} = \frac{n!}{n^k (n-k)!}
$$
Sanity check: for $k=1$, you get $1$.
Now, to answer 2. Your event corresponds to the union of $n$ disjoint events (namely: "all balls in bin #1", "all bins in bin #2", ..., "all balls in bin #n"). The probability of each of these events is exactly
$$
\left(\frac{1}{n}\right)^k = \frac{1}{n^k}
$$
since the $k$ balls are placed independently. So the overall probability is $n\cdot \frac{1}{n^k} = \frac{1}{n^{k-1}}$. (again, for $k=1$, you do get $1$, as expected).


text:
Q: PowerShell search string and copy file I'm preparing a script to find some text inside the files ('test' and 'test1' are the keywords in this scenario) and once all the files have been found, they should be copied to a different location while maintaining the folder structure.
For example:
The path c: \ src contains 10 files, 3 include the search words.
These 3 files should be copied to c: \ dst \
Everything should be recursive for all subdirectories of c: \ src.
So if in the path c: \ src \ somefolder \ there were other files with the same search words, they should be copied to c: \ dst \ somefolder \
Here my code:
Write-Host ""
Write-Host "Note: Path must end with '\'"
Write-Host ""

# Var.
$sourceDir = Read-Host 'Source path'
$targetDir = Read-Host 'Destination path'

# Decl.
$tree = gci -Directory -Name -Recurse $sourceDir

# Check if $sourceDir exist
if(!(Test-Path -Path $sourceDir )){
  "Source is not a valid path!" ; pause
exit 1
}

# Check (and create) $targetDir
if(!(Test-Path -Path $targetDir )){
  mkdir $targetDir -Force
}

# Rebuild Tree
foreach ( $folders in $tree ) { mkdir $targetDir\$folders -Force }

# Copy Founded Files
$ftc = Get-ChildItem $sourceDir -Recurse | Select-String "test","test2" | Select Path |
foreach{
  $targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);
  Copy-Item $_ -destination $targetFile
}

I can not figure out where the error is.
Does anyone know how I can solve it ?
The proposed error is: Copy-Item: Unable to find the unit. A unit named '@ {Path = C' does not exist.

A: Your script had some severe bugs

*

*the -Name parameter in your gci building the tree only left the
subdir Name so the rebuild tree part only had a flat structure the gci on files lateron can't match.

*your select-string pattern matches twice as the 2nd contains 1st, so I added the -Unique paramter to select Path

*used Get-Item $_.Path to build targetFile name pass to Copy-Item

This worked here on a (different) test tree:
## Q:\Test\2018\05\17\SO_50391092.ps1
Write-Host ""
Write-Host "Note: Path must end with '\'"
Write-Host ""

# Var.
#$sourceDir = Read-Host 'Source path'
#$targetDir = Read-Host 'Destination path'
$sourceDir = "C:\test"
$targetDir = "A:\Test"

# Decl.
$tree = gci -Directory -Recurse $sourceDir

# Check if $sourceDir exist
if(!(Test-Path -Path $sourceDir )){
  "Source is not a valid path!" ; pause
  exit 1
}

# Check (and create) $targetDir
if(!(Test-Path -Path $targetDir )){mkdir $targetDir -Force}

# Rebuild Tree
foreach ( $folder in $tree ) {
    mkdir ($folder.fullname.replace($sourceDir,$targetDir)) -Force |Out-Null
}

# Copy Found Files
$ftc = Get-ChildItem $sourceDir -Recurse | Select-String "test","test2" | Select -Unique Path |
foreach{
  $sourceFile = Get-Item $_.Path
  $targetFile = $sourceFile.Fullname.Replace($sourceDir,$targetDir)
  $sourceFile | Copy-Item -Destination $targetFile
}


text:
Q: Request.UrlReferrer is easily bypassed and not reliable to use as guard? I was trying to make a guard for some action so it is not accessible unless the request comes from a certain host. Here is the sample code.
public ActionResult test()
{
    if (Request.UrlReferrer == null || Request.UrlReferrer.Host != "mydomain.com") { return Content("Blocked!"); }
    else { return Content("Authorized!"); }
}

Everything seems to work well until I went to mydomain.com "typed the link in the addressbar" , opened the browser console and typed
window.location.href = "https://domainholdingthatacion.whatever/ActionRoute/test"; //trying to get unauthorized access

It worked! It enters the else branch. I need your input because I have no idea if I am using it wrong as Request.UrlReferrer is not meant to be used for that or It is inherently vulnerable.

A: UrlReferrer is not safe to use for authorization. Any browser or client can decide to set the referrer url to whatever they want. Additionally some browsers block refuse respecting this header (though that's mostly only true between different domains) for privacy reasons.
There's the Authorize annotation specifically for this.

*

*Authorize attribute in ASP.NET MVC

*https://www.red-gate.com/simple-talk/dotnet/asp-net/thoughts-on-asp-net-mvc-authorization-and-security/

*https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-3.1


text:
Q: Halide optimal scheduling I'm trying to work out the best schedule for a benchmark Halide code and I might be missing something because the timing results don't make much sense to me.
I'm using AOT compilation, and here's the algorithm part of the code:
ImageParam input1(type_of<float>(), 3);
ImageParam input2(type_of<float>(), 3);
Func in1 = BoundaryConditions::constant_exterior(input1, 0.0f);
Func in2 = BoundaryConditions::constant_exterior(input2, 0.0f);
f1(x, y, z) = (in1(x + 1, y, z) + in1(x, y, z) + in1(x - 1, y,z));
f2(x, y, z) = (in2(x + 2, y, z) + in2(x + 1, y, z) + in2(x, y, z) +in2(x - 1, y, z) + in2(x - 2, y, z));
res(x, y, z) = f1(x, y, z) + f1(x - 1, y, z) + f2(x - 1, y, z) + f2(x, y, z);

For the schedule this is what I have:
f1.store_at(res, y).compute_at(res, yi).vectorize(x, 8);
f2.store_at(res, y).compute_at(res, yi).vectorize(x, 8);
res.split(y, y, yi, 8).vectorize(x, 8).parallel(y);
res.print_loop_nest();

I use the current_time function to time the execution of my code. When I use the mentioned schedule for both f1 and f2 the execution time is more than when I use the schedule on only one of these Funcs. Considering the structure of the stencils I'd have thought scheduling both of them would improve performance. What am I missing here? Also when I print the loops to see the generated code:
  for k:
    parallel j.j:
      store f1:
        store f2:
          for j.in_y in [0, 7]:
            produce f1:
              for k:
                for j:
                  for i.i:
                    vectorized i.v122 in [0, 7]:
                      f1(...) = ...
            consume f1:
              produce f2:
                for k:
                  for j:
                    for i.i:
                      vectorized i.v126 in [0, 7]:
                        f2(...) = ...
              consume f2:
                for i.i:
                  vectorized i.v133 in [0, 7]:
                    result(...) = ...
consume result:

Is it just the indentation or is the produce f2 nested within produce f1?
Any suggestions for a better schedule?

A: I think this is probably memory-bandwidth limited. The few extra adds implied by inlining f1 or f2 into res don't really matter. Indeed, I get the best performance with the following schedule:
in1.compute_at(res, yi).vectorize(in1.args()[0], 8);
in2.compute_at(res, yi).vectorize(in2.args()[0], 8);
res.split(y, y, yi, 8).vectorize(x, 8).parallel(y);

I.e. just pulling in a padded scanline of each inputs and then doing all the math inlined.
But it's barely any faster than yours. The difference might be noise. My full experiment:
https://gist.github.com/abadams/c2e6f67d79e1768af6db5afcabb1caab
The produce of f2 is nested inside the consume of f1. That's normal - it doesn't use f1, but it's used by something that does use f1, so that's a reasonable place for it to end up.


text:
Q: Transform csv-coordinates into area I'm working with an inventory of a species in Southern Sweden. I have recorded my findings (together with coordinates, name of the species and year of finding) and created a CSV-file with i have imported to QGIS.
Example from my data
Decade;species;ort;lat,long
1880;falcata;Borgholm;56.882657,16.655931
1880;falcata;Algutsrum;56.674716,16.53471
1880;falcata;Borgholm;56.882657,16.655931

In order to make a map that's easy to grasp I would like to collect all findings from e.g 1890 into an area, all findings from 1900 into a second area an so on. Someone that have a clue on what I can to to achieve this?

A: and with area you mean a polygon using all "1880" points as nodes?
In this case you should look in the Sextante toolbox for something to convert points to polygons.
Or do you think of some kind of kernel density analysis? Have a look at the plugins "animove" and the homerangeplugin.


text:
Q: What is the meaning of Transaction? I've been reading about "Java Transaction" , and i've been  confused about what's it? and what's useful in?

A: You can google around and find pages like this: http://www.java-tips.org/java-ee-tips/enterprise-java-beans/introduction-to-the-java-transactio.html
but the bottom line is: a transaction is a set of operations which must all succeed or all fail and be reversed (rolled back).
The obvious example is banking: if you transfer money from savings to checking, both updates had better occur, or neither, otherwise there will be an error.

A: I would say the best place to start are:
http://en.wikipedia.org/wiki/Transaction_processing
http://en.wikipedia.org/wiki/ACID
Thanks,
Nitin


text:
Q: How to pass argument in callback function? I want get email (text value from txtEmail field) in callback
I have text field :
  <asp:TextBox MaxLength="50" runat="server" ID="txtEmail" ClientIDMode="Static" onblur="SendRequest()"></asp:TextBox>

my javascript handler :
 <script type="text/javascript">
      function SendRequest(arg) {
           window.UseCallback(arg);
      }
 </script>

and server event handler
 protected void Page_Init(object sender, EventArgs e)
 {
    string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "GetEmailFromServer", "context");
    string cbScript = "function UseCallback(arg, context){" + cbReference + ";}";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cbScript, true);
 }

 public void RaiseCallbackEvent(string eventArg)
 {
     var result = Controller.CheckEmail(eventArg);      // eventArg == undefined
 }

How can I set eventArg to txtEmail.Text ?

A: Change This Line and Check
 string cbScript = "function UseCallback(arg){" + cbReference + ";}";

or  change this
<script type="text/javascript">
       function SendRequest(arg)
        {
             window.UseCallback(arg,"");
        }
</script>


text:
Q: Multiple Mongo container in ECS I have made this task definition in ansible to create two container in an ECS cluster:
- name: Create task definition
  community.aws.ecs_taskdefinition:
    containers:
    - name: mongo-db
      essential: true
      image: "mongo:5.0.9"
      environment:
        - name: MONGO_INITDB_ROOT_USERNAME
          value: "{{ lookup('env', 'DB_USER') }}"
        - name: MONGO_INITDB_ROOT_PASSWORD
          value: "{{ lookup('env', 'DB_PASSWORD') }}"
      mountPoints:
      - containerPath: "/data"
        sourceVolume: mongodb-data-local
        readOnly: true
      - containerPath: "/dump"
        sourceVolume: mongodb-dump
      - containerPath: "/docker-entrypoint-initdb.d/init-mongo.sh"
        sourceVolume: db-init
        readOnly: true
      portMappings:
      - containerPort: 27017
        hostPort: 27017

    - name: roadmap-mongo-db
      essential: false
      image: "mongo:5.0.9"
      command: ["mongod", "--port", "27018"]
      environment:
        - name: MONGO_INITDB_ROOT_USERNAME
          value: "{{ lookup('env', 'DB_USER') }}"
        - name: MONGO_INITDB_ROOT_PASSWORD
          value: "{{ lookup('env', 'DB_PASSWORD') }}"
      mountPoints:
      - containerPath: "/data"
        sourceVolume: roadmap-mongodb-data-local
        readOnly: true
      - containerPath: "/dump"
        sourceVolume: roadmap-mongodb-dump
      - containerPath: "/docker-entrypoint-initdb.d/init-mongo.sh"
        sourceVolume: roadmap-db-init
      portMappings:
      portMappings:
      - containerPort: 27018
        hostPort: 27018

    volumes:
    - name: mongodb-data-local
    - name: roadmap-mongodb-data-local
    - name: mongodb-dump
      host:
        sourcePath: "/home/ec2-user/dump"
    - name: roadmap-mongodb-dump
      host:
        sourcePath: "/home/ec2-user/roadmap-dump"
    - name: db-init
      host:
        sourcePath: "/home/ec2-user/init-mongo.sh"
    - name: roadmap-db-init
      host:
        sourcePath: "/home/ec2-user/roadmapdb/init-mongo.sh"

    cpu: 128
    memory: 340
    family: showcase-task
    force_create: True
    state: present

basically I am creating two mongodb containers. The two containers start just fine, the first container (mongo-db) runs properly, I can exec into it and run mongo -u root to connect to it and also the services that interact with it can communicate just fine, so no problem with the first container.
Instead the second container is giving me problems, even if it runs ok and I can exec into it, I cannot do mongo -u root
mongo -u root gives this:
MongoDB shell version v5.0.9
Enter password:
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:372:17
@(connect):2:6
exception: connect failed
exiting with code 1

It seems it still wants to connect to 27017 instead of 27018. What am I doing wrong?
However the logs seems to be fine as it says:
{"t":{"$date":"2022-11-03T12:46:27.654+00:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"/tmp/mongodb-27018.sock"}}
{"t":{"$date":"2022-11-03T12:46:27.753+00:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"0.0.0.0"}}
{"t":{"$date":"2022-11-03T12:46:27.756+00:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27018,"ssl":"off"}}


text:
Q: Perform an OR of two LINQ IQueryables I've got two IQueryables:
    public static IQueryable<Counterparty> SearchByCode(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => x.Code.StartsWith(searchQuery.ToUpper()));
    }

    public static IQueryable<Counterparty> SearchByName(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => x.Name.ToLower().Contains(searchQuery.ToLower()));
    }

I want to create another IQueryable which combines the two queries as an OR e.g
    public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        // return SearchByName(searchQuery) OR SearchByCode(searchQuery)
    }

I'd rather avoid duplication of code so I want to reuse the existing queryables rather than rewriting a new lambda expression like Where(x=> x.Code.StartsWith.... || x.Name.Contains.....)

A: You can probably .Union the results of the two together
public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
{
     return SearchByName(searchQuery).Union(SearchByCode(searchQuery))
}

A: Depending on what code you do want to be able to reuse, this could be an alternative way of doing it where you are not duplicating the inner workings of your query conditions:
    private static Func<Counterparty, string, bool> CodeStartsWith = (x, searchQuery) => x.Code.StartsWith(searchQuery.ToUpper());

    private static Func<Counterparty, string, bool> NameContains = (x, searchQuery) => x.Name.Contains(searchQuery.ToLower());

    public static IQueryable<Counterparty> SearchByCode(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => CodeStartsWith(x, searchQuery));
    }

    public static IQueryable<Counterparty> SearchByName(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => NameContains(x, searchQuery));
    }

    public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
    {
        return queryable.Where(x => NameContains(x, searchQuery) || CodeStartsWith(x, searchQuery));
    }


text:
Q: Weird behavior of string methods in dart I am trying to check for the index of a character "-" in a string variable. Despite the fact that the variable contains "-", dart indexof and lastIndexof are returning -1. I also checked with "contain" method it is equally  returning that string does not contain "-" despite the fact it does. Here is the code:
     String s = "Oh yes, the past can hurt. But the way I see it, you can either run from it or learn from it. – The Lion King";
         int x = s.indexOf('-');
        print(x);
         if(s.contains("-")){
          // print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv............");
           print("Yipee string contains -");
         }else{
           print("string does not contain -");
              // the following is the output:
             //string does not contain -
         }

         if(x == -1){
         print(x);
         // It prints out -1
        }else{

          print(x);
           return s.substring(0,x);
         }

Please for the love of God, what am i doing wrong?

A: '–' and '-' are two different characters. See how the first one is slightly longer.
void main() {
  final str = '–-';
  print(str.codeUnitAt(0)); // 8211 (En Dash)
  print(str.codeUnitAt(1)); // 45 (Hyphen)
}

If you want to find either one or the other, you can also use Regular Expressions:
In the following code sample, str1 and str2 are almost the same. I just inverted the position of '–' and '-'.
void main() {
  final str1 = '123456–78-90';
  final str2 = '123456-78–90';
  final regExp = RegExp(r'[–-]');
  print(regExp.firstMatch(str1)?.start); // 6
  print(regExp.firstMatch(str2)?.start); // 6
}

A: The character - you are searching for is different than the character – in the text. Notice the length difference between the two.

A: The character present in the string is an en dash and is slightly wider than the hyphen (-) but narrower than the em dash (—).
Due to this the contains function is not able to detect hyphen as en dash is present.


text:
Q: How to fix event controller being called twice with Stimulus and HAML I've run into an issue. I'm using Stimulus within HAML and calling a controller using the keydown action. The event listener gets called twice.
This is my HAML code and controller code:
.comments-container{ "data-controller": "comments"}
%h3.short.pull-left
    = current_tenant.label_for_field(:comment).try(:pluralize)
.button-group.action-bar
    %a.fa.fa-cloud-download.export-comments-btn{ title: "Export" }
    %a.fa.fa-archive.archive-toggle-btn{ title: "View Comments Archives" }
.comment-form
    %form
        .form-group
            %textarea.form-control{ name: "Content" , "data-target": "comments.content" }
            .tag-inputs
                %span.help-block
                    Enter a tag followed by the tab, enter, comma or semi-colon key
                %span
                    %label.tags-input-label
                        Tags:
                    %div{ "data-target": "comments.tagsContainer" }
                    %input.tags-input-input{ type: "text" , "data-action": "keydown->comments#createTag" }
            .tag-inputs
                %span
                    %label.tags-input-label
                        Users to notify:
                    %select{ type: "select" , "data-action": "comments#notifiedUsers"}
                        = options_for_select(current_tenant.users.order(email: :asc).pluck(:email, :id).unshift(["Please Select a User",nil]))
            %button.btn.btn-info{ type: "submit" , "data-action": "comments#submit"}
                = "Post #{current_tenant.label_for_field(:comment)}"
.comment-search
    %input.search{ placeholder: "Search Comments" }
.comments-items
    = render @comments

controller.js:
    import { Controller } from "stimulus"

const getCSRFToken = () => {
    return Array.from(document.getElementsByTagName('meta')).find(meta => meta.name === 'csrf-token').content
  }

export default class extends Controller {
    static targets = ["content", "tagsContainer", "tag"]
    connect() {

    }
    submit(e) {
        e.preventDefault()
        console.log(this.contentTarget.value)
    }
    createTag(e) {
        const keys = ["Enter", "Semicolon", "Tab", "Comma"]
        if(keys.includes(e.key)){
            e.preventDefault()
            console.log("Anything")
            this.tagsContainerTarget.insertAdjacentHTML('beforeend', `<span class="tags-input-tag"> ${e.currentTarget.value} </span>`)
        }
    }
    notifiedUsers(e) {
        e.preventDefault()
        //console.log(e.contentTarget.value)
        console.log(e.type)
    }
}


text:
Q: variable datatype arguments in variadic functions Can we pass arguments of different datatypes to same variadic function at the same time?

A: sure, look at common usages of printf:
printf("Error %d: %s", errNum, errTxt);

A: so ross$ expand < variadic.c && cc -Wall -Wextra variadic.c
#include <stdio.h>
#include <stdarg.h>

void f(int, ...);
struct x { int a, b; } y = { 5, 6 };

int main(void) {
  float q = 9.4;
  f(0, 1.234, &q, "how now", 123, &y);
  return 0;
}

void f(int nothing, ...) {
  va_list ap;

  va_start(ap, nothing);
  double f = va_arg(ap, double);
  float *f2 = va_arg(ap, float *);
  char  *s   = va_arg(ap, char *);
  int    i    = va_arg(ap, int);
  struct x *sx = va_arg(ap, struct x *);
  va_end(ap);

  printf("%5.3f %3.1f %s %d %d/%d\n", f, *f2, s, i, sx->a, sx->b);
}
so ross$ ./a.out
1.234 9.4 how now 123 5/6

A: Here's a printf-free example ( old version: http://codepad.org/vnjFj7Uh )
#include <stdarg.h>
#include <stdio.h>

/* return the maximum of n values. if n < 1 returns 0 */
/* lying to the compiler is not supported in this version, eg:         **
**    va_max(4, 8, 8, 8, 8, 8, 8, 8, 8)                                **
** or                                                                  **
**    va_max(4, 2, 2)                                                  **
/* is a bad way to call the function (and invokes Undefined Behaviour) */
int va_max(int n, ...) {
  int res;
  va_list arg;

  if (n < 1) return 0;

  va_start(arg, n);
  n--;
  res = va_arg(arg, int);
  while (n--) {
    int cur = va_arg(arg, int);
    if (cur > res) res = cur;
  }
  return res;
}

int main(void) {
  int test6 = va_max(6, 1, 2, 3, 4, 5, 6);
  int test3 = va_max(3, 56, 34, 12);
  if (test6 == 6) puts("6");
  if (test3 == 56) puts("56");
  return 0;
}

A: I made a function to unpack binary data using a varadic function,it takes different types based on
what you want "encoded/decoded".
You'd use it like:
uint32_t a;
uint16_t b;
uint16_t c;
uint8_t *buf = ....;

depickle(buf,"sis",&a,&b,&c);

where 's' expects an uint16_t* and decodes 2 bytes from buf into a as little endian, 'i' says to decode 4 bytes as little endian into 'b'
Or to e.g. decode 4 bytes as big endian into a uint32_t:
uint32_t a;
uint8_t buf[] = {0x12,0x34,0x56,0x78};
depickle(buf,"I",&a);

There's still an early version around here.


text:
Q: Release project with previous release version of a snapshot dependency on Jenkins I have seen some similar questions but didn't find any working solution. Now Its been a day finding to solve it.
So, below is the problem.
I have a project which I want to maven release through a Jenkins job. But this project has a snapshot dependency.
<dependency>
    <groupId>com.domain</groupId>
    <artifactId>market</artifactId>
    <version>121b4-SNAPSHOT</version>
</dependency>

Below is my project info:
    <groupId>com.domain.tools</groupId>
    <artifactId>cash</artifactId>
    <name>Cash Flow</name>
    <version>123b4-SNAPSHOT</version>

When I try to release project manually with below commands:
mvn release:clean release:prepare release:perform

I got a prompt for resolving dependency snapshot version, So then I just input the previous released version of 'market'  - 121b3 and then everything worked fine.
But when I try to set up a Jenkins job to release the project, the problem is that how can I resolve the snapshot dependency on Jenkins (as we get the prompt when doing manually), as maven release plugin doesn't allow the dependencies with snapshot version.
Can somebody tell me

*

*Whether It is feasible in Jenkins to replace the snapshot versions with previous release versions of dependency ?

*If possible, How can we do that?

Thanks in advance.

A: You can not have any dependency with the word 'SNAPSHOT' in the version.
You will have to either
1) Release 123b4-SNAPSHOT so it is in the shared repository that Jenkins uses
2) Have an embedded repository (where you have a mini repository that is added to the project) and rename the 123b4-SNAPSHOT to 123b4, see here for an example
 <repositories>
    <repository>
      <id>in-project</id>
      <name>In Project Repo</name>
      <url>file://${project.basedir}/libs2</url>
    </repository>
  </repositories>

I recommend option 1.


text:
Q: Java versioning and terminology, 1.6 vs 6.0 OpenJDK vs Sun I'm having problems understanding Java versioning. I'm seeing lots of versions like 1.4.2, 1.5 and 1.6, but I also stumble upon 5.0 and 6.0. I don't understand this versioning or the progression.
I'm pretty new to Java, and I've read a bit about OpenJDK vs Sun, and I think I understand it. Are these versions the difference between OpenJDK and Sun? For example, OpenJDK's latest is 1.6 and Sun's is 6.0?
All these versions are pretty confusing to someone new to Java.

A: *

*Java 1.5.x is the same as Java 5.x

*Java 1.6.x is the same as Java 6.x

Basically throw away the 1. part of the version number.

A: The versioning is simply a mess:

*

*Java 1.0 and 1.1 were normal

*Then came Java 1.2, but you were supposed to call it "Java 2, JDK 1.2"

*This continued until 1.4 (There were also minor releases like 1.4.2)

*The next version was then supposedly "Java 5.0", but there was still "1.5" all over the place in the file names and URLs.

*Starting with Java 6, they've dropped the minor version and mostly (but not completely, see output of java -version) eliminated the traces of the old versioning scheme, but people have gotten used to it and continue to use it colloquially.

*Starting with Java 9 or 10, the 1.X notation also disappeared from the output of java -version (which caused some code that depended on parsing it to break), and people have pretty much stopped using it. We now have Java 15, Java 16, Java 17, etc.

Note also that when this question was asked, Sun JDK and OpenJDK were separate codebases (whith a large overlap), and Sun JDK was the official reference implementation.
In the more than 10 years since then, Java was sold to Oracle, OpenJDK became the official Java reference implementation, and Oracle stopped maintaining the Oracle JDK as a separate codebase. Instead, they just provide OpenJDK builds and provide commercial long term support for them with bugfixes and security patches. But you can also get builds for free from AdoptOpenJDK (which recently rebranded as "Adoptium"), they just aren't supported as long.

A: This is explained (cough) in Java SE Naming and Versions:

The current release is Java Platform,
Standard Edition 6 (Java SE 6). The
previous release was Java 2 Platform,
Standard Edition 5.0 (J2SE 5.0).
Sun Microsystems simplified the
platform name in 2006 to better
reflect the level of maturity,
stability, scalability, and security
built into the Java platform. Sun
dropped the "2" from the name and
deleted the "dot number" (the number
following the period). Any updates to
Java platforms will simply be noted as
updates rather than adding a "dot
number" at the end of the platform
name.
Due to significant popularity within
the Java developer community, the
development kit has reverted back to
the name "JDK" from "Java 2 SDK" (or
"J2SDK"). The runtime environment has
reverted back to "JRE" from "J2RE."
(Note that "JDK" stands for "J2SE
Development Kit" in version 5.0.)
For more information on platform names
and version numbers, see the following
pages:

*

*Java SE 6 Platform Name and Version Numbers

*J2SE Version 1.5.0 or 5.0?

*J2SE SDK/JRE Version String Naming Convention

And quoting Java SE 6 Platform Name and Version Numbers:

At this release, the platform name has changed from J2SETM to JavaTM SE. The official name is JavaTM Platform, Standard Edition 6.
Both version numbers (1.6.0 and 6) are used to identify this release of the Java Platform. Version 6 is the product version, while 1.6.0 is the developer version. The number 6 is used to reflect the evolving level of maturity, stability, scalability and security of Java SE.

And J2SE Version 1.5.0 or 5.0?:

Both version numbers "1.5.0" and "5.0" are used to identify this release of the Java 2 Platform Standard Edition. Version "5.0" is the product version, while "1.5.0" is the developer version. The number "5.0" is used to better reflect the level of maturity, stability, scalability and security of the J2SE.
The number "5.0" was arrived at by dropping the leading "1." from "1.5.0". Where you might have expected to see 1.5.0, it is now 5.0 (and where it was 1.5, it is now 5).

So, to summarize, the whole naming is a mess but this is finally over and the current platform name is JavaTM Platform, Standard Edition 6 (abbrev. JavaTM SE 6). Two Products are delivered under the platform: the JDKTM 6 and the JRETM 6.
OpenJDK 6 is an open-source implementation of the Java SE 6 Platform, it's different from Sun's JDK.

A: Both 1.6 and 6 are used to refer to the same version (and similarly for 1.5 and 5).

A: The only difference is the single digit numbers are usually used in conjunction with Java SE 5 and Java EE 6.
The 1.5 and 1.6 versions are what the Java compiler says using java -version and sometimes 'the minor release' is used as a version string, like SunOS 5.8 was called Solaris 8 as a product name.

A: Guide to java versions  is the best blog for any new person to understand java versioningSince 2019, Java releases new version every 6 months, i.e. March and September. It's October 2021, and Java 17 is already released. Here is the link to download OpenJDKCouple of noteworthy points

*

*you can use always use the latest version of java, it will execute the code written using previous versions

*previously JRE and JDK were separately distributed, now there is a trend to only distribute JDK

*There are two distributions: OpenJDK (free) and OracleJDK (paid)


text:
Q: trying to include curl library, Get the following error from nmake: windows.h file not found My System information : Windows Server 2008 R2 Standard, 64 bit

I am trying to use Curl(http://curl.haxx.se/) Library with my c++ code(Visual Studio MFC). I'm trying to build libcurl.dll from the curl source using nmake (Visual Studio 10). I need to run the following command from Visual Studio Command Prompt:
nmake /f Makefile.vc mode=dll

I get the following error:Error

A: Thanks to mikedu95, I was able to solve this.
Follow instruction from  curl.haxx.se/docs/install.html ("MSVC IDE" in my case)
Then Follow:Getting LibCurl to work with Visual Studio 2013
This will setup everything you need


text:
Q: WP Customer Reviews - shortcodes WP Customer Reviews Plugin
Looking for some shortcodes for displaying the review form only / reviews only.
On the plugin page there is an info about shortcode (Shortcodes available for inserting reviews and review form on any page or widget), but I cannot find theme anywhere.
http://wordpress.org/extend/plugins/wp-customer-reviews/
Have you got any experiences with the plugin?
Any suggestions much appreciated.

A: The plugin registrer some shortcodes in wp-custom-reviews.php:
add_shortcode( 'WPCR_INSERT', array(&$this, 'shortcode_wpcr_insert') );
add_shortcode( 'WPCR_SHOW', array(&$this, 'shortcode_wpcr_show') );

Try: [WPCR_INSERT] and [WPCR_SHOW]

A: For shortcodes and their use, see the WP Admin Dashboard: Settings | WP Customer Reviews.


text:
Q: Tools to help detect different uses of ambiguous tags I just discovered that case-when was sometimes being used when switch-statement should be used.
In order to find questions where it was mis-used, I looked for questions tagged with case-when, and eliminated questions with other tags indicating that it was used correctly (generally SQL related). I ended up with a query of
[case-when] -[sql] -[tsql] -[sql-server] -[hql] -[mysql] -[oracle] -[sql-server-2008] -[sql-server-2005] -[sybase] -[jpql]

is there a more efficient way of finding questions that have been mistagged with a given ambiguous tag?
I'm envisaging something that looks at all the questions tagged with case-when, evaluates how similar each question is with each other question, and manages to work out that there's there's two groups of questions, where questions within a group are similar to each other but questions in one group are fairly different to questions in the other group.

I am trying to retag questions where case-when was used but it should have been switch-statement. Also, I wouldn't envisage the tool doing the retagging, just provide me with a list of questions that probably should be retagged.

A:
is there a more efficient way of finding questions that have been mistagged with a given ambiguous tag?

data.se can be used to search for question that only include a specific tag:
https://data.stackexchange.com/stackoverflow/query/364341/filter-questions-by-a-single-tag

I am trying to retag questions where case-when was used but it should have been switch-statement

data.se can be used to search the accepted answer text and compare it to the tag:
https://data.stackexchange.com/stackoverflow/query/364342/find-questions-with-one-tag-and-specific-answer-text


text:
Q: How to use array values as keys without loops? Looping is time consuming, we all know that. That's exactly something I'm  trying to avoid, even though it's on a small scale. Every bit helps. Well, if it's unset of course :)
On to the issue
I've got an array:
array(3) {
    '0' => array(2) {
        'id'   => 1234,
        'name' => 'blablabla',
    },
    '1' => array(2) {
        'id'   => 1235,
        'name' => 'ababkjkj',
    },
    '2' => array(2) {
        'id'   => 1236,
        'name' => 'xyzxyzxyz',
    },
}

What I'm trying to do is to convert this array as follows:
array(3) {
    '1234' => 'blablabla',
    '1235' => 'asdkjrker',
    '1236' => 'xyzxyzxyz',
}

I guess this aint a hard thing to do but my mind is busted right now and I can't think of anything except for looping to get this done.

A: UPD: Warning the slowest solution! See benchmarks below.
Try this code:
$a = array(array('id'   => 1234,
                 'name' => 'blablabla'),
           array('id'   => 1235,
                 'name' => 'ababkjkj'),
           array('id'   => 1236,
                 'name' => 'xyzxyzxyz'));

var_export(array_reduce($a, function($res, $item) {
    $res[$item['id']] = $item['name'];
    return $res;
}));

Works fine even in PHP 5.3. And uses only one function array_reduce.
UPD:
Here are some benchmarks (PHP 5.6 over Debian 7 on a medium quality server):
$a = [];
for ($i = 0; $i < 150000; $i++) {
    $a[$i] = ['id' => $i,
               'name' => str_shuffle('abcde') . str_shuffle('01234')];
}

$start = microtime(true);

if (false) {
    // 7.7489550113678 secs for 15 000 itmes
    $r = array_reduce($a, function($res, $item) {
             $res[$item['id']] = $item['name'];
             return $res;
         });
}

if (false) {
    // 0.096649885177612 secs for 150 000 items
    $r = array_combine(array_column($a, 'id'),
                       array_column($a, 'name'));
}

if (true) {
    // 0.066264867782593 secs for 150 000 items
    $r = [];
    foreach ($a as $subarray) {
        $r[$subarray['id']] = $subarray['name'];
    }
}

if (false) {
    // 0.32427287101746 secs for 150 000 items
    $r = [];
    array_walk($a, function($v) use (&$r) {
        $r[$v['id']] = $v['name'];
    });
}

echo (microtime(true) - $start)  . ' secs' . PHP_EOL;

So, as a conclusion: plain iteration with simple for loop is a winner (as mentioned in this answer). On a second place there is array_combine allowed only for new versions of PHP. And the worst case is using my own solution with closure and array_reduce.

A: If you have php >= 5.5:
$res = array_combine(array_column($source, 'id'), array_column($source, 'name'));

If not - make a loop.

A: Make use of array_map function, (PHP 4 >= 4.0.6, PHP 5)
[akshay@localhost tmp]$ cat test.php
<?php

$array = array(
                array('id'   => 1234,'name' => 'blablabla'),
                array('id'   => 1235,'name' => 'ababkjkj'),
                array('id'   => 1236,'name' => 'xyzxyzxyz')
              );

$output = array();
array_map(function($_) use (&$output){ $output[$_['id']] = $_['name']; },$array);

// Input
print_r($array);

// Output
print_r($output);

?>

Output
[akshay@localhost tmp]$ php test.php
Array
(
    [0] => Array
        (
            [id] => 1234
            [name] => blablabla
        )

    [1] => Array
        (
            [id] => 1235
            [name] => ababkjkj
        )

    [2] => Array
        (
            [id] => 1236
            [name] => xyzxyzxyz
        )

)
Array
(
    [1234] => blablabla
    [1235] => ababkjkj
    [1236] => xyzxyzxyz
)

A: This is the fastest and simplest code here so far ...
$result = [];
foreach ($input as $subarray) {
    $result[$subarray["id"]] = $subarray["name"];
}

A: Simply use array_combine along with the array_column as
array_combine(array_column($array,'id'), array_column($array,'name'));

Or you can simply use array_walk if you have PHP < 5.5 as
$result = array();
array_walk($array, function($v)use(&$result) {
    $result[$v['id']] = $v['name'];
});

Edited:
For future user who has PHP > 5.5 can simply use array_column as
array_column($array,'name','id');

Fiddle(array_walk)

A: Try this function:
array_combine(array_column($array,'id'), array_column($array,'name'));


text:
Q: What is the benefit of having a String class for Rcpp I was wondering what is the benefit for having an Rcpp String class (documented here).
It is possible to convert between Rcpp:String and std::string, but why not just use std::string since many of its methods are already well implemented. I'm guessing there must be a reason for doing this. Thanks for any advice.

A: Easy: There is a STRSXP and Rcpp types are first and foremost proxy objects for the underlying R types. So no copies.
Using std::string would entail copies on the way in and out.  You don't want that.


text:
Q: Python simple regex So I have a pattern:
hourPattern = re.compile('\d{2}:\d{2}')

And match against the compiled pattern
hourStart = hourPattern.match('Sat Jan 28 01:15:00 GMT 2012')

When I print hourStart it gives me None. Any help?

A: Match expects the found value to be at the beginning of the string.  You want search.
>>> import re
>>>
>>> s = re.compile('\d+')
>>>
>>> s2 = 'a123'
>>>
>>> s.match(s2)
>>> s.search(s2)
<_sre.SRE_Match object at 0x01E29AD8>

A: Switch from the match method to the search method:
>>> hourPattern = re.compile('\d{2}:\d{2}')
>>> hourStart = hourPattern.search('Sat Jan 28 01:15:00 GMT 2012')
>>> hourStart.group()
'01:15'


text:
Q: Записать во внешний XML файл Подскажите плиз, как сделать так, чтобы записать в XML файл. Попробовал так ,но файл создаётся пустой(
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ "xmlFile.xml");
file.createNewFile();
FileOutputStream fileos = new FileOutputStream(file);
FileOutputStream fos = openFileOutput("xmlFile.xml",MODE_APPEND);
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8", true);
xmlSerializer.startTag(null, "userData");
xmlSerializer.startTag(null, "Date");
xmlSerializer.text(m1.dt);
xmlSerializer.endTag(null, "Date");
xmlSerializer.startTag(null,"Message");
xmlSerializer.text(m1.msg);
xmlSerializer.endTag(null, "Message");
xmlSerializer.endTag(null, "userData");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite = writer.toString();
fos.write(dataWrite.getBytes());
fos.close();

A: Если записать и прочитать эти данные, то можно использовать пример как  сохранение в TXT, используя SharedPreferences
Почитай про SharedPreferences и как его использовать

A:  loadText() {
    if ( loginInputEmail.getText().toString().equals(""))
    {
        sPref = getSharedPreferences("MyPref", MODE_PRIVATE);
        String savedText = sPref.getString(SAVED_TEXT, "");
        String savedTexts = sPref.getString(SAVED_TEXTS, "");
        loginInputEmail.setText(savedText);
        loginInputPassword.setText(savedTexts);

        Toast.makeText( LoginActivity.this, "Данные подгружены", Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(LoginActivity.this, "Данные не введены. Введите данные и нажмите сохранить, для авто.авторизации", Toast.LENGTH_SHORT).show();

    }
}

Сохранение данных  в TXT, используя SharedPreferences


text:
Q: Comparing a file with a reference file with Python I created fictional Data Frames that comprehends my doubt.
I have two excel spreadsheets that I want to compare, containing the data as follows:
DataFrame to compare

Product ID
Color
Brand

A
Red
Nike

A
Red
Nike

A
Red
Addidas

A
Purple
Nike

A
Red
Nike

B
Yellow
CK

B
Yellow
CK

B
Yellow
CK

B
Yellow
CK

B
Yellow
CK

C
Green
Puma

C
Green
Puma

C
Green
Puma

C
Green
Nike

C
Green
Puma

Reference DataFrame

Product ID
Color
Brand

A
Red
Nike

B
Yellow
CK

C
Green
Puma

Expected Output

Product ID
Color
Brand
Validation

A
Red
Nike
Ok

A
Red
Nike
Ok

A
Red
Addidas
Not Ok

A
Purple
Nike
Not Ok

A
Red
Nike
Ok

B
Yellow
CK
Ok

B
Yellow
CK
Ok

B
Yellow
CK
Ok

B
Yellow
CK
Ok

B
Yellow
CK
Ok

C
Green
Puma
Ok

C
Green
Puma
Ok

C
Green
Puma
Ok

C
Green
Nike
Not Ok

C
Green
Puma
Ok

Packages I am using for previous analysis: pandas, openpyxl
1.
My question here is: How to compare files with different number of
rows? I have five samples of A, that should be compared with one
unique row of the reference file. I couldn't write an iteration
because the counter will be different for each file. I was trying this for comparing the color column first:
for i in range(2, ref.max_row+1):
   cell_obj_1 = ref.cell(row=i, column=1)
   for n range(2, Compare_file.max_row+1):
     cell_obj_2 = Compare_file.cell(row=j, column=1)
        while(cell_obj_1.value == cell_obj_2.value):
            if(Compare_file.cell(row=J+1, column=2).value==(ref.cell(row=I+1, column=2)).value):
                print('Ok')
            else:
                print('Not Ok')

ref = Reference DataFrame
Compare_file = DataFrame to Compare
I just printed for now but my interest is to create a new column in Compare file.

A: As I understand your problem, you have a reference dataframe which contains correct product information and you want to compare this reference data against a second dataframe.  In the second dataframe you want to insert a new column which indicates the result of this evaluation.
So Given the reference dataframe df_ref as shown:
Product Color   Brand
0   A   Red Nike
1   B   Yellow  CK
2   C   Green   Puma

You want to compare the reference data against the dataframe df given below:
Product Color   Brand
0   A   Red Nike
1   A   Red Nike
2   A   Red Addidas
3   A   Purple  Nike
4   A   Red Nike
5   B   Yellow  CK
6   B   Yellow  CK
7   B   Yellow  CK
8   B   Yellow  CK
9   B   Yellow  CK
10  C   Green   Puma
11  C   Green   Puma
12  C   Green   Puma
13  C   Green   Nike
14  C   Green   Puma

create a comparfunction:
def compareFrames(dx: pd.DataFrame, dref: pd.DataFrame) ->list:
    rslt = []
    print(dx.shape[0])
    for i in range(dx.shape[0]):
        dx_data = dx.iloc[i].values
        dref_data = dref[dref['Product'] == dx_data[0]].values[0]
        if dref_data[1] ==dx_data[1] and dref_data[2] == dx_data[2]:
            rslt.append('OK')
        else:
            rslt.append('Not OK')
    return rslt

Which when used as follows:
df['Check'] = compareFrames(df, df_ref)

Yields:
    Product Color   Brand   Check
0   A   Red Nike    OK
1   A   Red Nike    OK
2   A   Red Addidas Not OK
3   A   Purple  Nike    Not OK
4   A   Red Nike    OK
5   B   Yellow  CK  OK
6   B   Yellow  CK  OK
7   B   Yellow  CK  OK
8   B   Yellow  CK  OK
9   B   Yellow  CK  OK
10  C   Green   Puma    OK
11  C   Green   Puma    OK
12  C   Green   Puma    OK
13  C   Green   Nike    Not OK
14  C   Green   Puma    OK

A: If you have this in a database, do the work in the database if you can.
The basic check is whether colour and brand are of the allowed combination.
Allowed = (("Red", "Nike"), ("Yellow", "CK"), ("Green", "Puma"))

for row in ws.iter_rows(min_row=2, min_col=2, max_col=3):
    values = (c.value for c in row)
    validation = values in Allowed and "OK" or "Not OK"
    check = row[0].offset(column=1)
    check.value = validation

This is probably the quickest way if your data is in Excel, otherwise I think you can do it in a dataframe using a lambda function, or in a database.


text:
Q: MBP frequent crashes from kernel panic caused by memory faults? There are 4 very similar crash reports listed here: http://pastebin.com/y7NUNJt6
The starting lines suggest to me it might be a CRC check failure but what do I know ;-)
This tends to happen with the lid closed and the machine not yet in sleep. Do I have bad/overheating memory? A similar report here was not solved.

*** Panic Report ***
panic(cpu 0 caller 0xffffff801f209f4a): Kernel trap at 0xffffff7fa0dee3d2, type 14=page fault, registers:
CR0: 0x000000008001003b, CR2: 0x0000000000000008, CR3: 0x0000000022e0b000, CR4: 0x00000000000226e0
Fault CR2: 0x0000000000000008, Error code: 0x0000000000000002, Fault CPU: 0x0, PL: 1


text:
Q: How to create a SVG file that is editable in Visio In eclipse GMF editor I am export a diagram as SVG Image but it is not editable in Visio. How can I create an SVG file format that is fully editable in MS-Visio. Is there any method in Java through which I can convert my SVG image to visio editable image??

A: I guess you just need to load the svg file in visio.


text:
Q: convert raw string source to html to use jquery selector I have this source

First Page

How can I convert it to html and use selector like $('.page') ? I tried to assign above string to a variable then use html() it doesn't work.

A: You can parse your string in HTML, after that if you look the object returned, there's a data property on the first row who contain the html string with good format.
EDIT
You can get HTML object properties without append it to the DOM. Check my edited code.
var test = '

First Page

';
var testHTML = $.parseHTML(test);
var elemHTML = $(testHTML[0].data);

console.log(elemHTML.text());

You can try this :

var test = '

First Page

';
var testHTML = $.parseHTML(test);
$("body").html(testHTML[0].data);
$(".page").css("color","blue");

//Without append element in the DOM
var elemHTML = $(testHTML[0].data);

console.log(elemHTML.text());

//For count number of element you can use a container without append it to the DOM

var container=$("

");
container.append(elemHTML);
console.log(container.find(".page").length);
.page{
 color:red;
}

A: See comments, first we have to process the entities, then use the result as HTML:

// The string
var str = '<div class="page"><h1>First Page </h1></div>';
// A wrapper element to put it in
var wrapper = $("");
// Process the character entities
wrapper.html(str);
str = wrapper.text();
// Convert the resulting HTML to a structure
wrapper.html(str);
console.log("Text of .page: ", wrapper.find(".page").text());

That's verbose for clarity; here's the concise version:

var str = '<div class="page"><h1>First Page </h1></div>';
var wrapper = $("");
wrapper.html(wrapper.html(str).text());
console.log("Text of .page: ", wrapper.find(".page").text());

A: You can use following script for this
$('.page').html('<div class="page"><h1>First Page </h1></div>');

or
var htmlString = '<div class="page"><h1>First Page </h1></div>';
$('.page').html(htmlString);

Jquery automatically convert it to html


text:
Q: What does "that" mean in this sentence?
turnpike
noun
a wide road, where traffic can travel fast for long distance and "that" drivers must pay a toll to use

(Oxford Advanced Dictionary)
What does "that" mean? Is it a relative pronoun? Must drivers pay a toll to use a wide road?

A: Yes, it's a relative pronoun and is pointing back to the subject "turnpike" (or perhaps "a wide road" -- it's not exactly clear since, being a dictionary entry, the whole thing is made up of sentence fragments). You can see its purpose more clearly if you split the definition into its three constituent parts:

*

*A turnpike is a road that is wide.

*A turnpike is a road that is useful for traffic traveling fast and for long distances.

*A turnpike is a road that drivers must pay a toll to use.

A: It's a pronoun, acting as the subject of the relative clause "that which drivers must pay a toll to use". Here, you could equally well use "which". It means that the previously mentioned road is the thing drivers must pay a toll to use.
It's much the same as "the book that I read".


text:
Q: Search in the middle of a column by default in jqGrid with toolbar search After reading the jqGrid wiki (and taking example from: Case insensitive search in jqGrid including hidden fields), I cannot find what I want to do.
Is there any search option to enable a search anywhere in a column (automatically wildcarded).
If the column contains "Apple Iphone" I would be able to find it by using the search "iphone".
The SQL equivalent would be select * from table where lower(columnX) like '%iphone%';

A: Since you use toolbar searching the solution of your problem seems to be simple. You should:

*

*include ignoreCase:true to the jqGrid parameters

*include defaultSearch:'cn' option to the call of filterToolbar. For example: $("#list").jqGrid('filterToolbar', {defaultSearch:'cn'}).

*If you use any select elements in the searching toolbar (stype:'select') you should include in the list of searchoptions the sopt options which begin with 'eq': stype:'select', searchoptions: {sopt:['eq','ne']} for example.

A: $(document).ready(function() {
  colNamesData = [ 'Description']

  {name:'description',index:'description', width:130, sorttype:"text", search:true, editable:true, edittype:"textarea", editoptions: {rows:"5",cols:"25",maxlength:"255"}, stype:'text', searchoptions:{sopt:['cn', 'nc', 'bw', 'bn', 'ew', 'en']}},

$("#description_table").jqGrid({
      datatype: "local",
      height: "auto",
      autowidth: true,
      ignoreCase: true,
      colNames: colNamesData,
      colModel: colModelHash,
      pager: '#pager',
      rowNum:10,
      rowList:[10,25,50,100],
      sortname: 'date',
      sortorder: 'desc',
      viewrecords: true,
      editurl:"/url_name.json",
      caption: 'Description'
 data:<%= raw @jqgrid_table.to_json %>
   });

   jQuery("#description_table").jqGrid('navGrid','#pager',{del:false,add:true,edit:false},{}, {modal: true,afterSubmit:processAddEdit,recreateForm:true, afterComplete:reloadJqGrid}, {modal: true}, {multipleSearch:true});

Now if your text contains "here i go" and if you search "go", it will surely search, it works for me.
Give a try and reply if it doesn't.

A: $("#list").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "cn"});

In the above example the **defaultSearch : "cn"** is used to search using any substring of item you want to search. Removing defaultSearch : "cn" starts search beginning with the substring.


text:
Q: Tensorflow: my custom gradient not applied There is a lot of examples of py_func usage on Stackoverflow, but I just want to define gradient for my custom activation function, something like this, which uses only tensorflow native operations. Example for Identity forward pass.
Suppose I have registered gradient for my activation "OPLU" (comments illustrate my understanding so far of what's going on):
@tf.RegisterGradient("OPLUGrad")
def oplugrad(op, grad):
    x = op.inputs[0] # Need x !

    # This print should be executed if oplugrad was launched!
    # Because it was set inside the evaluation chain for output !

    x = tf.Print(x, [tf.shape(x)], message = 'debug: ')

    grad_new = x*grad # let it be, just for example

    return grad_new

And defined my layer:
def tf_oplu(x, name="OPLU"):

     y = ...f(x)...

     # Here new op is created, as far as I understand
     with ops.op_scope([x], name, "OPLUop") as name:

         g = tf.get_default_graph()

         # As far as I understand, here I issue command to tensorflow
         # to use "OPLUGrad" when "OPLU" activation was applied

         with g.gradient_override_map({"OPLU": "OPLUGrad"}):
            # OK, gradient assigned, now return what forward layer computes
            return y

But I don't see any output from tf.Print inside gradient function, which means it is not executed.
Question1: How to register it properly and have these two functions in order to use embedded optimizers like AdamOptimizer?
Question2: As far as I understand, standard gradient computation is suppressed in this way. What if I want standard gradients to be computed and then do some modification without interference into Session() code with manual invocation and modification of gradients in Session() run that I've seen somewhere?
EDIT: Here is the example of code for which I want to replace tf.nn.relu with my tf_OPLU
Thank you!


text:
Q: Vendor Return Authorization Workflow Not Changing Approval Status (NetSuite) Vendor Return authorization is not getting approved through workflow.
Approval status field is set to approved in the final state of my workflow but still the main status of the transaction shows PENDING APPROVAL and the blue colored APPROVE RETURN button appears.
Can anyone advise what is needed to be done to do automatic approval through workflow, below is the screenshot of my Workflow.

A: On the transition of workflow from "Pending Approval" state to "Approved" state we need to be sure that the transition to approved state happens on a click on a button i.e. Execute on button "Approve". Also, when you click on the transition arrow, you will see (1) condition and (2) "Transition on" options. Having wrong values there can stop the transition. For eg. for "transition on" if you have "After record submit, it will only work on record edit and if it's on entry then it will work when workflow enters new state and if nothing is selected like my screenshot then it will work for all events
 Please see image for your reference

A: Use 'order status' in lieu of 'approval status'.
What status did you use for the rejected field?


text:
Q: Calculation mistake in variation of length functional? This should be pretty simple to check if you know the basics of variational calculus. I feel like I am making an obvious mistake somewhere like not using chain rule somewhere. Let $g : \mathbb{R}^n \times \mathbb{R}^n \rightarrow \mathbb{R}$ be a smooth metric on some domain in $\mathbb{R}^n$, and let $\gamma : [0,1] \rightarrow \mathbb{R}^n$ be a smooth path in this domain. I'm trying to show that minimising the length functional
$$A(\gamma) = \int_0^1 \sqrt{g(\dot{\gamma},\dot{\gamma})} dt$$
is equivalent to minimising the action functional
$$E(\gamma) = \frac{1}{2} \int_0^1 g(\dot{\gamma},\dot{\gamma}) dt.$$
I can do this in coordinates no problem, but this calculation is a bit messy. In general, the Lagrangian $L$ is not linear, but in this case $g$ is bilinear.
Let $v \in C^1$, $v(0) = v(1) = 0$. Question: is this use of the metric $g$ correct, and can we conclude the result via this calculation, or am I forgetting to use the chain rule somewhere?
\begin{align*}
A(\gamma+tv) &= \frac{d}{dt}\bigg|_{t=0} \int_0^1 \sqrt{g(\dot{\gamma}+t\dot{v},\dot{\gamma}+t\dot{v})} dt \\
&= \frac{d}{dt}\bigg|_{t=0} \int_0^1 \sqrt{g(\dot{\gamma},\dot{\gamma}) + 2t g(\dot{v},\dot{\gamma}) + t^2 g(\dot{v},\dot{v})} dt \\
&= \int_0^1 \frac{1}{\sqrt{g(\dot{\gamma},\dot{\gamma})}}g(\dot{v},\dot{\gamma})dt
\end{align*}
By comparison, the first variation of the action functional is
$$\frac{d}{dt}\bigg|_{t=0} E(\gamma+tv) = \int_0^1 g(\dot{\gamma},\dot{v})dt.$$
So if $\gamma$ has constant speed, i.e. if $g(\dot{\gamma},\dot{\gamma})$, then it seems that minimizing these functionals is identical. But this seems too easy (no derivatives of $g$ coming out)! Also, I can't get the Euler-Lagrange equations for geodesics to come out of this computation (integration by parts, right? -- so that's where the derivatives of $g$ would come out?).
A simple "incorrect" will be appreciated, and an explanation why even more so. Thanks!

A: Thanks to user98130's comment. Came back later and it seemed obvious. Anyway, because there is no dependence on $\gamma$ (which I'll call $f$ for simplicity) or $v$, the Euler-Lagrange equation is "homogeneous":
\begin{align*}
\int_0^1 g(\dot{f},\dot{v}) dt &= \int_0^1 g_{ij}\dot{f}^i\dot{v}^j dt \\
&= g_{ij}\dot{f}^iv(t)\bigg|_{t=0}^{t=1} - \int_0^1 \frac{d}{dt}(g_{ij}\dot{f}^i)v dt \\
\frac{d}{dt}(g_{ij}\dot{f}^j) &= \frac{\partial g_{ij}}{\partial f^k}\dot{f}^k\dot{f}^i + g_{ij}\ddot{f}^j = 0,
\end{align*}
which are the geodesic equations when $g(\dot{f},\dot{f}) = 0$.


text:
Q: How to lock page/content with javascript and html I'm looking to securely lock content on a basic html site based on various permissions of the user.  I'm looking to have a pop-up modal appear when the user's permissions don't check out... however it seems to be that any savvy user could simply open the console and delete that element (thus revealing the page anyways).
What am I missing here? What's the best way to approach this so that no matter what the actual page can't be accessed?
Thanks in advance for the help!

A: If content is downloaded to the client, it's always technically possible for a savvy user to access it.
You can either live with that, or alternatively do something like the following:

*

*Load the basic page template without any content

*Use an API call using cookies/other auth to get the content

*If logged in, display the content, if not, launch the modal.

A: Ok here is my answer to this one.
The answer given was agood one,  you can't hide the content truly so your options are:

*

*Don't download all the stuff you want until you have auth'd the user (via cookies etc.

*Use a simple redirect/buffer page infront of your hidden content.
In my use case (shopify)  partial downloading of store content isn't exactly configurable (or i don't have enough knowledge of their template language + theme design to pull it off!),  so I made use of javascript and cookies in order to check a user's status.  If the user didn't pass they'd get kicked back to a landing page.  Good enough!


text:
Q: Is it ok to put controller name as string? I was wondering if is it OK to put the controller name as a string, like in the following example.
Also, should I put the action as a string instead?
Is there any better approach?
My concert is that if I change the controller's name for any reason, my best option is to do a "find-replace" in the whole project as it is now.

Many thanks!

A: Yes, that is exactly how you use the anchor tag helpers. At least to me that asp-action seems convoluted and I would simply have written it as:
  ...

If you do change your controller name (which should not happen very often), then you would have to update the links.
For further reference see https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-3.1: "If the asp-controller attribute is specified and asp-action isn't, the default asp-action value is the controller action associated with the currently executing view. [...] If the asp-action attribute value is Index, then no action is appended to the URL, leading to the invocation of the default Index action. The action specified (or defaulted), must exist in the controller referenced in asp-controller."

A: In general, we directly use the name of the controller and action as strings, as shown below:
(However, this wording cannot be changed automatically after you change the controller name, you need to modify manually)

1. According to your current wording, you can update the code as follows:
(This will change dynamically as you change the name of the controller)
 link

2. As an alternative solution, you can add the Route attribute to the action specified by the a tag and set the route name.
In the a tag, you only need to use asp-route to link the corresponding action.
Please refer to this.
  link

Controller:
 public class OperationController: Controller
        {
            [Route ("CustomControllerName/Index", Name="MyRouteName")]
            public IActionResult Index ()
            {
                return View ();
            }
        }


text:
Q: Categorical attributes to Sparse Matrix First of all I´m new to Machine Learning.
I am trying to predict the price of second hand cars. This cars have makes and models, so I used a MultiLabelBinarizer to make a sparse matrix, to handle the categorical attributes, here's the code:
from sklearn.preprocessing import MultiLabelBinarizer
encoder = MultiLabelBinarizer()
make_cat_1hot = encoder.fit_transform(make_cat)
model_cat_1hot = encoder.fit_transform(model_cat)
type_cat_1hot = encoder.fit_transform(type_cat)

print(type(make_cat_1hot))
carInfoModHot = carsInfoMod.copy()
carInfoModHot["makeHot"] = make_cat_1hot.tolist()
carInfoModHot["modelHot"] = model_cat_1hot.tolist()
carInfoModHot["typeHot"] = type_cat_1hot.tolist()

doors   km      make        year    makeHot                       modelHot
5.0     78779   Mercedes    2012    [0, 0, 0,  0, 1, 0, 0, 0, ...[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, ...
5.0     25463   Bmw         2015    [0, 1, 0, 0, 0, 0, 0, ...   [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, ...

Then I used it to make a prediction and get the mean square error with a Linear Regression:
lr = linear_model.LinearRegression()

carsInfoTrainHot = carInfoModHot.drop(["price"], axis=1) # drop labels for training set

df1 = carsInfoTrainHot.iloc[:30000, :]
carsLabels1 = carsInfoMod.iloc[:30000, 3]
print(carsInfoTrainHot.head())
df2 = carsInfoTrainHot.iloc[30001:60000, :]
carsLabels2 = carsInfoMod.iloc[30001:60000, 3]
df3 = carsInfoTrainHot.iloc[60001:, :]
carsLabels3 = carsInfoMod.iloc[60001:, 3]

lr.fit(df1, carsLabels1)
print(carsInfoTrainHot.shape)
carPrediction = lr.predict(df2)

lin_mse = mean_squared_error(carsLabels2, carPrediction)

lin_rmse = np.sqrt(lin_mse)

But I get this error:

ValueError                                Traceback (most recent call
  last)  in ()
       12 carsLabels3 = carsInfoMod.iloc[60001:, 3]
       13
  ---> 14 lr.fit(df1, carsLabels1)
       15 print(carsInfoTrainHot.shape)
       16 carPrediction = lr.predict(df2)
/home/vagrant/anaconda3/lib/python3.6/site-packages/sklearn/linear_model/base.py
  in fit(self, X, y, sample_weight)
      510         n_jobs_ = self.n_jobs
      511         X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],
  --> 512                          y_numeric=True, multi_output=True)
      513
      514         if sample_weight is not None and np.atleast_1d(sample_weight).ndim > 1:
/home/vagrant/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py
  in check_X_y(X, y, accept_sparse, dtype, order, copy,
  force_all_finite, ensure_2d, allow_nd, multi_output,
  ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype,
  estimator)
      519     X = check_array(X, accept_sparse, dtype, order, copy, force_all_finite,
      520                     ensure_2d, allow_nd, ensure_min_samples,
  --> 521                     ensure_min_features, warn_on_dtype, estimator)
      522     if multi_output:
      523         y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False,
/home/vagrant/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py
  in check_array(array, accept_sparse, dtype, order, copy,
  force_all_finite, ensure_2d, allow_nd, ensure_min_samples,
  ensure_min_features, warn_on_dtype, estimator)
      400         # make sure we actually converted to numeric:
      401         if dtype_numeric and array.dtype.kind == "O":
  --> 402             array = array.astype(np.float64)
      403         if not allow_nd and array.ndim >= 3:
      404             raise ValueError("Found array with dim %d. %s expected <= 2."
ValueError: setting an array element with a sequence.

From what I understand is that I´m inserting an array in the categorical attributes, but how else can I change the categorical values to a sparse matrix?
Thanks.


text:
Q: MySQL where query by hour diff of 2 timestamps I have a table with 2 timestamps: start_time and end_time. How can I query with conditions like select all where the diff of those 2 fields is more than X hours.
Also does the field type (timestamp vs datetime) has any impact on the query i'm trying to achieve?

A: The data type of the fields does for sure have some differences.
As stated in MySQL Timestamp Difference, it is usually the case that, given two datetime fields, they get converted to timestamps in order to subtract them.
The query could be something like
SELECT *
FROM Table
WHERE TIMESTAMPDIFF(HOUR,start_time,end_time)>2

Edit:
What written above is valid for MySQL, you can use DATEDIFF if you are working in SQL Server


text:
Q: Merge Scala Seq I have following Seq as input:
Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))

I would like to create another Seq from this like below:
Seq(Seq(1,4),Seq(7,9))

I thought to use sliding operation (take 2) and merge as set to remove duplicates but I am not sure how to achieve it using Seq as it is immutable. Can someone help me?

A: I am not sure if I understand that correctly, but try below code:
val input = Seq(Seq(1, 2), Seq(2, 3), Seq(3, 4), Seq(7, 8), Seq(8, 9))

input.flatten.groupBy(x => x).mapValues(_.size).filter{
  case (key, value) => value == 1
}.keySet.toList.sorted.grouped(2).toList

Output for such is:
input: Seq[Seq[Int]] = List(List(1, 2), List(2, 3), List(3, 4), List(7, 8), List(8, 9))

res0: List[List[Int]] = List(List(1, 4), List(7, 9))

A: If I understand correctly, you want to remove all consecutive duplicate values, so that if you have Seq(..., (a, b), (b, c), ...) it returns Seq(..., (a, c), ...)
If you always have two elements in your inside Seqs, you should rather use pairs than Seq (because as much information known at compile time as possible should be given in the types), so I'll do it with pairs, and hopefully, you'll be able to adapt if needed.
def merge(l: Seq[(Int, Int)], acc: Seq[(Int, Int)] = Seq()): Seq[(Int, Int)] = l match {
  //if there's less than one element left, nothing can be merged
  case Seq() | Seq(_) => acc ++ l
  //if the first two elements are mergeable, merge them and call recursively (to allow merging the new pair with the next element)
  case (a, b) +: (c, d) +: tail if b == c => merge((a, d) +: tail, acc)
  //if the first two elements are not mergeable, put the first one in the accumulator, and carry on
  case p +: tail => merge(tail, acc :+ p)
}

You can probably replace this tail-recursive function by a foldLeft, but I find it more readable this way.

A: A more generic Seq-based solution could be:
val data = Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))

val merged = data.foldLeft(Seq.empty[Seq[Int]]) {
  case (acc :+ (last :+ tail), head :: e)
    if tail == head => acc :+ (last ++ e)
  case (acc, e) => acc :+ e
} //List(List(1, 4), List(7, 9))


text:
Q: Python - What is the logic behind + function(i) + In the following block of codes:
print('My name is')
for i in range(5):
    print('Jimmy Five Times (' + str(i) + ')')

I understand that the code will run 5 times where i = 0 to 4.
However, I don't understand the logic behind the + operators added before and after the str() function.
How can this + function() + applied to other scenarios?

A: str(i) is the string representation of i. Documentation:

Return a str version of object.

If a, b and c are strings, then a + b + c is the string resulting of their concatenation.
Therefore, with i being an int between 0 and 4, say 3, 'Jimmy Five Times (' + str(i) + ')' is the folowing string:
'Jimmy Five Times (3)'

A: In python, + is used for string contate.
i.e:
data1 = "Hello"
data2 = "World"

print(data1+data2)

The output will be :
HelloWorld

A: str is a function that returns a string representation of i, so:
print('My name is')
for i in range(5):
    print('Jimmy Five Times (' + str(i) + ')')
# => 'Jimmy Fine Times (0)'
# => 'Jimmy Fine Times (1)'
# => 'Jimmy Fine Times (...

Calling a function that returns a string within a string concatenation 'A' + func() + 'B', will just use replace the function call with the string returned by the function (if no error or exceptions were raised), example:
def getName():
  name=input('Enter name: ')
  return name

print('Hello '+getName()+', Welcome to StackOverflow.')

#In: Enter name:  Jack
#Out: Hello Jack, Welcome to StackOverflow.


text:
Q: Positive vs negative Dehn twist monoids Given a bounded surface $S$ and a mapping class $h$, construct the open book 3-manifold $(S,h)$. If $h$ lies in the positive monoid of the mapping class group, then $(S,h)$ supports a tight contact structure; if $h$ lies in the negative monoid of the mapping class group, then $(S,h)$ supports an overtwisted contact structure. My question is why there are different conclusions. The difference between a positive or negative Dehn twist seems to be just one of orientation, so it's not clear why they should have such different effects. Is there something fundamentally "handed" about contact structures that makes the difference? Or is there a bigger difference between the two monoids that I'm missing?
[This question is motivated by the fabulous article, "Contact Geometry and the Mapping Class Group," by Joan Licata, in the April 2022 issues of the Notices of the AMS.]

A: A general discussion may help clarify these points. There's a lot more to say (e.g. how the positive monoid gives Weinstein fillings, or how negative Dehn twists explicitly give overtwisted disks), but hopefully this is a start.

(1) Orientations in contact geometry
The most common definition of a contact manifold is as a pair $(Y^{2n+1},\xi)$ where $Y$ is an odd-dimensional manifold and $\xi \leq TY$ is a maximally non-integrable hyperplane distribution. If $\xi = \ker \alpha$ locally, then maximal non-integrability is the condition that $\alpha \wedge d\alpha^n \neq 0$. Many times, contact geometers restrict to the setting of cooriented contact manifolds, i.e. an orientation of $TY/\xi$. In such a case, $\alpha$ may be defined globally (in such a way that the corresponding trivialization of $TY/\xi$ matches its chosen orientation), and $\alpha \wedge d\alpha^n$. So in fact, cooriented contact manifolds always come with natural orientations. If $n$ is odd (e.g. $n=1$, meaning $2n+1 = 3$), then notice that negating $\alpha$ preserves the orientation of the contact manifold. This actually means that in dimensions $4n+3$, the contact manifold is canonically oriented even if the contact structure is not cooriented!
Here's a little digression, if you like thinking naturally without picking a contact form. Any hyperplane distribution $\xi$ determines a Lie bracket pairing $$\wedge^2\xi \rightarrow TY/\xi$$ (note that the full Lie bracket involves sections, but the image in $TY/\xi$ is well-defined as a bundle map) and maximal nonintegrability means that this pairing is non-degenerate.
Remark: The Frobenius Theorem is the statement we have a foliation if and only if this Lie bracket map is zero; hence we see the meaning of maximal non-integrability.
Remark 2: If you've chosen $\alpha$, yielding a map $TY/\xi \rightarrow \mathbb{R}$, then the composition $\wedge^2\xi \rightarrow \mathbb{R}$ is just $-d\alpha|_{\xi}$.
This non-degeneracy is equivalent to the $n$-fold wedge product $$\wedge^{2n}\xi \rightarrow \otimes^n(TY/\xi)$$ being an isomorphism of line bundles, or equivalently, the contact structure affords an isomorphism $$\wedge^{2n}\xi^* \cong \otimes^n(TY/\xi)^*$$ Using this isomorphism, we find $$\wedge^{2n+1}(T^*Y) = (TY/\xi)^* \otimes \wedge^{2n}\xi^* \cong \otimes^{n+1}(TY/\xi)^*$$ An orientation may be thought of as a trivialization (up to positive scale) of $\wedge^{2n+1}(T^*Y)$, which in turn is just a trivialization (up to positive scale) of $\otimes^{n+1}(TY/\xi)^*$. Since $\otimes^2 \ell$ is always canonically oriented for a line bundle, we see that if $n$ is odd, we get a canonical orientation, and if $n$ is even, an orientation is equivalent to a coorientation of the contact structure.

(2) Orientations and supporting open books
Part of the trickery is that the notion of a positive or negative Dehn twist depends precisely on the orientation of the surface $S$. A positive Dehn twist on $S$ is a negative Dehn twist on $\overline{S}$, and vice versa. For that reason, the positive monoid on $S$ is canonically identified with the negative monoid on $\overline{S}$.
In 3-dimensional contact geometry, the Thurston-Winkelnkemper construction takes as input the data of $(S^2,h)$ and constructs a contact manifold on the corresponding open book. However, when one really wants to say this precisely, one usually notes the following important point: $S$ comes with an orientation, and the output contact structure comes with a coorientation. It is also worth noting that if the input is $(\overline{S},h)$, the result is not just the same contact structure with the reverse coorientation! (Indeed, reversing coorientation preserves tightness, whereas the whole point of the story is that negative Dehn twists yield overtwistedness.)
Let me say a little about how the construction works. The idea is to first form the mapping torus $M_h = (S \times [0,1])/((x,1) \sim (h(x),0))$. Fix an exact area form $\omega = d\lambda$ on $S$ such that on an open collar neighborhood of the boundary $$\mathrm{Op}(\partial S) \cong (-\epsilon,0] \times \partial S,$$ we have $\lambda = e^t\lambda_0$ where $t$ is the coordinate on $(-\epsilon,0]$ and $\lambda_0$ a nowhere zero form on the boundary circles $\partial S$. There is a technicality, which is that we require that $h^*\lambda = \lambda$ itself, but this can be arranged up to isotopy of $h$. Let $\theta$ be the coordinate along the $[0,1]$ direction of $M_h$. Then we have a natural contact form $$\alpha := d\theta - \lambda$$ on $M_h$. The open book is constructed by gluing in a copy of $D^2 \times \partial S$ along the boundary $S^1 \times \partial S \cong \partial M_h$ via a filling procedure which can be made standard (since we know what $\alpha$ looks like near $\partial M_h$). If instead we used $-\omega = -d\lambda$, then $M_h$ is given the contact form $d\theta+\lambda$, which is not the same as $-\alpha$, and in particular, the construction does not simply reverse the coorientation. You can think instead that it both reverses the coorientation but also negates the $\theta$ direction independently. The filling procedure for gluing in $D^2 \times \partial S$ takes into account this orientation data along the boundary as well.
The reason that this construction does not take opposite orientations to the same contact structure with opposite coorientations may be thought of in the following way. On $M_h$, we are using the orientation which descends from the product orientation on $S \times [0,1]$. Reversing the orientation on $S$ thus reverses the orientation on $M_h$, but orientation in dimension 3 is invariant of the choice of coorientation, so this construction really is producing a different contact structure!
Adding to the digression of Section (1), more generally, the Thurston-Winkelnkemper construction takes as input an exact symplectic manifold $(S,\omega=d\lambda)$ with convex boundary (and such that the monodromy satisfies $h^*\lambda = \lambda$). We see that handedness still matters in the same way: we simultaneously reverse the coorientation but also negate $\theta$, and so the corresponding constructions are not the same under the involution of primitive $\lambda \mapsto -\lambda$. In terms of orientations, on $M_h$, we get that the $\theta$ direction parametrizes $TY/\xi$, and projection along $\partial_{\theta}$ identifies $TY$ with $\xi$. You can then compare this with the contact-form-invariant discussion of orientations above.


text:
Q: How to conditionally replace R data.table columns upon merge? I have the following two data.tables
library(data.table)

dt1 = data.table(index_column = c(12, 17, 29, 34, 46), column1 = c("dog", "cat", "bird", "elephant", "bird"), column2 = c(482, 391, 567, 182, 121))

dt2 = data.table(index_column = c(17, 29, 46), column1 = c("cat", "penguin", "bird"))

> dt1
   index_column  column1 column2
1:           12      dog     482
2:           17      cat     391
3:           29     bird     567
4:           34 elephant     182
5:           46     bird     121

> dt2
   index_column column1
1:           17     cat
2:           29 penguin
3:           46    bird

Upon merging these two data.table solely on the shared index_column with
merged = merge(dt1, dt2, by="index_column", all=TRUE)

the resulting data.table is:
   index_column column1.x column2 column1.y
1:           12       dog     482        NA
2:           17       cat     391       cat
3:           29      bird     567   penguin
4:           34  elephant     182        NA
5:           46      bird     121      bird

I am interested in replacing values of column1.x with the values of column1.y if they are not NA. Most of the values will be the same, but those that are not (e.g. bird/penguin) should be replaced.
One could do this would an if statement, e.g.
if ((merged$column1.x != merged$column1.y) & !is.na(merged$column1.y)){
   merged$column1.x = merged$column1.y
}

merged$column1.y = NULL

My concern is that this isn't a very data.table solution. It will not scale very well if the data.table has millions of rows.
How would one conditionally replace values of one column based on another column in an R data.table? Is it more efficient to simply replace one with the other, ignoring the NA's?

A: We can use the on based approach
dt1[dt2, column1 := i.column1, on = .(index_column)]
dt1
#   index_column  column1 column2
#1:           12      dog     482
#2:           17      cat     391
#3:           29  penguin     567
#4:           34 elephant     182
#5:           46     bird     121


text:
Q: PrivCopyFileExW Bug in Windows? I am issuing many parallel robocopy calls to copy files from one network share into one directory. Since the files are read only I tell robocopy to strip off the read only attribute in the target directory via /A-:R. It seems that on some many core machine (12 or more) the target directory! gets locked for up to 16s.
This problem does surface when concurrent MSBuild tasks are running and the CopyFile task is executed on read only files. It does also happen when robocopy is executed to download dependencies for a TFS build in parallel from a network share. Since all these issues point to kernel32 CopyFile (or its private implementation) I suspect that the problem is related to how Windows does copy files.
This does not seem to be a general issue in the kernel since the temp folder live from the fact that concurrent access to a directory must be possible. But the user mode implementation inside kernel32.dll of CopyFile seems to be flawed.
Update 2
With the repro below this does happen no matter if the file is read only or not.
Update 3
This repro does also show the same issue on Windows 8.
The procmon stack traces did show that the magic happens in kernel32.dll inside
PrivCopyFileExW which seems to be rather undocumented. There an IRP_MJ_CREATE call is issued to open the directory and a little later the directory is closed. This seems to be the root cause of the race condition when many parallel robocopy processes try to copy files into one directory.
Here is some procmon output how this problem feels like.
Why on earth does PrivCopyFileExW manage to lock the directory? A file system should be able support copying files into one directory. I am using Windows Server 2008 R2 and some latest multi cores machines with RAID arrays, SSDs and such stuff.
This seems to be related to reported problems with CopyFile in kernel32.dll which have not be solved until today. I can rule out virus scanners because this does also happen at machines which have none installed.
Update 1
It seems that another robocopy process does try to copy a file to the destination directory which opens the directory
Date & Time:    20.03.2012 08:30:06
Event Class:    File System
Operation:  CreateFile
Result: SUCCESS
Path:   C:\temp\dest
TID:    11672
Duration:   0.0000150
Desired Access: Read Data/List Directory, Write Data/Add File, Write EA, Read Attributes, Write Attributes, Delete, Synchronize
Disposition:    OpenIf
Options:    Directory, Synchronous IO Non-Alert, Open For Backup
Attributes: D
ShareMode:  None  <---- No sharing
AllocationSize: 0
OpenResult: Opened

0   fltmgr.sys  FltpPerformPreCallbacks + 0x2f7 0xfffff88001045027  C:\Windows\system32\drivers\fltmgr.sys
1   fltmgr.sys  FltpPassThroughInternal + 0x4a  0xfffff880010478ca  C:\Windows\system32\drivers\fltmgr.sys
2   fltmgr.sys  FltpCreate + 0x293  0xfffff880010652a3  C:\Windows\system32\drivers\fltmgr.sys
3   ntoskrnl.exe    IopParseDevice + 0x5a7  0xfffff800031cb537  C:\Windows\system32\ntoskrnl.exe
4   ntoskrnl.exe    ObpLookupObjectName + 0x585 0xfffff800031c1ba4  C:\Windows\system32\ntoskrnl.exe
5   ntoskrnl.exe    ObOpenObjectByName + 0x1cd  0xfffff800031c6b7d  C:\Windows\system32\ntoskrnl.exe
6   ntoskrnl.exe    IopCreateFile + 0x2b7   0xfffff800031cd647  C:\Windows\system32\ntoskrnl.exe
7   ntoskrnl.exe    NtCreateFile + 0x78 0xfffff800031d7398  C:\Windows\system32\ntoskrnl.exe
8   ntoskrnl.exe    KiSystemServiceCopyEnd + 0x13   0xfffff80002eca813  C:\Windows\system32\ntoskrnl.exe
9   ntdll.dll   NtCreateFile + 0xa  0x7718fc0a  C:\Windows\System32\ntdll.dll
10  kernel32.dll    BaseCopyStream + 0x11a9 0x77034b89  C:\Windows\System32\kernel32.dll
11  kernel32.dll    BasepCopyFileExW + 0x545    0x77033d85  C:\Windows\System32\kernel32.dll
12  kernel32.dll    PrivCopyFileExW + 0xb6  0x770b5296  C:\Windows\System32\kernel32.dll
13  Robocopy.exe    CZDir::CopyData + 0xb5  0xff8623a9  C:\Windows\System32\Robocopy.exe
14  Robocopy.exe    RoboCopyDir + 0xe4  0xff85af00  C:\Windows\System32\Robocopy.exe
15  Robocopy.exe    Walk + 0x12a    0xff85c6b6  C:\Windows\System32\Robocopy.exe
16  Robocopy.exe    wmain + 0x4f4   0xff85de78  C:\Windows\System32\Robocopy.exe
17  Robocopy.exe    operator+ + 0x19b   0xff867be5  C:\Windows\System32\Robocopy.exe
18  kernel32.dll    BaseThreadInitThunk + 0xd   0x7703f33d  C:\Windows\System32\kernel32.dll
19  ntdll.dll   RtlUserThreadStart + 0x1d   0x77172ca1  C:\Windows\System32\ntdll.dll

The other robocopy wants to check if the file already exists and calls FindFirstFile which lead to opening the directory as well with full sharing.
Date & Time:    20.03.2012 08:30:06
Event Class:    File System
Operation:  CreateFile
Result: SHARING VIOLATION
Path:   C:\temp\dest
TID:    8280
Duration:   0.0000099
Desired Access: Read Data/List Directory, Synchronize
Disposition:    Open
Options:    Directory, Synchronous IO Non-Alert
Attributes: n/a
ShareMode:  Read, Write, Delete <----- Full sharing
AllocationSize: n/a

0   fltmgr.sys  FltpPerformPreCallbacks + 0x2f7 0xfffff88001045027  C:\Windows\system32\drivers\fltmgr.sys
1   fltmgr.sys  FltpPassThroughInternal + 0x4a  0xfffff880010478ca  C:\Windows\system32\drivers\fltmgr.sys
2   fltmgr.sys  FltpCreate + 0x293  0xfffff880010652a3  C:\Windows\system32\drivers\fltmgr.sys
3   ntoskrnl.exe    IopParseDevice + 0x5a7  0xfffff800031cb537  C:\Windows\system32\ntoskrnl.exe
4   ntoskrnl.exe    ObpLookupObjectName + 0x585 0xfffff800031c1ba4  C:\Windows\system32\ntoskrnl.exe
5   ntoskrnl.exe    ObOpenObjectByName + 0x1cd  0xfffff800031c6b7d  C:\Windows\system32\ntoskrnl.exe
6   ntoskrnl.exe    IopCreateFile + 0x2b7   0xfffff800031cd647  C:\Windows\system32\ntoskrnl.exe
7   ntoskrnl.exe    NtOpenFile + 0x58   0xfffff800031e64a8  C:\Windows\system32\ntoskrnl.exe
8   ntoskrnl.exe    KiSystemServiceCopyEnd + 0x13   0xfffff80002eca813  C:\Windows\system32\ntoskrnl.exe
9   ntdll.dll   NtOpenFile + 0xa    0x7718f9ea  C:\Windows\System32\ntdll.dll
10  KernelBase.dll  FindFirstFileExW + 0x1ee    0x7fefd3a560e   C:\Windows\System32\KernelBase.dll
11  KernelBase.dll  FindFirstFileW + 0x1c   0x7fefd3a58dc   C:\Windows\System32\KernelBase.dll
12  Robocopy.exe    CZDir::Exists + 0xf7    0xff861bb7  C:\Windows\System32\Robocopy.exe
13  Robocopy.exe    RoboCopyDir + 0x58  0xff85ae74  C:\Windows\System32\Robocopy.exe
14  Robocopy.exe    Walk + 0x12a    0xff85c6b6  C:\Windows\System32\Robocopy.exe
15  Robocopy.exe    wmain + 0x4f4   0xff85de78  C:\Windows\System32\Robocopy.exe
16  Robocopy.exe    operator+ + 0x19b   0xff867be5  C:\Windows\System32\Robocopy.exe
17  kernel32.dll    BaseThreadInitThunk + 0xd   0x7703f33d  C:\Windows\System32\kernel32.dll
18  ntdll.dll   RtlUserThreadStart + 0x1d   0x77172ca1  C:\Windows\System32\ntdll.dll

I can repro this easily on Windows 7 as well. You only need to copy read only files from two parallel robocopy calls into the same directory in a loop and wait until it happens (ca. 30s).
for /L %i in (1,1,1000) do robocopy /E /XO /COPY:DAT /A-:R C:\ReadOnlySource1  c:\temp\dest
for /L %i in (1,1,1000) do robocopy /E /XO /COPY:DAT /A-:R C:\ReadOnlySource2  c:\temp\dest

You can put only one read only file into the source directories to get a fast copy and many concurrent directory accesses. Is this a known limitation of Windows to not allow accessing a directory while a file is copied to it?
My uneducated opinion is that this is a bug and it can get quite nasty when you want concurrent access to files in a reliable manner.

A: It looks like we are getting a fix from MS for this issue finally. They have found and understood the issue. But it will take some time until the fix is officially prepared. Currently it will be only fixed for Windows 7.


text:
Q: How to configure a minimum app version for an iOS app React-Native I want all users off my app to stay above a minimum threshold version. Is there a way I can configure it either in the code or app store that invalidates the users on a certain version and redirects them to the app store?

A: I assume you have already an application that in the production and installed to devices.
In this case, unfortunately you can't put version limit on them. The only way is, deprecating v1 APIs and creating v2 APIs. The older version app owners will get a warning (If you well made the error handling.).
Otherwise, you can add a new feature like checking the version on the startup of the application. And If it is older, you can show a message like "Please update the application." and put a button that redirects to the AppStore.

(The image is from a Medium blog post named "Mandatory Update for your apps".
I don't recommend forcibly redirecting users to AppStore. It is not a great UX practice. You can block the screen of the application with the warning but at least leave the basic functionalities open.


text:
Q: What does Commands.____.getAbbrev()) do in this code? I am pretty new to the Robot class so I need some help understanding a piece of code. The point of the project is to create a remote desktop and so while reviewing some code on the internet I couldn't figure out a specific part of the code was doing.
Server side:
import java.awt.Robot;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
/* Used to recieve server commands then execute them at the client side*/

class ReceiveEvents extends Thread{
            Socket socket= null;
            Robot robot = null;
            boolean continueLoop = true;

        public ReceiveEvents(Socket socket, Robot robot){

        this.socket = socket;
        this.robot = robot;
        start(); //Start the thread and hence calling run method
        }

        public void run(){
        Scanner scanner = null;
        try {
        scanner = new Scanner(socket.getInputStream());
        while(continueLoop){
        //recieve commands and respond accordingly

        int command = scanner.nextInt();
        switch(command){
                case-1:
                robot.mousePress(scanner.nextInt());
                break;
                case-2:
                robot.mouseRelease(scanner.nextInt());
                break;
                case-3:
                robot.keyPress(scanner.nextInt());
                break;
                case-4:
                robot.keyRelease(scanner.nextInt());
                break;
                case-5:
                robot.mouseMove(scanner.nextInt(),scanner.nextInt());
                break;
                }

                }
        }catch(IOException ex){
                ex.printStackTrace();
                }
            }//end function

            }//end class

Client Side:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JPanel;

class SendEvents implements KeyListener, MouseMotionListener, MouseListener{
    private Socket cSocket = null;
    private JPanel cPanel = null;
    private PrintWriter writer = null;
    String width = "", height = "";
    double w;
    double h;

SendEvents(Socket s, JPanel p, String width, String height){
    cSocket = s;
    cPanel = p;
    this.width = width;
    this.height = height;
    w = Double.valueOf(width.trim()).doubleValue();
    h = Double.valueOf(width.trim()).doubleValue();

    //Associate event listeners to the panel

    cPanel.addKeyListener(this);
    cPanel.addMouseListener(this);
    cPanel.addMouseMotionListener(this);

    try{
        //Prepare PrintWriter which will be used to send commands to the client
        writer = new PrintWriter(cSocket.getOutputStream());
        } catch(IOException ex) {
        ex.printStackTrace();
    }
}

public void mouseDragged(MouseEvent e){
}

public void mouseMoved(MouseEvent e){
    double xScale = (double)w/cPanel.getWidth();
    double yScale = (double)h/cPanel.getHeight();
    writer.println(Commands.MOVE_MOUSE.getAbbrev());
    writer.println((int)(e.getX()*xScale));
    writer.println((int)(e.getY()*yScale));
    writer.flush();
}

public void mouseClicked(MouseEvent e){
}

public void mousePressed(MouseEvent e){
    writer.println(Commands.PRESS_MOUSE.getAbbrev());
    int button = e.getButton();
    int xButton = 16;
    if(button==3){
        xButton = 4;
    }
    writer.println(xButton);
    writer.flush();
}

public void mouseReleased(MouseEvent e){
    writer.println(Commands.RELEASE_MOUSE.getAbbrev());
    int button = e.getButton();
    int xButton = 16;
    if(button==3){
        xButton = 4;
    }
    writer.println(xButton);
    writer.flush();
}

public void mouseEntered(MouseEvent e){
}

public void mouseExited(MouseEvent e){
}

public void keyTyped(KeyEvent e){
}

public void keyPressed(KeyEvent e){
    writer.println(Commands.PRESS_KEY.getAbbrev());
    writer.println(e.getKeyCode());
    writer.flush();
}

public void keyReleased(KeyEvent e){
    writer.println(Commands.RELEASE_KEY.getAbbrev());
    writer.println(e.getKeyCode());
    writer.flush();
}

My question is about client side, they are sending over writer.println(Commands.______.getAbbrev());
Does this line of code have something to do with the switch and case on serverside code?