text:
Q: IPC using Unix Domain Sockets I have two different applications where one of them has to feed data into the other. I am using Unix domain sockets for communicating between them. The client hooks onto the socket, checks for a sever connection and if available sends the data. The server waits for a client connection and whenever some data is available, it reads the data and writes it into a file. The main functions for the client is :
CLIENT:
int main(int argc, char* argv[]) {

if (argc < 2) {
    printf("Usage: Operating_Mode Path_to_DAQ_dataset output_file cudaBF\n");
    printf("Operating_Mode = 0 : Real Time BF processing\nUsage: Operating_Mode output_file cudaBF\n");
    printf("Operating_Mode = 1 : Pre-recorded data BF processing\nUsage: Operating_Mode Path_to_DAQ_dataset output_file cudaBF\n");
    return 1;
}

/*******************************************/
int s, len , packetTransferCount;
struct sockaddr_un remote;

if ((s = socket(AF_UNIX,SOCK_STREAM, 0)) == -1) {
    perror("socket");
}

remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCKET_DISPLAY_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
/*******************************************/

pthread_t threadBF;

struct beamRecordedArgs processParams;
processParams.dataPath = argv[2];
processParams.bfOutputFile = argv[3];

pthread_create(&threadBF,NULL,beamProcessRecorded,(void *)&processParams);

packetTransferCount = 0;
while(processStatus != COMPLETE){
if(processStatus == TRANSFER){
    printf("Checking for display...\n");
    if (connect(s, (struct sockaddr *)&remote, len) == -1) {
        printf("No display process found\n");
        processStatus = PROCESS;
}
    else{
        printf("Display process found.. Transferring packet\n");
        send(s, txPackDisp, sizeof(txPackDisp), 0);
        close(s);
        processStatus = PROCESS;
        printf("PACKETS TRANSFERRED : %d\n",++packetTransferCount);
    }
}
else{
    while(processStatus == PROCESS){
        //sleep(1);
    }
}
}

pthread_join(threadBF,NULL);

return 0;
}

For server its :
SERVER:
int main(void)
{

int dispSock, lenSock, packetTransferCount;
struct sockaddr_un localDisp;

if ((dispSock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(-1);
}
localDisp.sun_family = AF_UNIX;
strcpy(localDisp.sun_path, SOCKET_DISPLAY_PATH);
unlink(localDisp.sun_path);
lenSock = strlen(localDisp.sun_path) + sizeof(localDisp.sun_family);
if (bind(dispSock, (struct sockaddr *)&localDisp, lenSock) == -1) {
    perror("bind");
    exit(-1);
}
if (listen(dispSock, 5) == -1) {
    perror("listen");
    exit(-1);
}

packetTransferCount = 0;

do{
    struct sockaddr_un remoteDisp;
    int dispSockCon,dispConn;
    dispConn = sizeof(remoteDisp);

    if ((dispSockCon = accept(dispSock, (struct sockaddr *)&remoteDisp, &dispConn)) == -1) {
        perror("accept");
        exit(-1);
    }
    printf("Connected.\n");

    int status = recv(dispSockCon, &rxPack, PACKET_SIZE*sizeof(float),0);

    if (status != -1){
        FILE *fp;
        fp = fopen("bfo_sock","w");
        fwrite(rxPack, PACKET_LENGTH, sizeof(float), fp);
        fclose(fp);
    }
    else{
        printf("Error in receiving packets\n");
    }
    close(dispSockCon);
}while(1);

close(dispSock);
unlink(SOCKET_DISPLAY_PATH);
return 0;
}

The problem that I am facing is, the client is only able to send one packet after it connects to the server (doesnt matter which is started first or is already running), after which its not detecting the server process at all, even when its running and other processes can detect it.Typically the size of data being transferred at once is roughly 13.3 kilobytes. The print outs that I see on the terminal is :
Number of packets to be processed in BF : 60
PACKETS PROCESSED : 1
Checking for display...
Display process found.. Transferring packet
PACKETS TRANSFERRED : 1
PACKETS PROCESSED : 2
Checking for display...
No display process found
PACKETS PROCESSED : 3
Checking for display...
No display process found

If someone can point me in the direction where I am going wrong here, it would really helpful for me as I am pretty new to IPC using sockets.

A: Well, I figured out the problem here. The issue was that I needed to create the socket connection anew everytime I wanted to transfer a packet over and close it after that. So, main for the server remains the same, but the client now becomes :
int main(int argc, char* argv[]) {

if (argc < 2) {
    printf("Usage: Operating_Mode Path_to_DAQ_dataset output_file cudaBF\n");
    printf("Operating_Mode = 0 : Real Time BF processing\nUsage: Operating_Mode output_file cudaBF\n");
    printf("Operating_Mode = 1 : Pre-recorded data BF processing\nUsage: Operating_Mode Path_to_DAQ_dataset output_file cudaBF\n");
    return 1;
}

int packetTransferCount;
pthread_t threadBF;

struct beamRecordedArgs processParams;
processParams.dataPath = argv[2];
processParams.bfOutputFile = argv[3];

pthread_create(&threadBF,NULL,beamProcessRecorded,(void *)&processParams);

packetTransferCount = 0;
while(processStatus != COMPLETE){
if(processStatus == TRANSFER){
/****************************************************************/
/*This part was outside the loop, moving it inside creates a new
socket connector everytime I was to transfera packet and I close it before
the loops ends */
    int s, len;
struct sockaddr_un remote;

    if ((s = socket(AF_UNIX,SOCK_STREAM, 0)) == -1) {
    perror("socket");
}

remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCKET_DISPLAY_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
/****************************************************************/
    printf("Checking for display...\n");
    int dispConStatus = connect(s, (struct sockaddr *)&remote, len);
    if ( dispConStatus == -1) {
        printf("No display process found\n");
        processStatus = PROCESS;
    }
    else{
        printf("Display process found.. Transferring packet\n");
        send(s, txPackDisp, sizeof(txPackDisp), 0);
        processStatus = PROCESS;
        printf("PACKETS TRANSFERRED : %d\n",++packetTransferCount);
    }
    close(s);
}
else{
    while(processStatus == PROCESS){
        //sleep(1);
    }
}
}

pthread_join(threadBF,NULL);

return 0;
}


text:
Q: Check if a UserPrincipal is enabled I'm using C# code to query an Active Directory. The main issue I'm having is determining whether an account has been disabled or not. Looking through many online articles, it would appear that one cannot solely rely on the property UserPrincipal.Enabled to determine if a user account is enabled or not. Fair enough, as its a nullable Boolean but when an AD administrator disables an account, this does appear to get set to false. The problem I have is when I query a client's AD, I find that most user accounts UserPrincipal objects return false for this property. So when I use this code to check if an account is disabled:
private bool IsUserEnabled(UserPrincipal userPrincipal)
{
        bool isEnabled = true;

        if (userPrincipal.AccountExpirationDate != null)
        {
            // Check the expiration date is not passed.
            if (userPrincipal.AccountExpirationDate <= DateTime.Now)
            {
                Log.DebugFormat("User {0} account has expired on {1}", userPrincipal.DisplayName, userPrincipal.AccountExpirationDate.Value);
                isEnabled = false;
            }
        }

        if (userPrincipal.IsAccountLockedOut())
        {
            isEnabled = false;
            Log.DebugFormat("User {0} account is locked out", userPrincipal.DisplayName);
        }

        if (userPrincipal.Enabled != null)
        {
            isEnabled = userPrincipal.Enabled.Value;
            Log.DebugFormat("User {0} account is Enabled is set to {1}", userPrincipal.DisplayName, userPrincipal.Enabled.Value);
        }

        return isEnabled;
}

Most accounts appear disabled because of the userPrincipal.Enabled check.
However, if I leave this out and just rely on the account expiration date and the account lockout properties, then I may miss someone who is disabled using the checkbox in Active Directory which simply disables the account - without setting the account expiration date.
All the accounts where enabled returns false are actually active accounts who can log in to the domain.
How do you check if an account is actually enabled or not?

A: I ran into a similar issue, and was equally perplexed!
I initially was using a System.DirectoryServices.DirectorySearcher to search for disabled users.  The status of an AD user record (re: disabled, locked out, password expiry, etc) is stored within the UserAccountControl property.  You could pass in a filter to the DirectorySearcher to locate, lets says, disabled accounts by specifying the UserAccountControl property as part of the filter.
I was never fond of this approach as it amounted to using a magic string and some magic numbers in order to build the query;  for example, this is the filter used to locate disabled accounts:
 var searcher = new DirectorySearcher(dirEntry)
            {
                Filter = "(UserAccountControl:1.2.840.113556.1.4.803:=2)",
                PageSize = 50
            };

When I switched over to using the UserPrincipal, I was thrilled to see this nice handy "Enabled" property right on the class..  At least until I realized it didn't return the same value that the DirectorySearcher filter would return.
Unfortunately, the only reliable way that I could find to determine if the account was actually enabled was to dig into the underlying DirectoryEntry object, and go inspect the UserAccountControl property directly, ie:
var result = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
var uac = (int)result.Properties["useraccountcontrol"].Value;
var isEnabled = !Convert.ToBoolean(uac & 2);

Note - the UserAccountControl property is a "flags" enum;  all possible values for the UserAccountControl property can be found here: https://msdn.microsoft.com/en-us/library/aa772300(v=vs.85).aspx
I ended up building the above snippet into a little extension method;  fortunately doing this extra work to retrieve the UserAccountControl property didn't noticeable slow down my AD queries.

A: I got a solution by expanding the result and going to the base and expanding the base. You will see the enabled property there. Then I right click the expression and add to watch and copy the watch expression to my code.
  using (var context = new PrincipalContext(ContextType.Domain, "xyz.com", "Administrator", "xyz123"))
        {
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {
             foreach (var result in searcher.FindAll())
                {
                  DirectoryEntry de = result.GetUnderlyingObject() as DrectoryEntry;
             foreach (String key in de.Properties.PropertyNames)
                {
                   Console.WriteLine(key + " : " + de.Properties[key].Value);
                }
               Console.WriteLine("Enabled: "    +((System.DirectoryServices.AccountManagement.AuthenticablePrincipal)(result)).Enabled);
               Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
                    }
                 }
             }
        Console.ReadLine();

((System.DirectoryServices.AccountManagement.AuthenticablePrincipal)(result)).Enabled
is working fine to get the enabled true or false in the list of users.

A: I can tell you what works for me in one of my applications.  Here is a snippet from my application:
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "domain.com"))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(pc, "Doe, John"))
    {
        Console.Out.Write(user.Enabled);
    }
}

