text:
Q: What should I fix to create random calculation in this code? I wanted to fix my code to create random operation here, what should I fix here?
    #include <stdio.h>

    int main()
    {
        int x,y,z,a;
        char o;
        while(1)
        {
            printf("give your three numbers: ");
            scanf("%d %d %d",&x,&y,&z);
            printf("(%d*%d-%d) what is the correct among following answers? \n 1. %d\n 2. %d\n 3. %d\n ",
            x,y,z,x*y-z,x*y*z,x-y*z);
            printf("what is answer? \n: ");
            scanf("%d",&a);
            if(a == 1)
            {
                printf("you are right!\n");
            }
            else
            {
                printf("you are false!\n\n");
            }

            getchar();
            printf("Would you like to exit programm? (y/n) : ");
            scanf("%c",&o);
            if (o=='Y' || o=='y')
            {
                break;
            }
            else if(o=='N' || o=='n')
            {
                continue;
            }
            else
            {
                printf("Wrong input!!!!");
            }
            return 0;
        }
    }

What I mean is I want to try change operation such as * + - randomly when I run code, and also along with this question, the answer should be changed...
thank you!

A: Your question is mainly focused on shuffling the answers. By studying from couple of sites I have found an solution for this. This is little bit difficult but studying the code few times you can get it
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void randomize(int arr[], int n) {
    srand(time(NULL));
    int i;
    for(i = n-1; i > 0; i--) {
        int j = rand() % (i+1);
        swap(&arr[i], &arr[j]);
    }
}

int main() {
    int x,y,z,a;
    int i;
    int a1, a2, a3;
    int arr[] = {1, 2, 3};
    int n = sizeof(arr)/ sizeof(arr[0]);

    printf("give your three numbers: ");
    scanf("%d %d %d",&x,&y,&z);

    a1 = x*y-z;
    a2 = x*y*z;
    a3 = x-y*z;

    printf("Before shuffle = %d %d %d\n\n", a1, a2, a3);

    char answers[] = {a1, a2, a3};

    printf("(%d*%d-%d)what is the correct among following answers?\n", x, y, z);

    randomize (arr, n);
    for(i=0; i<n; i++) {
        int index = arr[i];
        printf("%2d - %d\n", i+1, answers[index]);
    }

    return 0;
}

This is the outputs
First time run
give your three numbers: 2
2
2
Before shuffle = 2 8 -2

(2*2-2)what is the correct among following answers?
 1 - 8
 2 - 2
 3 - -2

Second time run
give your three numbers: 2
2
2
Before shuffle = 2 8 -2

(2*2-2)what is the correct among following answers?
 1 - -2
 2 - 8
 3 - 2

You can try this multiple times. Every time answers will be shuffle. This is the Source I have referred.

A: Just provide one of examples here. There are many kinds way to implement. In the random operation generation part. I would like to write a random number generator function, which purpose is to generate the given range of random number.
int gen_random(int min, int max)
{
    srand( time(NULL) );
    return rand() % (max - min + 1) + min;
}

