text:
Q: ngStyle background-image I have the following problem. I have a component that has @Input string value that is a link to the image.
In my HTML file I have:

but it's clearly not working (there is an error and page is not rendered at all). What syntax should I use to achieve my goal? I also tried to wrap this into function:
.ts file
  getParallaxImage(){
    return "'url(" + this.parallaxImage + ")'";
  }

.html file

Now, page is rendered but background-image is not set.

A: Try this

or
 getParallaxImage(){
    return "url(" + this.parallaxImage + ")";
  }

Both solutions will work now, use as per your requirements.

A: This should also work:
[style.background-image]="'url(' + parallaxImage + ')'"


text:
Q: Shell script backup routers Below is a script I've wrote to backup my routers and adsl modem, Any ideas to compact this script in less lines?
Each router have a different kind of structure as you can see.
#!/bin/sh
http_txt="10.0.0.59"
cgi="10.0.0.60"
http="10.0.0.66"
date="$(date +%d-%m-%y)"
dest="/home/yamash/"
archive_file="$dest$date.tgz"
local="$dest$date"
login="admin"
pass="PASSWORD"

mkdir $local
cd "$local"
echo "Iniciando Backup"

for http_txt_for in $http_txt; do
    echo "$http_txt_for"
    wget --auth-no-challenge --user=$login --password=$pass $http_txt_for/config.dat -O $http_txt_for.dat
done

for cgi_for in $cgi; do
    echo "$cgi_for"
    wget --user=$login --password=$pass $cgi_for/cgi-bin/export_settings.cgi -O $cgi_for.dat
done

for http_for in $http; do
    echo "$http_for"
    wget --user=$login --password=$pass $http_for/rom-0 -O $http_for
done

cd ..
tar czf $archive_file $local
#rm -R $archive_file $local
echo "Backup Finalizado"

A: Some possibilities:

*

*You don't need to loop if the variable only has a single value.

*Use verbose mode instead of echoing debug information. echos like this are like comments: They aren't code and they may get obsolete. Printing what's actually going on is much more useful for debugging.

*You can use wget --output-document=/path/to/file to avoid cding before wgetting.

*You can use tar -C .. to go to the parent directory before doing the tar operation without cd.

*Why create a directory and a file name with the date? You only need a date indicator in the tarball name. The canonical solution for this sort of thing is to
tmp="$(mktemp -d)"
trap -- 'rm -frv -- "$tmp"' EXIT
cd -- "$tmp"

and store the temporary files there. This also removes the need for the previous two tips.

*If you only need the date once, you can inline $date.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python FLASK get all value from bootstrap select (multiple) I am using the flask web framework to get the values of select.
HTML,

       Add User To Groups:
       <select id = "usergroups" name = "usergroups" class="selectpicker" data-live-search="true" multiple>
        {% for i in range(record_num): %}
        <option value="{{ name[i] }}" data-tokens="{{ name[i] }}">{{ name[i] }}</option>
        {% endfor %}
       </select>

Python Code,
groupnames = request.form.getlist['usergroups']

Output on the browser
I get an internal server error.
AM I MISSING SOMETHING HERE ?

A: reques.form.getlist is function,not a dict:)
Try:
request.form.getlist('usergroups')


text:
Q: Can ios Bluetooth api discover android device? I know, transferring is restricted and i do not need that. Also, i'm aware of BLE capabilities. However, ~35% of android devices out there do not support peripheral mode.
If someone ever tried this, could you tell me: does ios BT api allow to discover android devices? I need only mac (or whatever it called) address from android device, nothing else.

A: iOS (CoreBluetooth) can discover any Android BLE device as long as it supports the Peripheral role. If your Android device does not support Peripheral role then the iOS device needs to be the Peripheral in your connection scenario.
If you want to use Bluetooth Classic, that is a completely different story because in order to use Bluetooth Classic on iOS you need to be member of Apple's MFI program that comes with extra fees and an NDA.


text:
Q: Manage/Limit Internet Bandwidth on Specific Wireless Network I offer wireless internet to my tenant and the problem I have is we are constantly hitting the cap for the monthly internet usage. What I ideally would like to do is create 2 wireless networks: one for the tenant and one for me. Then apply a limit on the monthly data usage download/upload for the tenant network say 100 GB. However, I don't want that limitation for myself. What is the best way to achieve that? Is there a home router that can do that?

A: One of the easiest way to do this is by using Routerboard/Mikrotik devices.
You can have virtual APs (different SSIDs & WPA2 PSKs) with a single device/AP and apply whatever QoS and/or Traffic Shaping (among tons of other things) you need by using the extremely intuitive winbox interface. You can set up very complicated stuff in a matter of a few clicks.
Routerboard devices come with Mikrotik pre-installed and it's included in the price (some models are even cheaper than the license itself - so it's a good deal generally given the features that both the hardware and software provide).
Keep in mind that by using 1 physical AP with a virtual AP to separate the network for your tenant you may have strange issues with the Hidden Node Problem on WiFi networks.
It's certainly better in terms of performance to use 2 different APs. You can get a routerboard to use as an AP for you and connect your existing AP on one of the ethernet ports of the Routerboard and apply your QoS rules on that ethernet interface.
You can find out about available Routerboard models here
Of-course you can always install OpenWRT as well on those devices in case you don't like Mikrotik RouterOS.

A: Some routers can do this, or can be enabled to do this by installing new firmware such as DD-WRT:
https://en.wikipedia.org/wiki/DD-WRT#Features
There is a paid version of the DD-WRT firmware which has exactly the feature you're looking for, however it may be possible to accomplish the same thing for free using a bit of script hacking as explained here:
http://www.kczon.com/ddwrt-how-to-set-bandwidth-limit-to-each-users-router/
Of course all of that depends on whether the firmware is compatible with your router in the first place. But it's something worth investigating.

A: You would need to get two wireless access points or purchase enterprise class hardware. With two AP/Routers you could have one (or both) filtered through squid & a tunnel but the config is not super strait forward since you're trying to cap at a max amount over time instead of given throughput.
There is a decent chance someone else has already written software to do this for you automatically but I'm unfamiliar with any.


text:
Q: Saving file java Because the File object constructor needs a String to represent the path and considering other reasons, I chose to make a temporary file and when the user wants to save, to take the content of the temporary to the final file and ask the user to give the path at that time.
I have some code I will explain, but for many reasons, I think it's not one of the best solutions to do what I am trying to do.
public String FileSavePath() throws NullPointerException {

        boolean acceptable = false;
        String theFilepath = null;

        do {
            theFilepath = null;
            File f = null;
            JFileChooser FileChooser = new JFileChooser();
            if (FileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                theFilepath = FileChooser.getSelectedFile().getAbsolutePath();
                f = FileChooser.getSelectedFile();
                //System.out.println(theFile);
                if (f.exists()) {
                    int result = JOptionPane.showConfirmDialog(this, "The file exists, overwrite?",
                            "Existing file", JOptionPane.YES_NO_CANCEL_OPTION);
                    if (result == JOptionPane.YES_OPTION) {
                        acceptable = true;
                    }

                }
            } else {
                acceptable = true;
            }
        } while (!acceptable);
        saved=true;
        return theFilepath;

    }