This, for me, accurately returns whether the account is enabled or not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not set font for html2pdf in Laravel app In laravel 5.7 app I work with spipu/html2pdf 5.2 to generate piece of html/bootstrap code
into pdf file and I have a problem with font definition
My pages use Roboto font, but if I make :
$html2pdf = new HTML2PDF('P','A4','en', true, 'UTF-8');
$html2pdf->addFont('Roboto', '', public_path('/fonts/roboto/Roboto_regular.ttf'));

I have font in my app /fonts/roboto/Roboto_regular.ttf
and I can preview it : https://prnt.sc/tgcgjq
$html2pdf->WriteHTML(htmlspecialchars_decode($pdf_content));
$html2pdf->Output($save_to_file,'F');

But I got error :
TCPDF ERROR: The font definition file has a bad format: /mnt/_work_sdb8/wwwroot/lar/the-box-booking/public/fonts/roboto/Roboto_regular.ttf

The difference in path is that I use links :
ln  -s   /mnt/_work_sdb8/wwwroot  /_wwwroot

If I try to use times font(which I want to use for generated pdf file) as
$html2pdf->addFont('times');

I got error :
TCPDF ERROR: Could not include font definition file: &#039

looks like in last case fontname is not set , but I do not know how have I to set it ?
I have times set in my OS, I suppose I do not to put it under /public/fonts/?
Thanks!


text:
Q: Bootstrap 4 – Text/Icon on  element I am trying to overlay an icon on a progress bar in the Bootstrap 4 alpha.
<progress class="progress progress-primary" value="100" max="100">

</progress>

It should look like the following (roughly):

Instead, I end up with the following:

Unfortunately, no combination of appearance:initial; and !important tags are doing the trick.
What am I missing that is causing the text within the <progress> element to not show?

A: Move the icon outside the progress element and use position:relative..
<progress class="progress" value="10" max="100"></progress>

.fa {
    position: relative;
    z-index: 2;
    top: -35px;
    left: 50%;
}

http://www.codeply.com/go/gl3DnWcPKu

A: In the latest version of Bootstrap 4, alpha-6, this issue isn't a problem anymore:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

25%


text:
Q: No tidy method for objects of class LiblineaR
I have fitted text data based on regression and LiblineaR engine. And I want to `tidy()` my results. I have also installed the dev version of `broom`.
But I always get an error.  `ERROR: No tidy method for objects of class LiblineaR`
> svm_fit %>%
+   pull_workflow_fit() %>%
+   tidy()
ERROR: No tidy method for objects of class LiblineaR

A: We just merged in support for the tidy() method for parsnip models fitted with the LiblineaR engine, so if you install from GitHub, you should be able to have this feature now:
devtools::install_github("tidymodels/parsnip")

Here is a demo of how it works:
library(tidymodels)
#> Registered S3 method overwritten by 'tune':
#>   method                   from
#>   required_pkgs.model_spec parsnip

data(two_class_dat, package = "modeldata")
example_split <- initial_split(two_class_dat, prop = 0.99)
example_train <- training(example_split)
example_test  <-  testing(example_split)

rec <- recipe(Class ~ ., data = example_train) %>%
  step_normalize(all_numeric_predictors())

spec1 <- svm_linear() %>%
  set_engine("LiblineaR") %>%
  set_mode("classification")

spec2 <- logistic_reg(penalty = 0.1, mixture = 1) %>%
  set_engine("LiblineaR") %>%
  set_mode("classification")

wf <- workflow() %>%
  add_recipe(rec)

wf %>%
  add_model(spec1) %>%
  fit(example_train) %>%
  tidy()
#> # A tibble: 3 x 2
#>   term  estimate
#>   <chr>    <dbl>
#> 1 A        0.361
#> 2 B       -0.966
#> 3 Bias     0.113

wf %>%
  add_model(spec2) %>%
  fit(example_train) %>%
  tidy()
#> # A tibble: 3 x 2
#>   term  estimate
#>   <chr>    <dbl>
#> 1 A        1.06
#> 2 B       -2.76
#> 3 Bias     0.329

svm_linear() %>%
  set_engine("LiblineaR") %>%
  set_mode("regression") %>%
  fit(mpg ~ ., data = mtcars) %>%
  tidy()
#> # A tibble: 11 x 2
#>    term  estimate
#>    <chr>    <dbl>
#>  1 cyl    0.141
#>  2 disp  -0.0380
#>  3 hp     0.0415
#>  4 drat   0.226
#>  5 wt     0.0757
#>  6 qsec   1.06
#>  7 vs     0.0648
#>  8 am     0.0479
#>  9 gear   0.219
#> 10 carb   0.00861
#> 11 Bias   0.0525

Created on 2021-04-22 by the reprex package (v2.0.0)


text: Q: How do I reduce the tarball size of an R package? In Bioconductor, it is required that the tarball size should be <= 4MB but my package's tarball size is 50MB.  I checked the folders and found that the actual package is less than 1MB but the .git folder is taking all the spaces. Why is the size of the package's tarball high?


text:
Q: trying to add a stats object to a DoublyLinkedList Im trying to add a Stats object which would be a player with first, last name ,level and experience.  I have that set up in a Stats.h.  But my problem is in the main i cannot figure out how to add the stats player to the list.  Here is what i am trying to do:
Stats stats;
DoublyLinkedList<Stats> list;
DoublyLinkedListIterator<Stats> itr = list.getIterator();