In order to represent four operator (+, -, *, /), The number (let's call the operation number) 1 to 4 is used for represent four operator respectively. The calculation function map the operation number to operation and get the result.
int calculation(int number1, int number2, int op)
{
    switch(op)
    {
        case 1:
            return number1 + number2;
        case 2:
            return number1 - number2;
        case 3:
            return number1 * number2;
        case 4:
            return number1 / number2;
    }
}

You can use the gen_random and the calculation function above to change operation randomly. The usage of the gen_random and the calculation function is something like:
    int op = gen_random(1, 4);        //  Generate operation randomly
    printf("%d\n", op);
    printf("%d\n", calculation(x, y, op));        //  Pass x, y, and operation number into calculation function to get answer


text:
Q: WebGL attributes per element in drawElements Is there a way to specify attributes per element index in WebGL?  Here's what I mean.
I want to draw shapes with lines at the edges and fat dots at vertices.  So, here's the data structure I would have for a triangle:
Vertices: [0,0,0,  1,0,0,  0,1,0]
Edges: [0,1,  1,2,  2,0]
The vertices are an ARRAY_BUFFER and edges are an ELEMENT_ARRAY_BUFFER. So when I call drawElements on the edges using LINES, I get an outline of a triangle. Now, I can also bind color attributes to the vertices. Suppose I make them all red:
Colors: [1,0,0,  1,0,0,  1,0,0]
If I want to highlight a particular vertex, I just write the bufferSubData over the colors before I draw the fat dots for vertices and change it back before drawing the edges.  But what if I want to highlight an edge?  I change the colors to [1,1,1,  1,1,1,  1,0,0] and wish for the best.  The edge (0,1) will be white, but the other two edges will be colored with a gradient: red at vertex 2 and white at the other (0 or 1).
So, can I specify that I want to use a particular color for the elements at indices 0 and 1 and a different color for elements at indices 2, 3, 4, and 5?  And all that without doubling up on every vertex (e.g. making each vertex data look like [x,y,z, r,g,b] and having two of them side by side in the buffer so that an edge can point to a regular or a highlighted version of the same vertex).

A: Sorry, but no, it doesn't work like that—you'll have to duplicate data somewhere.  A vertex isn't just a position, it's the collection of all attributes associated with that position, and so in WebGL/OpenGL's view, they're different vertices.
The simplest solution is to just duplicate the vertices with the updated colors.  You could do more elaborate things like having an array of colors, passing in an attribute that enumerates the vertices (e.g., vertex 0 gets '0', vertex 1 gets '1', etc.), and then having logic in your vertex shader to compensate.  That's a lot of work and complexity, and may not be simpler or faster.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento Core API: XML-RPC Error adding tracking number I'm looking for suggestions on troubleshooting the error "100 -     Requested shipment not exists. " when I use sales_order_shipment.addTrack to send tracking updates to Magento. I'm currently using vbscript and XML to post via XML-RPC calls.  I'm able to query and parse shipment info for import without issue.  The problem occurs when I attempt to write tracking back.
During the export I use the steps below.
1. I'm able to successful create a  shipment 1st and obtain the shipment increment id using sales_order_shipment.create

*

*When I transmit the command sales_order_shipment.addTrack I receive an XML fault message back

*I have verified the increment id


text:
Q: SSIS Custom component salesforce source (kingswaysoft) not configured properly via BIML I am trying to connect to Salesforce using using kingswaysoft SSIS connector.
I am able to successfully connect to Salesforce using Microsoft visual studio GUI in Data Integration project and retrive the data from salesforce. Because I have to generate 100+ SSIS packages to handle I am trying to write using BIML which in turn generates SSIS packages.
I have my BIML code as below
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
    <Connections>
      <CustomSsisConnection Name="Salesforce Connection Manager" CreationName="Salesforce (KingswaySoft)" ObjectData="<SalesforceConnectionManager ConnectionString="InstanceType=Production;UserName=XXXXXXXXXXX;ServiceTimeout=250;ProxyMode=NoProxy;ProxyServer=;ProxyServerPort=0;ProxyUsername=;RetryOnIntermittentErrors=True">
  <Password Sensitive="1" xmlns="www.microsoft.com/SqlServer/Dts" Encrypted="0">XXXXXXXXX</Password>
  <SecurityToken Sensitive="1" xmlns="www.microsoft.com/SqlServer/Dts" Encrypted="0">XXXXXXXXXXXXXXXXXX</SecurityToken>
</SalesforceConnectionManager>" />
    </Connections>
  <Packages>
    <Package Name="Package_1" Language="None" ProtectionLevel="EncryptSensitiveWithUserKey" SsisPackageType="5" VersionBuild="9" CreatorName="84336" CreatorComputerName="84336-WX-1" CreationDate="2018-07-03T15:40:13">
      <Variables>
        <Variable Name="recordsCount" DataType="Int32" IncludeInDebugDump="Include">0</Variable>
      </Variables>
      <Tasks>
        <Dataflow Name="Data Flow Task">
          <Transformations>
            <RowCount Name="Row Count" VariableName="User.recordsCount">
              <InputPath OutputPathName="Salesforce Source.Salesforce Source Output" />
            </RowCount>
            <CustomComponent Name="Salesforce Source" ComponentTypeName="KingswaySoft.IntegrationToolkit.Salesforce.SalesforceSourceComponent" ContactInfo="KingswaySoft Inc.; http://www.kingswaysoft.com; support@kingswaysoft.com; Copyright (c) 2011-2018 KingswaySoft Inc.">
              <DataflowOverrides>
                <OutputPath OutputPathName="Salesforce Source Output">
                <Columns>
                    <Column ErrorRowDisposition="FailComponent" TruncationRowDisposition="FailComponent" ColumnName="AccountNumber" />
                </Columns>
                </OutputPath>
              </DataflowOverrides>
              <CustomProperties>
                <CustomProperty Name="SourceType" DataType="Int32" TypeConverter="KingswaySoft.IntegrationToolkit.Salesforce.SalesforceSourceType" SupportsExpression="true" Description="Specifies the type of source data from Salesforce">0</CustomProperty>
                <CustomProperty Name="SourceObject" DataType="String" SupportsExpression="true" Description="Salesforce object to retrieve data from.">Account</CustomProperty>
                <CustomProperty Name="ObjectQuery" DataType="String" SupportsExpression="true" Description="Salesforce object query statement."></CustomProperty>
                <CustomProperty Name="BatchSize" DataType="Int32" SupportsExpression="true" Description="Specifies the batch size of the query.">1000</CustomProperty>
                <CustomProperty Name="IncludeDeletedArchived" DataType="Boolean" SupportsExpression="true" Description="Specifies whether deleted or archived records should be returned.">false</CustomProperty>
                <CustomProperty Name="UseBulkApi" DataType="Boolean" SupportsExpression="true" Description="Specify whether to use Salesforce Bulk API to read data.">false</CustomProperty>
                <CustomProperty Name="OutputTimezone" DataType="Int32" TypeConverter="KingswaySoft.IntegrationToolkit.Common.DescriptiveEnumTypeConverter`1[[KingswaySoft.IntegrationToolkit.Salesforce.SfdcSourceOutputTimezone, KingswaySoft.IntegrationToolkit.Salesforce, Version=1.0.2017.0, Culture=neutral, PublicKeyToken=705df8e0751bcea7]], KingswaySoft.IntegrationToolkit.Salesforce, Version=1.0.2017.0, Culture=neutral, PublicKeyToken=705df8e0751bcea7" SupportsExpression="true" Description="Specifies the output timezone for Salesforce datetime fields.">1</CustomProperty>
                <CustomProperty Name="PKChunkingHeader" DataType="String" SupportsExpression="true" Description="Specify the PK Chunking Header that helps with Bulk API data read performance."></CustomProperty>
              </CustomProperties>
              <OutputPaths>
                <OutputPath Name="Salesforce Source Output">
                  <OutputColumns>
                    <OutputColumn Name="AccountNumber" Length="40" DataType="String" ExternalMetadataColumnName="AccountNumber" ErrorOrTruncationOperation="Conversion" ErrorRowDisposition="FailComponent" TruncationRowDisposition="FailComponent" />
                  </OutputColumns>
                  <ExternalColumns>
                    <ExternalColumn Name="AccountNumber" Length="40" DataType="String" />
                  </ExternalColumns>
                </OutputPath>
              </OutputPaths>
              <Connections>
                <Connection Name="Salesforce" ConnectionName="Salesforce Connection Manager" />
              </Connections>
            </CustomComponent>
          </Transformations>
        </Dataflow>
      </Tasks>
      <Connections>
        <Connection ConnectionName="Salesforce Connection Manager" />
      </Connections>
    </Package>
  </Packages>
</Biml>

I am able to see Salesforce connection(properly) got created inside BI project after generating SSIS package from BIML.

And the generated SSIS looks this way package

When I double click on Salesforce Source, I am getting a warning which as

Please suggest what I am missing here. Why salesforce source not getting configured automatically via BIML?
Any suggestions much appreciated!!

A: I am able to solve the issue. I added below property to CustomComponent
UsesDispositions="true"

Now the error has gone and reference is here


text:
Q: How to avoid the user from repeating to fill in the form if there is an error? Problem: I'm doing a form to be filled by the user. Once the user clicks submit, if there is an error in the form, it will show an alert. However, when the user clicks "ok" the form will reset all the fields that have been filled so the user needs to repeat in fill in the form all over again.
Question: How to fix this so that when the user clicks "ok" the data is still there?

A: To stop the page from re-loading add return false; after alert statement, it stops the default action from taking place from the form submit.
alert("Please fill in all mandatory fields");
return false;

A: You should reset form:
document.getElementById("formId").reset();

A: The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

*

*Use <button type="button"> to override default submission behavior.

*Use event.preventDefault() in the onSubmit event to prevent form
submission.

var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('onSubmit', handleForm);

A: I have something that does exactly that. It's a complete working code, but I am going to give you the task of figuring out which part does what.

function submitInfo(e){
  var fields = document.getElementsByClassName('input-field').length;
  for(let x = 0; x < fields; x++){
    var value = document.getElementById(x).value;
    if(value == ''){
       e.preventDefault();
     var element = document.getElementById(x);
     element.classList.add('no-value');
     setTimeout(function(){
        element.classList.remove('no-value')
     },3000);
     break;
    }
  }
}
.no-value {
  border: 2px solid red;
}
<form method="post" action="">
  <input type="text" name="email" placeholder="Email" class="input-field" id="0"/>

  <input type="password" name="password" placeholder="Password" class="input-field" id="1"/>

  <input type="submit" value="Submit" onclick="submitInfo(event)"/>
</form>

I hope this is what you are looking for.


text:
Q: Drop down "context" menu appearing in Eclipse that I can't get rid of A few days again, a new drop-down auto-complete menu started showing up in Eclipse. I have no idea how I turned it on, I don't find it useful, and I can't figure out for the life of me how to get rid of it. It will show up on top of Eclipse's "Content Assist" menu, which I actually do use, and also causes every word I type to blink after I finish typing it.
Please, someone tell me you've seen this before and you know how to make it go away.

Note to mods: if this doesn't belong here, please tell me where I can get this question answered! It's driving me NUTS!

A: Depending on what version of Eclipse you are running, I have had a similar issue with a JavaScript auto-complete plug-in not finding what I was typing.  This behavior was truly annoying because I would get a Java Exception dialog almost every time I would type something related to JavaScript, and I would have to acknowledge it every single time.  There was something good about my situation, though.  The Exception dialog told me that if I wanted this dialog to go away (which I most certainly did) I would need to disable the JavaScript plug-in associated with it.
So while this is probably a scorched earth type of solution to your problem, try disabling plug-ins to see if the auto-complete dialog goes away.


text:
Q: Does Rust f64/f32 round correctly? After a recent discussion about mathematical rounding with my colleagues, we analyzed the rounding of different languages.
For example:

*

*MATLAB: "Round half away from zero"

*Python: "Round half to even"

I would not say the one is correct or the other isn't but whats bothers me is the combination of the writing in the Rust Book and what the documentation say about the round function.
The book 1:

Floating-point numbers are represented according to the IEEE-754 standard. The f32 type is a single-precision float, and f64 has double precision.

The documentation 2:

Returns the nearest integer to self. Round half-way cases away from 0.0.

My concern is that the standard rounding for IEEE-754 is "Round half to even".
Most collegues who I ask tend to use and learned mostly/only "Round half away from zero" and they where actually confused as I came up with different rounding strategies. Does the developer of rust decided because of that possible confusion against the IEEE standard?

A: The documentation you cite is for an explicit function, round.
IEEE-754 specifies the default rounding method for floating-point operations should be round-to-nearest, ties-to-even (with some embellishment for an unusual case). The rounding method specifies how to adjust (conceptually) the mathematical result of the function or operation to a number representable in the floating-point format. It does not apply to what functions functions calculate.
Functions like round, floor, and trunc exist to calculate a specific integer from the argument. The mathematical calculation they perform is to determine that integer. A rounding rule only applies in determining what floating-point result to return when the ideal mathematical result is not representable in the floating-point type.
E.g., sin(x) is defined to return a result computed as if:

*

*The sine of x were determined exactly, with "infinite" precision.

*That sine were then rounded to a number representable in the floating-point format according to the rounding method.

Similarly, round(x) can be thought of to be defined to return a result computed as if:

*

*The nearest integer of x, rounding a half-way case away from zero, were determined exactly, with "infinite" precision.

*That nearest integer were then rounded to a number representable in the floating-point format according to the rounding method.

However, because of the nature of the routine, that second step is never necessary: The nearest integer is always representable, so rounding never changes it. (Except, you could have abnormal floating-point formats with limited exponent range so that rounding up did yield an unrepresentable integer. For example, in a format with four-bit significands but an exponent range that limited numbers to less than 4, rounding 3.75 to the nearest integer would yield 4, but that is not representable, so +∞ would have to be returned. I cannot say I have ever seen this case explicitly addressed in a specification of the round function.)

A: Nobody has contradicted IEEE-754, which defines five different valid rounding methods.
The two methods relevant to this question are referred to as nearest roundings.

*

*Round to nearest, ties to even – rounds to the nearest value; if the number falls midway, it is rounded to the nearest value with an even least significant digit.

*Round to nearest, ties away from zero (or ties to away)  – rounds to the nearest value; if the number falls midway, it is rounded to the nearest value above (for positive numbers) or below (for negative numbers).

Python takes the first approach and Rust takes the second. Neither is contradicting the IEEE-754 standard, which defines and allows for both.
The other three are things we would probably more colloquially refer to as truncation, i.e. always rounding down, or always rounding up, or always rounding toward zero.


text:
Q: Solve $y''+y=\cos^2(x)$ by variation of parameters The answer I got is
$$y=c_1 \cos(x) + c_2 \sin(x) + \frac{1}{2} \sin(2x) + \frac{1}{3} \cos(2x).$$
Can the last two trig terms be simplified further?

A: $$y''+y=\cos^2(x) \tag 1$$
Your answer
$\quad y=c_1 \cos(x) + c_2 \sin(x) + \frac{1}{2} \sin(2x) + \frac{1}{3} \cos(2x)\quad$ is FALSE.
Why didn't you put it back into Eq.$(1)$ in order to check your result ?
You should find :
$$y=c_1 \cos(x) + c_2 \sin(x) - \frac{1}{6} \cos(2x)+\frac12$$
$y'=-c_1 \sin(x) + c_2 \cos(x) + \frac{1}{3} \sin(2x)$
$y''=-c_1 \cos(x) - c_2 \sin(x) + \frac{2}{3} \cos(2x)$
$y''+y=\frac{2}{3} \cos(2x)- \frac{1}{6} \cos(2x)+\frac12 = \frac{\cos(2x)+1}{2}=\cos^2(x)$


text:
Q: Textblock in Viewbox not multiline I'm having a bit of a trouble with the autosizing of a text. I read somewhere that if I wanted to achieve that, i need to put my textblock in a viewbox. The problem with that is this way the text isn't split into multiple lines. For example "very very very long text" is almost unreadable, but "simpletext" looks just fine.
<Viewbox Grid.Row="1" Grid.Column="0" Grid.RowSpan="2" Grid.ColumnSpan="4" StretchDirection="DownOnly">
     <TextBlock
         Text="{Binding FieldName}" VerticalAlignment="Center" HorizontalAlignment="Center"
         TextWrapping="Wrap" FontWeight="Bold" FontFamily="Nueva Std" />
</Viewbox>

Thank you in advance!

A: Try to set a width (or max width) on the TextBlock.

A: Add these properties to your textblock TextWrapping="Wrap" - wrapping IsHyphenationEnabled="True" - breaking the word with hyphen

A: In this case, here is another solution: take this class and make your own LimitedViewbox version, which will have some LowerStretchLimit property. I think it should work.


text:
Q: Sort files on the filesystem My MP3 player plays files in the order they have been placed onto the filesystem. Now it seems to Nautilus copies files in some random order, so when listening to an audio book or something I get all the chapters in random order, wich isn't so great when your on a bicycle so you can't take your MP3 player out of your pocket to find the right one. When using mc (Midnight Commander) most files are copies in alphabetical order, and that's the way I want it to happen.
So is there...

*

*any way to tell Nautilus to copy files and folders in alphabetical order?

*a program wich can sort the files and folders in alphabetical order directly on the filesystem?

Additional information:

*

*Elementary OS 0.1 Jupiter (based on Ubuntu 10.10)

*64-bits

*Copying music over from an NTFS filesystem to a strangely formed FAT32 filesystem on the MP3 player.

A: To embellish the answer by enzotib ; these players play files in the order they find them in the File Allocation Table (the FAT, in FAT).
FATSort is therefore one potential solution to the problem. The noted warning is for 2 reasons ;

*

*The tool edits the file allocation table right at the bare metal level

*

*It moves the file entries around within the confines of the directory table, so a corrupt filesystem will be more broken than it was before

*As long as the filesystem passes a fsck.vfat check, you should be fine.

*The author appears to feel that he hasn't devoted enough time to making his code secure

*

*Potentially, you could create a (broken) file allocation table that caused a buffer overrun or similar problem in the FATSort application

*In reality, this is unlikely - it's something of a niche application, the opportunities for an attacker to place a specially crafted file system on your MP3 player are limited, and if he had such an opportunity, there are much softer targets he'd go after first

*Again, if your filesystem passes fsck.vfat (or a disk check in Windows), you should be fine - this is a belt-and-braces disclaimer by the author

palimpsest / Disk Utility has options to do a disk check from the GUI.
Other programs that sort the FAT can be seen here : http://www.murraymoffatt.com/software-problem-0010.html
Alternate solutions ;
Copy files in the play order
The simplest and most obvious is to copy the files to the player in the order which you wish them to play. Nautilus copies files in an apparently indeterminate order to the player file system for much the same reason - it tends to operate on files in the order the iNodes are arranged on disk.
If your track file names have the track number at the beginning, this is ideal. Most of the command line tools will sort things in lexicographic order. As you note, tools like Midnight Commander will also do this.
# Find the files in the source     | copy them to the target folder
# Note we use the          -print0 |       -0   args because media file names
# commonly contain spaces

find /path/to/music/folder -print0 | xargs -0 cp -t /path/to/target/folder

Create a playlist
Some players support playlist files. I keep scripts in my MP3 player filesystem to support generating these playlists. My player is an iRiver device, which has a specific binary playlist format. If your player supports .m3u playlists, the format is extremely simple, and just consists of commented metadata and paths in a text file. I used to make playlists in Rhythmbox and transform them to the iRiver format ; I've not had occasion to make one using Banshee yet (I only make them for workout purposes and my workouts are very predictable...)

A: The utility you look for exists, and is FATSort.
It is available in Ubuntu Repositories in the fatsort package.

A: It could be that the player uses the modification time of the file. You could use a python script like the following to get all files in a folder, and touch them to change the last access time. Without the player, I can't test the result of cause.
import os
import sys
path = sys.argv[1]
thefiles = os.listdir(path)
thefiles.sort()
for fname in thefiles:
    os.utime(os.path.join(path, fname), None)

This script should be run on the player folder (replace "path_to_the_player_folder" with the actual path) like this (if you saved it as touch_all.py): python touch_all.py "path_to_the_player_folder"
I have no idea on how to tell nautilus how to copy files. Others might answer that part of the question, though.

A: Regarding fatsort, use it like this :
sudo umount /dev/sdxxxx
fatsort /dev/sdxxx
You need to figure out what dev it actually is - could be sda, sdb, etc.
sudo fdisk -l

should show you the mounted systems.

A: Find out which device name the MP3-Player has:
lsblk
(In my case it was /dev/sdb1)
Show the current order of all files (without doing any changes):
sudo fatsort -l /dev/sdb1
Sort all files on the MP3-Player in alphabetical order:
umount /dev/sdb1
sudo fatsort -a /dev/sdb1
If fatsort complains about a defective file system => repair it:
sudo dosfsck -r -l -v /dev/sdb1
Any questions about command line parameters:
man fatsort
man dosfsck


text:
Q: Is it possible to build containers from within a container on a system where I am not admin? I would like to build singularity recpies locally, rather than relying on Singularity hub and wasting my limited daily build quota on fixing stupid syntax errors. However, I am not admin on the machine where I will be running the containers.  I would like to build a container on Singularity hub, within which I am an admin and can build other other containers. However, my attempts to build a container where I can use sudo and su make me think this can't be done. Is there any way to set up a container within which I can build containers, and if so what is the problem with my current approach?
I have the following code in my recipe to create a user "ubuntu" with password "ubuntu" and membership in the "sudo" group:
Bootstrap:docker
From:ubuntu:xenial
#...some other stuff that doesn't matter here...
%post
apt-get update
apt-get install -y sudo

useradd ubuntu
echo "ubuntu:ubuntu" | chpasswd
usermod -aG sudo ubuntu

The recipe builds successfully on Singularity hub.  However, I can't use sudo or su within the container:
$singularity build --sandbox xenial shub://path/to/my/container:xenial
<container builds with some warnings about my account being non-root>
$singularity shell xenial
Singularity: Invoking an interactive shell within container...

Singularity xenial$ su ubuntu
Password:            #I type "ubuntu"
su: Authentication failure
Singularity xenial$ sudo whoami
sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set
Singularity xenial$ls -l /usr/bin/sudo
-rwxr-xr-x. 1 hbraunDSP dip 136808 Jun 10 22:53 /usr/bin/sudo

Is this just too unsecure to be possible? If it is possible, how do I make a container I can use to build containers?

A: Singularity mounts /etc/passwd by default, so the users available inside the container are the same as the ones on the host machine. So the new ubuntu user you added doesn't exist as far as the image is concerned when you're shelled into it.
If you want to build singularity images while running in another one, at minimum you'd need to sudo singularity shell ... so you retain your sudo / root privileges.
Alternatively, you can build singularity images from inside Docker containers if you use the --privileged option.


text:
Q: DDD : Where should data be converted, formatted, encrypted etc? For future projects i decided to use dto's to pass data to the domain layer . Here is also where i make most of the data validation .
Where should i put data formatting ?
1) In the DTOs when it's ready to be sent to the domain layer
OR
2) In the infrastructure layer right before it's being persisted ?
OR
3) Somewhere else :)
i.e. : A password that needs to be encrypted before it's persisted or an image thats needs to be converted, resised etc before its stored.
I want to keep all data formating in one layer , don't like it to be scatered all over the place.
With other words : Should the data be prepared for the domain to handle it or should the domain get raw data and change it after it's being handled by the domain ?