And the method is called in the save function this way:
    FileChannel sourceChannel=null;
    FileChannel targetChannel=null;

                try
                {
                    try{
                        file=new File(FileSavePath());
                    }
                    catch(NullPointerException npe)
                    {
                        System.exit(0);
                    }
                    sourceChannel = new FileInputStream(temp).getChannel();
                    targetChannel = new FileOutputStream(file).getChannel();
                    targetChannel.transferFrom(sourceChannel, 0,
                            sourceChannel.size());
                }
                catch(IOException ioe)
                {
                    System.out.println(ioe.getMessage());
                }

                finally
                {

                    try {
                        if (sourceChannel != null) {
                            sourceChannel.close();
                        }
                        if (targetChannel != null) {
                            targetChannel.close();
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                }

Basically the mechanism is the following: All the data is saved to a temporary file. When the user wants to save, a JFileChooser appears and saves the path. Then the final file is iniatialized, the temporary data passed to the final file and that's it. The NPE is important to handle if the user did not chose a valid path or cancelled somewhere during the
What I am not sure of is if my code is efficent or if there were any ways to make it better.
P.S. Please don't bother telling that the exceptions are not handled yet, I know this, but I want to know if the basic idea would efficently do what is should.


text:
Q: Need a fast method to convert large amount of double to string I am writing a results output module for a high speed computing program.
My plan is:

*

*My task is to insert the results into database (PostgreSQL) with relative fast speed.

*I use [COPY FROM STDIN] of libpq, which I was told as the fastest way.

*The method requires converting the results into char* format.

While the results looks like this:

*

*Monthly CashFlow for next 106 years (1272 double in Total).

*Around 14 CashFlows for each entiry.

*Around 2800 entities (2790 for tested data).

And the table in database looks like this:

*

*Each row of the table contains one entity.

*There are some prefix to identify different entities.

*CashFlows are double array that follows the prefix (float8[] type in PGSQL).

The following present the code for creating the table in database:
create table AgentCF(
PlanID     int4,
Agent      int4,
Senario    int4,
RM_Prev    float8[], DrvFac_Cur float8[], Prem       float8[],
Comm       float8[], CommOR     float8[], FixExp     float8[],
VarExp     float8[], CIRCFee    float8[], SaftyFund  float8[],
Surr       float8[], Benefit_1  float8[], Benefit_2  float8[],
Benefit_3  float8[], Benefit_4  float8[], Benefit_5  float8[],
Benefit_6  float8[], Benefit_7  float8[], Benefit_8  float8[],
Benefit_9  float8[], Benefit_10 float8[]
);

Presenting code for function that prepare the inserted CashFlow:
void AsmbCF(char *buffer, int size, int ProdNo, int i, int Pos, int LineEnd)
{
    int     j, Step = sizeof(nodecf) / sizeof(double), PosST, Temp;
    double *LoopRate = &AllHeap[ProdNo].Heap.AgentRes[i].CF.NodeCF[0].Prem;
    strcpy_s(buffer, size, "{");
    for (j = 0; j < TOTLEN / 10; j++) {
        PosST = j * 10 * Step + Pos;
        sprintf_s(&buffer[strlen(buffer)], size - strlen(buffer), "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,",
            LoopRate[PosST],
            LoopRate[PosST + 1 * Step],
            LoopRate[PosST + 2 * Step],
            LoopRate[PosST + 3 * Step],
            LoopRate[PosST + 4 * Step],
            LoopRate[PosST + 5 * Step],
            LoopRate[PosST + 6 * Step],
            LoopRate[PosST + 7 * Step],
            LoopRate[PosST + 8 * Step],
            LoopRate[PosST + 9 * Step]
        );
    }
    Temp = j * 10;
    PosST = Temp * Step + Pos;
    sprintf_s(&buffer[strlen(buffer)], size - strlen(buffer), "%f", LoopRate[PosST]);
    Temp = Temp + 1;
    for (j = Temp; j < TOTLEN; j++) {
        PosST = j * Step + Pos;
        sprintf_s(&buffer[strlen(buffer)], size - strlen(buffer), ",%f", LoopRate[PosST]);
    }
    if (LineEnd) {
        strcat_s(buffer, size, "}\n");
    }
    else {
        strcat_s(buffer, size, "}\t");
    }
}

The following are the code for speed testing:
void ThreadOutP(LPVOID pM)
{
    char       *buffer = malloc(BUFFLEN), sql[SQLLEN];
    int         Status, ProdNo = (int)pM, i, j, ben;
    PGconn     *conn = NULL;
    PGresult   *res;
    clock_t     begin, end;

    fprintf_s(fpOutP, "PlanID %d Start inseting...\n", AllHeap[ProdNo].PlanID);
    begin = clock();
    DBConn(&conn, CONNSTR, fpOutP);

#pragma region General cashflow
    //============================== Data Query ==============================
    //strcpy_s(&sql[0], SQLLEN, "COPY AgentCF(PlanID,Agent,Senario,Prem,Comm,CommOR,CIRCFee,SaftyFund,FixExp,VarExp,Surr");
    //for (ben = 1; ben <= AllHeap[ProdNo].Heap.TotNo.NoBenft; ben++) {
    //  strcat_s(&sql[0], SQLLEN, ",Benefit_");
    //  _itoa_s(ben, &sql[strlen(sql)], sizeof(sql) - strlen(sql), 10);
    //}
    //strcat_s(&sql[0], SQLLEN, ") FROM STDIN;");
    //res = PQexec(conn, &sql[0]);
    //if (PQresultStatus(res) != PGRES_COPY_IN) {
    //  fprintf_s(fpOutP, "Not in COPY_IN mode\n");
    //}
    //PQclear(res);
    //============================== Data Apply ==============================
    for (i = 0; i < AllHeap[ProdNo].MaxAgntPos + AllHeap[ProdNo].Heap.TotNo.NoSensi; i++) {
        sprintf_s(buffer, BUFFLEN, "%d\t%d\t%d\t", AllHeap[ProdNo].PlanID, AllHeap[ProdNo].Heap.AgentRes[i].Agent, AllHeap[ProdNo].Heap.AgentRes[i].Sensi);
        //Status = PQputCopyData(conn, buffer, (int)strlen(buffer));
        //if (1 != Status) {
        //  fprintf_s(fpOutP, "PlanID %d inserting error for agent %d\n", AllHeap[ProdNo].PlanID, AllHeap[ProdNo].Heap.AgentRes[i].Agent);
        //}
        for (j = 0; j < 8 + AllHeap[ProdNo].Heap.TotNo.NoBenft; j++) {
            if (j == 7 + AllHeap[ProdNo].Heap.TotNo.NoBenft) {
                AsmbCF(buffer, BUFFLEN, ProdNo, i, j, 1);
            }
            else {
                AsmbCF(buffer, BUFFLEN, ProdNo, i, j, 0);
            }
            //Status = PQputCopyData(conn, buffer, (int)strlen(buffer));
            //if (1 != Status) {
            //  fprintf_s(fpOutP, "PlanID %d inserting error for agent %d\n", AllHeap[ProdNo].PlanID, AllHeap[ProdNo].Heap.AgentRes[i].Agent);
            //}
        }
    }
    //Status = PQputCopyEnd(conn, NULL);
#pragma endregion

#pragma region K cashflow

#pragma endregion

    PQfinish(conn);
    FreeProd(ProdNo);
    free(buffer);
    end = clock();
    fprintf_s(fpOutP, "PlanID %d inserted, total %d rows inserted, %d millisecond cost\n", AllHeap[ProdNo].PlanID, i, end - begin);
    AllHeap[ProdNo].Printed = 1;
}

Please note that I disable the code that involving inserting.
The tested results are:

*

*Cost of only assembling the string is 45930 millisecond.

*Cost of assembling the string and insert is 54829 millisecond.

So the most of the cost lie on converting double to char.
Therefore I would like to ask if there is a faster way of converting series of double into string, because compare to the calculation cost, the bottleneck actually is the outputting of results.
By the way, my platform is Windows 10, PostgreSQL 11, Visual Studio 2017.
Thanks a lot!

A: There are actually several faster methods for accurately representing floating point numbers as strings, one of them is Grisu, by Florian Loitsch.
This github repo compares several algorithms in C and C++, and it contains the source code for the Grisu2 method in C, which he claims to be 5.7x faster than sprintf.
However, the author of the same repo (Milo Yip) provides his own C++ single header implementation which is claimed to be 9.1x faster, presumably since more of the functions are completely inlined. I believe porting this code to C should be trivial, since it doesn't use any special C++ syntax.

A: I did some bookkeeping on the original code:

  Total score("function" calls):
    2 + 4*TOTLEN * strlen()
    1 + 2*TOTLEN * sprintf()
    1 * strcat()

  Estimated string() cost:
    3 + 4* size * (TOTLEN*TOTLEN) / 2 (measured in characters)

  Estimated sprintf() cost:
    2 * TOTLEN (measured in %lf conversions)
    2 * size (measured in characters)

Now, I dont know what TOTLEN is, but calling strlen() and friends on a ever growing string results in quadratic behaviour, see https://en.wikipedia.org/wiki/Joel_Spolsky#Schlemiel_the_Painter.27s_algorithm

*

*profile/measure (or think) before you optimise

*snprintf() , when used correctly, is overflow-safe; read the manual page and use the return value

*the strxxx_x() functions are nearly useless, they only exist to please the PHBs

A:
fast method to convert large amount of double to string

For full double range application, use sprintf(buf, "%a", some_double).  If decimal output required, use "%e".
Any other code will only be faster if it is comprises accuracy or allowable input range somehow.
The usual approach is to convert double x to some wide scaled integer and convert that to a string.  This implies limitations on x not clearly expressed yet by OP.
Even if some other approaches appears faster, it may not be faster as code evolves or is ported.

What OP needs to post is speed test code for objective performance assessment.

A: Alternative to chux's answer, I made the following function:
__inline char* dbltoa(char* buff, double A, int Precision)
{
    int     Temp;
    char   *ptr;

    Temp = (int)A;
    _itoa_s(Temp, buff, 50, 10);
    ptr = buff + strlen(buff);
    ptr[0] = '.';
    Temp = (int)((A - Temp) * pow(10, Precision));
    _itoa_s(Temp, ptr + 1, 50, 10);
    return ptr + strlen(ptr);
}

And updated the function that make the CashFlow string:
void AsmbCF(char *buffer, int size, int ProdNo, int i, int Pos, int LineEnd)
{
    int     j, Step = sizeof(nodecf) / sizeof(double), PosST, Temp;
    double *LoopRate = &AllHeap[ProdNo].Heap.AgentRes[i].CF.NodeCF[0].Prem;
    char   *ptr;
    strcpy_s(buffer, size, "{");
    ptr = buffer + 1;
    for (j = 0; j < TOTLEN; j++) {
        PosST = j * Step + Pos;
        ptr = dbltoa(ptr, LoopRate[PosST], 8);
        ptr[0] = ',';
        ptr++;
    }
    ptr[-1] = 0;
    if (LineEnd) {
        strcat_s(buffer, size, "}\n");
    }
    else {
        strcat_s(buffer, size, "}\t");
    }
}

The tested result without insert is 4558 millisecond, while with insert tooks 29260 millisecond (probably parallel running of the database made this nonequivalent by ratio).


text:
Q: Preservation of universes in presheaves In Lifting Grothendieck universes Hofmann and Streicher construct a universe in the category of presheaves over a small category given a Grothendieck universe in $\mathbf{Set}$.
Suppose now I have two small categories $\mathbb{C}$ and $\mathbb{D}$, a functor $\mathfrak{f} : \mathbf{Set}^{\mathbb{C}} \to \mathbf{Set}^{\mathbb{D}}$ and a universe $u : E \to V$ in $\mathbf{Set}^{\mathbb{C}}$ that is closed under the formation of dependent products, sums and W-types.
What conditions on $\mathfrak{f}$ are sufficient to ensure that $\mathfrak{f}(u) : \mathfrak{f}(E) \to \mathfrak{f}(V)$ is a universe in $\mathbf{Set}^{\mathbb{D}}$ that is closed under the same constructions?
I am mostly interested in the case where $\mathbb{C}$ and $\mathbb{D}$ are posets, if this makes anything easier.


text:
Q: How would I extract the second lowest value of a particular column of a table? var rowText = $('tbody tr:eq(2) td:eq(2)').map(function() {
return $(this).text();
}).get()[0];

window.alert(rowText);

http://jsfiddle.net/pcxx9dyy/2/
I'm specifically looking to extract the lowest price on the marketplace of an item excluding the NPC's one.
The rows are always sorted, but sometimes there are zero NPC Shop records.

A: If this table is always sorted INCR and first row always has NPC Shop records, then just fix your code like that:
$('tbody tr:eq(2) td:eq(1)')

And it works.
But if rows can be unsorted, and there might be more than one, or even zero NPC Shop records, then you need more complex algo.
Update
Here is the code for "unsorted" and "any number of NPC shop records": JSFiddle
Code:
var price = null;
$("tbody tr").each(function(i,e){
    var $col1 = $(e).find("td:eq(0)"),$col2 = $(e).find("td:eq(1)");
    if ($col1.html().indexOf("NPC")===-1) {
        var rowPrice = parseFloat($col2.html().replace(",","."));
        if (!price || price.price>rowPrice)
            price = {
                name:$col1.find("a").html(),
                price: rowPrice
            };
    }
});

alert("Min price is:"+price.price+" from "+price.name);


text:
Q: ADB commands in code Is there a way to run adb commands like

adb get-state

in the code I write in eclipse
For e.g.
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    testADB();
}

and in testADB() run some adb commands?

A: Adithya , I believe you are trying to drop adb commands programmatically.Check this link.

A: Not literally, due to permissions and the security model.  The usb adb daemon on a consumer phone runs with slightly higher privileges than ordinary applications, so accepting commands from them would be a security hole.
However as others have pointed out, there may be alternative means to obtain some kinds of data.

A: You can probably use some of the classes in ddmlib.jar for that.


text:
Q: Using Project Oxford's Emotion API I came across Project Oxford and became really interested in it and using its API, specifically the emotion one. Microsoft provides sample code
########### Python 2.7 #############
import httplib, urllib, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': 'add key',

}

params = urllib.urlencode({
    # Request parameters
    'faceRectangles': '{string}',

})

try:
    conn = httplib.HTTPSConnection('api.projectoxford.ai')
    conn.request("POST", "/emotion/v1.0/recognize&%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()

except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

This doesn't contain the request body. I thought all I need to add was
body = {
    'url': 'url here',
}

and change
   conn.request("POST", "/emotion/v1.0/recognize&%s" % params, "{body}",headers)

to
conn.request("POST", "/emotion/v1.0/recognize&%s" % params, body, headers)

However that isn't working. I am getting this when I run it
Traceback (most recent call last):
File "C:/Users/User/Desktop/python/emotion.py", line 29, in <module>
print("[Errno {0}] {1}".format(e.errno, e.strerror))
AttributeError: 'exceptions.TypeError' object has no attribute 'errno'

Any help is much appreciated!

A: You need to pass str(body) to the request.
Also, make sure to not include params if you don't have any face rectangles.

A: The following works for me (Python 2.7), also based on the sample code provided by MSDN. You don't need to specify faceRectangles (unless you want to because they've already been detected, to save compute time).
import httplib, urllib, base64