int main ()
{
    Stats s1 = ("John","Campbell",0,0);//This causes error.
    //No suitable conversion between int and string.

    list.Append(s1);
    list.Append(144);
    list.Append(1);
    list.Append(1111);
    list.Prepend(1000);

I really cant figure out if i am attempting it correctly or if i am off course completely. Any help will be greatly appreiacted.

A: You probably meant:
Stats s1("John","Campbell",0,0);

That's assuming that Stats has a constructor that accepts those four parameters.
If Stats is a POD struct containing those four datatypes, this will work:
Stats s1 = {"John","Campbell",0,0};

And if you're using C++11, either case would work with:
Stats s1 {"John","Campbell",0,0};

A: Stats s1 = ("John","Campbell",0,0);//This causes error.

You should do this
Stats s1("John","Campbell",0,0);


text:
Q: Long mathematical computations in android app I'm an amateur developer and I'm creating an Android app that will perform long mathematical calculation (involving multiple for-loops for example). I've read on the Android Developer website that Renderscript is a possible way of reducing computational time and memory. However, I have no readability (or writability for that matter) in C, so I was wondering if there's any more effective (time/memory) ways of carrying out the computations.
Otherwise, if there's really no other ways, are there helpful resources for me to look besides the Renderscript section on the Android website?

A: You have two choices to compute directly on device:
Renderscript:

*

*(+) Supports different types of current and future architectures.

*(+) It will enable computations on GPU in future.

*(+) It is easily scalable to run on multiple cores.

*(-) Minimal API level 11.

Android NDK:

*

*(+) cross-platform code

*(-) Application have to be compiled for each available architecture by developer.

*(-) If new architecture emerge then new build is needed.

A: What about doing the computations on a server and sending back the results to the Android device?
You can implement a RESTful service server side and call it via http from Android.


text:
Q: Searching a data.frame in R I have data.frame similar to following simplified one:
ddf
  id                  country          area
1  1 United States of America North America
2  2           United Kingdom        Europe
3  3     United Arab Emirates          Arab
4  4             Saudi Arabia          Arab
5  5                   Brazil South America

ddf = structure(list(id = 1:5, country = c("United States of America",
"United Kingdom", "United Arab Emirates", "Saudi Arabia", "Brazil"
), area = c("North America", "Europe", "Arab", "Arab", "South America"
)), .Names = c("id", "country", "area"), class = "data.frame", row.names = c(NA,
-5L))

I want to print all rows where the text 'america' (case-insensitive) comes in

*

*any column

*column with name 'area'

The number of rows and columns and the column names are variable so I cannot use ddf[,1] etc.
I tried following but it is not working:
ddf[apply(ddf, 1, function(x) grepl('america',x, ignore.case=T) ),]
   id              country   area
2   2       United Kingdom Europe
3   3 United Arab Emirates   Arab
NA NA                 <NA>   <NA>

A: Here's an approach using qdap package:
library(qdap)
Search(ddf, "america")

##   id                  country          area
## 1  1 United States of America North America
## 5  5                   Brazil South America

Have a look at the source code for more info on how it works.
For the second request...
Search(ddf, "america", "area")

A: In base R:
ddf[do.call(mapply,c(any,lapply(ddf,grepl,pattern="america",ignore.case=TRUE))),]

#  id                  country          area
#1  1 United States of America North America
#5  5                   Brazil South America

A:  hasAm <-  sapply( ddf, grepl, patt="america", ignore.case=TRUE)
 ddf[ rowSums(hasAm) > 0 , ]
  id                  country          area
1  1 United States of America North America
5  5                   Brazil South America

The first value, hasAm is just a logical 'image' of the dataframe, which the second line delivers via logical indexing any row where there is a TRUE.

A: It was suggested I un-delete this answer, so here it is.
One other way that uses mapply
> m <- mapply(grep, "america", ddf, ignore.case = TRUE)
> ddf[unique(unlist(m)), ]
#   id                  country          area
# 1  1 United States of America North America
# 5  5                   Brazil South America

You can also use lapply and sapply in the same manner
> s <- sapply(ddf, grep, pattern = "america", ignore.case = TRUE)
> ddf[unique(unlist(s)), ]
#   id                  country          area
# 1  1 United States of America North America
# 5  5                   Brazil South America


text:
Q: Complex jQuery and SVG interactions I have a very complex svg that I am trying to get to play nicely with jQuery. Basically I am trying to introduce a hover and click state on the various petals, where the outcome will be different depending on which one I've interacted with. My svg looks like;
<svg version="1.1" id="run-compare-graph"  style="margin-top:-30px;height:400px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 356.2 356.5" enable-background="new 0 0 356.2 356.5" xml:space="preserve">

                    <g id="mask_1" class="card-toggle">
                        <path fill="#BDBDBD" d="M52.2,52.3"/>
                        <path fill="#BDBDBD" d="M0,178.3"/>
                        <path fill="#BDBDBD" d="M52.2,304.3"/>
                        <path fill="#BDBDBD" d="M178.2,356.5"/>
                        <path fill="#BDBDBD" d="M304.1,304.3"/>
                        <path fill="#BDBDBD" d="M356.3,178.3"/>
                        <g>
                            <defs>
                                <polyline id="SVGID_1_" points="304.1,52.3 178.2,0.1 178,178.3          "/>
                            </defs>
                            <clipPath id="SVGID_2_">
                                <use xlink:href="#SVGID_1_"  overflow="visible"/>
                            </clipPath>
                            <circle clip-path="url(#SVGID_2_)" fill="#57D6AC" cx="178" cy="178.3" r="149"/>
                        </g>
                    </g>
                    <g id="mask_2" class="card-toggle">
                        <path fill="#BDBDBD" d="M52.2,52.3"/>
                        <path fill="#BDBDBD" d="M0,178.3"/>
                        <path fill="#BDBDBD" d="M52.2,304.3"/>
                        <path fill="#BDBDBD" d="M178.2,356.5"/>
                        <path fill="#BDBDBD" d="M304.1,304.3"/>
                        <path fill="#BDBDBD" d="M356.3,178.3"/>
                        <g>
                            <defs>
                                <polyline id="SVGID_3_" points="356.3,178.4 304.1,52.4 178,178.3            "/>
                            </defs>
                            <clipPath id="SVGID_4_">
                                <use xlink:href="#SVGID_3_"  overflow="visible"/>
                            </clipPath>
                            <circle clip-path="url(#SVGID_4_)" fill="#F1F954" cx="177.7" cy="178.8" r="101"/>
                        </g>
                    </g>
                    <g id="mask_3" class="card-toggle">
                        <g>
                            <defs>
                                <polyline id="SVGID_5_" points="304,304.4 356.2,178.5 178,178.3             "/>
                            </defs>
                            <clipPath id="SVGID_6_">
                                <use xlink:href="#SVGID_5_"  overflow="visible"/>
                            </clipPath>
                            <circle clip-path="url(#SVGID_6_)" fill="#6B6565" cx="177.7" cy="178.5" r="112"/>
                        </g>
                    </g>
                    <g id="mask_4" class="card-toggle">
                        <g>
                            <defs>
                                <polyline id="SVGID_7_" points="177.9,356.6 303.9,304.4 178,178.3           "/>
                            </defs>
                            <clipPath id="SVGID_8_">
                                <use xlink:href="#SVGID_7_"  overflow="visible"/>
                            </clipPath>
                            <circle clip-path="url(#SVGID_8_)" fill="#0F5947" cx="178.3" cy="178.3" r="109"/>
                        </g>
                    </g>
                    <g id="mask_5" class="card-toggle">
                        <g>
                            <defs>
                                <polyline id="SVGID_9_" points="51.9,304.3 177.8,356.5 178,178.3            "/>
                            </defs>
                            <clipPath id="SVGID_10_">
                                <use xlink:href="#SVGID_9_"  overflow="visible"/>
                            </clipPath>
                            <circle clip-path="url(#SVGID_10_)" fill="#57D6AC" cx="178" cy="178.3" r="101"/>
                        </g>
                    </g>
                    <g id="mask_6" class="card-toggle">
                        <g>
                            <defs>
                                <polyline id="SVGID_11_" points="-0.3,178.2 51.9,304.1 178,178.3            "/>
                            </defs>
                            <clipPath id="SVGID_12_">
                                <use xlink:href="#SVGID_11_"  overflow="visible"/>
                            </clipPath>
                            <circle clip-path="url(#SVGID_12_)" fill="#0F5947" cx="178" cy="178.3" r="111"/>
                        </g>
                    </g>
                    <g id="mask_7" class="card-toggle">
                        <g>
                            <defs>
                                <polyline id="SVGID_13_" points="52,52.1 -0.2,178.1 178,178.3           "/>
                            </defs>
                            <clipPath id="SVGID_14_">
                                <use xlink:href="#SVGID_13_"  overflow="visible"/>
                            </clipPath>
                            <circle clip-path="url(#SVGID_14_)" fill="#57D6AC" cx="178" cy="178.3" r="93"/>
                        </g>
                    </g>
                    <g id="mask_8" class="card-toggle">
                        <g>
                            <defs>
                                <polyline id="SVGID_15_" points="178.1,0 52.1,52.2 178,178.3            "/>
                            </defs>
                            <clipPath id="SVGID_16_">
                                <use xlink:href="#SVGID_15_"  overflow="visible"/>
                            </clipPath>
                            <circle clip-path="url(#SVGID_16_)" fill="#F1F954" cx="177.9" cy="178.2" r="101"/>
                        </g>
                    </g>
                    <g id="Layer_5">
                        <circle fill="#414045" cx="178.2" cy="178.4" r="63"/>
                        <circle opacity="0.3" fill="none" stroke="#FFFFFF" stroke-miterlimit="10" cx="178.2" cy="178.3" r="100.7"/>
                        <circle opacity="0.3" fill="#414045" stroke="#FFFFFF" stroke-miterlimit="10" cx="178.2" cy="178.3" r="81.3"/>
                    </g>
                    <g id="RUN_SCORE">
                        <text transform="matrix(1.0008 0 0 1 145.7867 148.506)" fill="#BDBDBD" font-size="12.147">RUN SCORE</text>
                    </g>
                    <g id="_x36_7">

                            <text id="run-compare-value"  transform="matrix(1.0008 0 0 1 136.7773 210.2179)" fill="#57D6AC" font-size="67.0697" letter-spacing="-1">98</text>
                    </g>
                    </svg>

where the output looks like this:

I am now trying to implement some jQuery action like click and hover states over the various petals. The best I could do was to target the circles using
$('svg .card-toggle').mouseover(function(){
  $('.data-card').eq($(this).index()).addClass("big");
});

This works well-ish... However it breaks down close to the edges of where the colors change, and close to the center of the circle.
QUESTION:
Do I need to rework how I am using the jQuery? Or am I 'SOL' as they say, because this is the best markup I am going to get, given the shape I am trying to reproduce?
Thanks,
Alex


text:
Q: Get check box state when state changed foundation How to get the check box state when it is changed. I am using zurb foundation
<input id="checkbox2" type="checkbox" name="chk[2]"></input>

   Check Box 1

But in function  state prior to clicked is shown.
How should i get the latest value
Please Help

A: I would remove the onclick="toggleState(2)" and try some jquery code similar to:
$('#checkbox2').on('change', function() {
  console.log($(this).is(':checked'));
});

Also, you should change your label to  rather than  as an element with the id checkbox3 doesn't exist.
It would also help if you could mention what version of Foundation you are using.


text:
Q: Any word embedding methods that keep lexicological order? I want to turn a string into a feature vector but also keeps its lexicological order (actually it is the only thing I care about for the vector).
I know that ASCII value is the easiest way(?) to do so ("abc123"->[97,98,99,49,50,51]). But it seems not that intuitive with respect to the string order. Say we can set a max string length of 3, then the distance between 'am9' and 'ama' should be 1 but it isn't if using ASCII values.


text:
Q: I want to change the Django list output format I want to change the Django list output format.
I want to change the output format of list
The view code is as follows:
def team_todo_list(request, team_name):
    print("team_name : ", team_name)

    teamId = TeamInfo.objects.get(team_name = team_name).id
    team_leader_name = TeamInfo.objects.get(team_name = team_name).leader.username

    print("team_leader_name : ", team_leader_name)

    team_member = TeamMember.objects.filter(team=teamId)
    classification_list = Classification.objects.all()
    team_name= team_name

    member_array = []
    for member in team_member:
        # print(member.member.id) # nomad_coder, terecal
        member_array.append(member.member)

    team_todo_list = Todo.objects.filter(author__in=member_array)

    print('team_todo_list : ' , team_todo_list)
    print('team_member : ' , team_member)

    return render(request, 'todo/team_todo_list.html', {
        "team_todo_list":team_todo_list,
        "team_member_list":team_member,
        "classification_list":classification_list,
        "team_name":team_name,
        "team_leader_name": team_leader_name
    })

The template code is:

            check
            class
            manager
            title
            remaining time
            deadline

        {% if team_todo_list.exists %}
        {% for p in team_todo_list %}

                <input type="checkbox" id="{{p.pk}}" class="td_check">

            {{p.classification}}
            {{p.author}}

                    {{p.title}} ( from {{p.director}} )

                modify

                {% if p.dead_line %}
                {{p.remaining_time}}
                {% else %}
                {% endif %}

            {{p.dead_line}}

        {% endfor %}

        {% else %}

there is no article

        {% endif %}

Currently in this format
current
I want to change it like this.
after
Thanks for telling us how to modify the view or the template to change the output format of the list.
Thank you very much for telling us how
problem is resolved by this code

        {% regroup team_todo_list by author as author_list %}

        {% for author in author_list %}

                        {{ author.grouper }}

                체크
                분류
                담당
                title
                남은 시간
                마감 기한

            {% for todo in author.list %}

                    <input type="checkbox" id="{{todo.pk}}" class="td_check">

                {{todo.classification}}
                {{todo.author}}

                        {{todo.title}} ( from {{todo.director}} )

                    수정

                    {% if todo.dead_line %}
                        {{todo.remaining_time}}
                    {% else %}

                    {% endif %}

                {{todo.dead_line}}

            {% endfor %}

        {% endfor %}

A: You can use regroup template tag, which allow you to group your data when rendering in Django template. Like so:
{% regroup team_todo_list by author as author_list %}

{% for author in author_list %}

Author name: {{ author.grouper }}

    {% for todo in author.list %}

Show your todo here {{ todo }}

    {% endfor %}
{% endfor %}

*

*author is the keyword which you want to group on

*author_list is the list of grouped data

*.grouper is the value of the field which you're grouping on

*.list is the list of item which grouped by the field

Hope that helps!

A: My answer suggests that your views.py is okay.

            check
            class
            manager
            title
            remaining time
            deadline

      {% for p in team_todo_list %}

                {{p.author}}

         {% if team_todo_list.exists %}

                <input type="checkbox" id="{{p.pk}}" class="td_check">

            {{p.classification}}
            {{p.author}}

                    {{p.title}} ( from {{p.director}} )

                modify

                {% if p.dead_line %}
                {{p.remaining_time}}
                {% else %}
                {% endif %}

            {{p.dead_line}}

         {% endfor %}

         {% comment %}
            I don't know what this tbody is for so I would comment it out

         {% comment %}

         {% else %}

there is no article

         {% endif %}

     {% endfor %}

Then you can style your CSS table similar to this:
.table-no-border {
    border-collapse: collapse;
    border: none;
}

th, td {
    border: 2px solid black;
}

.user{
    border:none;
    font-size: 1em;
    padding-top: 20px;
    padding-bottom: 20px;
}

*

*Just the placement of the for loop, the if-else statement and slight css can change the looks.


text:
Q: Interface Mobile SDRAM (1.8V) with 3.3V SDRAM controller I am looking for a 256Mbit SDRAM module in BGA format, to buy in units of 1000. However the cost for these modules are extremely high for packages using a 32bit bus in standard 3.3V voltages, however Mobile SDRAM running at 1.8V is available for the 32bit bus at half the price, or lower!
I am wondering if it is possible to 'overpower' these modules to 3.3V (probably not very likely) or get away with connecting the SDRAM without using many buffers?
I would appreciate any input.
Regards,
James

A: SDRAM can be a bit difficult to work with, and unless you have the tools, ability, and time to  debug things then it is not a good idea to use what probably won't work.  And by "tools", I mean an o-scope + probes that goes up to at least 350 MHz (1 GHz is preferred) and maybe a logic analyzer.  "Ability" means that you know the SDRAM protocol inside and out.  And "time" means at least several weeks to figure things out.   You might also have difficulty probing the BGA pins, too.
You cannot "overpower" an SDRAM, since that'll break it.  You need to convert the 3.3v signals to 1.8v, and vice versa, and you need to do it cleanly.  Basically, you need buffers that will do the translation (and match the signaling specification as well).  To make matters worse, some of these buffers must be bidirectional and they eat into your timing budget.  If your clock rate is slow enough you might get away with this.  Designing something like this requires at least an "intermediate engineer".  A newbe engineer just isn't going to cut it, given all the complex timing, termination, and control that needs to be done for the buffers.
Given that, the correct 3.3v SDRAM might not be looking all that expensive after all!  :)  There is something to be said about using the right parts in the right places.