A: Data formatting is a technical concern and as such it should be handled by infrastructural services, not by the domain. For example, password hashing should be handled by the repository which persists the corresponding aggregate. Formatting may also happen in a adapter in a hexagonal architecture which is where DTOs typically reside. This type of formatting is dependent on the type of adapter at hand. For example, you can consider a RESTful API exposing a domain model as being an adapter between HTTP and the domain model. In this case, formatting or translation must be performed between a resource representation and the corresponding domain objects.


text:
Q: Increase word space between words in small caps With tracking activated for small caps, it can be a little bit hard to detect interword spaces. Cf. below.
\documentclass{article}
\usepackage{fontspec}
    \setmainfont{Libertine Serif}[
        SmallCapsFeatures = {Letters = SmallCaps, LetterSpace = 5}]
\begin{document}
The title of my article is \textsc{This is the moment your life changed forever}.
\end{document}

I'd like to increase the space between words in small caps, therefore, but only when words on either side are in small caps (i.e. there should be no extra space before the first word written in small caps or after the last word).
I would've thought I could do this by adding WordSpace = <> to SmallCapsFeatures, but this will change the interword space everywhere.
\documentclass{article}
\usepackage{fontspec}
    \setmainfont{Libertine Serif}[
        SmallCapsFeatures = {Letters = SmallCaps, LetterSpace = 5, WordSpace = 5}]
\begin{document}
The title of my article is \textsc{This is the moment your life changed forever}.
\end{document}

A: You want to set \spaceskip to a non null value (and perhaps also \xspaceskip).
\documentclass{article}
\usepackage{fontspec}
\usepackage{xpatch}

\setmainfont{Linux Libertine O}[
  SmallCapsFeatures = {
    Letters = SmallCaps,
    LetterSpace = 20,
  }
]

\xapptocmd{\scshape}
  {\spaceskip=3\fontdimen2\font plus 3\fontdimen3\font minus \fontdimen4\font
   \xspaceskip=2\fontdimen7\font}
  {}{}

\begin{document}

The title of my article is \textsc{This is the moment your life changed forever}.
Here the space is normal.

\end{document}

The values are of course exaggerated: here the interword space is set to three times the normal value.
When \spaceskip has a nonzero value, it is used for the interword space instead of the default font defined one. The relevant font parameters are

*

*\fontdimen2\font (the natural width of the interword space)

*\fontdimen3\font (the stretch component)

*\fontdimen4\font (the shrink component)

Thus, specifying
\spaceskip=3\fontdimen2\font plus 3\fontdimen3\font minus \fontdimen4\font

we're telling to use three times the normal interword space, stretchable three times as much it is normally and shrinking it the same as the default. The parameter \xspaceskip is related to the space factor: when the space factor is >2000, TeX adds its value to the normal interword space (this is how the space is increased after periods); by default TeX uses \fontdimen7\font, but it uses \xspaceskip if it is nonzero.