# Image to analyse (body of the request)

body = '{\'URL\': \'https://<path to image>.jpg\'}'

# API request for Emotion Detection

headers = {
   'Content-type': 'application/json',
}

params = urllib.urlencode({
   'subscription-key': '',  # Enter EMOTION API key
   #'faceRectangles': '',
})

try:
   conn = httplib.HTTPSConnection('api.projectoxford.ai')
   conn.request("POST", "/emotion/v1.0/recognize?%s" % params, body , headers)
   response = conn.getresponse()
   print("Send request")

   data = response.read()
   print(data)
   conn.close()
except Exception as e:
   print("[Errno {0}] {1}".format(e.errno, e.strerror))


text:
Q: Get Job step run for all jobs and job steps using TSQL I was wondering if there is an easy way to check the "Run as" value for each job step using TSQL code instead of opening every job on the server and each individual step? I cannot figure out where to get this data from and I have scoured the MSDB in search of this but cant find anything in the sysjobs and related tables? SQL has to store this value somewhere. The question is where?

A: This should get you close, if NULL for ProxyName then it's using the SQL Server Agent credentials.
USE msdb

SELECT J.job_id
    , J.name
    , S.step_name
    , S.step_id
    , P.name AS ProxyName
    , SP.name AS CredentialUserName
    , SP.type_desc AS CredentialUserType
FROM msdb.dbo.sysjobs J
    INNER JOIN msdb.dbo.sysjobsteps S ON S.job_id = J.job_id
    LEFT OUTER JOIN msdb.dbo.sysproxies P ON P.proxy_id = S.proxy_id
    LEFT OUTER JOIN sys.server_principals SP ON SP.sid = P.user_sid


text:
Q: The points of a segment contained in a surface are parabolic Let $S\subseteq\mathbb{R}^3$ be a regular surface and let $p$ be a point of $S$.
If $p$ lies in a segment contained in $S$ show that $p$ is either parabolic or planar.
Well, I think that an idea is to show that the differential of the Gauss map is zero if calculated on a tangent vector parallel to the segment, but I don't know how to formalize it...

A: The statement is false. The hyperbolic paraboloid $z=x^2-y^2$ has negative curvature at $p=(0,0,0)$ even though $p$ lies on two lines contained in the surface: $y=\pm x, z=0$. More generally, there are lots of ruled surfaces.
It is correct that $K\le 0$ at such a point.


text:
Q: Commit button greyed out when merging in VSCode Since today, when doing a merge, the "Commit" button in VSCode is greyed out for me (see below screenshot). Committing via the command line works just fine, so it seems to be a VSCode issue.
Note that this is specific to committing a merge. Committing code normally still works fine.
VSCode Version: 1.72.0 on Mac
Anybody else got the same issue?

A: Update: the issue has since been closed as of the second recovery update for September 2022, presumably the bug has been fixed.