text:
Q: Using Matlab regexp on a cell array to return specific filenames I have a folder in which there are many files and I want to create a matrix that holds filenames with a specific pattern. For example: The folder contains files with names starting with a subject number (e.g. 03T1A.xxx.nii, 03T1A.yyy.nii) as well as filenames with specific patterns in the middle (e.g. 03T1A.c100.nii, 03T1A.c200.nii, 03T1A.c300.nii). In this specific case I am looking to extract all the filenames with the pattern c1 and c2 in the middle (e.g. 03T1A.c100.nii and 03T1A.c200.nii but not 03T1A.c300.nii).
To this point I have used the following code to create a pattern matching variable in 'pattern' which I would like to apply to the cell array of filenames I have extracted into the variable 'all_files' via the dir call.
func_path = char(strcat(input_dir, '/', subs(files), '/Func'));
pattern = 'c[12]*.nii'
all_files = dir(func_path);
all_files = {all_files.name};

I'd like to use (read. practice) regexp and doing it with string input seems easy but I am 100% stumped as to how to do it with cell input.
I started trying to do something like this:
files = all_files(cellfun(@(x)regexp(x, pattern));

But it doesn't work, obviously. Could someone help me figure out what to do here if my ultimate goal is to get a matrix output with just the relevant filenames? I've been searching MATLAB answers and other Stack Overflow posts but part of my problem is I don't understand what's happening in their code snippets. I took the above line (or at the least the beginning of it) from another post but I don't know what, for example, 'x' is (an output variable?) or what's going on in the larger command such as
fin = cellfun(@(x)regexp(x, '\.', 'split'), res, 'UniformOutput', false)

Which I found in another thread.
So basically, can someone help me figure out a command that will work while explaining it to me?

A: A couple of recommendations for doing this sort of thing

*

*Do not use strcat and '/' characters to construct file paths. strcat trims whitespace from all inputs prior to concatenation (filenames may have actual leading or trailing whitespace) and also rather than hard-coding a file path separator such as '/' , use filesep or better yet use fullfile to construct the path to ensure that it will work on various platforms without problems.
func_path = fullfile(input_dir, subs(files), 'Func');

*regexp works directly on cell arrays therefore you can simply do:
all_files = dir(func_path);

% Search for the pattern in all filenames
matches = regexp({all_files.name}, pattern);

% Get the filenames of those that matched
all_files = {all_files(~cellfun('isempty', matches)).name};

*Your pattern isn't matching any files because it currently would match only strings that contain a "c" with only zero or more 1's or 2's before the file extension. Instead, you'll want to use .* to match anything between the "c1" or "c2" and the filename. Also you'll want to not use a * after [12] since that will actually match c3 since that has zero 1's or 2's.  Also you'll want to escape the . in .nii so that it's not treated like a wildcard. For your pattern I would use something like
pattern = 'c[12].*\.nii';

*If you really don't want to work with regular expressions, you could avoid all of this by simply using wildcards in your dir call
c1_files = dir(fullfile(func_path, '*c1*.nii'));
c2_files = dir(fullfile(func_path, '*c2*.nii'));


text:
Q: nulled object parameter value re-appearing in GSP Am implementing User controller around springsource-security-core plugin.
When I "show" a user instance in my controller ("User") I want to ensure that the password parameter is nulled and is displayed as a blank edit control.
This is the code for the "show" method:
@Secured(['ROLE_SUPERUSER','ROLE_USER'])
def show(Long id) {

/**
 * If we're not the Superuser, then we only want to see the instance of the logged in user.
 */
def userInstance

if (SpringSecurityUtils.ifNotGranted('ROLE_SUPERUSER')) {
    userInstance=springSecurityService.currentUser
} else {
    userInstance = User.get(id)
}

    if (!userInstance) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
        redirect(action: "list")
        return
    }

    userInstance.setPassword(null)

    [userInstance: userInstance]
}

Setting a "watch" on 'userInstance' indicates that the userInstance.setPassword(null) has the desired effect and sets the "password" parameter to 'null'.
However, when the view is rendered with the same parameter set, the password is populated.
I'm looking to implement a "password-confirmation" field as well. I'm a bit new to groovy/grail so I'm feeling my way around this step by step. It appears that by passing in "userInstance" I pass an Instance of the "User" domain class.
Do I need two encoded fields in the domain class or can I add a field to the GSP on the fly and then validate this in the controller before saving the domain class with an encoded password?

A: Best way to do this is to use command objects, please see :
Official documentation


text:
Q: How can I use UIImageView with aspectFill and alignment to the top? How could I use UIImageView with aspectFill and alignment to the top? Auto-layout or programmatically don't mind.

A: It can be done, but you are talking about quite a bit of coding. Let's start with a detailed description of what you are asking for.
We'll start with an iPhone6s in portrait mode with a screen size of 667x375 points, or a regular height by compressed width in size classes.
(Keep in mind, on any iPad you'll also need to work with slide-over and split screen too.)
But for now we'll go with 667x375. Into that we'll add our imageView as a square size of 375x375. Along the top of the screen when in portrait mode.
(Keep in mind that with AutoLayout you'll also have it pinned, and without putting some code in to determine if it's in landscape or portrait, otherwise, that 375x375 will shrink in landscape if you have other views underneath it.)
So now, stripped out to the most minimum (for now), we are talking about how to pin "an image" to the top of a UIImageView that is 375x375 in size and with a contentMode of aspectFill.
We need to find the size of the image next, based on both the largest dimension (height or width) AND how that dimension compares to the size of the imageView, calculate how the imageView will normally render it. The key figure you want is the height it will render it as
For instance, how will a 480x1020 (HxW) image fit into it? The 1020 width will be taken down to 375, so the height will be 480/(1020375) or 176.4705 points.
Always do the math for both dimensions - if your imageView isn't square or if the height isn't the "bounded" dimension, you'll be off.
Once you've calculated what the "Aspect Filled" height will be, check it against the dimensions of the imageView, and adjust the height of it as needed.
Here's where the real work comes in. If you are using AutoLayout, you can do a heightAnchor adjustment, but depending on how you pinned those other views things may be laid out really bad after you do. If you are using frames and CGRects be aware that you have to take into account iPad slide-out and split screen, etc.
Finally, if you want your app to load a different image in that imageView after it was loaded, you will have to "reset" the height back to what it originally was, at least in your calculations.
My recommendation is to find an alternative to what you are asking. For instance, put a small border around the image view to let the user know the true dimensions of that view.


text:
Q: Concrete5 Stacks & Blocks I am working on existing concrete5 website and I don't have sufficient knowledge of concrete database structure.
I am creating api to fetch all the products which are added in "Stacks and Blocks".
I have cID, stID values and fetched the info from stacks table, Can anyone please let me know How to fetch the complete details including image from database.
I tried to make the relation between tables based on cID, stID.
Thanks in advance.

A: The images are stored in the application/files directory although you'll need to retrieve the path from the database to find them. as @1stthomas noted, without more details of the information you are working with, it's difficult to provide any specific advice.
FWIW, the API documentation for concrete5 can be found here.


text:
Q: Joint distribution where one of the random variable is discrete Let $X$ be uniform over $(0,1)$ and let $Y$ be a discrete random variable having Poisson distribution. Suppose $X , Y$ are independent. Let $Z = X + Y$. Show that $Z$ is a continuous random variable.
I came across this problem in my college previous year paper.
Tried to solve it.
$$ P[Z=z] = P[Z=x+y] =P[X=k , Y=z-k]$$
Limits will be $$ 0≤K≤1 \text{ and }z-k>0 $$
Now Limit for $K$ will be $$ 0≤k<z≤1 $$ Since $k$ is continuous can we stop here saying $Z$ is continuous? Or if we need to calculate pdf I tried using the below method but I am not sure if am on the right path.
$$ P[Z=z] =  \int_0^z \frac{m^{z-k}e^{-m}}{z-k!} \, dk $$
Not sure if I am on the right path and I am stuck not able to proceed. Need guidance here to solve the problem.

A: Fix $n \in \mathbb{Z}$ and $a \in [0,1)$.
$$P(Z \le n + a) = P(X \le n-1) + P(X = n, Y \le a) = P(X \le n-1) + P(X = n) P(Y \le a)$$
$$P(X \le n-1) + P(X = n) \cdot a.$$
Hence $P(Z \le x)$ is a continious function of $x$.


text:
Q: Using local TFS workspace for non-VisualStudio source code I am trying to use TFS storing non-VisualStudio source code. Working with Visual Studio 2012 and Microsoft's online Team Foundation Service.
I've setup a TeamProject and mapped its root to a local folder. All it contains at the moment is a BuildProcessTemplates folder in it. (which was created as part of the TeamProject)
I copied my source code externally (using windows explorer) into the TeamProject root folder on my hard drive and since my TFS workspace is NOT a server workspace but rather a local workspace, I was expecting VS to detect the folders/files and show them in Pending Changes window .... yet it doesn't.
Interestingly, new files in the root folder are detected as "Excluded Changes" but new folders are not detected.
What am I missing?

A: First make sure the newly added folders contains files.
Are there any Detected changes shown in the Excluded Changes section?

Pending Changes > Detected changes link > The Promote Candidate Changes dialog box appears > check the files you want and click Promote.

A: I can't say I have ever noticed nor expected TFS to automatically pick up files or folders added to a mapped directory as pending changes.
I always just add them manually using the 'Add existing items' option from the source control view.
It may actually do (or at least be meant to do) the auto-detection, but I can't say I've ever relied on it. I don't think it's something to fret too much about - adding them manually is easy enough, and the 'Add existing items' option is usually smart enough to show you which files are not already under source control, so even if you need to add even more files later, it shouldn't be too much extra effort.


text:
Q: How to push string in a given range in stack in C++? int main()
{
    istringstream iss(dtr);
    Stack <string> mudassir;
    mudassir.push1(s1);
    string subs;
    do {
        iss >> subs;
        if (subs == "|post_exp|")
        {
            iss >> subs;
            while (subs != "|\\post_exp|")
            {
                mudassir.push(subs);
                cout << "heloo";
                iss >> subs;
            }
        }
    } while (iss);
}

I want to push a certain element of string in stack. But the problem is in this code, the inner while loop which has hello (just for testing) in it is running infinitely. I don't know why.

A:
the inner while loop which has hello (just for testing) in it is running infinitely. I don't know why.

Your inner while loop is not taking into account when the stream reaches the end of its data.
When operator>> reaches the end of the stream, it will put the stream into the eofbit state, and subs will be set to whatever data was left in the stream. Subsequent reads with operator>> will put the stream into the failbit state, and set subs to a blank value.
Your inner loop is ignoring the stream's state completely, and the blank value satisfies the != condition that you are checking.  That is why your loop runs forever.
You need to pay attention to the stream's state. For example:
int main()
{
    istringstream iss(dtr);
    Stack <string> mudassir;
    mudassir.push1(s1);
    string subs;
    while (iss >> subs) {
        if (subs == "|post_exp|")
        {
            while (iss >> subs && subs != "|\\post_exp|")
            {
                mudassir.push(subs);
                cout << "heloo";
            }
        }
    }
}


text:
Q: C# SqlConnection Exception: Keyword not Supported 'Port' I have looked at a lot of posts with the same topic.
But neither helped me.
I want to use Postgresql with a CrossPlatform-App. Later I will use a server in the cloud but for trying I think it's easier to use a local database.
Therefore I have installed database itself and the "npgsql" Package with "NuGet", like recommended from the Postgres guys. After getting always the same error while connecting, I reduced the code to a console-App with really ten lines of code.
namespace SqlTester_ConsolApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string MyConnection = "Server=127.0.0.1;Port=5432;Database=sample;UserId=Postgresql;Password=zzzzzzzzz;";

            try
            {
                SqlConnection Connection = new SqlConnection(MyConnection);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("---------------------------------------------------------------------");
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
            System.Diagnostics.Debug.WriteLine("Ready");
        }
    }
}

The new SqlConnection always terminates with and System.ArgumentException telling Keyword not supported 'port'.
The cause is clear, the .Net Framework tries to use SQL Server instead of passing my String to the npgsql driver. Therefore it does not make sense to cut the "port" from the string.
My question is how can I change the string parsing to the Progresql Provider? Actively I did nothing for that wrong selection, it's obviously part of the default behavior from the .Net Framework and it's either an error or intention to support only MS-Products.
I tried somethings to change the behavior.
Update for clarification: Because the usage of "NpgsqlConnection" is not acceptable for me. My code should be provider-independent.
As I found in the Postgresql-Docu to npgsql and to another question with the same problem I added the following lines to the App.Configfile of the Console-App.
<system.data>
  <DbProviderFactories>
    <add name="Npgsql Data Provider" invariant="Npgsql" description=".Net Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"/>
  </DbProviderFactories>
  <defaultConnectionFactory type="Npgsql.NpgsqlFactory, Npgsql, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"></defaultConnectionFactory>
</system.data>

It did not help. The other thing is, if it would help with the App.Config how can I transfer that to my Cross-Platform-App. There is no App.Config.
My Problem is the environment not the programming itself. I start programming again after years in other jobs. So all the environment is absolutely new to me. Until that point Visual Studio handled anything automatically. So I have not to learn many details. I tried to find some information about the .Net-internals for DbProviderFactories and configuring of apps. But I did not find useful information, mostly because of not knowing how to search.  So any help is useful to me. Thanks in advance.

A: SqlConnection is specific to SQL Server. You would need to use NpgsqlConnection to use a Postgres connection, which means you will need the references to the Postgres assemblies.
But you are intending to move to a different provider in future, so to minimise the impact of that move, try to use the generic base classes in your code. For example:
var connString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";
using (DbConnection conn = new NpgsqlConnection(connString))
{
    conn.Open()
    using (DbCommand command = conn.CreateCommand())
    {
        // etc
    }
}

This way, when you swap over, all you need to do is replace NpgsqlConnection across your solution with SqlConnection. If you want to use DbProviderFactory (there's a good example in there) then you can, but basically you are only saving yourself this single search/replace, removing the references, and releasing a new version of the code.
I'd suggest putting the connection string in the config file rather than code (as shown in the question) to avoid having it in multiple places, and make it easier to change without a rebuild.
And of course you may have to fix any implementation-specific details in the SQL itself.

A: Here's a basic code to get you started. But the best way for beginners i to take a tour through tutorial http://www.npgsql.org/doc/index.html
var connString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";
using (var conn = new NpgsqlConnection(connString))
{
    conn.Open();
}


text:
Q: Find friends page with user NSContacts is very slow + "This application is modifying the autolayout engine from a background thread" I'm trying to develop a find friends page that checks if any of the user's contacts has already joined my platform. It shouldn't take too long, however it take about 2 to 3 minutes which makes me think there's something wrong with it. I have a couple ideas on what that could be :

*

*I'm messing up somewhere in my asynchronous call. This is my main hypothesis, although I'm not sure where. That's very likely to be the cause though also because on the console I get the following error :

This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.  This
  will cause an exception in a future release.

I think that is hapenning inside one of the for loops since I get the error multiple times.

*

*My other idea is that the delay has something to do with the constraints since I also get :

Will attempt to recover by breaking constraint NSLayoutConstraint:0x127c2ab00 UITextView:0x127011000'Name lastname created ...'.centerY == UIView:0x1278c21b0.centerY>
            let store = CNContactStore()

            //Find all  the contacts and store them in an instance variable

            store.requestAccessForEntityType(.Contacts) { granted, error in
                guard granted else {
                    dispatch_async(dispatch_get_main_queue()) {
                        // user didn't grant authorization, so tell them to fix that in settings
                        print(error)
                    }
                    return
                }

                // get the contacts
                self.showActivityIndicator()

                var localcontacts = [CNContact]()
                let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactPhoneNumbersKey])

                request.sortOrder = CNContactSortOrder.GivenName

                do {
                    try store.enumerateContactsWithFetchRequest(request) { contact, stop in
                        if !contact.phoneNumbers.isEmpty {
                            localcontacts.append(contact)
                        }

                    }
                } catch {
                    print(error)
                }

                self.cncontacts = localcontacts

                var cs = [contactObject]()

                for contact in self.cncontacts {
                    let formatter = CNContactFormatter()
                    formatter.style = .FullName
                    let name = formatter.stringFromContact(contact)
                    var numbers = [String]()
                    if (contact.isKeyAvailable(CNContactPhoneNumbersKey)) {
                        for phoneNumber:CNLabeledValue in contact.phoneNumbers {
                            let a = phoneNumber.value as! CNPhoneNumber
                            let number = a.stringValue.stringByReplacingOccurrencesOfString(" ", withString: "-", options: NSStringCompareOptions.LiteralSearch, range: nil)
                            numbers.append(number)
                        }
                    }
                    if numbers.count > 0 {
                    let c : contactObject = contactObject.init()
                    c.name = name!
                    c.numbers = numbers
                    cs.append(c)

                    }

                }

                self.contacts = cs
                //For each contactObject check if there's an user associated with it

                for localcontact in self.contacts {

                    print(localcontact.name)

                    for number in localcontact.numbers {

                        print(number)

                        if number.hasPrefix("+1") || number.hasPrefix("(") || number.hasPrefix("1"){
                            //Is american phone number
                            var formattednumber = number

                            if number.hasPrefix("+1") {

                                if number.hasPrefix("+1 "){
                                    formattednumber = number.stringByReplacingOccurrencesOfString("+1 ", withString: "")
                                    formattednumber = formattednumber.stringByReplacingOccurrencesOfString(" ", withString: "")
                                }
                                else if number.hasPrefix("+1-"){
                                    formattednumber = number.stringByReplacingOccurrencesOfString("+1-", withString: "")
                                }
                                else {
                                    formattednumber = number.stringByReplacingOccurrencesOfString("+1", withString: "")
                                }

                            }

                            else if number.hasPrefix("1"){
                                if number.hasPrefix("1-") {
                                formattednumber = number.stringByReplacingOccurrencesOfString("1-", withString: "")
                                }
                                else{
                                    formattednumber = number.stringByReplacingOccurrencesOfString("1 ", withString: "")
                                }
                            }

                            formattednumber = formattednumber.stringByReplacingOccurrencesOfString(" ", withString: "-")

                            print(formattednumber)
                            let userquery = PFUser.query()
                            userquery?.whereKey("phone", equalTo: formattednumber)
                            userquery?.getFirstObjectInBackgroundWithBlock({ (user, error) in
                                if error == nil {
                                    if let user = user as? PFUser {

                                        localcontact.userid = user.objectId!

                                    }
                                }
                            })

                        }

                    }

                }

                self.hideActivityIndicator()
                let encodedData = NSKeyedArchiver.archivedDataWithRootObject(self.contacts)
                userDefaults.setObject(encodedData, forKey: "contacts")
                userDefaults.synchronize()
                self.tableView.reloadData()

            }

If you have any suggestion or thoughts about what I could be doing wrong I would really appreciate it if you could let me know. Thanks in advance.

A: My guess is
self.showActivityIndicator()
self.hideActivityIndicator()
self.tableView.reloadData()
are all trying to modify the layout of the UI and hence the warning.
Try doing them in
dispatch_async(dispatch_get_main_queue()) {
}
blocks


text:
Q: Genetic Algorithm does not find suitable weights for Neural Network I'm trying to use a Genetic Algorithm for finding optimal weights of a Neural Network. The fitness function is the mean square error of the training results. I use truncation to get rid of the worst half of the genes and afterwards I use  Roulette selection. I'm using a mutation rate of 0.01 and uniform crossover.
Unfortunately, the GA does not find any suitable solution. (I ran the GA 5 times with 1000 generations and a population size of 100 and no gene was good. The MSE is 10 times higher than for the weights I found using Backpropagation)
The GA worked well on finding the minimum of the Drop-Wave function and Levy Function 13 but performs poorly on the ANN weights. How can I improve the GA or the fitness function to make it work?


text:
Q: Issue with BackProjection and Opencv I am trying to implement a backprojection algorithm with opencv to detect hands. This algorithm is composed from multiple sources. I have tried multiple methods such as morphologies and adding backgroundSubtraction to the projection to try to get a better result.I looked online too. However, I keep on getting the pic below. Does anyone have suggestions on what I am possibly doing wrong?
-Thank you
Here is my code with just the backProjection:
import cv2
import numpy as np

#module for esc keyMap on my computer
import keyMappings as kM

#set up webcam
cap = cv2.VideoCapture(0)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1000)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 600)

#read a picture of a hand from my desktop
Hand = cv2.imread('/home/lie/Desktop/handPic.jpg')

#convert HSV and calc Histogram of this Pic
hsvHand = cv2.cvtColor(Hand, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsvHand)
roihist = cv2.calcHist([hsvHand], [0,1], None, [180,256],[0,180,0,256])
cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)

#while not pressing esc
while cv2.waitKey(30) != kM.esc:

  #take pic convert HSV
  _,frame = cap.read()
  hsvt = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

  #backproject
  dst = cv2.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256],1)

  #filtering
  disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  cv2.filter2D(dst,-1,disc,dst)

  #threshold
  ret,thresh = cv2.threshold(dst,50,255,0)

   #find contours in thresholded pic
   contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

   ci =0
   max_area =0

   if len(contours)!=0:
      #find max contour
      for i in range(len(contours)):
        cnt = contours[i]
        area = cv2.contourArea(cnt)
        if(area>max_area):
            max_area = area
            ci =i
      #create hull around contour
      cnt = contours[ci]
      hull = cv2.convexHull(cnt)

 #Code to draw contours and show pic is ommited

This is the image used to help recognize a hand:

This is the thresholded picture:

The picture obviously shows not much of the hand and a lot of noise.

A: Its a very very long time since this post, and frankly I'm a bit surprised nobody responded to you. Although I'm quite sure you've found the answer/alternative solution, for the benefit of others I'll answer this.
What you are observing is directly caused by the number of bins that you are using in your H-S histogram. A larger number of bins means that you will be more finely representing skin, meaning that your eventual histogram will not be able to build up a "trend" of skin. You should absolutely reduce the number of bins. In my experience, about anything between 8 and 12 for both Hue and Saturation channels works well.
However, doing this isn't going to guarantee a very nice backprojected image. You still have a major issue and that is you're using the entire hand template to generate your histogram. As it is, the template contains a lot of skin, but a lot of area around the hand which is not skin. The eventual histogram that you generate will represent background as well. In my experience with this (and I've got a lot of it), even relatively small amounts of noise filtering into the eventual histogram will cause large amounts of noise in your backprojected image. Keeping background in your histogram to a minimum is key. So consider rather taking a small area inside your hand template and generating your histogram only on that. I modified your code as below and it works like a dream on my config.
Note that I made a few changes e.g. this just uses the button 'q' to quit, and the path to the template has been modified, etc. It is mostly the same.
import cv2
import numpy as np

#set up webcam

cap = cv2.VideoCapture(0)
#cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 640)
#cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 480)

#read a picture of a hand from my desktop
Hand = cv2.imread('handPic.jpg')
hh,hw, __ = Hand.shape
#convert HSV and calc Histogram of this Pic
hsvHand = cv2.cvtColor(Hand[220:292, 110:220], cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsvHand)
roihist = cv2.calcHist([hsvHand], [0,1], None, [12,12],[0,181,0,256])
#cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)

#while not pressing esc
while cv2.waitKey(30) & 0xFF != ord('q'):

  #take pic convert HSV
  _,frame = cap.read()
  hsvt = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

  #backproject
  dst = cv2.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256],1)

  #filtering

  # ret, dst = cv2.threshold(dst,0,255,cv2.THRESH_OTSU)

  disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  cv2.filter2D(dst,-1,disc,dst)

  cv2.imshow("Skin Areas", dst)


text:
Q: ObjectDisposedException in EntityFramework I have this class and i often(but not always) get NullReferenceException or ObjectDisposedException when use method ExecuteQuery:
public class Dao
{
    protected StoreDbContext Context = new StoreDbContext();

    public IEnumerable<T> ExecuteQuery<T>(string query, params object[] parameters)
    {
        return  Context.Database.SqlQuery<T>(query, parameters).ToList();
    }

}

but, if if i will create Context in method i don't get any exception. Why?
public class Dao
{
    protected StoreDbContext Context = new StoreDbContext();

    public IEnumerable<T> ExecuteQuery<T>(string query, params object[] parameters)
    {
        return  new StoreDbContext().Database.SqlQuery<T>(query, parameters).ToList();
    }

}

A: Don't keep the StoreDbContext hanging around when doing updates. It will end up with stale data/entities in it. The accepted pattern is to fire up a new Context for a unit of work/scoped set of operations. The second example might be acceptable, but you need to ensure you dispose of the context by creating it with a using statement. Refactor the method to account for this.
I tend to keep search results in a separate context with no tracking (read only) but would use a fresh context for updates, as I'm using WCF Data Services.


text:
Q: Is it possible to preload the spell check dictionary in Internet Explorer (10 & 11)? I'm working with a client that would like to use the built-in Internet Explorer spell check to help their staff with some complex legal and medical terms. We have a list of words, and what we'd like to do is preload the user's browser dictionary so that we can skip each user having to add each word, and avoid the likely errors that may have.
I'd also consider a browser add-in or adding a custom language, but I haven't be able to find anything for the first or much detail for the latter.


text:
Q: External backup drive unmounted, then endless churn I have a 5 year old Seagate USB2 drive for backups, used for a few months with time machine on my Retina MBP.
Lately, I've been getting an error that it was improperly ejected (I didn't actually eject it), and I can hear the drive churn endlessly on its own. I can't remount it, its power button doesn't respond, I have to power cycle it, then it mounts again and seems to work. Until the next incident.
Is it dying on me? It's old but has only been lightly used, until recently.

A: I've had a similar problem with a 2 TB Fantom drive.  Worked flawlessly for years, then it started to spontaneously unmount for no apparent reason. Time Machine being on or off doesn't have an effect.
It had been chained through another USB device (a MiniStack drive), and simply by taking it off the chain and plugging it directly into the Mac, I solved the problem.
Before ditching the drive, try changing USB cables and changing the routing (even a different USB port on the Mac.)  Five years is a bit old for a hard drive, but it's not unreasonable.

A: Sounds like this drive is on its last legs, given that it spontaneously dismounts and then churns. Inexpensive USB3 drives with larger capacities exist for probably less than you paid 5 years ago for this aging drive.
Go for a replacement - you won't be sorry when you really need to restore something important. Why take the chance that the drive will fail tomorrow, tonight, or even five minutes from now?


text:
Q: How to override to can Subclass of NSMutableDictionary Does anyone know any way to subclass NSMutableDictionary?
What I want is to have a class which is a subclass of NSMutableDictionary and add some own methods.
I have seen in internet this code: http://www.cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html
Which is close to what I want, but I need the class to have no properties at all and in the example they use a NSMutableDictionary and a NSMutableArray
Is it possible to override those methods without using any property?

A: I think you should use Category over NSMutableDictionary and Should Add your own methods than your own methods will be available in NSMutableDictionary class.
For any reference to the category use this link
https://coderwall.com/p/fqnptq