A: Here, \theskip defines the new inter-word space inside \textsc{}.  EDITED to fix bug which chopped last word.  I also show that it works in headers in this MWE.
\documentclass{article}
\let\svtextsc\textsc
\def\theskip{\hspace{4ex}}
\def\textsc#1{\def\myskip{}\wspaceout#1 \relax\relax}
\def\wspaceout#1 #2\relax{%
  \myskip\svtextsc{#1}\let\myskip\theskip\ifx\relax#2\else\wspaceout#2\relax\fi}
% HEADER STUFF
\usepackage{fancyhdr}
\lhead[\rm\thepage]{\textsc{Word1 Word2 Word3}}
\rhead[xxx]{\rm\thepage}
\pagestyle{fancy}
\begin{document}
The title of my article is \textsc{This is the moment your life changed forever}.
And some more text

\def\theskip{\hspace{1.5ex}}
The title of my article is \textsc{This is the moment your life changed forever}.
And some more text

\def\theskip{\ }
The title of my article is \textsc{This is the moment your life changed forever}.
And some more text

\def\theskip{\hspace{2ex}}
The title of my article is \textsc{This is the moment your life changed forever}.
And some more text
\end{document}

A: Imho fontspec could do better here and allow WordSpace to be set for small caps alone. The following is not meant as usable document code -- it redefines an internal command of fontspec and probably miss some cleaning up -- but only as proof of concept:
\documentclass{article}
\usepackage{fontspec}

\ExplSyntaxOn\makeatletter
\cs_set:Nn \__fontspec_declare_shapes_smcaps:nn
 {
    \tl_if_empty:NF \l__fontspec_nfss_sc_tl
     {
      \__fontspec_DeclareFontShape:xxxxxx {\l__fontspec_nfss_enc_tl} {\l_fontspec_family_tl} {#1}
        { \__fontspec_combo_sc_shape:n {#2} } {\l__fontspec_nfss_sc_tl} {\l__fontspec_postadjust_tl
         \l__uf_fontspec_postadjust_sc_tl
        }
     }
  }

 \tl_set:Nn \l__uf_fontspec_postadjust_sc_tl
     {
      \fontdimen 2 \font = 5 \fontdimen 2 \font
      \fontdimen 3 \font = 5 \fontdimen 3 \font
      \fontdimen 4 \font = 5 \fontdimen 4 \font
     }

\ExplSyntaxOff

 \setmainfont{Linux Libertine O}[
        SmallCapsFeatures = {Letters = SmallCaps, LetterSpace = 5,}
           ]

\ExplSyntaxOn
%should not affect Arial:
 \tl_clear:N \l__uf_fontspec_postadjust_sc_tl
\ExplSyntaxOff
 \setsansfont{Arial}
\begin{document}
The title of my article is

\textsc{This is the moment your life changed forever}.

{\large \scshape Large: the title of my article}

\textsc{\bfseries the title of my article}

the title of my article

\sffamily some words in sans

\scshape some words in small caps sans

\end{document}

A: Your problem should be solved by using \caps command form soul package.
An example:
\documentclass{article}
\usepackage{soul}
\begin{document}
   \scshape{abcde fghijk lmnopqr stuvwxyz abcdefghij klmnopqr stuvwxyz}

   \caps{abcde fghijk lmnopqr stuvwxyz abcdefghij klmnopqr stuvwxyz}
\end{document}

You can change the font, spacing and even the command in use with command \capsdef.
Usage:
\capsdef{<font>}{<command>}{<inter-letter space>}{<inner space>}{<outer space>}

It seems that you want to increase <inner-space>. It can be done as follows:
\capsdef{T1/ppl/m/n/5-15}{\scshape}{.16em}{.6em}{.2em}

This also sets the command to \scshape so you won't need to use \caps.


text:
Q: How to debug javascript in Eclipse served by a Django Server Let me 1st explain my setup.
I am trying to build a website using Django as backend framework and with Twitter bootstrap as  frontend framework (using the django frontend)
My env is CentOS 5.9 with Eclipse Kepler with Pydev, JSDT, WDT plugins (Python 2.7, Django 1.4+).
I am able to debug Django Python files (views.py) using --noreload (argument to manage.py) using the pydev perspective.
But how do I debug the frontend Javascript from Eclipse (I know I can use Chrome/Firefox tools, but I would like to debug and use JS autocomplete feature of Eclipse) that is served from a Django server? To make things simple, I am running the Django manage.py from a terminal (unless someone can tell me how to debug Django and JS at same time from Eclipse?)
I know I can debug static pages using chrome dev tool with Eclipse, but I am looking for way to debug pages (JS, CSS) served by Django.
Thanks for the help :) Let me know if you think there is a better way to debug JS.

A: *

*Start a server on localhost

*open a browser and navigate to your local server.

*Use the built-in debugging capabilities of your browser.


text:
Q: Faster way to tag a cell if its column name appears in preceding cells of the same row
*

*I have a big data frame (~ 280000 rows x 1200 columns), each row represents a basket of items.

*The first column has the basket id.

*The next ~120 columns have either a 4 digit item code (of one of the items present in the basket) or are blank (for remainder of 120 cells after all items of the basket have been accounted for).

*The subsequent columns (from 121 till 1200) are each named with one of the unique 4 digit item codes from the items universe. All these columns are blank.

Now, I want to tag the cells in these columns (121 to 1200), if that item (the column name) appears in that row/basket.
Following is a smaller version of the dataframe (df);
df <- data.frame(BasketID = c("001", "002"),
                 Item1 = c(1001, 1002), Item2 = c(1002,""), Item3 = "",
                 `1001` = "", `1002` = "", `1003` = "", check.names=F)

BasketID   Item1   Item2   Item3   ...   1001   1002   1003
001        1001    1002
002        1003

Below is what I require;
BasketID   Item1   Item2   Item3   ...   1001   1002   1003
001        1001    1002                  tag    tag
002        1003                                        tag

I wrote the following for loop to achieve the above;
for (i in rownames(df)) {

    for (j in colnames(df[,121:1200])) {

        if (j %in% df[i,121:1200]) {

            df[i,j] <- "tag"
        }
    }
}

However, since the dataframe is big, the above command is taking forever to run forcing me to abort midway. Is there a more efficient way to do this? Thanks v. much in advance!!

A: This might be more easily done using the data.table package. Convert into a long format using melt. Subset to those with valid value. Then pivot the data using length > 0 as the fun.aggregate:
library(data.table)
dcast.data.table(
    melt(setDT(df), id.vars="BasketID"),
    BasketID ~ value,
    function(x) length(x) > 0,
    subset=.(value!=""))

#the join the results with original dataset to get OP's desired format
tags[df, on=.(BasketID)]

#    BasketID  1001  1002  1003 Item1 Item2 Item3
# 1:      001  TRUE  TRUE FALSE  1001  1002
# 2:      002 FALSE FALSE  TRUE  1003

data:
df <- data.frame(BasketID = c("001", "002"),
    Item1 = c(1001, 1003), Item2 = c(1002,""), Item3 = "")


text:
Q: Change Broadcom Wireless adapter MAC addres to any address I need to change my MAC address of Broadcom 802.11n Network Adapter to address of my choice - I need to mask myself as another device in the network. The conflict of the devices will not happen.
Under windows 7 it seems that either the OS or the card driver is ignoring/rejecting all addresses except those that begin with 02 occet.
Are there some cracked drivers or other ways to bypass to protection?

A: These mac combinations will all work on windows 7.
X2-XX-XX-XX-XX-XX
X6-XX-XX-XX-XX-XX
XA-XX-XX-XX-XX-XX
XE-XX-XX-XX-XX-XX

X - is any hexadecimal number ( they don't have to be the same ).

A: Broadcom Wireless cannot change / spoof MAC address....SOLVED
Looks like it is an issue with Broadcom WiFi drivers that do not support spoofing the MAC address to any random number. I can change the MAC of my LAN adapter (nVidia) to any MAC address but not the WiFi one on the very same system.
The suggested solution works for the WiFi (strangely)


text:
Q: Why do I get different outputs with \r escape sequence in different IDLE? When is used the \r in sublime, it behaved as a \n escape sequence.
carriage_return = "I will use a carriage\rreturn"
print (carriage_return)

I will use a carriage
return

But when I used it in the python 3.7.2 IDLE, the output was:

I will use a carriagereturn

Why is there's a different output?
How do you use the \r escape sequence?

A: A "carriage return" traditionally moved the cursor back to the beginning of the line so you should have seen the output as:
return use a carriage

because the i will would have been overwritten.
However, this tradition has now changed as standards have developed and there is no more uniform handling of a "carriage return". For example, HTML treats a \r as a whitespace.
Since I am new to stackoverflow please tell me how to improve my answer.


text:
Q: Unity how to reset score after scene change? When I get my game over the scene the score still remains when a start a new game:
ScoringSYstem.cs
    public GameObject scoreText;

    public static int theScore;

    void Update()
    {
        scoreText.GetComponent<Text>().text = "Score: " + theScore;
    }

Timer.cs
   public string LevelToLoad;
 public static float timer1 = 30f;
 private Text timerSeconds;

    public GameObject scoreText;

    public static int theScore;

 // Use this for initialization
 void Start ()
 {
  timerSeconds = GetComponent<Text> ();
 }

 // Update is called once per frame
 void Update ()
 {
  timer1 -= Time.deltaTime;
  timerSeconds.text = timer1.ToString("f0");
  if (timer1 <= 0)
     {
        timer1 = 30f;
        Application.LoadLevel (LevelToLoad);

 }
}

How does it in order to reset the score whenever a scene changes?

A: First of all you need to create an empty GameObject that you call GameManager then you add a Script to it that you call GameManager as well. So that you can acces your Score from everywhere.
public int score = 0;
public static int time = 30;

#region Singelton
public static GameManager instance;

void Awake()
{
   if (instance != null)
   {
      Debug.LogWarning("More than one Instance of Inventory found");
      return;
   }

   instance = this;
}
#endregion

public void GameOver()
{
   score = 0;
   scoreText.GetComponent<Text>().text = "Score: " + gm.score;
}

Then you can call theese variables from everywhere and change them as well:
GameManager gm;

void Start()
{
   gm = GameManager.instance;
}

void Update()
{
   if (time >= 0)
      gm.GameOver();
}

A: You may use the
void OnSceneLoaded(Scene scene, LoadSceneMode mode)

method in your gameover scene to reset theScore variable in your GameObject that holds the variable, if the GameOver scene using a GameEngineObject of some kind.
Unity Doc SceneManager


text:
Q: In Angular, how can one component to have multiple HTML templates? I am developing an ecommerce application, and one major feature is that this app should have multiple themes. The total number of themes could be 100 or even more. However, these themes all have the same data (For example: all home page have same banner images, new product, feature product data.) .
I know I can use ng-template or TemplateRef to determine which piece of HTML should display. But since I have over 100 themes, both ng-template or TemplateRef methods will load a lot of extra files. So I think I need some sort of lazy load, when a component loads the data then lazy loads the correct HTML template. So how can I have this work?

A: Looks like it is possible, all our routes are handled by lazy loaded modules. This is our out-of-the-box route config:
const routes: Routes = [
  { path: '', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];

While module lazy has this route config:
const routes: Routes = [
  { path: 'home', component: HomeComponent },
]

While HomeComponent is taken from the declarations of module lazy.
Then define another module, called for example lazy-two with the same route config, and its own HomeComponent.
Finally, you can switch between the modules by using this code:
lazyLoad() {
  const routes: Routes = [
    {
      path: '',
      loadChildren: () => import('./lazy-two/lazy-two.module')
                            .then(m => m.LazyTwoModule)
    }
  ];

  this.router.resetConfig(routes);
  this.router.navigateByUrl('/home');
}

This will lazy load module lazy-two and refresh the route to /home - you will see the component of the new module displayed.
I couldn't create a stackblitz, some errors occurred probably because of lazy loading. So I ran it locally on my machine and pushed the code to GitHub
EDIT I managed to make a StackBlitz

A: I recommend used ComponentFactoryResolver to create the components that you need to render.
this.templates = [
  {
    id: "template-1",
    component: Template1,
  },
  {
    id: "template-2",
    component: Template2,
  },
];

  ngOnInit() {
    this.templates.forEach((element) => {
      this.containerReference.createComponent(
        this.factoryResolver.resolveComponentFactory(element.component)
      );
    });
  }

in the .html you should have
<ng-container #containerReference><ng-container>

A: what about using the same component and styling it different when you select the template?


text:
Q: Sorting objects in Python I want to sort objects using by one of their attributes. As of now, I am doing it in the following way
USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True)

This works fine, but I have read that using operator.attrgetter() might be a faster way to achieve this sort. First, is this correct? Assuming that it is correct, how do I use operator.attrgetter() to achieve this sort?
I tried,
 keyFunc=operator.attrgetter('utility[chosenCar]')
 USpeople.sort(key=keyFunc,reverse=True)

However, I get an error saying that there is no attribute 'utility[chosenCar]'.
The problem is that the attribute by which I want to sort is in a dictionary. For example, the utility attribute is in the following form:
utility={chosenCar:25000,anotherCar:24000,yetAnotherCar:24500}

I want to sort by the utility of the chosenCar using operator.attrgetter(). How could I do this?
Thanks in advance.

A: No, attrgetter will not be any faster than the lambda - it's really just another way of doing the same thing.
You may have been confused by a recommendation to use key instead of cmp, which is indeed significantly faster, but you're already doing that.

A: to access chosenCar item you'd have to use:
>>> P.utility={'chosenCar':25000,'anotherCar':24000,'yetAnotherCar':24500}
>>> operator.itemgetter('chosenCar')(operator.attrgetter('utility')(P))
25000

for the key function you'll have to do the following:
>>> def keyfunc(P):
    util = operator.attrgetter('utility')(P)
    return operator.itemgetter('chosenCar')(util)

>>> USpeople.sort(key=keyfunc,reverse=True)

However, your main claim re the better performance of this approach seems poorly researched. I'd suggest to use timeit module to test performance of both approaches for your own data.

A: *

*Never, ever, ever optimize based on something you've read. Going into your code and making random changes from what you have to something you think should be faster is not a working optimization strategy.

*Here is how you optimize if you want to improve your code.

*

*Don't. It's often a waste of time.

*Make a working, testable program.

*Determine performance metrics—be able to answer "Is this code fast enough?"

*Realize that your code is already fast enough.

*If you weren't able to do step (4), profile your code for realistic input to determine where it spends its time. In Python you can use http://docs.python.org/library/profile.html to do this. Bottlenecks occur at unexpected places, and this will tell you where you actually have to put in the effort.

*Examine the time-consuming code for algorithmic suboptimality. This sometimes occurs at the level you are, but often occurs several levels out too. Improving your algorithm will almost always be the biggest chance at a speedup.

*If you cannot improve your algorithm, test various pieces of code that do the same thing based and see how they perform. Use http://docs.python.org/library/timeit.html to test snippets (this is harder to get right than people realise, so be careful) and re-run your performance tests and profile.
It can be tempting to try to do this step upfront, but this would often prove to be unfruitful. You need to know that what you're optimizing makes sense.
I hope this provides some insight into how to speedup your code (and when not to bother). I've seen lots of people try replacing random code with rule-of-thumb optimizations, but I haven't seen those people producing great, fast software. Optimization must be done scientifically, using theory (such as the computer science in 6) and experimentation (such as the timing in 7).

*In this specific case, I would bet money that SilentGhost's code ultimately is slower than yours. I of course don't know for sure, but neither do you unless you time it.
(And I don't think you should bother timing it, I think you should go with the clearest approach, your original one.)


text:
Q: How can I use CSS to vertically center the text in an anchor, within a LI? Variations on this question have been asked many times. Vertical centering with CSS is a challenge.
I have a particular scenario, dealing with a list displayed horizontally. The markup is like this:

Fribble Fromme

Fobble

Foo Fickle Pickle

The style is like this:
  ul.c {
    height:52px;
    text-align:center;
  }
  ul li a {
    float:left;
    text-decoration:none;
    border: 1px solid Maroon;
    padding:2px 12px;
    background:#FFEF8A;
    line-height:1em;
    width:100px;
  }
  ul li a:hover {
    background: #CCC;
  }
  ul li {
    height:52px;
    display:inline-block;
  }

The resulting list looks like this:

But I want all the boxes to be the same height, and I want the text to be vertically centered in each box.  I can set the box-height by adding a height style for the A elements.  The result looks like this:

...which is close to what I want, but the vertical-centering isn't happening.
I can set line-height for the text, as suggested in this post, to do the vertical centering. I can even pick different values of line-height for different A elements, if I know which of the elements will get multiple lines of text.  But I don't know which ones will require multiple lines.
How can I get it to center when some of the A elements have text that wraps?

A: Old question, but the answer can now be updated with Flexbox.
a {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}

A: You could use display:table, etc. along with vertical-align:middle
ul.c {
    text-align:center;
    display:table;
}

ul li {
    float:left;
}

ul li a {
    text-decoration:none;
    border: 1px solid Maroon;
    padding:2px 12px;
    background:#FFEF8A;
    width:100px;
    height:52px;
    display:table-cell;
    vertical-align:middle;
}

ul li a:hover {
    background: #CCC;
}

Example: http://jsfiddle.net/kf52n/2/

A: I could not figure a way to do this in CSS.  I found that I could do what I needed with Javascript, setting the padding-top and padding-bottom to appropriate values at runtime.  The technique is to measure the "natural" height of the A element, then set the padding so that the A element is vertically centered.
here is the necessary js code:
  function setHeightIntelligently(ulElement) {
    var items, L1, i, anchor, availableHeight = ulElement.clientHeight,
        naturalHeight, pad;
    items = ulElement.children;
    for(i=0, L1 = items.length;i<L1;i++){
      if (items[i].tagName.toUpperCase() == 'LI') {
        anchor = items[i].children[0];
        naturalHeight = anchor.clientHeight;
        pad = (availableHeight - naturalHeight)/2;
        anchor.style.paddingTop= pad+'px';
        anchor.style.paddingBottom= pad+'px';
      }
    }
  }

  function init() {
    var element = document.getElementById('ul1');
    setHeightIntelligently(element);
  }

In the CSS, one must not explicitly set height or padding for the A elements. Doing that would cause the "natural" height to not be what we need it to be.
The result is like this:

To see it in action, go here.

A: in the css you have set the height and line-height to the same. Then you will get a rectangular box.
But still you are seeing space in the bottom the reason is due to padding
adding two values in padding adds top and bottom padding
padding: top bottom;
since it is 2 and 12 you are seeing huge space.
try this
height: 52px;
line-height:52px;
padding: 6px 6px; // here you have to tweak and see the output
vertical-align:center;

let me know it is working

A: line-height:250%; worked for me


text:
Q: How to set time on a Date object to be zero (00/00/00) Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(0);

This sets it to the deafult value. How do I set it to zero?

A: (00/00/00) is not a valid date; the API will not produce this value.

A: You should probably be aware of what setTimeInMillis() expects:

public void setTimeInMillis(long millis)
Sets this Calendar's current time from the given long value.
Parameters:
millis - the new time in UTC milliseconds from the epoch.

The epoch is defined as:

An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

A: You can zero-out what value you want using the set method. For example:
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);


text:
Q: In Java-8 Locale Object convert to old ISO in some Language code. How can i fix this issue without update Java version? Like when i take input (he-IL) then output comes like "iw_IL". But i do not want this convert to old iso.
public static void main(String[] args) {
    Locale locale = getLocaleIn("he-IL");
    System.out.println(locale.toString());
}
private static Locale getLocaleIn(String langCode) {
    LocaleCode code = LocaleCode.getByCodeIgnoreCase(langCode);
    Locale locale = code.toLocale();
    return locale;
}

OutPut:
iw_IL,
Expected Output:
he-IL
Main Problem in Here, In Java Locale.Class:

Finally I Want an Locale Object without Converting to old ISO.

A: You should avoid non-standard 3rd party classes in problem descriptions, especially when they do not contribute to the problem at all.
We can simply use
Locale locale = new Locale("he", "IL");
System.out.println(locale.toString());
locale = new Locale("iw", "IL");
System.out.println(locale.toString());

and get
iw_IL
iw_IL

under JDK 8, which is in line with the documentation:

This constructor accepts both the old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other API on Locale will return only the OLD codes.

This has changed with JDK 17:

Obsolete ISO 639 codes ("iw", "ji", and "in") are mapped to their current forms.

and running the same example program with JDK 17 accordingly now prints
he_IL
he_IL

So the cleanest and probably the only solution to your issue would be updating the Java version. Any patch forcing Locale to return the new code in older versions may cause compatibility problems with other components of the runtime relying on the old behavior.


text:
Q: oracle creating cubes in parallel Is there a way to run two cube builds in parallel:
For instance i have the following two cube builds running sequentially:
 BEGIN
    DBMS_CUBE.BUILD(
      'OLAPTRAIN."TIME", OLAPTRAIN.CHANNEL, OLAPTRAIN.PRODUCT, OLAPTRAIN.GEOGRAPHY, OLAPTRAIN.SALES_CUBE',
      'CCCCC', -- refresh method
      false, -- refresh after errors
      1, -- parallelism
      false, -- atomic refresh
      false, -- automatic order
      false); -- add dimensions
  END;

BEGIN
    DBMS_CUBE.BUILD(
      '
    OLAPTRAIN.FORECAST USING
    (
      EXECUTE OLAP DML ''do_forecast''
    )',
      'C', -- refresh method
      false, -- refresh after errors
      1, -- parallelism
      false, -- atomic refresh
      false, -- automatic order
      false); -- add dimensions

  END;

However I would like these to be build in a parallel fashion. One build taking one CPU respectively.
Can that be achieved in Analytic Workspace? If not how can I do that in PL/SQL code?
Thanks.

A: DBMS_Scheduler might be what you're looking for.
If this is part of a regular job, then create a scheduler chain that executes both of these procedure in parallel.
You might investigate using the SCHEDULER_JOB parameter to run the build as its own job, but typically you would then have to write your own monitoring code to wait until both jobs have finished, which a scheduler chain would handle for you.
https://docs.oracle.com/cd/B28359_01/server.111/b28310/scheduse009.htm#ADMIN10021
By the way your code would be more robust as:
BEGIN
  DBMS_CUBE.BUILD(
    script               => 'OLAPTRAIN."TIME", OLAPTRAIN.CHANNEL, OLAPTRAIN.PRODUCT, OLAPTRAIN.GEOGRAPHY, OLAPTRAIN.SALES_CUBE',
    method               => 'CCCCC',
    refresh_after_errors => false,
    parallelism          => 1,
    atomic_refresh       => false,
    automatic_order      => false,
    add_dimensions       => false);
END;


text:
Q: Is virtual reality a contradiction? When you consider the word "virtual" you would usually picture something that is simulated or exists in a computational manner.
Does this mean that virtual reality is actually contradictory? After all, reality is literally reality.

A:
virtual -  very close to being something without actually being it; existing or occurring on computers or on the Internet; being on or simulated on a computer or computer network
virtual reality - an artificial environment which is experienced through sensory stimuli (as sights and sounds) provided by a computer and in which one's actions partially determine what happens in the environment

Going by these definitions, I would not call it a contradiction at all.
Reality is not simulated.  It is our conscious world—what really exists.   Virtual experience would be a simulation, that is, a representation of reality.  So going by this, "virtual reality" is like saying "artificial reality".  Maybe even "turkey bacon" ;)
On the other hand, reality as we know it could be computerized—if you believe in The Matrix

A: It is an oxymoron which by definition (see below), is composed of apparently contradictory terms.
So yes, you are right to an extent when you consider the usual meanings of the separate words. However, they have alternative meanings (to be used in this context) which make virtual reality not such a contraction after all.
From oxforddictionaries.com:

virtual: ADJECTIVE
2 [Computing] Not physically existing as such but made by software to
appear to do so: virtual images
See also virtual reality.
More example sentences:
Once they figured out how to get Trojans onto computer, creating their
own virtual spamming super computer, spammers have adopted this method
for most of the spam they send out.
This paper explores the potential for developing virtual dissection
software for physical collaboration.
The software also supports multiple virtual desktops.
reality:
NOUN
1.3 The quality of being lifelike: the reality of Marryat's detail
More example sentences:
Harsh reality is created with striking clarity throughout the
collection, leaving the reader both awed and dismayed.
He loved acting and the people that were in it and that could produce
and create moments of great reality.
Only when films regain the sparks of creativity, originality and
reality, will we see crowds in cinema halls again.
virtual reality: NOUN
The computer-generated simulation of a three-dimensional image or
environment that can be interacted with in a seemingly real or
physical way by a person using special electronic equipment, such as a
helmet with a screen inside or gloves fitted with sensors.
Example sentences:
You play as a character that has entered a computer system in virtual
reality to destroy a virus infecting the main frame.
As virtual reality simulators are computer based systems they generate
output data, or what is commonly referred to as metrics.
Their aim is simple: to generate a truly immersive virtual reality
environment that has a useful commercial function.
oxymoron:   NOUN
A figure of speech in which apparently contradictory terms appear in
conjunction (e.g. faith unfaithful kept him falsely true).
Example sentences:
Yes, but it does leave a reader ever more certain that the term 'mature male' is an oxymoron.
One day I sat her down to explain to her the word oxymoron and then
to describe a magnificent and bucolic world of insults.
The idea of a light of darkness is certainly an oxymoron,
certainly a contradiction in terms, and yet we find that among
various mystics.


text:
Q: Child component textbox default value not updating I have a collection of questions and a textbox to get the answer. I want the textbox to have a blank default value every time I click the next button to get to the next one but it keeps having the value of the last answer I submitted. I've looked at changing state in the child component but that doesn't seem to do it and would appreciate any suggestions/ideas? Here is the code:
  // function is rendering each question one by one.
  function generateQuestions() {

    return <Grid container spacing={3}>
              <Grid item xs={12}>
                <QuestionTile
                  questionNumber={questionNumber}
                  question={currentQuestions[questionNumber].question}
                  answer={currentQuestions[questionNumber].answer}
                  updateUserAnswer={updateUserAnswers}
                  currentUserAnswer={" "}
                  // currentUserAnswers[questionNumber] === null ? " " : currentUserAnswers[questionNumber]
                />
              </Grid>
              <Grid item xs={12}>
                {getNextAndPrevButtons(currentQuestions.length)}
              </Grid>
            </Grid>;
  }

And the child component:
export default function QuestionTile({question, questionNumber, answer, updateUserAnswer, currentUserAnswer}) {
    const classes = useStyles();
    const [userAnswer, setUserAnswer] = useState(currentUserAnswer)

    function updateTextBoxValue(questionNumber, value) {

      console.log("Updating text box value")
      setUserAnswer(value)
      console.log(userAnswer)
      updateUserAnswer(questionNumber, value)
      setUserAnswer(currentUserAnswer)
    }

    return (
        <React.Fragment>
            <Grid container spacing={3} >
              <Grid item xs={12}>
                <Title>{questionNumber + 1}) {question}</Title>
              </Grid>
                <Title>Answer: </Title>
                <TextField
                  id={questionNumber}
                  defaultValue={currentUserAnswer}
                  type="number"
                  className={classes.basicQuestionPadding}
                  onChange={(event) => updateTextBoxValue(questionNumber, event.target.value)}
                />
            </Grid>
        </React.Fragment>
    )
}

I am storing the user's answers as a list in the state of the parent component, this is the code for the function I'm passing to the child:
  function updateUserAnswers(questionNumber, answer) {
    currentUserAnswers[questionNumber] = answer
  }

For the sake of completeness, the code for the Submit and prev buttons is below:
 // Store the question number in state to trigger re-render on question change (and hence show new question)
  function getNextAndPrevButtons(numberOfQuestions) {
    if ((questionNumber < (numberOfQuestions-1)) && questionNumber >= 1) {
      return <Grid container direction="row"  spacing={10}>
        <Grid className={classes.QuestionNavButtons} justify="space-between" item xs={5}>
          <Button variant="contained" onClick={() => setQuestionNumber(questionNumber-1)}>Prev</Button>
        </Grid>
        {/* <Grid item xs={6}>

</Grid> */}
        <Grid className={classes.QuestionNavButtons} justify="space-between" item xs={5}>
          <Button variant="contained" onClick={() => setQuestionNumber(questionNumber+1)}>Submit</Button>
        </Grid>
      </Grid>;
    }

    if (questionNumber >= 1) {
      return <Grid container direction="row"  spacing={10}>
      <Grid className={classes.QuestionNavButtons} justify="space-between" item xs={5}>
        <Button variant="contained" onClick={() => setQuestionNumber(questionNumber-1)}>Prev</Button>
      </Grid>
      <Grid className={classes.QuestionNavButtons} justify="space-between" item xs={5}>
        <Button variant="contained" onClick={() => setLevel("answers")}>View Answers</Button>
      </Grid>
    </Grid>;
    }

    if (questionNumber < (numberOfQuestions-1)) {
      return <Button variant="contained" onClick={() => setQuestionNumber(questionNumber+1)}>Next</Button>;
    }
  }

This is my first time posting a question on stack overflow so please let me know if there are any details I'm missing.
Thanks!

A: I was able to answer this by adding a key prop to the TextField element and made sure it was something that changed for each question. In this case the answer. This is not optimal as it misses the use case of two questions having the same answer(this would not trigger a re-render). Something better could be to pass down a counter or something. Its also probably not the cleanest solution either so still welcoming better ones in the meantime.


text:
Q: How to get data using nested maps in single render? I'm trying to print the data as given below. .I have used the nested map in the render wherein the first map is to print the Category name and the link view all.And in the second/nested map i'm trying to loop over the data belonging to the category as listed in the parent map.
But i'm getting an error as unexpected token at nested return .

render function in FeaturedSection.js

      {this.state.newData && Object.keys(groupedByCategory).map(function(categoryName,i)
        {return(

Featured {`${categoryName}`}

                <Link to="#" className="routeDecorator ">

View All

                </Link>

              groupedByCategory[categoryName].map(function(data,i)
                {
                  return (

                        <FeaturedOffer
                          title={data.name}
                          offerDescription={data.offerdescription}
                          rewardImage={data.reward_image}
                          productName={data.modelname}
                          thumbnailImage={data.thumbnailimage}
                        />
                );
              })

        );})}

A: I think you need to wrap your map within {}.
{
  groupedByCategory[categoryName].map((data,i) => {(
    <FeaturedOffer
      key={i}
      title={data.name}
      offerDescription={data.offerdescription}
      rewardImage={data.reward_image}
      productName={data.modelname}
      thumbnailImage={data.thumbnailimage}
    />
  })
}


text:
Q: CSS responsive box that maintains aspect ratio but NEVER overflows the viewport Every example that I have found including what is supposedly the right answer:
Maintain the aspect ratio of a div with CSS -
Maintain the aspect ratio of a div with CSS
The problem always is that at some point the box clips (Overflows) usually on the vertical axis.
I am trying to create a responsive box that maintains the aspect ratio in both directions AND NEVER clips(Overflows) in either direction (ie: the aspect ratio box is never larger than 90% of the viewport). I've tried using both height and width as the basis for the calculation but neither works and height seems to be cleaner for my purposes (The height of the images never change but the width will depending on the aspect ratio of the image.
Is it possible to have a box that maintains its aspect ratio and never overflows the viewport?

.demoWrapper {
  padding: 1vh;
  background: white;
  box-sizing: border-box;
  resize: both;
  border: 1px dashed;
  overflow: auto;
  max-width: 100%;
  height: 80vh;
}

div {
  width: 50%;

  padding-bottom: 35%;
  background: gold; /** <-- For the demo **/
}

A: To ensure the box keeps its aspect ratio but never overflows the viewport (which has been specified as width not exceeding 90vw and height not exceeding 90vh) CSS can calculate the best fit:

.box {
  display: inline-block;
  --ratio: calc( 3 / 2);
  /* put the aspect ratio width to height you want */
  --h: min(calc(90vw / var(--ratio)), 90vh);
  height: var(--h);
  width: calc(var(--h) * var(--ratio));
  background-color: red;
}

This assumes the aspect ratio of the box is known.
If not it can be calculated on first load and the CSS variable set, but this requires Javascript. It is unclear from the question whether the aspect ratio is known or not.
If the aspect ratio is set by an image then there may be other ways.


text:
Q: Bootstrap columns not appearing inline I'm new to bootstrap and CSS in general. I have some html which looks like this:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>My Site</title>
    <link rel="stylesheet" href="/css/bootstrap-theme.css">
    <link rel="stylesheet" href="/css/font-awesome.css">

My Site

          <input type="text" placeholder="Search" class="search-bar">

          <button class="btn btn-default"></button>

I want all of those col- divs to be inlined, but they are all showing up on their own rows:

What's going on here?

A: You are using /css/bootstrap-theme.css. Use /css/bootstrap.css or /css/bootstrap.min.css instead. bootstrap-theme.css doesn't have "col- " properties.
Also, instead of using just one class="col-md-1" (for medium sized viewport/screen) you might want to use something like class="col-xs-12 col-sm-6 col-md-3 col-lg-3" that makes your columns responsive to different screens. ('xs' for extra small screen, 'lg' for large screen etc. Play around with these numbers. Bootstrap uses a 12 columns grid layout, so use factors of 12 as the numbers.)

A: If you are viewing it with small screen width then use following way:

My Site

      <input type="text" placeholder="Search" class="search-bar">

      <button class="btn btn-default"> button</button>

Experiment with changing col-md-#(column number) or others to achieve your desired result.
Liveweave : http://liveweave.com/9MGL33

A: Maybe your screen resolution is too small. If you don't want to add responsive behaviour, you should start with col-xs-*, so the columns will always be horizontal (or inline).
Remember that bootstrap uses 12 columns by default, so maybe col-xs-1 will be a little to small.

My Site

      <input type="text" placeholder="Search" class="search-bar">

      <button class="btn btn-default"></button>

A: In bootstrap 4 for extra small screens do not declare "col-xs-#" it's just "col-#". Took 2 hours of banging my head against the wall to figure it out.
So instead of

L

M

R

It should be

L

M

R


text:
Q: Give users Edit permission to a list, but no access to the site On my (SharePoint 2013) sub site I have a list (where users from a specific store can report errors). This list I want to share with another group of users, those who will do something about the errors (entrepreneurs). I want them to be able to Edit in this list: they don't need delete and create items, just being able to change an item is fine.
The problem is, I don't want them to have access to the sub site itself, because there is  information on the sub site that they don't need to know about, they should only see this list. So they don't have any access at all to the sub site, but I'm giving them permission to the list.
However, it seems like since they can't access the sub site, no matter what permission I give them to the list (Edit, Contribute, Full Control), in the end they only have Reading-access to the list and can't even update an item.
This error message turns up whenever they try to edit something in the list:

The entrepreneur group is external users, but that shouldn't matter, should it? I've added them to SharePoint groups with the right permissions.
Is there any possible way to solve this problem?

A: I've solved it now.
The solution was to first give the user group access to the sub site itself. Before I had given the user group the Permisson Level Read - but then they would be able to see all the links in QuickLaunch and go to the site.
However, I found there was already an existing Permission Level with very restricted permissions Restricted Interfaces for Translation that I could use. (Can open lists and folders and use remote interfaces). So on the site, I gave the user access to the site with this Permission Level.
After that, I went to the List Permission Settings and chose Contribute for the user group. Now they were able to edit the items in the list.
The Restricted Interfaces for Translation Permission Level did it: the users can edit in the list, but they can't see the site itself, no links are even showing. I'm content with this.

A: Similar issue in our environment and fix seemed to been adding "View Application Pages"  and/or "Use Client Integration Features" permissions to the users.
Full permisisons assigned
List:

*

*Edit Items

*View Items

*View Application Pages

Site:

*

*View Pages

*Use Remote Interfaces

*Use Client Integration Features

*Open


text:
Q: @html does not exist in the current context Trying to start with Blazor. I took the Weatherforecast project and tried to add a dropbox with @HTML. All very standard. However I do keep getting the error that @html does not exist in the current context. This question has been asked before, I did see the warnings about similar questions but I did not find a good answer yet. I did add System.Web.MVC to the Imports.razor sheet. Also as added as an assembly.  I could not find the dll at nuget, so I got it from this directory: C:\Program Files (x86)\Microsoft VisualStudio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\Web\Razor\v3.0\MVC5.2.2.
I rebuilded the project, got the latest update for VS 2109. I still just cant seem to access the right dll for @html. Any help would be greatly appriciated.
Arnold
'''
    @page "/fetchdata"
    @using VAblazor.Data
    @using System.Web.Mvc.Html
    @using System.Web.Mvc
@inject VAEntryService VAService

//the dropdown wont work offcourse, it is just that this leads to the error
@Html.DropDownList("StudentGender",
                    new SelectList(Enum.GetValues(typeof(Gender))),
                    "Select Gender",
                    new { @class = "form-control" })

'''

A: You can't use Html Helpers in Blazor...
You should learn the Component model...how to create components, and how to embed inside them html elements such as select, button, etc.
In addition to using the common html elements, you can use Blazor Forms components that represent those html elements, such as InputText and InputSelect.
As per request, the following code creates a component with a select element:
countries.razor
@page "/countries"

@if (countries == null)
{

Loading...

}
else
{
    <select id="countries" onchange="@CountrySelectionChanged">
        <option></option>
        @foreach (var country in countries)
        {
            <option value="@country.ID">@country.Name</option>
        }
    </select>
}

@code
{
   // Here you should have code that retrieve a list of counties from a data store.
}


text:
Q: Crawling website with dynamic pages I need to crawl websites and extract some information from dynamically created pages after a form submission.
The information which I need to crawl would mostly come from databases on these sites.
Added:
Crawlers usually work by jumping from one hyper-link to another. So these are mostly static pages. What about crawling pages that are not statically present but created on the fly.

A: From crawler's point of view there's no big difference. You're still getting genrated HTML.
The only thing you need to be careful about is links leading to infinite number of pages, e.g. calendar that's dynamically generated and has links to next/previous month/year.


text:
Q: jQuery: why doesn't jQuery.inArray() work?
As shown in the image, I just do inArray on an array, looking for a node. and $previously_selected_node and the item at index 37 in $shapes are the same object.... so... why isn't it working?
EDIT:
I found another way to search after one of the aswerers postedd his answer:
var result = -1;
jQuery.each(shapes, function(key, value){
    if (value.id == shape.id){
        result = key;
    }
});
return result;

apparently, part of my problem is that I can't return in the middle of a loop. (I was returning the instant a match was found, which was causing some issues.)

A: Your object is not an array.
$.inArray only work on array-like objects with a length and a set of properties named 0 through length - 1.
You need to search your non-array manually.
For example, you could use a for / in loop to loop through all properties that actually exist and see if any of them match your object:
for (var key in $shapes) {
    if ($shapes[key] === yourObject) {
        //Match!
    }
}

A: You're doing it the wrong way round. It's actually $.inArray(value, array).
And as others already stated: inArray is for arrays, not for objects.


text:
Q: java synchronization from memory model I read that JVM achieves the synchronization by copying data of shared variable from the main memory to the thread's working memory according to this link.
enter link description here
for example, there is a class like this.
class Test {
private Test2 test2 = new Test2();

public void print1() {}

public synchronized void print2() {
    test2.print();
}

}
If this Test class is executed in multiple threads and "print2" method is executed in one thread, I think that a lock on Test is acquired by one Thread and other threads have to wait until the lock is released.
Now I have a question. If a lock on Test is acquired by a Thread, does it mean that data of Test and Test2 is copied from the main memory to a thread's working memory? The reason that I am saying is that "synchronized" keyword is used at instance method level and test2 is a instance variable of Test class.
I am just trying to clarify what is copied from the main memory to a thread's working memory.
Please correct me if I am wrong.

A: In brief, all shared variables will be copied (i.e. written from cache to main memory so all threads have the same data) when you use synchronized. When you use volatile, only the one volatile variable is guaranteed to be copied.
I found this to be a helpful resource which touches on the topic.
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html

EDIT: Regarding your comment, section 17.6 of the specification answers your question:

Let T be any thread, let V be any variable, and let L be any lock.
  There are certain constraints on the actions performed by T with
  respect to V and L:
Between a lock action by T on L and a subsequent use or store action
  by T on a variable V, an assign or load action on V must intervene;
  moreover, if it is a load action, then the read action corresponding
  to that load must follow the lock action, as seen by main memory.
  (Less formally: a lock action acts as if it flushes all variables from
  the thread's working memory; before use they must be assigned or
  loaded from main memory.)

A: synchronized is only required if you have at least one a writer and a reader thread. As you are not modifying anything you don't need synchronized.
The only thing which is copied is the reference test2 which will most likely be placed in a register.  This will happen whether your method is synchronized or not.


text:
Q: What is the best option between buying, building from scratch or implementing an open source ERP? I was required to do a medium ERP with the inventory, Bill of Materials, and production modules. However, I do not know how long it would take me.
I am calculating three months for the analysis and lifting of requirements, and 3 months per module. It is a company that manufactures cardboard boxes.
However, I don't know if it would actually be something feasible, or I'm also considering the option of an open source ERP that is in PHP.
What is your opinion?
Thank you very much in advance. Good day.

A: In parallel to the requirements collection and analysis, I would gather a list of open source ERP solutions (and possibly even commercial ones for comparison) and build a feature matrix.
A system that already supports most of the requirements might allow you to focus on customizing to meet the client's (or employer's) needs and might be ultimately more cost-effective.
I wouldn't be too fixated on an implementation language such as PHP. Of course it should be something that you or your team can handle, and it should be supported in your infrastructure, but code written in Python, Java, JS, Ruby, Go or Rust possibly with Angular, Vue, or React frontends should not be ruled out from the beginning.
Even if the final decision is to write the software from scratch, looking at what existing software provides might be useful.


text:
Q: Rigourous formalism of Hamiltonian mechanics on Manifolds I'm looking for books / articles that provide rigorous formulations of Hamiltonian mechanics on Manifolds. I found the book "Global Formulations of Lagrangian and Hamiltonian Dynamics on Manifolds" [1] by Lee, Leok and McClamroch, but I'm looking for more references.
My goal is to study the math behind those formulations and what problems still demand rigorous definitions.
[1] - http://www.math.ucsd.edu/~mleok/pdf/LHDynamics.pdf

A: Another good reference:

*

*"Mathematical Methods of Classical Mechanics" by V.I. Arnol'd
https://www.amazon.com.br/Mathematical-Classical-Mechanics-Graduate-Mathematics-ebook/dp/B00HWVUUDW/

A: Arnold' work is great. The Russian school of writing a textbook. More abstract and more comprehensive is the American "bible" on mathematical mechanics>
Abraham & Marsden, "Foundations of Mechanics".
https://www.amazon.com/Foundations-Mechanics-2nd-Ralph-Abraham/dp/080530102X


text:
Q: How can I calculate covariance matrix from a random vector? Given a random vector, Y=[y1,y2,...,yn];, its covariance matrix looks like this:

How can I calculate the covariance matrix in MATLAB?

A: the covariance matrix can be computed with the cov() function. But be aware: the covariance matrix of a vector will always be a 1-by-1 matrix, because there are no cross-variances in a single variable.
% random vector of length 10
vec = rand(10,1);

% covariance matrix
cov(vec)


text:
Q: Exiftool via batch file: redirecting output to original console I'm trying to get the dimensions width/height from a webp image, using exiftool via a batch file and saving those values as variables. I can get the bat file to output the dimensions (in this example it outputs "400x222" in the exiftool window), however I'm not too sure how to redirect those values sucessfully back inside the bat file console window as variables.
Below code gives me what I want, but in the exiftool window:
@echo off
setlocal EnableDelayedExpansion
echo ===============     WEBP EXIF    ===============
echo.

for %%f in ("C:\ffmpegConvert\*.webp") do (

    exiftool -k -s -s -s -ImageSize %%f

)

endlocal
pause
exit

Below is what I tried, but I'm not able to echo back those values in my initial bat file console window (I get "echo is off, once for each failed echo")
@echo off
setlocal EnableDelayedExpansion
echo ===============     WEBP EXIF    ===============
echo.

for %%f in ("C:\ffmpegConvert\*.webp") do (

    for /f "tokens=1,2 delims=x" %%a in ('exiftool -s -s -s -ImageSize %%f') do (
        set sW=%%a
        set sH=%%b
    )
    @echo !sW! >CON:
    @echo !sH! >CON:
)

endlocal
pause
exit

A: Ok, so after checking out all your feedback and doing some extra googling, I noticed that my exiftool.exe in c:\Windows had "run as admin" checked in its properties. Unticking this option now returns the variables in my original console...To be sure, I re-checked it, and it went back to not displaying the info properly. I don't understand why that is, but now it works as I wanted:) Thanks again for your responses!


text:
Q: NumPy complex128 division inconsistent with float64 division I'm doing complex division in a context where numerical precision really matters. I find that dividing two complex128 numbers with no imaginary part gives a different result beyond 15 decimal digits that dividing the same two numbers as float64.
a = np.float64(1.501)
b = np.float64(1.337)

print('{:.20f}'.format(a / b))
# 1.12266267763649962852

a_com = np.complex128(1.501)
b_com = np.complex128(1.337)

print('{:.20f}'.format((a_com / b_com).real))
# 1.12266267763649940647

I have a C++ reference implementation where complex division agrees with NumPy float division beyond 15 decimal digits. I'd like to use NumPy complex division with the same precision. Is there a way to accomplish that?

A: This seems to work:
import numpy as np

def compl_div(A,B):
    A,B = np.asarray(A),np.asarray(B)
    Ba = np.abs(B)[...,None]
    A = (A[...,None].view(float)/Ba).view(complex)[...,0]
    B = (B.conj()[...,None].view(float)/Ba).view(complex)[...,0]
    return A*B

a = np.random.randn(10000)
b = np.random.randn(10000)
A = a.astype(complex)
B = b.astype(complex)

print((compl_div(A,B)==a/b).all())

print((np.sqrt(b*b)==np.abs(b)).all())

ac = a.view(complex)
bc = b.view(complex)

print(np.allclose(compl_div(ac,bc),ac/bc))

Sample run:
True    # complex without imag exactly equal float
True    # reason it works
True    # for nonzeron imag part do we actually get complex division

Explanation:
Let us write /// for complex by float division (x+iy)///r = x/r + iy/r
numpy seems to implement complex division A/B as A*(1/B) (1/B can be computed as B.conj()///(B.conj()*B)), indeed A/B appears to always equal a*(1/b)
We do instead (A///abs(B)) * (B.conj()///abs(B)) as abs(B)^2 = B*B.conj() this is mathematically, but not numerically, equivalent.
Now, if we had abs(B) == abs(b) then A///abs(B) = a/abs(b) and B///abs(B) = sign(b) and we could see that compl_div(A,B) indeed gives back exactly a/b.
As abs(x+iy) = sqrt(x^2+y^2) we need to show sqrt(b*b) = abs(b). This is provably true unless there is over or underflow in the square or the square is denormal or the implementation does not conform to IEEE.


text:
Q: Mask with Snap.svg first of all here is my simple example on codepen:
http://codepen.io/anon/pen/EVgJwb

    <svg id="drawing">
    </svg>

#slider{
    position: relative;
    width: 80vw;
    height: 80vh;
}
#drawing{
    position:absolute;
    width:100%;
    height:100%;
    left:0;
}

$(document).ready(function(){

var slider_height = $("#slider").height();
var slider_width = $("#slider").width();

var s = Snap("#drawing");

var overlay = s.rect(0,0,slider_width,slider_height).attr({fill:'white',opacity:0.5});

var image = s.image('http://i.imgur.com/4fgQczZ.png', 0, 0, slider_width,slider_height);

});

What I want to do is to subtract the font-image from the overlay, so that the font transforms into transparent. It should be similar like -webkit-mask-image. Is it possible to do that with snap.svg or should I take another framework? I also tested svg.js but I have no clue how to do that.
Anyone can help me?
Thank you very much!


text:
Q: Proper way tho change file associations using VBS? How can I remove or change ALL file associations for certain application ?
For example I have MS office 2007 installed and I want to remove all file associations which are associated with Office package or at least those which are associated with certain exe files from office package.
I need this for various apps not just Office.
Best regards, Primoz

A: Option Explicit
Dim objShell
set objShell = WScript.CreateObject ("WScript.Shell")

'Change this line
addFileAssociation ".txt", "notepad.exe"

Sub addFileAssociation( fileExt, whichApp )
If ( Left(fileExt, 1) <> "." ) Then
fileExt = "." & fileExt
End If
objShell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" & fileExt & "\Application", whichApp
End Sub


text:
Q: Bundling Styles doesn't work, but straight Link tag works In my _Layout page, following works:
<link rel="stylesheet" href="@Url.Content("~/Kendo/Content/kendo/2013.2.918/kendo.common.min.css")"             />
<link rel="stylesheet" href="@Url.Content("~/Kendo/Content/kendo/2013.2.918/kendo.blueopal.min.css")"           />
<link rel="stylesheet" href="@Url.Content("~/Kendo/Content/kendo/2013.2.918/kendo.dataviz.min.css")"            />
<link rel="stylesheet" href="@Url.Content("~/Kendo/Content/kendo/2013.2.918/kendo.dataviz.blueopal.min.css")"   />

This doesn't work (the styles do get applied, however images referenced in the css don't render):