There is an open issue on the Visual Studio Code repository that seems similar, although the user reported it occurs after resolving a merge conflict (though I don't think that is actually relevant, it seems to just be for merges in general based off the commit to fix it).
This seems to be a regression that is slated to be addressed in the recovery update:

Apologies for the inconvenience. This is a recent regression and will be fix in our recovery release later this week.

This is the actual change that was made for this.  Thus, the recovery update for 1.72 should fix this.


text:
Q: How can I get better at TDD im a beginner I'm trying to learn how to write Test driven development and want to get good at it. I'm currently looking some practice on google and found this one but I don't know how to make this test pass.
Here is the test code add-one.test.js:
var addOne = require("./add-one.js");

test("Add 1 to each item in myArray", function () {
  var myArray = [31, 57, 12, 5];

  var unchanged = [31, 57, 12, 5];
  var expected = [32, 58, 13, 6];
  var output = addOne(myArray);

  expect(output).toEqual(expected);
  expect(myArray).toEqual(unchanged);
});

add-one.js:
module.exports = function(numbers) {};

A: What normally happens in TDD is that we do the work in two steps.  First, we prove that our test is working (by introducing a trivial change to the test subject that passes the test) and then we clean up the test subject until the code is not embarrassing.
return [32, 58, 13, 6]

Mark is exactly right that we can make the test pass that easily.  We won't keep the code in that shape forever, but for now it gives us a starting point.
In some cases, we'll introduce a change in behavior behind a "guard clause" first, so that we can get an easy pass without breaking any other code
   if numbers[0]== 31 && ... && numbers[3] == 5 {
      return [32, 58, 13, 6]
   }

Having done this, we're now in a situation where all of our tests are passing.  So our goal is to clean up the code without breaking any of the tests.
"Remove duplication" is one of the themes of the changes that we make.  In this example, there's a bunch of duplication between our input and our output.
return [31 + 1, 57 + 1, 12 + 1, 5 + 1]

return [numbers[0] + 1, numbers[1] + 1, numbers[2] + 1, numbers[3]+1]

return numbers.map(n => n+1)

Small steps shown here just to show how you might tease out the duplication in this case.  You don't have to use the smallest possible steps every time; it's sometimes a useful skill to have.
Jumping straight to the form with the duplication already removed is OK too, if you can see it right away.
TDD is just a ritual for ensuring that your code is under your control.  It doesn't actually tell you what changes to the code you should make.  That comes from practicing design (and also learning what language/library features are available).


text:
Q: Are holomorphic functions between Riemann surfaces continuous? From differential topology, we know that every smooth map between smooth manifolds is continuous. But for the definition of holomorphic functions between Riemann surfaces as follows

I do not think that the map is guaranteed to be continuous since it does not have the critical condition that $f(U_n) \subset V_m$.

A: This is a subtle point that many authors overlook.
It depends on precisely what you mean by saying that a function $f$ defined on an arbitrary subset $A\subset \mathbb C$ is analytic. One common definition is that the domain $A$ must be an open subset of $\mathbb C$ and $f$ has a complex derivative everywhere in $A$ (or is given locally by convergent power series). Using this definition, saying that $g_m\circ f \circ f_n^{-1}\colon f_n (U_n \cap f^{-1}(V_m))\to g_m(f(U_n)\cap V_m)$ is analytic includes the tacit requirement that $ f_n (U_n \cap f^{-1}(V_m))$ is open in $\mathbb C$ for each $m$ and $n$. Using this interpretation, if $f\colon S_1\to S_2$ is analytic according to the quoted definition, then it is automatically continuous.
To see why, let $p\in S_1$ be arbitrary. There exist charts $U_n$ containing $p$ and $V_m$ containing $f(p)$, and then
$$
f_n (U_n \cap f^{-1}(V_m)) \text{ is open in $\mathbb C$}
\implies
U_n \cap f^{-1}(V_m)\text{ is open in $S_1$}
$$
(because $f_n$ is a homeomorphism onto its image). Restricted to the open set $U_n \cap f^{-1}(V_m)$, $f$ is given by the formula
$$
f= g_m^{-1} \circ \big( g_m \circ f \circ f_n^{-1}\big) \circ f_n^{-1},
$$
which is a composition of continuous maps. Thus $f$ is continuous in a neighborhood of each point, and hence continuous on $S_1$.
If, on the other hand, your interpretation of "analytic on a subset of $\mathbb C$" does not necessarily entail being defined on an open subset, then an analytic map by this definition might not be smooth. For example, one might define a function $f$ to be analytic on a subset $A\subset\mathbb C$ if each point of $A$ has a neighborhood $U$ in $\mathbb C$ such that $f$ is equal to a convergent power series on $U\cap A$.
Using this interpretation, a function $f\colon S_1\to S_2$ that is analytic by the quoted definition need not be continuous. Here's a counterexample. Let $S_1 = S_2  = \mathbb C$, with the analytic structure given by, say, the countable collection of disks with rational centers and radius $1/2$, and with $f_n$ and $g_m$ the respective identity maps. Define $f\colon S_1\to S_2$ by
$$
f(z) = \begin{cases}
1, & \operatorname{Re}z\ge 0,\\
0, & \operatorname{Re}z <0.
\end{cases}
$$
Then for each $m$ and $n$ for which $U_n \cap f^{-1}(V_m)\ne\varnothing$, the composite map $g_m\circ f \circ f_n^{-1}$ is either identically $0$ or identically $1$ (but not always defined on an open set), so it is analytic by our broader definition. But $f$ is not continuous.


text:
Q: How to import CSV to SQL and insert file name to the last column? I have many CSV files and I want to import them to MyTable using BULK INSERT. Each time I import a new file I want to insert to last column 'ColumnNameWithFileName' the name of the file. The files are named like file01.csv, file02.csv etc.
When I try to use BULK INSERT while importing second file I get truncation error. Probably because the CSV table does not fit MyTable where already is additional column. How to handle this?
-- Add a column 'ColumnNameWithFileName' This code done only once
ALTER TABLE dbo.MyTable
ADD ColumnNameWithFileName VARCHAR(20) NULL
DECLARE CSVFileName VARCHAR(20)
-- Bulk insert from CSV file
Bulk insert dbo.[MyTable]
from 'C:\file01.CSV' with (
    fieldterminator =';'
    ,rowterminator='\n'
    ,FIRSTROW=2
    ,CODEPAGE ='ACP')
-- Insert to new column file name
UPDATE dbo.MyTable SET ColumnNameWithFileName = CSVFileName
WHERE ColumnNameWithFileName IS NULL

A: Use a variable for the file name (and file path if you want) and bulk insert into a #temp table, then INSERT INTO final table with an additional column that will have the file path.
declare @filename varchar(255)
set @filename = file.csv
CREATE TABLE #Temp
BULK INSERT #Temp
from 'C:\file01.CSV' with (
    fieldterminator =';'
    ,rowterminator='\n'
    ,FIRSTROW=2
    ,CODEPAGE ='ACP')
insert into [REALFINALTABLE]
select #temp.*, @filename as [FileName] from #Temp
--Drop #Temp (In case is not necesary any more)

A: There may be a more elegant way to do it, but you could just do this;

*

*import your data from the file into a temporary table

*select *,FileName into YourTable

*truncate your temp table

*process next file


text:
Q: untangling .h dependencies What do you do when you have a set of .h files that has fallen victim to the classic 'gordian knot' situation, where to #include one .h means you end up including almost the entire lot?  Prevention is clearly the best medicine, but what do you do when this has happened before the vendor (!) has shipped the library?
Here's an extension to the question, and this is probably the more pertinent question -- should you even attempt to disentangle the dependencies in the first place?;

A: I've done this on a C++ code base that was already split into many libraries (which was a good start).
I had to workout (or guess) which library was the most depended upon, which depended upon nothing else in the code base.  I then processed each library in turn.
I looked at each module (*.cpp files) in turn and made sure that its own header was #included first and commented out the rest, then I commented out all the #includes in that header file and then re-compiled just that module to let the compiler tell me what was needed.  I would un-comment the first header that seemed to be needed, and reviewed that one, recursing as necessary.  It was interesting to see how many headers ended up not being needed.
Where only the name is needed (because you have a pointer or reference) use class name; or struct name;, which is called forward declaration and avoid #including the header file.
The compiler is very helpful in telling you what the dependencies are when you comment out #includes (you need to recompile with ALL the compilers you have to maintain portability).
Sometimes I had to move modules between libraries so that no pairs or groups of libraries were mutually dependant.

A: As you have the opportunity, you should refactor the code to reduce includes that are too large, however that assumes you can achieve some sort of package cohesion.  If you disentangle things just to discover that every user of the code has to include all the elements anyway, the end result is the same.
Another option is to use #defines to configure sections on and off.  Regardless, for an existing code base the solution is to move toward package cohesion.
Read: http://ivanov.files.wordpress.com/2007/02/sedpackages.pdf and research issues related to package cohesion.

A: I've untangled that knot a few times, and it generally helps a lot when maintaining a system to reduce the .h dependencies as much as possible. There are decent tools for generating dependency trees ( I was using Klocwork at the time ).
The downside I found was with conditional compilation. Someone might remove a header file because they think we don't need it, but it turns out that we only don't need it because VxWorks has some screwed up headers... on Solaris (or any reasonable Posix system) you do need it.

A: There is a balance to be struck between an enormous number of finely organized headers and a single header that includes everything.  Consider the Standard C library; there are some biggish headers like <stdio.h>, which declares a lot of functions, but they are all related to I/O.  There are other headers that are more of a miscellany - notably <stdlib.h>.
The Goddard Space Flight Center guidelines for C are worth hunting down.
The basic rule is that each header should declare the facilities provided by a suitable (usually small) set of source files.  The facilities and header should be self-contained.  That is, if someone needs the code in header "something.h", then that should be the only header that must be added to the compilation.  If there are facilities needed by "something.h" that are not declared in the header, then it must include the relevant headers.  That can mean that headers end up including <stddef.h> because one of the functions uses size_t, for example.
As @quamrana points out, you can use forward declarations for structures (not classes, since the question is tagged C and not C++) when appropriate - which primarily means when the interface takes pointers and does not need to know the size of the structures or any of the members.


text:
Q: How to add values from another DataFrame onto rows where a column matches? I have two DataFrames:
a = pd.DataFrame()
a['id'] = range(0,100)
a['N'] = 100

b = pd.DataFrame()
b['id'] = 3*np.arange(0,100)
b['N'] = 50

What I want to do, is for rows in a where the 'id' matches the 'id' of a row in b to add b['N']. With a very inefficient and poorly-coded for-loop, that would be something like:
for idx in a[a.id.isin(b.id)].index:
    a.loc[idx, 'N'] = a.loc[idx, 'N'] + b.loc[b.id == a.loc[idx, 'id'], 'N'].iloc[0]

Is there a way to do the above, but with efficient DataFrame operations? For example, a better way might be to take only the rows in a and b that have matching 'id', sort them both by ascending (so that they are the same exact ids in the same order), and then just add the 'N' column. This would require us to select the rows, sort them, add them, and finally concatenate back into the rows of a that didn't have matching 'id' in b, but also seems inefficient. What is the recommended way of doing this in pandas/numpy

A: IIUC you can simply do a merge and then sum:
a = a.merge(b,on="id",how="left")
a["result"] = a[["N_x","N_y"]].sum(1)

print (a)

    id  N_x   N_y  result
0    0  100  50.0   150.0
1    1  100   NaN   100.0
2    2  100   NaN   100.0
3    3  100  50.0   150.0
4    4  100   NaN   100.0
..  ..  ...   ...     ...
95  95  100   NaN   100.0
96  96  100  50.0   150.0
97  97  100   NaN   100.0
98  98  100   NaN   100.0
99  99  100  50.0   150.0

A: Assuming "id" is unique, you can use Series.map and add the mapped values:
a['N'] = a['N'].add(a['id'].map(b.set_index('id')['N']), fill_value=0)

a
    id      N
0    0  150.0
1    1  100.0
2    2  100.0
3    3  150.0
4    4  100.0
..  ..    ...
95  95  100.0
96  96  150.0
97  97  100.0
98  98  100.0
99  99  150.0

[100 rows x 2 columns]


text:
Q: How to get Java model object back from String object? I have a model class:
public class Person{
    private String personnelId;
    private String lastName;
    private String firstName;
}

Now I have service class
public class A{
    @Autowired
    private OfficerService officer;

    public List<Person> getAccounts(Param param){
        List<Person> personList = personDao.getAccounts(param);
        List<String> stringList = personList.stream().map(Person::getPersonnelId).collect(Collectors.toList());
        List<String> list = Officer.getVisiblePerson(stringList);
        List<Person> visiblePersonList= new ArrayList<>();

        return visiblePersonList;
    }

Now when I convert List<Person> into List<String> which gets the personnelId from Model class. After the method call I get back personnelId. I need to convert back into List<Person> which will contain all the data with firstName and lastName in Person class attached to that Id. How can I do that?
EDIT:
Map<String, Person> personMap = personList.stream()
        .collect(Collectors.toMap(Person::getPersonnelId, person -> person));
    List<Person> visiblePersonList = list.stream()
        .map(id -> personMap.get(id))
        .collect(Collectors.toList());

I get an error on collect of map:
The method collect(Collector<? super String,A,R>) in the type Stream<String> is not applicable for the arguments (Collector<Person,capture#2-of ?,Map<String,Object>>)

What am i doing wrong?

A: One way to will be to have it in a map and then get these values from a map. There is one additional iteration , but depending on how big the list is or if it can be parallel , performance will be slightly more or less.
public static void main(String[] args) throws Exception {
    List<Person> personList = new ArrayList<Person>(); // personDao.getAccounts(param);

    Person person1 = new Person("1", "ln1", "fn1");
    Person person2 = new Person("2", "ln2", "fn2");
    Person person3 = new Person("3", "ln3", "fn3");
    Person person4 = new Person("4", "ln4", "fn4");
    personList.add(person1);
    personList.add(person2);
    personList.add(person3);
    personList.add(person4);

/*Of interest , the logic*/
        List<String> stringList = personList.stream().map(Person::getPersonnelId).collect(Collectors.toList());
        Map<String, Person> mapStringToPerson = personList.stream()
                .collect(Collectors.toMap(Person::getPersonnelId, person -> person));

/*as a logic filter even number id , in a real life this will be officer filter*/
            List<String> listFiltered = stringList.stream().filter(personId -> (Integer.parseInt(personId) % 2 == 0))
                    .collect(Collectors.toList());// Officer.getVisiblePerson(stringList);
            List<Person> visiblePersonList = listFiltered.stream().filter(id -> mapStringToPerson.containsKey(id))
                    .map(id -> mapStringToPerson.get(id)).collect(Collectors.toList());
            visiblePersonList.forEach(System.out::println);

}

Prints ::
    Person with id : 2 and name fn2 ln2
    Person with id : 4 and name fn4 ln4

A: First, let me address some naming issues:

*

*Officer should be officer.

*stringList should be named idList, since that's what it contains, conceptually. You don't name it for the type, because:

*

*You can see that by looking at ... (you guessed it) ... the type.

*Saying "String" is meaningless and says nothing about what the string represents.

*Similarly, list should be named visibleIdList.
Now I'll use the name I just suggested.
Since getVisiblePerson() returns a list of the entries from idList that are visible, i.e. a filtered list, you can do one of two things:

*

*Create Map<String, Person> of id to Person, then iterate visibleIdList and lookup the Person and build a list of that.

*Turn visibleIdList into a visibleIdSet, then iterate personList and filter to those in the Set.
Option 2 has a smaller memory footprint, and likely better performance too.


text:
Q: How to unproxy a collection of entities in Hibernate? I have a JPQL query like this
select e from department d join d.employee d where d.id = :departmentId

Unfortunately this returns a ... proxy which is a Proxy-List of ByteBuddyInterceptor?
I tried to unproxy like
(List<Employee>) Hibernate.unproxy(department.getEmployees())

Unfortunately this is not working and I would like to get the List related to the query (instead of having a proxy).
How could I do this?


text:
Q: Multiple dropdown menu's pure javascript show/hide I'll try to keep this simple, trying to create a form that when completed the page will be printed, on the form I want 3-4 drop down lists with yes or no options, some of the drop downs will open the next hidden div on the form no matter the answer others will open specific parts if the answer is yes.
And yes I can not use PHP or Jquery has to be in pure javascript
<!DOCTYPE html>

<select  onchange="showHideInput(this)">
<option value="0" ></option>
    <option value="1" >Yes</option>
    <option value="2">No</option>
</select>

<select onchange="showHideInput(this)">
<option value="3" ></option>
    <option value="4" >Yes</option>
    <option value="5">no</option>
</select>

`enter code here`
     words

        <input id="a" type="text" name="b" value="" />

     more words

        <input id="a" type="text" name="b" value="" />

Now I will admit I am not the greatest at any of this, but my problem is I can only get it to slightly work with what I have here but with dropone will only allow droptwo work if the answer is yes but I want it latter on to work when the answer is no two.
Any help whatsoever is more than welcome!

A: 1.Your open close tag was not matched, and droptwo was in dropone.
2.If you hard code the value it's not very good for you to scale up to 3-4 dropdown, so I refactored the code a bit

function showHideSwitcher(elementIdToShow) {
  return {
    showHideInput: function(sel, showOnValue) {
      var currentValue = sel.value;
      if (currentValue === showOnValue + "") {
        document.getElementById(elementIdToShow).style.display = 'block';
      } else {
        document.getElementById(elementIdToShow).style.display = 'none';
      }
    }
  }
}

var dropone = showHideSwitcher("dropone");
var droptwo = showHideSwitcher("droptwo");
<select onchange="dropone.showHideInput(this, 1)">
    <option value="0" ></option>
    <option value="1" >Yes</option>
    <option value="2">No</option>
</select>

<select onchange="droptwo.showHideInput(this, 4)">
    <option value="3" ></option>
    <option value="4" >Yes</option>
    <option value="5">no</option>
</select>

<select class="dropOneAlter" onchange="dropone.showHideInput(this, 1)">
    <option value="0" ></option>
    <option value="1" >Yes</option>
    <option value="0">no</option>
</select>

<select class="dropTwiAlter" onchange="droptwo.showHideInput(this, 'T')">
    <option value="F" ></option>
    <option value="T" >Yes</option>
    <option value="0">no</option>
</select>

  `enter code here` words

    <input id="a" type="text" name="b" value="" />

  more words

    <input id="a" type="text" name="b" value="" />

A: I'm not entirely sure what you're asking, but if I think that most of your problems could be fixed by hiding your elements at the beginning of each function call. Try replacing the code in the script tag with this:

and see if that helps.


text: Q: Full screen date picker Is there any way to get that new full screen date picker with background blur (like in the image below) when tapping a custom button other than tapping the CompactDatePickerStyle() date picker?


text:
Q: Dynamically imported module in react won't react to Mobx observable I load a react component dynamically (via webpack's import('module').then) into my bundle. The problem is that the component won't react to Mobx observable's changes. If i import the module the normal way everything works.
Looking at Mobx dev tools i can see that when the component is statically imported when the observable changes i see:
Updated 'ReviewsStore@6.profile': (ReviewsStore@6.profile) (was (ReviewsStore@6.profile))
Scheduled async reaction 'Reviews#0.render()'
Reaction '$Reviews#0.render()'
In contrary when i use code splitting i don't see any render invoked:
Updated 'ReviewsStore@6.profile': (ReviewsStore@6.profile) (was (ReviewsStore@6.profile))
Bellow is my code with test data
class ReviewsStore { // My store
@observable profile = {};

@action
getProfile() {
    $.ajax({ url })
        .then(action((data) => {
            this.profile = {
                user: 'John Doe',
                userid: 123,
                followers: 25,
                reviewsCount: 22,
                reviews: [
                    {
                        body: 'Lorem ipsum ',
                        date: '20/12/2016',
                        rating: 4.5,
                    },
                    {
                        body: 'Lorem ipsum dolor sit',
                        date: '23/12/2016',
                        rating: 4.2,
                    },
                ],
            };

        }));
}

}
@observer class Reviews extends Component { // My View
constructor() {
    super();
    this.getProfile = this.getProfile.bind(this);
    this.state = {
        asyncModule: null,
    };
}

getProfile(id) {
    this.props.store.getProfile(id)
    import('../components/reviews/user-profile')
                .then(({ default: Profile }) => {
                    this.setState({
                        asyncModule: <Profile user={this.props.store.profile} />,
                    });
                });
}

render() {
    return (
        <div>
        {this.state.asyncModule}
        </div>
    );
}

}

A: Could you verify mobx package is included only once? Only in your base bundle and not again in your splitted of bundles?


text:
Q: No module named 'pyexpat' error when embedding Python in C++ I linked Python 3.8.7 dynamically to a Visual Studio C++ console application TestPython.exe with the following code to try plistlib library (which is necessary in my real application):
#include <iostream>

#include "Python.h"

int main()
{
    std::string name;
    std::cout << "Write name:   ";
    std::cin >> name;

    std::cout << "name: " << name << "\n";

    Py_Initialize();

    PyObject* moduleMainString = PyUnicode_FromString("__main__");
    PyObject* moduleMain = PyImport_Import(moduleMainString);

    PyRun_SimpleString(
        "import plistlib\n"\
        "def testDict(a):\n"
        "   pl = dict(aString = a)\n"\
    );

    PyObject* func = PyObject_GetAttrString(moduleMain, "testDict");
    PyObject* args = PyTuple_Pack(1, PyUnicode_FromString(name.c_str()));
    PyObject* result = PyObject_CallObject(func, args);

    Py_Finalize();

    system("pause");
}

In my developer computer (where I have Python installed) the executable works well. When I run it in a different computer with no Python installed, the application shows the following error:
Traceback (most recent call last):
   File "<string>", line 1, in <module>
   File "<frozen zipimport>", line 259, in load_module
   File "plistlib.py", line 65, in <module>
   File "<frozen zipimport>", line 259, in load_module
   File "xml\parser\expat.py", line 4, in <module>
ModuleNotFoundError: No module named 'pyexpat'

error picture
When I run it in a different computer I took care of including in the same directory:

*

*Application TestPython.exe.

*python38.dll and python38.zip which are found in https://www.python.org/downloads/windows/ Python 3.8.7 Windows embeddable package (64-bit).

The Python files bundled with TestPython.exe properly match the Python version of the developer computer (this was typically the solution in related 'pyexpat' questions, but not for this one).

A: Solution: place ALL files found in the Python 3.8.7 Windows embeddable package in the same directory (not just the .dll and .zip). In particular, there is file pyexpat.pyd which was missing.


text:
Q: Hide subprocess output and store it in a variable in Python I would like to call a FFmpeg command, which produces a very big output.
I need to store the output in order to make a regex on it.
On the first command (echo), nothing is printed in my terminal, but for the ffmpeg command, huge output is produced (which I want to store in a variable, I don't want to have the output in my terminal)
So my code looks like this for example:
import subprocess
output = subprocess.check_output("echo a lot of wooooords")
output = subprocess.check_output("ffmpeg -i audio.mp3 -f null -", shell=True)

Is it possible to hide the output for this command? Why does it show me an output? Thank you


text:
Q: Why does [][[]] evaluate to undefined? The expression [][[]] evaluates to undefined in JavaScript. My understanding of this was that the compiler sees the second set of [...] and interprets that to be an array subscript operator (because you can't have two arrays next to each other).
So the compiler knows that the inner expression, [], must be an index, and so after evaluating it, it coerces it to a number. Number([]) evaluates to 0, and so we have [][0], which is undefined.
However, [1][[]] does not evaluate to 1 as I would expect, but rather to undefined suggesting that in this case (or maybe also in the previous case), [] isn't being coerced to a number. It seems that I must use the unary + to force the type coercion:
[1][+[]] // returns 1

So if the inner [] in the expression [][[]] is not being coerced to a number, then why does that expression evaluate to undefined?

A: The faulty assumption was that the expression that evaluates to the index is coerced to a number. It is in fact coerced to string as are all object keys (except for Symbols, which stay Symbols).
Thus, [1][[]] turns into [1][""], and since the "" property doesn't exist on the array, we get undefined instead of 1.

A: You are trying to get data with object.property.property so objects have properties, yes true but properties dont have properties, so it makes undefined. Think like this;
let myArray = [1, 2, 3];
console.log(myArray['length']);
// -> 3
console.log(myArray['length']['length']);
// -> undefined

And there i think there is a problem,
[][[]] These brackets doesnt affect the code. Try to result it with some Codes;
let myArray = [[[1, 2, 3], 2, 3], 2, 3];
console.log(myArray[0][[0]]);
// -> [1, 2, 3]
console.log(myArray[0][0]);
// -> [1, 2, 3]


text:
Q: magnific-popup, how to play an audio file when popup open and stop playing when closing it I am using magnific-popup to display pictures ...
Is it possible to start playing au audio file when the popup window open and stop it when closing the window ?

ANIMA'SON

        Participants: minimum 10, maximum: 20

A: I solved it by adding an audio tag  within each image-popup link

ANIMA'SON

60€ / heure / groupe

        Participants: minimum 10, maximum: 20

    <audio  id="berimbau-audio" loop="loop" preload="none">
        <source src="./sounds/berimbau.ogg" type="audio/ogg">
        <source src="./sounds/berimbau.mp3" type="audio/mpeg">
    </audio>

and adding callbacks into he magnific-popup-options.js, using the data-sound parameter and audio.id
$(document).ready(function() {
    var soundName;
    var audioElement;

    // MagnificPopup
    $('.image-popup').magnificPopup({
        ....
        callbacks: {
            elementParse: function(item) {
                soundName = item.el[0].attributes['data-sound'].value;
                audioElement= document.getElementById(soundName + "-audio")
                audioElement.load();
            },
            close: function() {
                audioElement.pause();
            },
            change: function() {
                audioElement.play();
            }
        },
    });
});


text:
Q: How change standard decoration in zend form in my Directory Form i have FormArena
$this->addElement('radio', 'warrior',array(
            'decorators' => array(
                'ViewHelper',
            ),
            'disableLoadDefaultDecorators' => true,
            'separator' => '',
        ));

On my view page i have
 <?php echo $this->forms['formarena']->getItem('warrior'); ?>

And in controller i have
$getWarriorsList = $this->objArena->getActiveUsers($this->varUserData['id']);

        $objFormArena = new FormArena();
        if (!empty($getWarriorsList)){
            foreach($getWarriorsList AS $varWarriors)
                $varOptions[$varWarriors['id_users']] = $varWarriors['nick'];
            $objFormArena->warrior->addMultiOptions($varOptions);
            unset($varOptions);
        }

       $this->view->forms = array(
            'formarena' => $objFormArena,
        );

Ok so it is easy. I take data from base and add option to view by controller. But when i see source code on page i have:

        <input type="radio" name="warrior" id="warrior-27" value="27">makapaka

        <input type="radio" name="warrior" id="warrior-29" value="29">Kasia

but i need do

    <input id="warrior-27" type="radio" name="warrior" value="27">
    makapaka
    <input id="warrior-29" type="radio" name="warrior" value="29">
    Kasia

What should i need to do. I tried search from web but i have still nothing from 2 days :(

A: The current option does not allow rendering in the exact format you wished.
It can only be either

        <input type="radio" name="warrior" id="warrior-27" value="27">makapaka

        <input type="radio" name="warrior" id="warrior-29" value="29">Kasia

or

        makapaka
        <input type="radio" name="warrior" id="warrior-27" value="27">

        Kasia
        <input type="radio" name="warrior" id="warrior-29" value="29">

To render your form element as you mentioned, you need to create either a custom view helper and pass it as an option to the ViewHelper decorator or use the ViewScript decorator to generate a custom output.
Personally, I would prefer the ViewScript decorator for its easy of use.
Example of use :
$this->addElement('radio', 'warrior',array(
        'decorators' => array(
            array('ViewScript', array('viewScript' => 'decorator.phtml'))
        )
    ));

and in your decorator.phtml

    <?php foreach($this->element->getMultiOptions() as $value => $label): ?>
    <input id="<?php echo $this->element->getName() ?>-<?php echo $value ?>" type="radio" name="<?php echo $this->element->getName() ?>" value="<?php echo $value ?>">
    <label for="<?php echo $this->element->getName() ?>-<?php echo $value ?>"><?php echo $label ?>
    <?php endforeach ?>

NB : This script file can be used for all your form radio elements
Hope it helps


text:
Q: How to clear E1000 network card interrupt I'm trying to make E1000 generate an interrupt when a packet is received,
 // enable Receiver Timer Interrupt
 reg_IMS = (uint32_t *) (base + E1000_IMS);
 *reg_IMS = E1000_IMS_RXT0;

Unfortunately, the interrupt occurs only once. My guess is interrupt wasn't cleared. According to the manual,

Interrupt Cause Read Register ICR (000C0H; R)
All register bits are cleared upon read. As a result, reading this
  register implicitly acknowledges any pending interrupt events.

and the comment of some code, reading ICR (Interrupt Cause Read Register) would clear the interrupt,
/* Clear any pending interrupt events. */
icr = E1000_READ_REG(hw, ICR);

but this didn't work. Here are the relevant messages (E1000_DEBUG=TX,TXERR,RX,RXERR,RXFILTER,interrupt),
e1000: tx disabled
e1000: set_ics 2, ICR 0, IMR 0
e1000: set_ics 0, ICR 2, IMR 80
e1000: set_ics 80, ICR 2, IMR 80
e1000: RCTL: 127, mac_reg[RCTL] = 0x84008002
e1000: set_ics 80, ICR 82, IMR 80
e1000: ICR read: 82
ICR=82
e1000: ICR read: 0
ICR=0
e1000: set_ics 0, ICR 0, IMR 80
...
e1000: set_ics 80, ICR 0, IMR 80
e1000: set_ics 3, ICR 80, IMR 80
ns: 52:54:00:12:34:56 bound to static IP 10.0.2.15
NS: TCP/IP initialized.
opened socket
trying to bind
bound

which showed my nework card interrupt handler did read ICR (ICR=82 and ICR=0 was printed by the handler) for the first time. For there is no interrupt for later "set_ics 80, ICR 0".
Does anyone know how to clear/acknowledge the interrupt? Actually this is part of Project 6 of MIT 6.828.
Thank you!


text:
Q: WiX Permissions, how do I express 'Modify' in terms of DACL flags I'm attempting to apply custom rights to a folder as part of a WiX 3.0.4318.0 installer.
In terms of the Security properties UI in explorer, I want to add Modify to the rights for BUILTIN\Users.  Obviously it needs to be resilient against localisation of the user name. So based on my research to date, I want at least:
<CreateFolder Directory="XYZ" >
    <PermissionEx User="[WIX_ACCOUNT_USERS]"
         GenericRead="yes" GenericWrite="yes" Delete="Yes" />
</CreateFolder>

Questions:

*

*I'm doing this in a subdirectory - am I correct in assuming that the choice between Permission and PermissionEx is Moot?

*What does 'Modify' in the Folder Permissions dialog in Explorer map to in terms of rights - I see many samples where people have translated it to a magic number or a big set of flags - what have other people used (the intent is to allow create, read, write, append and delete, which is best expressed in the UI in terms of Simple Rights as 'Modify').  I've looked at the underlying permissions with icacls which tells me its called 'M', but I have no way to map them to 'specific rights' (in terms as used by icacls /?). There's another mapping table in the windows help. Has anyone got an authorative answer that's worked?
There is a very similar unanswered question at Question regarding PermissionEx (WIX), which it would be cruel but fair to cite as a duplicate.

A: The following combinations are what I've found
"modify" permission:
<util:PermissionEx GenericRead="yes" GenericWrite="yes"
   GenericExecute="yes" Delete="yes" DeleteChild="yes" User="SOMEUSER" />

"read" permission:
<util:PermissionEx Read="yes" GenericRead="yes" User="SOMEUSER" />

A: After some more work on this, my findings are:

*

*In 3.0.5419.0, PermissionEx vs util:"PermissionEx vs Permission gets moot, and no Extended="true" like you see around the net with previous versions is required. Previous versions give errors at runtime resolving BUILTIN\USERS.

*Selecting the three rights I picked seems to achieve the requirements of my context

I'm still very interested in seeing other responses, as I remain a WiX-noob.

A: To get it exactly as you would by setting the permissions by hand on Windows 7 and Windows XP using WiX 3.6, you would need to use this:
<util:PermissionEx
    User="Users" Domain="BUILTIN"
    GenericWrite="yes" GenericExecute="yes" GenericRead="yes"
    Delete="yes" Synchronize="yes" />


text:
Q: Почему в DearPyGUI не получается добавить виджет в основное окно? Я написал такой код:
from dearpygui.core import *
from dearpygui.simple import *

set_main_window_size(740, 520)

with window("window", width=720, height=480):
    set_window_pos("window", 0, 0)

start_dearpygui()

Он создает большое, нестилизованное окно (основное), и второе со стилями.
Когда я хочу добавить виджет в основное окно (вне with window()), мне дает ошибку
Exception: Error: [1000] Message:       Error parsing Dear PyGui
command: Marvel::add_button

 The above exception was the direct cause of the following exception:

 Traceback (most recent call last):
     File "UI.py", line 9, in <module>
         add_button()
SystemError: <built-in function add_button> returned a result with an error set

Это так задумано? Зачем вообще нужно основное окно? Можно ли его скрыть?


text:
Q: Add & execute package to Defrag a fragmented Ext3 Volume under BusyBox in Synology CS407? How? Add & execute package to Defrag a fragmented Ext3 Volume under BusyBox in Synology CS407? How?

Note: Debunking the myth of Linux Filesystems not getting fragmented.
http://www.webupd8.org/2010/03/install-defrag-defragmentation.html
But that's a common misconception and in some cases you do have to defragment your Linux filesystems. This is even confirmed by an Ubuntu developer on a very recent post I stumbled upon just a few minutes ago about ureadahead on the ubuntuforums.
From: Ubuntu Forums Post: http://ubuntuforums.org/showthread.php?t=1434502
The only way to avoid this is defragmenting your disk.

But Linux filesystems don't need defragmenting!
Whoever told you that is deeply mistaken, this is one of the most common myths of Linux.
What is true is that Linux filesystems avoid, where possible, fragmenting their inode tables. This means that the index of how files are split up (fragmented) across the disk, and where those parts are, tends to be kept together as a whole.
That's a good thing; fragmentation of inode tables is a big problem for other filesystems (FATs in that filesystem, etc.) so by keeping them together, it wins a lot of performance.
But the data itself is still fragmented, and spread all over your disk in a random order. And unfortunately during boot, it's the data we need.
One of the future things we want to do is use the ureadahead analysis of what we need during boot to feed into a defragmenter, so everything we need is in one big block on the disk.

Update:
Apparently, the CS407 uses a Marvel processer 88f5281 so it might need something like a specially built optware/ entware first. Please, do guide more in this direction if possible.

http://www.nas-central.org/w/index.php?title=Collection_of_NAS-Hacking_communities#Marvell_Orion-1.2FOrion-NAS.2FOrion-2_based_NAS_devices

https://forum.synology.com/enu/viewtopic.php?t=66550
https://forum.synology.com/enu/viewtopic.php?f=39&t=83186#p339475
Based on the steps & lessons in these 2 links I ran the following (key stuff marked & bolded with double Asterix):
Busybox Version:
BusyBox v1.16.1 (2011-04-08 10:15:04 CST) built-in shell (ash)
Enter 'help' for a list of built-in commands.
Commandline Input & Output:
CubeStation> /usr/syno/etc.defaults/rc.d/S80samba.sh stop
CubeStation> df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/md0               2451064    478484   1870180  20% /
/tmp                     63396       288     63108   0% /tmp
/dev/md2             2879637816 2336710312 542825104  81% /volume1
CubeStation> unmount /volume1
-ash: unmount: not found
CubeStation> sudo unmount /volume1
-ash: sudo: not found
CubeStation> syno_poweroff_task
CubeStation> df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/md0               2451064    478460   1870204  20% /
/tmp                     63396       284     63112   0% /tmp
CubeStation> vgdisplay
CubeStation> e2fsck -v -n -f /dev/md2
e2fsck 1.41.12 (17-May-2010)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
/lost+found not found.  Create? no
Pass 4: Checking reference counts
Pass 5: Checking group summary information
1.41.12-1613: ********** WARNING: Filesystem still has errors **********
   42150 inodes used (0.02%)
3618 non-contiguous files (8.6%)
20 non-contiguous directories (0.0%)
         # of inodes with ind/dind/tind blocks: 20326/8705/71
595654428 blocks used (81.44%)
       0 bad blocks
     114 large files
   36634 regular files
    4434 directories
       0 character device files
       0 block device files
       0 fifos
       1 link
    1073 symbolic links (1073 fast symbolic links)
       0 sockets

*

*I am not a *Nix expert, but have a CS & IT background and am fine with running stuff on the command line. I've read a lot but just wish to piece together the right compatible packages/ components (for this system) & steps here.

*

*https://askubuntu.com/questions/21142/is-there-a-ext3-defragmenter

*http://www.webupd8.org/2009/10/defragmenting-linux-ext3-filesystems.html

*http://vleu.net/shake/

*I am guessing this may be lacking some packages/ components that will provide me with the ability to run a Defrag.

*Should I/ Can I install them (the ones linked above)?  Which ones & how?

*How best to execute them?

What can I do to DEFRAG the volume FS & the non-contiguous data?

A: When running commands from the internet, it's always a good idea to cross check what the commands does with the manual page.
In your specific case, your e2fsck command:
e2fsck -v -n -f /dev/md2

If we check what this commands does in the e2fsck man page you'll see:

-n  Open the filesystem read-only, and assume an answer of 'no' to all questions. Allows e2fsck to be used non-interactively. (Note: if the -c, -l, or -L options are specified in addition to the -n option, then the filesystem will be opened read-write, to permit the bad-blocks list to be updated. However, no other changes will be made to the filesystem.)

So what the -n flag does is to do a disk check without repairing any issues it found. You'd want to remove this flag to let it repair issues. You'll get prompts for each issue e2fsck found and try to repairs. If you want e2fsck to just repair everything without prompts, add -p flag:

-p Automatically repair ("preen") the file system without any questions.


text:
Q: Quotes problem in beamer I'm trying to make nice big quotes work in my presentation, but there is some error, a clashing of packages I assume, and I don't know how to resolve this :
So my mwe is here:
%&latex
\RequirePackage[demo]{graphicx}
\documentclass[xcolor=dvipsnames,hyperref={breaklinks=true},mathserif,10pt]{beamer}
\usecolortheme[named=RoyalPurple]{structure}
\useoutertheme{infolines}
\usetheme[height=7mm]{Rochester}
\setbeamertemplate{items}[ball]
\setbeamertemplate{navigation symbols}{}
\usefonttheme{professionalfonts}

\usepackage{amsmath,amssymb,amsthm,amssymb}
\usepackage{mathtools}
\usepackage{bbm}
\usepackage{graphicx}
\usepackage{float}
\usepackage[croatian]{babel}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{txfonts}
\usepackage{subfigure}
\usepackage{listings}
\usepackage{time}
\usepackage{extarrows}

\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{framed}

\newcommand*\openquote{\makebox(25,-22){\scalebox{5}{``}}}
\newcommand*\closequote{\makebox(25,-22){\scalebox{5}{''}}}

\makeatletter
\newif\if@right
\def\shadequote{\@righttrue\shadequote@i}
\def\shadequote@i{\begin{snugshade}\begin{quote}\openquote}
\def\endshadequote{%
  \if@right\hfill\fi\closequote\end{quote}\end{snugshade}}
\@namedef{shadequote*}{\@rightfalse\shadequote@i}
\@namedef{endshadequote*}{\endshadequote}
\makeatother

%\logo{\includegraphics[width=0.25\textwidth]{logo.eps}}

\title{RANDOM TITLE}
\subtitle{Random subtitle}
\author{John Doe}
\institute[Random institute at random place}
\date{\today}

\begin{document}
\maketitle

\begin{frame}
\frametitle{TOC}
\tableofcontents
\end{frame}

\section{Intro}

\begin{frame}
\frametitle{Intro}
\begin{columns}
    \begin{column}{0.5\textwidth}
        \begin{itemize}
        \item[]
        \flushleft{\includegraphics[width=0.5\textwidth]{elvish.eps}}
        \end{itemize}
    \end{column}
    \begin{column}{0.5\textwidth}
        \begin{shadequote}
        A common mistake that people make when trying to design something completely
        foolproof is to underestimate the ingenuity of complete fools.\par\emph{Douglas Adams}
        \end{shadequote}
    \end{column}
\end{columns}
\end{frame}

\end{document}

Basically I'd like to have image on the left and next to it (on the right) two quotes.
I followed the instructions here, but I guess I made sth wrong :\ I didn't want any shade underneath my quotes so I left out the colorlet part...
So any help would be helpful.

A: Summary

*

*You must not leave the \colorlet part out as that is important in the definition of \shadequote, I think, based on the error I get:

Package xcolor error: Undefined error 'shadecolor'\end{frame}

*

*The svgnames was important for the color name Azure so you may use the option xcolor={svgnames, dvipsnames}. Or if you don't want to load svgnames, use more generic colors or combination of them in your \colorlet{shadecolor}. If you don't want shading in your quote, use \colorlet{shadecolor}{white} instead. In that case, svgnames may not be loaded.

*the mathserif option is already deprecated. Use \usefonttheme[onlymath]{serif} instead.

*There is a scoping problem in \institute[Random institute at random place}. I changed [ to }.

*Compile with the latex->dvips->ps2pdf sequence.

Revised Code
%&latex
\RequirePackage[demo]{graphicx}
\documentclass[xcolor={dvipsnames}
,hyperref={breaklinks=true}
%,mathserif
,10pt]{beamer}
\colorlet{shadecolor}{blue}
\usefonttheme[onlymath]{serif}
\usecolortheme[named=RoyalPurple]{structure}
\useoutertheme{infolines}
\usetheme[height=7mm]{Rochester}
\setbeamertemplate{items}[ball]
\setbeamertemplate{navigation symbols}{}
\usefonttheme{professionalfonts}

\usepackage{amsmath,amssymb,amsthm,amssymb}
\usepackage{mathtools}
\usepackage{bbm}
\usepackage{graphicx}
\usepackage{float}
\usepackage[croatian]{babel}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{txfonts}
\usepackage{subfigure}
\usepackage{listings}
\usepackage{time}
\usepackage{extarrows}

\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{framed}

\newcommand*\openquote{\makebox(25,-22){\scalebox{5}{``}}}
\newcommand*\closequote{\makebox(25,-22){\scalebox{5}{''}}}

\makeatletter
\newif\if@right
\def\shadequote{\@righttrue\shadequote@i}
\def\shadequote@i{\begin{snugshade}\begin{quote}\openquote}
\def\endshadequote{%
  \if@right\hfill\fi\closequote\end{quote}\end{snugshade}}
\@namedef{shadequote*}{\@rightfalse\shadequote@i}
\@namedef{endshadequote*}{\endshadequote}
\makeatother

%\logo{\includegraphics[width=0.25\textwidth]{logo.eps}}

\title{RANDOM TITLE}
\subtitle{Random subtitle}
\author{John Doe}
\institute{Random institute at random place}
\date{\today}

\begin{document}
\maketitle

\begin{frame}
\frametitle{TOC}
\tableofcontents
\end{frame}

\section{Intro}

\begin{frame}
\frametitle{Intro}
\begin{columns}
    \begin{column}{0.5\textwidth}
        \begin{itemize}
        \item[]
        \flushleft{\includegraphics[width=0.5\textwidth]{elvish.eps}}
        \end{itemize}
    \end{column}
    \begin{column}{0.5\textwidth}
        \begin{shadequote}
        A common mistake that people make when trying to design something completely
        foolproof is to underestimate the ingenuity of complete fools.\par\emph{Douglas Adams}
        \end{shadequote}
    \end{column}
\end{columns}
\end{frame}

\end{document}

Output


text:
Q: Add attribute to Table class from pandastable I would like to add a new attribute to the class table from the package pandastable by inheritance. I use the following code for this:
import pandas as pd
from pandastable import Table
import tkinter as tk

class MyTable(Table):

    def __init__(self, list_items, *args, **kwargs):
        self.list_items = list_items
        super(MyTable, self).__init__(*args, **kwargs)

top = tk.Tk()
top.geometry("300x300")

df = pd.DataFrame()
df["column1"] = [1,2,3,4,5,6,7,8,9,10,11,12,13,1,1,1,1,1,1,1]
df["column2"] = [1,2,3,4,5,6,7,8,9,10,11,12,13,1,1,1,1,1,1,1]
df["column3"] = [1,2,3,4,5,6,7,8,9,10,11,12,13,1,1,1,1,1,1,1]
df["column4"] = [1,2,3,4,5,6,7,8,9,10,11,12,13,1,1,1,1,1,1,1]

frame = tk.Frame(top)
frame.pack(fill="both", expand=True)

pt = MyTable(frame, dataframe=df)
pt.focus_set()
pt.show()

top.mainloop()

When I run the code, I get following error message:
Traceback (most recent call last):
File "....py", line 47, in <module>
    pt = MyTable(frame, dataframe=df)
  File "/....py", line 9, in __init__
    super(MyTable, self).__init__(*args, **kwargs)
  File "...e.py", line 134, in __init__
    self.doBindings()
  File "....py", line 262, in doBindings
    self.parentframe.master.bind_all("<KP_8>", self.handle_arrow_keys)
AttributeError: 'NoneType' object has no attribute 'master'

The error occurs in the package function doBindings. but why does it occur only after I have changed the __init__ function?

A: First you need to pass the parent option to Table().  Second suggest to use keyword argument list_items instead of positional argument.
class MyTable(Table):
    # add parent argument and remove *args
    def __init__(self, parent, **kwargs):
        # get the keyword argument 'list_items' if provided, otherwise set it to None
        self.list_items = kwargs.pop('list_items', None)
        # pass required parent argument to Table class
        super().__init__(parent, **kwargs)


text:
Q: Using nobarrier with ext4 and google persisten disks I was looking into speeding up some heavy DB write workload on google cloud vm. I saw nobarrier option for ext4 FS can provide some performance boost. I was wondering if anyone knows if it is safe to use nobarrier option with google persistent storage (Balanced PD). My understanding is that If your disks are battery-backed in one way or another, disabling barriers may safely improve performance, but I dont know how that applies to google balanced PD storage. Will I have more FS corruption/problems if my VM hangs or if I perform hard reset of the VM while having write operations happening, when compared to no using nobarrier option?

A: Red Hat has a document on the use of barriers:

The use of nobarrier is no longer recommended in Red Hat Enterprise
Linux 6 as the negative performance impact of write barriers is
negligible (approximately 3%). The benefits of write barriers
typically outweigh the performance benefits of disabling them.
Additionally, the nobarrier option should never be used on storage
configured on virtual machines.

ENABLING/DISABLING WRITE BARRIERS


text:
Q: Jquery yii CJuiTabs add new tabs Please help, i want to make like this, when i click "+" will add new tabs with same render partial

i have a basically script like this
  <?php
                $tabs=array();
                $i=0;
                $a=1;
                for ($i=0;$i<$a;$i++){
                $tabs['Persyaratan '.$a]=array(
                    'id'=>'syarattab',
                    'content'=>$this->renderPartial("_formsyarat",array('mdsyarat'=>$mdsyarat),$this));
                }
                $tabs['+']=array(
                    'id'=>'tambah');

                $this->widget('zii.widgets.jui.CJuiTabs',array(
                    'tabs'=>$tabs,
                    'options'=>array(
                        'collapsible'=>true,
                    ),
                    'id'=>'Tabs_syarat',
                ));?>

how can i add jquery code in tabs + ?? please help.. thank

A: TLDR:
In jquery-ui 1.9, how do you create new tabs dynamically?
You can use this method, because CJui is jQuery UI plugin.

You can use documentation for jQuery Ui Tabs API, there is a method called "refresh".
Basic algorithm for adding new tab will be:

*

*Add event on pressing plus sign, and add new content and link directly in DOM with new IDs.

*Call "refresh" method linked above.

You can also check upgrade guide, if your CJuiTabs is using old version of jQuery UI:
http://jqueryui.com/upgrade-guide/1.9/#deprecated-add-and-remove-methods-and-events-use-refresh-method


text:
Q: Searching for elementsbyid where ID is set from a dataset I am trying to get items to be visible/invisible based on an onclick function being called however I am getting "Unhandled Rejection (TypeError): Cannot read property 'style' of null"
My code reads as follows:

        {output.map((group) => (

{group}

            {this.state.items.filter(item =>  item.GroupDesc === group).map((items) => (

{items.TypeDesc}
))}

))}

with a function
function item_open(group) {
  document.getElementById(group).style.display = "block";
}

I believe these should:
-give all items in the group an id of the group name
-the function should call all of those items with getElementById
-they should then all get the display: "block" attribute
Can anyone see why this might not work?

A: just this will work: onClick={item_open(group)} since you already put the braces, anything you put inside it will be interpreted as javascript code


text:
Q: CSS: How can I set image size relative to parent height? I am trying to figure out how to re-size an image so that it keeps it ratio of width to height, but gets re-sized until the height of the image matches the height of the containing div. I have these images that are pretty large and long (screenshots), and I want to put them into a 200px width, 180px height div for display and without re-sizing the images manually. To make this look good, the sides of the image need to overflow and be hidden with the containing div. This is what I have so far:
http://jsfiddle.net/f9krj/2/
HTML

CSS
a.image_container {
    background-color: #999;
    width: 200px;
    height: 180px;
    display: inline-block;
    overflow: hidden;
}
a.image_container img {
    width: 100%;
}

As you can see, there is grey color showing on the images parent container which should not be shown at all. In order for that container to be filled completely, the width needs to be overflowed equally on both sides. Is this possible? Is it also possible to account for an image that is also too tall?

A: Change your code:
a.image_container img {
    width: 100%;
}

To this:
a.image_container img {
    width: auto; // to maintain aspect ratio. You can use 100% if you don't care about that
    height: 100%;
}

http://jsfiddle.net/f9krj/5/

A: you can use flex box for it.. this will solve your problem
.image-parent
{
     height:33px;
     display:flex;
}

A: Use max-width property of CSS, like this :
img{
  max-width:100%;
}

A: If you take answer's Shekhar K. Sharma, and it almost work, you need also add to your this height: 1px; or this width: 1px; for must work.

A: Original Answer:
If you are ready to opt for CSS3, you can use css3 translate property. Resize based on whatever is bigger. If your height is bigger and width is smaller than container, width will be stretch to 100% and height will be trimmed from both side. Same goes for larger width as well.
Your need, HTML:

And CSS:
.img-wrap {
  width: 200px;
  height: 150px;
  position: relative;
  display: inline-block;
  overflow: hidden;
  margin: 0;
}

div > img {
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  min-height: 100%;
  min-width: 100%;
  transform: translate(-50%, -50%);
}

Voila! Working: http://jsfiddle.net/shekhardesigner/aYrhG/
Explanation
DIV is set to the relative position. This means all the child elements will get the starting coordinates (origins) from where this DIV starts.
The image is set as a BLOCK element, min-width/height both set to 100% means to resize the image no matter of its size to be the minimum of 100% of it's parent. min is the key. If by min-height, the image height exceeded the parent's height, no problem. It will look for if min-width and try to set the minimum height to be 100% of parents. Both goes vice-versa. This ensures there are no gaps around the div but image is always bit bigger and gets trimmed by overflow:hidden;
Now image, this is set to an absolute position with left:50% and top:50%. Means push the image 50% from the top and left making sure the origin is taken from DIV. Left/Top units are measured from the parent.
Magic moment:
transform: translate(-50%, -50%);
Now, this translate function of CSS3 transform property moves/repositions an element in question. This property deals with the applied element hence the values (x, y) OR (-50%, -50%) means to move the image negative left by 50% of image size and move to the negative top by 50% of image size.
Eg. if Image size was 200px × 150px, transform:translate(-50%, -50%) will calculated to translate(-100px, -75px). % unit helps when we have various size of image.
This is just a tricky way to figure out centroid of the image and the parent DIV and match them.
Apologies for taking too long to explain!
Resources to read more:

*

*https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate

*https://css-tricks.com/centering-css-complete-guide/

A: For me the easiest way to do it without using position absolute, translate.

the CSS should look like this :
.img-container {
 height:100px;
 width:100px;
 overflow:hidden;
}
.img-container > img {
width:100%;
height:100%;
object-fit:cover;
}

A: If all your trying to do is fill the div this might help someone else, if aspect ratio is not important, is responsive.
.img-fill > img {
  min-height: 100%;
  min-width: 100%;
}


text:
Q: Alternative solution to null layout manager when absolute positioning is needed Few months ago i read this Swing tutorial http://zetcode.com/tutorials/javaswingtutorial/resizablecomponent/ for understanding how implementing resizable components inside Swing.
The tutorial tells about using a null LayoutManager in order to have the possibility of absolute positioning child components.
In a discussion relative to another subject @Andrew Thompson pointed out that using null layout is a bad idea. This article http://download.oracle.com/javase/tutorial/uiswing/layout/none.html describe null layout manager as not desirable too, anyway it says that in certain situations the might be useful.
In a situation where:

*

*i need absolute positioning for a JPanel's child components

*i need to implement my own bounding box conditions for child components (in order to establish possible overlapping situations )

*i need JPanel's child component be resizable

Is correct in the described situation use a null layout manager?
Or there are other better solutions to achieve that goals using a layout manager for my JPanel container component?
thanks in advance

A: Your best solution would be to implement your own LayoutManager (or extend an existing one, if one is really close to your needs) using the features and controls you are looking for.  Your absolute positioning requirements would simply become a method of your layout manager.
For instance, I have, in the past, followed techniques to extend FlowLayout to give it abilities to properly wrap elements when contained in a JScrollPane.  Here is an example, although this is not the same one that I used.


text:
Q: Is there a difference between sass and scss? I've worked on a few ruby apps with .scss scripts for the CSS of the website. But I came across a new ruby app which uses .sass instead.
Are there any advantages or things to look out for with this change?

A: They are functionally equivalent but have a different syntax. From the SASS homepage:

[...] there is no functional difference between them. Use the syntax you prefer.

A: Sass is a cleaner way to make Scss:
..Older syntax is known as the indented syntax (or just ".sass"). Inspired by Haml's terseness, it's intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.
Scss
$blue: #3bbfce;
$margin: 16px;

.content-navigation {
  border-color: $blue;
  color:
    darken($blue, 9%);
}

.border {
  padding: $margin / 2;
  margin: $margin / 2;
  border-color: $blue;

}
Sass
$blue: #3bbfce
$margin: 16px

.content-navigation
  border-color: $blue
  color: darken($blue, 9%)

.border
  padding: $margin / 2
  margin: $margin / 2
  border-color: $blue

Check more info on sass page

A: SASS and SCSS are the same thing, there are however two different syntaxes used.


text:
Q: facebook api: event url lets say I know I have an event ID. I would like the event URL (to link users to it), but the graph API does not seem to have it (https://developers.facebook.com/docs/graph-api/reference/event/), for example if I use the command GET /v2.9/310917539364835 HTTP/1.1 the output is:
{
  "description": "...",
  "end_time": "2017-06-23T22:30:00+1000",
  "name": "UQ Postgrad Masquerade Party (End of Semester)",
  "place": {
    "name": "Cloudland",
    "location": {
      "city": "Brisbane",
      "country": "Australia",
      "latitude": -27.45891,
      "longitude": 153.0349699,
      "state": "QLD",
      "street": "641 Ann Street",
      "zip": "4006"
    },
    "id": "103221159774910"
  },
  "start_time": "2017-06-23T19:30:00+1000",
  "id": "310917539364835"
}

but there is not URL.
Thanks

A: after doing some searching, it turns out that the URL is:
facebook.com/ + ID
so in this example. facebook.com/310917539364835


text:
Q: Displaying Single Document from Firebase I'm having problems getting data from my firebase. I have the data but do not know how to display it.
Here is my Database:

This is my code:
class Home extends StatefulWidget {

  final dynamic userUid, nicked;
  Home({this.userUid, this.nicked});

  @override
 _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  final int delayedAmount = 500;
  //final AuthService _auth = AuthService();

  void getNick() {
  //get nickname of this User
  final CollectionReference userNickname  = Firestore.instance.collection('NickNames of Users');
  var documentNick = userNickname.document(widget.userUid);
  documentNick.get()
  .then((DocumentSnapshot ds){
      var nick = ds.data['MyNickName'];
      print(nick);
      var nicked = Home(nicked: nick,);
  });
}

  @override
  Widget build(BuildContext context) {
    return Container(
          child: Scaffold(
            backgroundColor: Colors.greenAccent[400],

      body:  SingleChildScrollView(
        physics: ScrollPhysics(),
          child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.fromLTRB( 0 , 50, 0, 0),
              child: Column(
                children: <Widget>[
                  Align(
                    alignment: Alignment.topLeft,
                                  child: DelayedAnimation(
                   child:
                    Text(
                             widget.nicked,//This i where the firebase data nickName code will go

                     textScaleFactor : 1,
                    style: TextStyle(
                      fontFamily: 'Comic',
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                      fontSize: 30,

                    ),
                    ),

So i just dont know how to get the single document from firebase and display it.
So this is how i get userUid...
  import 'package:firebase_auth/firebase_auth.dart';
//import 'package:flutter/cupertino.dart';
import 'package:fruithero/model/user.dart';
import 'package:fruithero/services/database.dart';
import 'package:fruithero/pages/myHome.dart';

class AuthService {
  final dynamic nickNamesofUser;
  AuthService({this.nickNamesofUser});

  final FirebaseAuth _auth = FirebaseAuth.instance;

  void homeTransporter(uid){
   dynamic homeTransport = uid;
   Home(userUid: homeTransport,);
  }

  // create user obj based on firebase user
  User _userFromFirebaseUser(FirebaseUser user) {
    return user != null ? User(uid: user.uid) : null;
  }

  // auth change user stream
  Stream<User> get user {
    return _auth.onAuthStateChanged
      //.map((FirebaseUser user) => _userFromFirebaseUser(user));
      .map(_userFromFirebaseUser);
  }

  // sign in anon
  Future signInAnon() async {
    try {
      AuthResult result = await _auth.signInAnonymously();
      FirebaseUser user = result.user;
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // sign in with email and password
  Future signInWithEmailAndPassword(String email, String password) async {
    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
      return user;
    } catch (error) {
      print(error.toString());
      return null;
    }
  }

  // register with email and password
  Future registerWithEmailAndPassword(String email, String password) async {
    try {
      AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
      //storing user uid
      homeTransporter(user.uid);
      //create new document for user with the uid
      await DataBaseServices(uid: user.uid).createDocumentWithUid(nickNamesofUser);
      //await DatabaseService(uid: user.uid).updateUserData(nickNamesofUser);
      return _userFromFirebaseUser(user);
    } catch (error) {
      return null;
    }
  }

  // sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (error) {
      print(error.toString());
      return null;
    }
  }

}

I hope this helps. Sir..............................................................................................................................................................

A:    String nick,userID;

 void initState() {
super.initState();
userID = widget.uid;
getNick();
print(userID);
}

 void getNick() {
  var users;
  //get nickname of this User
 Firestore.instance.collection('NickNames of Users').document(userID).get().then((data){
    setState(() {
      users = data;
      nick = users['MyNickName'];
      print(nick);
    });
  });
}


text:
Q: Xamarin App not showing up in Emulator, even though it compiles without errors? Here is a picture of my file structure and MainPage.Xaml file
MainPage.xaml Here is the code in that file
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:AppXam"
             x:Class="AppXam.MainPage">
    <ContentPage.BindingContext>
        <local:MainPage/>
    </ContentPage.BindingContext>
    <Grid>
        <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="2*"/>
        <RowDefinition Height=".5*"/>
        <RowDefinition Height="2*"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Image Source="https://s2.dmcdn.net/v/AmZGT1VXLk5NDRThE/x1080" BackgroundColor="red"
           Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2"/>

    <Editor Grid.Column ="0" Grid.ColumnSpan="2" Grid.Row="1"
            Placeholder="Enter Note Here" Text="{Binding TheNote}" />

    <Button Grid.Row="2" Grid.Column="0" Text="Save" Command="{Binding SaveCommand}"   />

    <Button Grid.Row="2" Grid.Column="1" Text="Erase"    Command="{Binding EaseCommand}"/>

    <CollectionView ItemsSource="{Binding AllNotes}" Grid.Row="3" Grid.ColumnSpan="2">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                    <Frame>
                        <Label Grid.Row="3" Grid.Column="0" Text="{Binding .}" FontSize="Large" />
                    </Frame>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

</Grid>

Here is a picture of the MainPage.XAML.cs which is the namespace that contains the MVVM code.
MainPage.xaml.cs
The code is as follows :
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace AppXam
{
    public partial class MainPage : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public MainPage()
        {
            EraseCommand = new Command(() =>
            {
                TheNote = string.Empty;
            });

           SaveCommand = new Command(() =>
           {
               AllNotes.Add(TheNote);

               TheNote = string.Empty;
           });
        }
        public ObservableCollection<string> AllNotes {get; set;}

        string theNote;
        public string TheNote
         {
             get => theNote;
             set
             {
                 theNote = value;
                 var args = new  PropertyChangedEventArgs(nameof(TheNote));
                 PropertyChanged?.Invoke(this,args);
             }
         }

        public Command SaveCommand { get; }
        public Command EraseCommand { get; }
    }
}

The screenshots contain the output on the screen, which is a blank white page. The project directory can be found here
https://drive.google.com/drive/folders/1sp4qh3Wzse1KVZN1IKdteaGcgncCG4p4?usp=sharing

A: Remove the binding in the XAML and use this:
    public MainPage()
    {
        InitializeComponent();  //1. no init, no page
        BindingContext = this;  //2. must bind after init

        //other things to do
    }

*

*Please, clean the solution (remove the bin & obj folders) before uploading next time.


text:
Q: Java MDI application with IntelliJ Does IntelliJ have any special support for developing a MDI (Multiple Document Interface) application?
I found some generic articles that go over creating one in Java, but I was wondering if IntelliJ makes it any easier.
I'm using IntelliJ 11 (Community Edition) if that matters.

A: I kind of doubt it. You can just design panels in the normal gui designer and then put them into internal frames. As far as I know the basic gui designer would be sufficient for that.
By coincidence, a co-worker and I were just discussing MDI this afternoon, because I was using SoapUI (which is MDI). We both agreed that MDI is a pretty rough for the users. Internal frames are constrained by the main frame, so the space quickly becomes cluttered and things become hard to find. Users are constantly sorting through them to find what they want. Have you noticed that most apps these days either use multiple top level windows or tabbed panes?