text:
Q: Parse json with javascript I have this json file I want parse and get value of subcat for test1 as an array in javascript. Is there an easy way to do this? I have used AngularJS $http to get the json.
For the input:
[
   {
    "category":"test1",
    "ID":"1",
      "subcat":[
        {
         "completed":"4",
         "uncompleted":"5"
        }
     ]
   },{
    "category":"test2",
    "ID":"2"
    "subcat":[
        {
         "completed":"1",
         "uncompleted":"5"
        }
   }

]

Expected result is [4,5]

A: Corrected Array

 [
       {
         "category":"test1",
          "subcat":[
                    {
                      "completed":"4",
                      "uncompleted":"5"
                     }
                   ]
       },
       {
          "category":"test2",
          "subcat":[
                    {
                      "completed":"1",
                      "uncompleted":"5"
                    }
                   ]
         }
    ]
var JsonArray=[
                {
                  "category":"test1",
                  "subcat":[{"completed":"4","uncompleted":"5"}]},
                {
                  "category":"test2",
                  "subcat":[{"completed":"1","uncompleted":"5"}]
                }
              ];
for(var i=0;i<JsonArray.length;i++)
      {
          if(JsonArray[i].category=="test1")
            var Res=JsonArray[i].subcat;
      }

"Res" will contain your desired result;
If you want array as [4,5]
Then
var finalRes=[];
finalRes.push(Res[0].completed);
finalRes.push(Res[0].uncompleted);

A: Try this...
     <script type="text/javascript">
      var newarray=new Array();
var test='[{"category":"test1","ID":"1","subcat":[{"completed":"4","uncompleted":"5"}]},{"category":"test2","ID":"2","subcat":[{"completed":"1","uncompleted":"5"}]}]';

var tags = JSON.parse(test);

for(i=0;i<tags.length;i++)
{

if(tags[i]['category']=='test1')
{
var subcat=tags[i]['subcat'];
for(j=0;j<subcat.length;j++)
{
newarray.push(subcat[j]['completed']);
newarray.push(subcat[j]['uncompleted']);
}

}
}
console.log(newarray);
      </script>

Output:["4", "5"]
DEMO:https://jsfiddle.net/t4yfb923/

A: You can use lodash and the method find :
https://lodash.com/docs#find
// Stock your json in a variable
var json = [
   {
    "category":"test1",
    "ID":"1",
      "subcat":[
        {
         "completed":"4",
         "uncompleted":"5"
        }
     ]
   },{
    "category":"test2",
    "ID":"2"
    "subcat":[
        {
         "completed":"1",
         "uncompleted":"5"
        }
   }

]

//find your object with lodash
var result = _.find(json, {"ID": "1"});

//then, get subcat value
console.log(result.subcat)


text:
Q: how to turn list of tuples to data frame with different scores I have data like this which was the output of gensim LDA model
date       id   score
1/1/2019    11  [(5,0.8), (11,0.2)]
1/2/2019    21  [(4,0.7), (10,0.1)]
1/3/2019    35  [(3,0.4)]
1/4/2019    44  [(5,0.8),(3,0.5), (11,0.2)]

The results should like this. Can anyone help?
date        id  score   new_score
1/1/2019    11  5       0.8
1/1/2019    11  11      0.2
1/2/2019    21  4       0.7
1/2/2019    21  10      0.1
1/3/2019    35  3       0.4
1/4/2019    44  5       0.8
1/4/2019    44  3       0.5
1/4/2019    44  11      0.2

A: Update:
A better method is to use DataFrame.explode():
df = pd.read_csv('your_file_name.csv')

df = df.explode('score')
df[['score', 'new_score']] = df.score.apply(pd.Series)

You can do this with a nested list comprehension:
df = pd.read_csv('your_file_name.csv')

unpacked = [
    {'date': row.date, 'id': row.id, 'score': x[0], 'new_score': x[1]}
    for _, row in df.iterrows() for x in row.score
]

df = pd.DataFrame(unpacked)

DataFrame.iterrows() returns a tuple of index and row contents for each row in the frame, so you can unpack it systematically:

*

*grab a single row

*unpack the score tuple into score and new_score

*format it as entries in a dictionary (along with date and id) to build a new frame from

*iterate across all rows and build the final frame


text:
Q: What does lower bound maximization mean? I was reading about the Expectation Maximization algorithm for parameters in a statistical model.
In the notes that I'm reading it says that EM is used for lower bound maximization.
What does this mean?


text:
Q: Upload Files to Google Drive from HTML form and save url to google sheet I am totally new to this stuff and get quite nothing of it.
I used some tutorials to write this, but I don't know how to get the link to the uploaded document in the google sheet.
This is the Apps Script code:
function doGet() {
  var html = HtmlService.createHtmlOutputFromFile('index');
  return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

// App Script function to save data to sheet
function saveData(data) {
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.appendRow(data);

}

function uploadFiles(data)
{
 var file = data.myFile;
 var folder = DriveApp.getFolderById('1NWq9CoBxzYumYQzTlCjLMS95Y6G2NY6X');
 var createFile = folder.createFile(file);
 return createFile.getUrl();
 var uploadURL = file.getUrl();

}

And here the HTML code in: index.html
<!DOCTYPE html>

    <base target="_top">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Custom HTML Forms to Google Sheet

        <form>

            Name
            <input type="text" class="form-control form-data" id="Name">

            Email
            <input type="text" class="form-control form-data" id="Email">

            Age
            <input type="text" class="form-control form-data" id="Age">

            Company
            <input type="text" class="form-control form-data" id="Company">

            Mob
            <input type="text" class="form-control form-data" id="Mob">

            <input type="file" name="myFile">

          <button type="button" class="btn btn-primary" onclick="send_data()" id="submitBtn" value="Upload Files">Submit</button>

        </form>

        Thank you for completing this form!

It is totally ok, if you say that there is no way to change this code into something that works, but please say how I could solve it elsewise.
I would really appreciate it, if you help me. Thanks!


text:
Q: 0 rows Deleted/Updated/Inserted require COMMIT in ORACLE? In an Oracle database, I just ran a query and I get

0 rows deleted.

Does a "0 row" DML operation lock a table in ORACLE and do I need to COMMIT if yes?

A: The answer is yes, and yes. Oracle locks rows that are modified etc. - so that won't happen if no rows are affected; but Oracle also creates a subexclusive table lock regardless of any rows that may or may not be modified, and it releases such locks only on COMMIT or ROLLBACK or equivalent. (Of course, in this case you can also ROLLBACK - same effect since no rows are affected).
Demonstrated easily in the following session:
SQL> create table xx as
  2  select level lvl from dual connect by level <= 5;

Table created.

SQL> select * from xx;

       LVL
----------
         1
         2
         3
         4
         5

SQL> select a.object_name, b.locked_mode
  2  from   user_objects a join v$locked_object b
  3  on a.object_id = b.object_id;

no rows selected

SQL> delete from xx where lvl = 10;

0 rows deleted.

SQL> select a.object_name, b.locked_mode
  2  from   user_objects a join v$locked_object b
  3  on a.object_id = b.object_id;

OBJECT_NAME     LOCKED_MODE
--------------- -----------
XX                        3

SQL> commit;

Commit complete.

SQL> select a.object_name, b.locked_mode
  2  from   user_objects a join v$locked_object b
  3  on a.object_id = b.object_id;

no rows selected


text:
Q: How can I prevent my Python web-scraper from stopping? Ahoy! I've written a quick (Python) program that grabs the occupancy of a climbing gym every five minutes for later analysis. I'd like it to run non-stop, but I've noticed that after a couple hours pass, one of two things will happen.

*

*It will detect a keyboard interrupt (which I did not enter) and stop, or

*It will simply stop writing to the .csv file without showing any failure in the shell.

Here is the code:
import os
os.chdir('~/Documents/Other/g1_capacity') #ensure program runs in correct directory if opened elsewhere

import requests
import time
from datetime import datetime
import numpy as np
import csv

def get_count():
    url = 'https://portal.rockgympro.com/portal/public/b01ab221559163c5e9a73e078fe565aa/occupancy?&iframeid=occupancyCounter&fId='
    text = requests.get(url).text
    line = ""

    for item in text.split("\n"):
        if "\'count\'" in item:
            line = (item.strip())

    count = int(line.split(":")[1][0:-1]) #really gross way to get count number for this specific source

    return count

while True: #run until manual stop

    with open('g1_occupancy.csv', mode='a') as occupancy:
        occupancy_writer = csv.writer(occupancy)
        occupancy_writer.writerow([datetime.now(), get_count()]) #append new line to .csv with timestamp and current count

    time.sleep(60 * 5) #wait five minutes before adding new line

I am new to web scraping (in fact, this is my first time) and I'm wondering if anyone might have a suggestion to help eliminate the issue I described above. Many thanks!


text:
Q: Is there any real benefit using crosswalk for Android 4.4 & above? Crosswalk plugin is very important in bringing huge performance improvement for hybrid app. But the problem is, once it is added, the APK is becoming HUGE, adding about 15-18MB of size to the installer.
So, is there any real benefit (especially in performance) for adding the crosswalk into the installer for Android 4.4 & above?

A: I recently done some performance tests of angularJS cordova app on android 4.4+ devices. I prepered short stories and tested cordova app vs cordova + crosswalk app using browser-perf utility (https://github.com/axemclion/browser-perf). The only performance boost I saw was painting (aprox. 4 times faster in comparison with 'clean' cordova). All other metrics were worse, some even much worse (rendering: aprox 1.5 times slower). Summarizing times, my cordova+crosswalk app was 9% slower than cordova. Also crosswalk added 21MB to my apk size and 60MB(!) to app size after installation. In case of my project, using crosswalk was pointless because of weight and speed. App used to tests was really rich angular SPA project, maybe simple apps can achieve some boost from crosswalk.


text:
Q: How can i prove $p\to (q \vee r) \equiv (p \wedge \sim q) \to r$? please Help me in this question
i have tried to solve it like this:
$$p \to (q \vee r) \equiv (p \wedge \sim q)\to r$$
$$p \vee \sim (q \vee r) \equiv \sim(p \wedge q)\vee r$$
$$p \vee \sim q \wedge \sim r \equiv \sim p \vee q \vee r$$
Thank you

A: Using the rule of implication we have
$$p\to (q\vee r) \equiv \sim p \vee (q \vee r).$$
Using associativity we have
$$\sim p \vee (q \vee r) \equiv (\sim p \vee q) \vee r.$$
Next is De Morgan
$$(\sim p \vee q) \vee r \equiv \sim(p \wedge \sim q) \vee r .$$
And now use implication once again
$$\sim(p \wedge \sim q) \vee r \equiv (p \wedge \sim q) \to r .$$
Regarding you answer:
Your first step is what you need to prove. What is the second step?
Edit
The rule of implication is
$$ a\to b \equiv \sim a\vee b.$$


text:
Q: Access XML nodes inside php functions I was trying to extract from an XML file using SimpleXML xpath() function. I registered a new namespace  and it works perfectly.
$data  = simplexml_load_string('sample.xml');
$data->registerXPathNamespace("a", "http://ns.hr-xml.org/2007-04-15");
$education = $data->xpath("//a:Education");
$this->saveEducationData($education);

The issue is how can i access an an XML node inside a function ? The below code doesn't work. Should a register a namespace again ?
function saveEducationData($data = ''){
  $school =  $data->xpath('/a:Institution');
}

Any help will be highly appreciated.
Sample xml data
<?xml version="1.0" encoding="utf-8"?>
<Resume xmlns="http://ns.hr-xml.org/2007-04-15" xmlns:bgt="http://wsi.com/wsinamespace" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<SResume>
<Education>
<School>
<SchoolName>Jane Institute of Technology</SchoolName>
<Address>
<Country>USA</Country>
<Region>NY</Region>
</Address>
<Degree>
<Name>MS</Name>
<StartDate>
<StringDate>2007-09-01</StringDate>
</StartDate>
<EndDate>
<StringDate>2010-05-01</StringDate>
</EndDate>
</School>
<School>
<SchoolName>Cochin Universityy</SchoolName>
<Address>
<Country>IN</Country>
<Region>COC</Region>
</Address>
<Degree>
<Name>BTech in computer science</Name>
<StartDate>
<StringDate>2005-04-10</StringDate>
</StartDate>
<EndDate>
<StringDate>2009-01-10</StringDate>
</EndDate>
</School>
<School>
<SchoolName>Indian institute of Geographic studies</SchoolName>
<Address>
<Country>IN</Country>
<Region>ALP</Region>
</Address>
<Degree>
<Name>DIploma in cartography </Name>
<StartDate>
<StringDate>2002-08-18</StringDate>
</StartDate>
<EndDate>
<StringDate>2005-01-08</StringDate>
</EndDate>
</School>
</Education>
</SResume>
</Resume>

Regards,
Tismon Varghese.

A: You could read your XML using DOMDocument:
$doc = new DOMDocument();
$doc->loadXML($xmlstr);

$elements = $doc->getElementsByTagName("Education");
$value = $elements->item(0)->nodeValue;

var_dump($value);

where $xmlstr is your XML as a string.
To read the value you can simply pass the element to the function where you would like to extract the value.


text:
Q: how can I generate and change random large files to test snapshot performance? I have an attach volume that gets a snapshot every hour.
In order to test the snapshot performance, I need to run a process that will, between snapshot backups, generate a large amount of "churn" or file change.
There are two questions related to this:

*

*simply and obviously, how to generate large blocks of text EFFICIENTLY and write them to disc.  With my limited knowledge about the only thing I can think of is a for loop generating random characters, but that's probably extremely slow.  Also, the new randomness if replacing a file has to be such that the snapshot essentially has no patterns to match.

*what is the most effective way to store this?  e.g. 1 Gigabyte in 1000 files, or 100 GB in 10 files

Since a picture is worth 1K words, I drew up this conceptually:

Thanks in advance for insight on coupling tools-to-use with insight on the file system.

A:
simply and obviously, how to generate large blocks of text EFFICIENTLY and write them to disc. With my limited knowledge about the only thing I can think of is a for loop generating random characters, but that's probably extremely slow.

Why would it be slow? What other way of generating data than running a software loop would exist?
Yeah, a for loop is pretty much exactly what you want. Allocate a reasonably sized buffer (512 kB each, for example), fill it with random text (or, really, just bytes, it's not like it makes a difference to your storage medium whether a byte means something specific like "A") and call write with that buffer. Move on to the next buffer. Since this is all very linear there's little to be won by being smarter than that – and your CPU is much faster at filling  a buffer in RAM than your storage would ever be.
What happens when you call write is that the buffer handed in is copied into a file system buffer (in RAM), and write returns instantly, so you can generate the next chunk of data. In the meantime, the kernel will start writing that buffer to storage in the background.
This will work fine until the file system buffer is full, and there's no space to immediately copy your data to. Then, your write will block until there is space. That's a clever method of always keeping the storage busy and the application working!
So, the first few iterations of your for-loop are very fast, but at some point you'll get "throttled" to the average write speed of your storage. Great!

Also, the new randomness if replacing a file has to be such that the snapshot essentially has no patterns to match.

Use a reasonably fast but not bad PRNG (pseudo-random number generator), anything but libc's rand (which is bad, in any way you look at it; never use rand). I use xoroshiro128+ for pretty high data generation rates.
I benchmarked that once, on my PC, I do ca 0.65 ns per generated pseudo-random 8-byte value, so ca 0.01 ns per random bit, or theoretically 100 Gb/s, single core performance, without even using a SIMD version of xoroshiro128+. Chances are  that's orders of magnitude faster than your storage interfaces probably are (unless you're forgetting to tell us you work at Google, Cloudflare, LHC or the NSA).

what is the most effective way to store this? e.g. 1 Gigabyte in 1000 files, or 100 GB in 10 file

Doesn't really matter, 1000 files are not many, and the overhead is negligible. Still, the least-overhead variant would be 1 file of 1 TB.

A: Here is a script that I have developed that works:
# init
__PWD__=$(pwd)
cd $(dirname $0)
__THIS_FILE__=$0
__THIS_DIR__=$(pwd)
write_loc='/../create-large-files-repository/'
__TARGET_DIR__="$__THIS_DIR__$write_loc"
cd $__PWD__

# output
echo running script: $__THIS_FILE__
echo current directory: $__THIS_DIR__
echo files written to: $__TARGET_DIR__

if [[ ! -d $__TARGET_DIR__ ]]; then mkdir $__TARGET_DIR__; fi

FILE_COUNT=100
FILE_SIZE=1000000

for ((i = 0 ; i < $FILE_COUNT ; i++)); do
  file="file$i.dta"
  file="$__TARGET_DIR__$file"
  echo processing $file..
  dd if=/dev/urandom of=$file bs=2048 count=$FILE_SIZE
done

This is running at about 30s per Gigabyte, so at 2GB per minute one could conceivably get about .12TB in an hour.  The actual goal would be to generate >1TB in an hour so I will update this with system load when running ~10 of these in parallel.  /dev/urandom/ is not blocking so this seems (for the moment) to be performant.


text:
Q: How can I get Chromium (Chrome) DevTools' NodeJS inspector to properly expand complex objects which have been console.log()'d? I am using nodejs to retrieve a large and complex object (a JSON version of a big reddit thread), and I'm using chrome://inspect to connect DevTools to node.  I'm running the script like so:
nodejs --inspect-brk main.js

When I console.log() the parsed JSON, DevTools collapses the data structure in the console, and displays it as such:
(2) [{…}, {…}]

Pressing the arrow which normally expands objects in console does not expand it.
Being able to explore this object in a pretty way, collapsing and expanding different parts of it as I go was the point of the Inspector in the first place, therefore other solutions such as JSON.stringify(), or just viewing the massive wall of text in the terminal window are not acceptable.
Chromium version 79.0.3945.79, Nodejs v8.10.0, on Mint 19.3.
Very likely answers pertaining to Chrome will work for Chromium.


text:
Q: Does Container.getComponents() return references to the original components? I'm using Container.getComponents() to get an array of Components stored inside the Container. I'm then modifying one of these Components (which happens to be a JLabel), but the changes are not showing on the GUI.
So I'm thinking maybe the method creates new instances of each Component which prevents me from making changes to the original component?
Here's my code:
Component[] components = source.getComponents();
if(components.length >= 2) {
    if(components[1] instanceof JLabel) {
        JLabel htmlArea = (JLabel) components[1];
        htmlArea.setText("new changes here");
        htmlArea.revalidate();
    }
}

A: It is either another problem outside of the code, or you are doing this from the wrong thread.
Any changes on Swing components should be done in the event dispatch thread. Often is it most easy to surround the changing code with EventQueue.invokeLater(...) (or SwingUtilities.invokeLater, this is the same).
And make sure your component is actually visible on the screen.

A: There is no need to revalidate() or repaint() anything (unless you are doing something really strange)!
Where is your SSCCE that demonstrates your problem???
It works fine for me:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class TabbedPaneLabel extends JFrame
{
    JTabbedPane tabbedPane;

    public TabbedPaneLabel()
    {
        tabbedPane = new JTabbedPane();
        add(tabbedPane);

        tabbedPane.addTab("First", createPanel("label with text"));
        tabbedPane.addTab("Second", createPanel("another label"));

        JButton remove = new JButton("Change Label on first tab");
        add(remove, BorderLayout.SOUTH);
        remove.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                Component[] components = tabbedPane.getComponents();
                JPanel panel = (JPanel)components[0];
                JLabel label = (JLabel)panel.getComponent(0);
                String date = new Date().toString();
                label.setText("" + date + "");
            }
        });
    }

    private JPanel createPanel(String text)
    {
        JPanel panel = new JPanel();
        panel.add( new JLabel(text) );
        return panel;
    }

    public static void main(String args[])
    {
        TabbedPaneLabel frame = new TabbedPaneLabel();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}


text:
Q: How to determine 32 or 64 bit version of Windows Server 2008 using Powershell? Using the Powershell console, what command/commands can be executed to determine if the 32 or 64 bit bersion of Windows Server 2008 is installed?

A: echo %PROCESSOR_ARCHITECTURE%

A: So be it:
[System.Environment]::Is64BitOperatingSystem

A: "echo %PROCESSOR_ARCHITECTURE%" down-voted?  Must not be powershelly enough, which is funny if you look at the other examples using WMI and other aliases.
oh well, try this:
($env:PROCESSOR_ARCHITECTURE -eq "AMD64")

EDIT - pointed out in the comment that this is not the version of windows, it's the arch.
FWIW- It's not the "real" arch, it's what WOW64 is reporting to the app.  But you are right... if it's x32 powershell, it'll say x86.  Often times this will get you what you want but...
Either way,
http://support.microsoft.com/kb/556009 is the registry location to the correct value, and here's a script.
Get-ChildItem HKLM:\HARDWARE\DESCRIPTION\System\CentralProcessor\ | Get-ItemProperty -Name Identifier | Select-Object -Property PSChildName,Identifier | ft -AutoSize

A: Or try this:
PS C:\Users\jeffh> $os=Get-WMIObject win32_operatingsystem
PS C:\Users\jeffh> $os.OSArchitecture
64-bit

Found at: http://msgoodies.blogspot.com/2008/05/is-this-powershell-session-32-bit-or-64.html

A: With PowerShell:
(gwmi win32_computersystem).SystemType

Source: http://www.sysadmit.com/2015/10/windows-como-saber-si-es-de-32-o-64-bits.html

A: you may type in cmd "systeminfo"
then easily you can detect about 32bit or 64bit

A: I would assume you can just open a command prompt and type:
cd "C:\Program Files (x86)"
if you get somewhere, you got 64 bit.


text:
Q: post and get data using jquery ajax and update html table row only in mvc I have a HTML table and I want that when the user clicks on the Count cell, the data for that row is updated in the database and the result is also updated in that row. I only want to update that row and not the whole page. This is what I have so far:
View (the view contains a partial view that represents a row:

        @foreach (var item in Model)
        {

                @Html.Partial("TableTransactionsTableRow", item)

        }

        @if (!string.IsNullOrEmpty(log.Opmerking))
        {

                @log.Opmerking

        }

Model:
public class Transaction
{
    private int ProductID { get; set; }
    private int Count { get; set; }
    private string Description { get; set; }
    private decimal Total { get; set; }
}

Partial view (TableTransactionRow):
@model Transaction

                @Model.Count

                @Model.Description

    @Model.Total

Ajax script:
$(document).ready(function () {
    $('.CountClick').click(function () {
        var productID = getParameterByName('productID', $(this).attr("href"));
        var id = "#" + productID;

        $.ajax({
            cache: false,
            url: $(this).attr("href"), // used data from url
            datatype: "text",
            type: "POST",
            success: function (data) {
                $(id).html(data);
            },
            error: function () {
                $(id).html("ERROR");
            }
        });
        return false;
    });
});

The TablesController:
public ActionResult UpdateProductCount(int? productID, int? count)
{
    if (productID.HasValue)
    {
        Transaction t = new Transaction();
        t.Count += count.Value;
        t.Total= t.Count * t.Price;
        //save the transaction to the database and return it to the partial view
        return PartialView("TableTransactionsTableRow", t);
    }
    return RedirectToAction(MVCItems.TableTransactions);
}

How can I update the values in the cells without refreshing the whole table? Any help is appreciated.

A: After thinking for a while I have solved the problem. I used this answer as base of my solution. So I return a json object of the Transaction from the controller to ajax jQuery. I have removed the partialview and used the html as a row within the main view. I have set id's for div of the count and total div element. When I return the json object to the view I update the values by using element.innerText.
Controller:
public ActionResult UpdateProductCount(int? productID, int? count)
    {
        if (productID.HasValue)
        {

Transaction t = new Transaction();
    t.Count += count.Value;
    t.Total= t.Count * t.Price;

            if (transaction == null)
                return Json(t, JsonRequestBehavior.AllowGet);

    }

jQuery:
$(document).ready(function () {
$('.CountClick').click(function () {

    var productID = getParameterByName('productID', $(this).attr("href"));
    var countID = "Count" + productID;
    var totalID = "Total" + productID;

    var countElement = document.getElementById(countID);
    var totalElement = document.getElementById(totalID);
    var rowElement = document.getElementById(productID);

    $.ajax({
        cache: false,
        url: $(this).attr("href"), // used data from url
        datatype: "text",
        type: "POST",
        success: function (response) {

            var count = parseInt(response.Count);

            if (count > 0)
            {
                countElement.innerText = response.Count;
                totalElement.innerText = response.Total;
            }
            else
            {
                rowElement.innerHTML = "";
            }
        },
        error: function () {
            $("#divResult").html("ERROR");
        }
    });

    return false;
});
});

Hope this helps someone else in the future.