@Styles.Render("~/bundles/kendoStyle")

here's the Bundle def in App_start -> BundleConfig.cs:

        //Kendo Styles:
        bundles.Add(new StyleBundle("~/bundles/kendoStyle").Include(
          "~/Kendo/Content/kendo/2013.2.918/kendo.common.min.css"
        , "~/Kendo/Content/kendo/2013.2.918/kendo.blueopal.min.css"
        , "~/Kendo/Content/kendo/2013.2.918/kendo.dataviz.min.css"
        , "~/Kendo/Content/kendo/2013.2.918/kendo.dataviz.blueopal.min.css"
            //, "~/Kendo/Content/contextMenu.css"
        ));

What am I doing wrong here? (please note, "Kendo" is setup as an mvc4.5 web app under my main website

A: Image paths are relative to the folder in which styesheets are located. For example, an image might be referenced like this:
.k-icon {
  background-image: url('BlueOpal/sprite.png');
}

Because your bundle redefines the path to your stylesheets, the browser attempts to download the image from ~/bundles/BlueOpal/sprite.png, which doesn't exist. The actual path to the image is ~/Kendo/Content/kendo/2013.2.918/BlueOpal/sprite.png.
Everything works fine when you link to your stylesheets directly (without the bundle) because relative paths correctly point to images on your server. However, because your bundle redefines the virtual path in which the stylsheets are located the relative paths to images no longer work.
If you want to use a bundle you must define it with a path that will not break relative image paths in the stylesheets. In your case, since the KendoUI stylesheets are located at ~/Kendo/Content/kendo/2013.2.918, you should define the bundle with that same path:
bundles.Add(new StyleBundle("~/Kendo/Content/kendo/2013.2.918/bundle").Include(
    "~/Kendo/Content/kendo/2013.2.918/kendo.common.min.css",
    "~/Kendo/Content/kendo/2013.2.918/kendo.blueopal.min.css",
    "~/Kendo/Content/kendo/2013.2.918/kendo.dataviz.min.css",
    "~/Kendo/Content/kendo/2013.2.918/kendo.dataviz.blueopal.min.css"
));

I hope that helps.

A: Hi I hat the same problem. but I saw that the page was able to get the sprite file, but does not show some symbols. The temporally solution was set the bundle EnableOptimizations property to false.
BundleTable.EnableOptimizations = False


text:
Q: What App Pool configuration do you recommend for this? I have a website which does convertion of pdfs to word docs. My server is 8GB Quad-Core Opteron.
A conversion can take between 1 seconds for a small pdf file (eg 35kb) to 60 seconds (for pdf files of 5Mb).
I have about 10 requests for conversions per minute with medium files size of pdf being about 1-2 Mb.
I know that for web apps which depends on CPU high usage it's better to have multiple worker processes so I put 5 being maximum. (so a user does not have to wait for others to finish their conversion but can have a process opened for it). I also put PrivateMemoryLimit being about 1GB. Also Request Limit is 500 (to have it recycled from time to time).
Well, sometimes the CPU goes 90-100% or memory goes 70-90%.
Do you have any better configuration proposals for such cases?

A: Check out this TechNet article which lists in table form the default settings for IIS7 and the settings the Microsoft.com team uses on their servers.  This might give you enough to get started with and make a decision on.  They hardly ever recycle their application pools because they need the resources up and running.
Either way, this question doesn't work well for ServerFault because each admin will have their own opinion on how best to configure a server.  There is no wrong answer a lot of the time.  You application is performing CPU and Memory intensive functions in the first place so its not all that surprising the amount of memory and CPU usage you are seeing.  Instead of worrying about the server you may want to investigate your code to make sure you are disposing of objects properly and potentially forcing garbage collection to clear out resources as well.


text:
Q: Is there a way to create a button with corner radius, gradient, and with dynamic shadows? I'm creating a button with corner radius and gradient, but I also want its shadows to react on user press and release. I'm trying out a Container with decoration but no luck since I can't seem to find an onRelease callback. So I'm thinking that I'm on the wrong direction. So is there any way to do this?

A: This button has exactly what I need:
A gradient, rounded corners, dynamic shadows, ripple effectPadding(
                                padding: const EdgeInsets.only(bottom: 50),
                                child: Transform.scale(
                                  scale: btnScale,
                                  child: GestureDetector(
                                    onTapCancel: () {
                                      setState(() {});
                                      btnHeight = 5;
                                      btnScale = 1.0;
                                    },
                                    onTapDown: (loc) {
                                      btnHeight = 0;
                                      btnScale = 0.99;
                                      setState(() {});
                                    },
                                    onTapUp: (loc) {
                                      setState(() {});
                                      btnHeight = 5;
                                      btnScale = 1.0;
                                    },
                                    child: Container(
                                      width: 190,
                                      height: 62,
                                      decoration: BoxDecoration(
                                          boxShadow: [
                                            new BoxShadow(
                                              blurRadius: 4,
                                              color: Colors.black12,
                                              offset: new Offset(
                                                  -btnHeight, btnHeight),
                                            ),
                                            new BoxShadow(
                                              blurRadius: 4,
                                              color: Colors.black12,
                                              offset: new Offset(
                                                  btnHeight, btnHeight),
                                            )
                                          ],
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(100)),
                                          gradient: BtnTeal),
                                      child: Material(
                                        color: Colors.transparent,
                                        child: InkWell(
                                          borderRadius:
                                              (BorderRadius.circular(100)),
                                          onTap: () {},
                                          highlightColor:
                                              const Color(0xFF63DCA0),
                                          splashColor: Colors.teal,
                                          child: Center(
                                            child: Text(
                                              "LOG IN",
                                              style: TextStyle(
                                                fontWeight: FontWeight.bold,
                                                color: Colors.white,
                                                fontSize: 21,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ),