text:
Q: Is it possible to place two grid side by side? So here is my problem. I use some ui-grid on my interface to show information, but I would like to have 2 grid of 3 columns side by side (aligned vertically). So far, I haven't found exemple of it and i tried to code it, but without success. Is there someone here with better experience then me who knows how its possible? So far, that's what i thought about the solution :

Header 1

Header 2

Header 3

Header 1

Header 2

header 3

I just try to get two table side by side like this one:https://jsfiddle.net/8o39tqgz/1/
EDIT
Just tried display: inline, but it doesn't work on the same line... https://jsfiddle.net/s71zpcgs/

A: How about this?

Header 1

Header 2

header 3

Header 1

Header 2

header 3

And then at your css add this
.column{
   width:33%;
   float:left;
   /* you can optionally set a fixed height */
}

A: I guess its not exactly what I wanted, but that will do it. Ty to @ezanker for the solution :
HTML

My page

header 1	header 2	header 3

content 1	Some bigger content in this cell	content 3

content 1	content 2	content 3

header 1	header 2	header 3

content 1	content 2	content 3

content 1	content 2	content 3

CSS
.halfGrid {
margin-left: 1%;
margin-right: 1%;
border-spacing: 0;
border-collapse: collapse;

}

.halfGrid td, .halfGrid th {
border: 1px solid #aaa;
padding: 4px;
text-align: center;
width: 33%;
font-weight: normal;
white-space: normal;
}
.halfGrid th {
 font-weight: bold;
}

IMPORTANT EDIT
Actually, I got the idea of splitting the screen in two and wrap one table in each side and that work exactly as I wanted! Im so happy, I was working on it for many hours... Felt like running in circle, but its finally done! Here is the code :
HTML

PN

Amendment

Designation

Info1

Info2

Info3

PN

Amendment

Designation

Info1

Info2

Info3

CSS
.wrap
{
width: 100%;
overflow:auto;
padding:2px;
}
.fleft
{
float:left;
width: 50%;
}
.fright
{
float: right;
width: 50%;

}

Found solution in this post : Split page vertically using CSS and integrated the part of my code. Here is the jsfiddle : http://jsfiddle.net/G6N5T/1211/

A: You could nest two 3 column grids within one 2 column grid:

header 1

header 2

header 3

Header 1

Header 2

header 3

.halfGrid {
    margin-left: 1%;
    margin-right: 1%;
}

.halfGrid .cell {
    border: 1px solid #aaa;
    padding: 4px;
    text-align: center;
}

Updated FIDDLE


text:
Q: Updating swing components correctly? I'm new to swing, any help appreciated.
In this piece of code I'm turning a card over face up, if it turns out that they don't match I want them to turn back face down again.
At the moment what is happening:
1. when clicked the first card turns over
2. when a second card is clicked either of two things happen
(a) if they are the same they both stay up which is what I want
(b) if they are not the same I never see the 2nd card at all as it immediately re-displays the back of the card (and the back of the previous card also as defined in my method).
I thought putting in the sleep timer might keep the 2nd card displayed for a period of time before turning back over but it does not.
I attempted to use contentPane.revalidate(); & contentPane.repaint(); but it doesn't change anything.
I have put in some console outputs:
Console output:
Card: 0 set
Card: 6 set
Sleeping now
Card: 6 unset
Card: 0 unset

Above is the resulting console output when clicking two card which do not match
@Override
public void actionPerformed(ActionEvent e)
{
    String buttonPressed = e.getActionCommand();
    int pos = Integer.valueOf(buttonPressed);
    action = Control.model.ReceiveCardsTurned(pos);

    keypadArray[pos].setIcon(myIcons[pos]);
    System.out.println("Card: "+pos+" set");
    currentTime.setText("" + Control.model.time);
    currentScore.setText("" + Control.model.score);

    //contentPane.revalidate();
    //contentPane.repaint();

    if(Control.model.twoCardsTurned == false)
    {
        if (action == "unturn")
        {
            System.out.println("Sleeping now");

            try
            {
                Thread.sleep(1000);
            }

            catch (InterruptedException e1)
            {
                e1.printStackTrace();
            }

            keypadArray[pos].setIcon(back);
            keypadArray[Control.model.lastCard].setIcon(back);
            System.out.println("Card: "+pos+" unset");
            System.out.println("Card: "+Control.model.lastCard+" unset");
        }
    }
}

A: You can't sleep in the event dispatch thread, because your GUI will freeze. You have to use Swing Timer. For background tasks you'll probably have to worry about in the future, take a look at SwingWorker.

A: There are a number of important concepts you seem to be missing.

*

*Swing is an event driven environment.  That means that there is no means (or at least only a very few) that you can "wait" for user input, typically, you just need to react to their interaction.

*Swing is driven by a single thread, known as the Event Dispatching Thread (AKA EDT).  It is the responsibility of this thread to dispatch/process events coming into the application to the appropriate parts of the application so that they can take action.

*The repaint manager posts its update requests onto the EDT.

ANY action you take that stops the EDT from carrying out this work will make your application look like it's hung.
You must NEVER carry out any time consuming operations (such as I/O, loops or Thread#sleep for example) on the EDT, doing so will make your application "pause", which is never pretty.
Have a read through Concurrency in Swing for more information.
Now, you have a number of choices.  You could use a Thread to "wait" in the background and turn the cards back or you could use a SwingWorker or a javax.swing.Timer.
The other problem you have, is that you should NEVER update any UI components from any Thread other than the EDT.  This means if you were to use a Thread, you would become responsible for re-syncing that thread with the EDT.  While not difficult, it just becomes messy.
SwingWorker and javax.swing.Timer have functionality that make this much easier.
Threads and SwingWorker are great for performing background processing and would simply be overkill for this problem.  Instead, a javax.swing.Timer would fit perfectly here.
if (!Control.model.twoCardsTurned)
    {
        if ("unturn".equals(action))
        {
            new Timer(1000, new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    keypadArray[pos].setIcon(back);
                    keypadArray[Control.model.lastCard].setIcon(back);
                    System.out.println("Card: "+pos+" unset");
                    System.out.println("Card: "+Control.model.lastCard+" unset");
                }
            }).start();
        }
    }

This is a really simple example. You might like to put in some controls that will prevent the user from clicking anything until the timer fires, for example ;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert additional products inside a grid when clicked on any products Functional requirement:

*

*The products are displayed in a grid format.

*On click of any product it'll call 6 more products from the API.

*The new set of products should be inserted rite next to the product which has been clicked.

*The other products in the grid has to be shifted to later position on the grid (rite next to newly added products).

A: you have to pass id on click then changes its property using render2 angular library or you can do it using simple js too passing id on click is like

{{x.product_name}}


text:
Q: BasicNetwork.performRequest: Unexpected response code 403 for http://localhost/database/login.php I am using Volley to connect to MySql database. I created the database tables and wrote the php function and below is the java code. All this was working all along but just yesterday it woke up giving this error in the logcat and its not returning any response, testing the php script using google chrome postman works just fine so im thinking there is something wrong in my java code.
BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.43.71/database/login.php
I know several questions like this have been asked before, i have gone through them all and nothing seems to work at all. I am going nuts.
private void login() {
      StringRequest jsonObjRequest = new StringRequest(Method.POST, Constants.ACCOUNTLOGIN,
              loginSuccessListener(),
              loginErrorListener()) {
      protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
          Map<String, String> params = new HashMap<String, String>();
          params.put("user_phone_number", sPhoneNumber);
          params.put("user_password", sPassword);
          return params;
          };
      };
  mVolleyQueue.add(jsonObjRequest);
     }

A: First check if you can open the same url on your mobile browser. I assume you use Apache2.4.9 webserver. If you've not changed default values for you get "denied permission".
To solve this problem you need change some values in "httpd.conf" file which has Apache settings.
1- Under DocumentRoot change Directory xml tag as following:
<Directory />
     AllowOverride none
     Require all granted
</Directory>

2- Under "onlineoffline tag" update the line as following:
<Directory />
    ...
    ...
    ...
#   onlineoffline tag - don't remove
    Require all granted
</Directory>

Note: If you use older version of Apache you need google for right syntax in httpd.conf
Let me know if this changes work or not. :)

A:
BasicNetwork.performRequest: Unexpected response code 403 for http://localhost/database/login.php

Here is the problem in the URL, use your system IP where you hosted your web services and disable firewall, antivirus that may sometimes block to access your system services from other.
It may your IP address has changed, confirm it again. Service URL format would be something like http://your_system_ip_address/database/login.php

A: Please check :

*

*Internet permission in your android manifest file.

*Check http://localhost/database/login.php on your system browser.

I think it will help.

A: Try it...
Go to XAMPP..
In Apache open file http-xampp.conf
comment this lines in the end...
# New XAMPP security concept
#<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
# Require local
# ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
#</LocationMatch>

save changes...
restart apache... !!

A: This solved my problem.
In C:\wamp64\bin\apache\apache2.4.23\conf\extra\httpd-vhosts.conf
change Require local o require local to Require all granted.
Unexpected response code 403 for

A: I've got similar error to this one (400, instead of 403). Try do the following.

*

*go to src/com/android/volley/toolbox/BasicNetwork.java

*Change the following lines

 if (statusCode < 200 || statusCode > 299) {
     throw new IOException();
 }

with

 if (statusCode < 200 || statusCode > 405) {
     throw new IOException();
 }

Hope this helps.


text:
Q: How to renew yii RBAC assignments I'm working on a simple yii RBAC manager. All RBAC data is stored in database and everything works fine, but ...
When I decide to manage RBAC assignments I've got in trouble. For example, I assign operation "myNewOperation" to user "admin". Everything goes fine, accessControll and checkAccess() do their job. Then I decide to remove assignment record from database, but accessControll and checkAccess() still displays, that user have such rights. I tried to logout, clear cache, destroy session and clear cookies, but nothing changed. User "admin" still have rights "myNewOperation", but "myNewOperation" was physically removed from assignments table. What can be wrong?

A: Yeah, I found the reason. It takes me to rummage in CDbAuthManager to understand it.
I did a logical mistake in my roles relations. I used default role "authenticated" so all authenticated users automaticly have that role. And I create a children operation from this role. By yii logic, if the is no access found, search will be continued on the parent branch. So I removed assignments, but had "authenticated" as parent, thats why I always had the "true" value. Thank you.


text:
Q: Ionic 3 - how to deselect a tab on leaving the page I am unable to find any proper resource and I have tried multiple items including the following code:
  this.navCtrl.setRoot('xxxxx')

How do I deselect a tab on leaving the page?


text:
Q: Ubuntu 19.10 can't able to access the internet in the VMware Workstation I had installed Ubuntu 19.10 a couple of months ago in my VMware. Everything was working fine. But today I noticed that Ubuntu can't able to access the internet.
There is no issue with my internet. The network is working fine on my host machine. I have a couple of other virtual machines. The Internet is working fine there also. It's not working only in Ubuntu even though it shows the network is connected.

I use NAT as my Network Connection settings.

I rebooted the virtual machine, changed the network connection NAT to Bridged but nothing worked
Does anybody know how to solve this issue?
Thanks

A: This issue is commonly related to time synchonisation. run
date -u

in both your host and your guest and compare the results. If the date and time in the guest is significantly different, you can run the command
hwclock --set --date="2020-05-11 12:37:25"  --utc

but being careful to change my date and time above to the one given by your host system.


text:
Q: Open execl sheet using xlrd but it shows xml.etree.ElementTree' has no attribute '_IterParseIterator Hello i am trying to open excel sheet using xlrd .
But it was shows AttributeError: module 'xml.etree.ElementTree' has no attribute '_IterParseIterator'.
import xlrd
sheet=xlrd.open_workbook('sheet.xlsx')
print(sheet)


text:
Q: SQLAlchemy secondary relationship not using JOIN I created a Many to Many relationship on SQLAlchemy, but for some reason when I access it it's not emitting a JOIN clause, but rather selecting from a cross product of the three tables and filtering with WHERE clauses. I can't understand why it's doing this, and how to fix it.
Here's the python code for the association table and the primary model. The secondary model is overly complex and I think that the fact that it has sku and account_id columns which have indices (and together are part of the PK) is enough info to go on
product_info_to_product_profile_association_table = Table(
    "tpl_products_to_product_profiles_r1",
    metadata,
    sa.Column(
        "sku",
        sa.String(128),
# This FK is failing at the MySQL level
        # sa.ForeignKey(ProductInfo.sku),
        nullable=False,
    ),
    sa.Column(
        "account_id", mysql.INTEGER(11), sa.ForeignKey(ProductInfo.account_id), nullable=False
    ),
    sa.Column(
        "product_profile_id",
        mysql.INTEGER(11, unsigned=True),
        sa.ForeignKey("tpl_product_profiles.id"),
        nullable=False,
    ),
    sa.UniqueConstraint("sku", "account_id", "product_profile_id", name="product_unique"),
)

class ProductProfile(BillingBaseModel):

    __tablename__ = "tpl_product_profiles"

    id = sa.Column(mysql.INTEGER(11, unsigned=True), primary_key=True)
    name = sa.Column(sa.String(90), nullable=False)
    account_id = sa.Column(mysql.INTEGER(11), sa.ForeignKey(Account.id), nullable=False)

    product_infos = orm.relationship(
        ProductInfo,
        secondary=product_info_to_product_profile_association_table,
        secondaryjoin=sa.and_(
            ProductInfo.sku
            == orm.foreign(product_info_to_product_profile_association_table.c.sku),
            ProductInfo.account_id
            == orm.foreign(product_info_to_product_profile_association_table.c.account_id),
        ),
        secondaryjoin=(
            id
            == orm.foreign(product_info_to_product_profile_association_table.c.product_profile_id)
        ),
        backref=orm.backref("product_profile", uselist=False),
    )

Here's the generated SQL when I try to access the relationship through an instance
>>> pp.product_infos

[SELECT product_info.sku..........
FROM product_info, tpl_products_to_product_profiles_r1
WHERE tpl_products_to_product_profiles_r1.product_profile_id = %s AND product_info.sku = tpl_products_to_product_profiles_r1.sku AND product_info.account_id = tpl_products_to_product_profiles_r1.account_id]
[parameters: (6L,)]

A: This might not be the best answer, but I've dug into some of sqlalchemy's inner working and it is explicitly creating the cross join when doing lazy loading
        if self.parent_property.secondary is not None:
            q.add_criteria(
                lambda q: q.select_from(
                    self.mapper, self.parent_property.secondary
                )
            )

The best solution I have found is to use eager loading of some kind.
Whether that's

*

*lazy='selectin' inside of the relationship definition

*adding selectinload(ProductProfile.product_infos) when querying for a ProductProfile object and know you will need to access that attribute

*or doing the same as above but explicitly defining the joins in the query and using contains_eager(ProductProfile.product_infos)
For the first 2 cases sqlalchemy suggests you use selectin or subquery eager loading when handling x-to-many tables (especially when the many table is large): https://docs.sqlalchemy.org/en/14/orm/loading_relationships.html#what-kind-of-loading-to-use


text:
Q: Downloads files instead of opening them I downloaded EasyPHP 14.1 VC9, and downloaded all of my files from my webhost (new computer). Now when going to any folder below the data/localweb/ level just causes my browser to download the file instead of executing and opening it.
For example:
data/localweb/index.php works fine.
data/localweb/somefolder/index.php doesn't work.
No wordpress or any craziness, just vanilla PHP. Any PHP on the root folder works fine, but my server architecture is just folders off the root - any way to keep it and have PHP find ALL php files and execute them as long as they are under the root folder?
I have these lines in the Apache config:
AddType application/x-httpd-php .phtml .pwml .php5 .php4 .php3 .php2 .php .inc

LoadModule php5_module "${path}/binaries/php/php_runningversion/php5apache2_4.dll"

OS: Win7 Home Premium 64bit

A: facepalm
Let this be a lesson learned for everyone out there.
The key we should be looking for from now on is 'downloaded from webhost'.
My somefolder/ contained an extra .htaccess that was from my webhost. Deleting it solved the problem.


text:
Q: How to show innerHTML of texarea after deleting existing content I am trying to hide and show the innerHTML of a textarea based on focus and blur. Its working well. But an issue is, when i delete the entered text the inside innerHTML is already there in the element but its not showing. Following is the issue replication steps:

*

*Enter text inside the textarea

*Select all the text and delete it

*Then mouseout from the textarea

*The innerHTML is not visible there in the browser

*But innerHTML is visible in the elements when i check with browser inspect element

let textarea = document.querySelectorAll("textarea");

for (i = 0; i < textarea.length; i++) {
  let innertext = textarea[i].innerHTML;

  textarea[i].addEventListener("focus", (e) => {
    e.target.innerHTML = "";
  })

  textarea[i].addEventListener("blur", (e) => {
    e.target.innerHTML = innertext;
  })
}
<textarea name="" id="" cols="30" rows="10">Test</textarea>

A: This solution is using placeholder:
<textarea name="" id="" cols="30" rows="10" placeholder='Test'></textarea>

let textarea = document.querySelectorAll("textarea");

for(i=0;i<textarea.length;i++) {
let innertext = textarea[i].placeholder;
    textarea[i].addEventListener("focus",(e)=>{
      console.log( e.target.placeholder);
  e.target.placeholder = '';
    });

    textarea[i].addEventListener("blur",(e)=>{
         e.target.placeholder = innertext;
    })
}

A: Use .value instead of .innerHTML to change/retrieve the value of the textarea. The innerHTML property does not update in the browser once a change has been made to the textarea's content.

let textarea = document.querySelectorAll("textarea");

for (i = 0; i < textarea.length; i++) {
  let innertext = textarea[i].innerHTML;

  textarea[i].addEventListener("focus", (e) => {
    e.target.value = "";
  })

  textarea[i].addEventListener("blur", (e) => {
    e.target.value = innertext;
  })
}
<textarea name="" id="" cols="30" rows="10">Test</textarea>


text:
Q: meaning of the word "marginal" in context It is from this news article. The context is that Mr Trump asks a child if he believes in Santa.

Footage of the incident circulating on social media shows Mr Trump then telling the boy: "Because at seven, it's marginal, right?"

Does Mr Trump mean that Santa is not important to a boy of 7?

A: I think so, "Mr. Trump means that Santa is not important to a boy at 7"
The following evidence from here is acknowledging it:

Trump tells boy that believing in Santa at 7 is 'marginal'
WASHINGTON (AP) — President Donald Trump and first lady Melania Trump
  took calls from children anxious to find out where Santa is on his
  gift-giving journey.
In one conversation, Trump asked a 7-year-old named Coleman, "Are you
  still a believer in Santa?" He listened for a moment before adding,
  "Because at 7, it's marginal, right?" Trump listened again and
  chuckled before saying, "Well, you just enjoy yourself."
Mrs. Trump told a caller that Santa was in the Sahara. Several minutes
  later, she reported that Santa was far away in Morocco but would be at
  the caller's home on Christmas morning.
Mrs. Trump later tweeted that helping children track Santa "is
  becoming one of my favorite traditions!"
The NORAD Tracks Santa program became a Christmas Eve tradition after
  a child mistakenly called the forerunner to the North American
  Aerospace Defense Command in 1955 and asked to speak to Santa.

First, Mr. Trump has asked:

"Are you still a believer in Santa?"

Then he has said:

Because at 7, it's marginal, right?

Apparently, Mr. Trump meant that Santa is not important to a boy at 7!


text:
Q: for loop iterating through list of df's is merging data I have a list(ldf) that contains 12 data frames. I'm dropping rows with null values. That is working fine, but my output is saving all the data out as one data frame. I want 12 cleaned data frames not one giant one. I'm not sure how to do this. I've researched but come up dry. Here is my code.
for (i in ldf) {
  ldf_no_null  <- i[complete.cases(i), ]
}

A: A lapply one-liner will do it.
ldf_no_null <- lapply(ldf, \(x) x[complete.cases(x), ])
str(ldf_no_null)
#> List of 3
#>  $ :'data.frame':    80 obs. of  5 variables:
#>   ..$ Sepal.Length: num [1:80] 5.1 4.9 4.7 5.4 4.6 5 4.9 5.4 4.8 4.3 ...
#>   ..$ Sepal.Width : num [1:80] 3.5 3 3.2 3.9 3.4 3.4 3.1 3.7 3 3 ...
#>   ..$ Petal.Length: num [1:80] 1.4 1.4 1.3 1.7 1.4 1.5 1.5 1.5 1.4 1.1 ...
#>   ..$ Petal.Width : num [1:80] 0.2 0.2 0.2 0.4 0.3 0.2 0.1 0.2 0.1 0.1 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#>  $ :'data.frame':    80 obs. of  5 variables:
#>   ..$ Sepal.Length: num [1:80] 5.1 4.9 4.7 5.4 4.6 5 4.9 5.4 4.8 4.3 ...
#>   ..$ Sepal.Width : num [1:80] 3.5 3 3.2 3.9 3.4 3.4 3.1 3.7 3 3 ...
#>   ..$ Petal.Length: num [1:80] 1.4 1.4 1.3 1.7 1.4 1.5 1.5 1.5 1.4 1.1 ...
#>   ..$ Petal.Width : num [1:80] 0.2 0.2 0.2 0.4 0.3 0.2 0.1 0.2 0.1 0.1 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#>  $ :'data.frame':    80 obs. of  5 variables:
#>   ..$ Sepal.Length: num [1:80] 5.1 4.9 4.7 5.4 4.6 5 4.9 5.4 4.8 4.3 ...
#>   ..$ Sepal.Width : num [1:80] 3.5 3 3.2 3.9 3.4 3.4 3.1 3.7 3 3 ...
#>   ..$ Petal.Length: num [1:80] 1.4 1.4 1.3 1.7 1.4 1.5 1.5 1.5 1.4 1.1 ...
#>   ..$ Petal.Width : num [1:80] 0.2 0.2 0.2 0.4 0.3 0.2 0.1 0.2 0.1 0.1 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

Created on 2023-02-03 with reprex v2.0.2

Test data
set.seed(2023)
df1 <- iris
df1[] <- lapply(df1, \(x) {is.na(x) <- sample(length(x), 20); x})
ldf <- list(df1, df1, df1)
str(ldf)
#> List of 3
#>  $ :'data.frame':    150 obs. of  5 variables:
#>   ..$ Sepal.Length: num [1:150] 5.1 4.9 4.7 NA 5 5.4 4.6 5 4.4 4.9 ...
#>   ..$ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#>   ..$ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#>   ..$ Petal.Width : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 NA 0.1 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 NA 1 1 1 1 1 ...
#>  $ :'data.frame':    150 obs. of  5 variables:
#>   ..$ Sepal.Length: num [1:150] 5.1 4.9 4.7 NA 5 5.4 4.6 5 4.4 4.9 ...
#>   ..$ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#>   ..$ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#>   ..$ Petal.Width : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 NA 0.1 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 NA 1 1 1 1 1 ...
#>  $ :'data.frame':    150 obs. of  5 variables:
#>   ..$ Sepal.Length: num [1:150] 5.1 4.9 4.7 NA 5 5.4 4.6 5 4.4 4.9 ...
#>   ..$ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#>   ..$ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#>   ..$ Petal.Width : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 NA 0.1 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 NA 1 1 1 1 1 ...

Created on 2023-02-03 with reprex v2.0.2

A: The problem is that yoi overwrite ldf_no_null in each iteration, and it will contain just the result of the last iteration. If you want a for loop, you need to initialize an empty list with three elements first (or in R language a vector of mode "list") and fill it thereafter. It al;so might be better to loop over the indices of the list instead of the list elements directly, we can do this by using seq_along.
ldf_no_null <- vector(mode='list', length=length(ldf))

for (i in seq_along(ldf)) {
  ldf_no_null[[i]] <- ldf[[i]][complete.cases(ldf[[i]]), ]
}

ldf_no_null
# [[1]]
# X1 X2 X3 X4 X5
# 1  1  2  3  2  3
# 3  1  1  1  3  1
# 5  2  3  2  1  1
#
# [[2]]
# X1 X2 X3 X4 X5
# 2  2  2  2  1  2
# 6  2  3  2  2  1
#
# [[3]]
# X1 X2 X3 X4 X5
# 5  2  2  1  2  3
# 6  2  3  1  1  3

Data:
set.seed(42)
ldf <- replicate(3, data.frame(matrix(sample(c(1:3, NA), 6*5, replace=TRUE), 6, 5)), simplify=FALSE)


text:
Q: SolrCloud 6 not deleting tlogs on hard commits We have just implemented SolrCloud 6 with CDCR, and our tlogs are not deleting / rolling off after hard commits.  We currently have 242 tlogs, and they just keep increasing with each days processing.
solrconfig.xml - source
solrconfig.xml - target

A: Have you seen: https://lucidworks.com/blog/2013/08/23/understanding-transaction-logs-softcommit-and-commit-in-sorlcloud/

tlogs are "rolled over" automatically on hard commit (openSearcher true or false). The old one is closed and a new one is opened. Enough tlogs are kept around to contain 100 documents [1], and older tlogs are deleted.


text:
Q: layout a graph in JDesktopPane I have objects that build a graph. Each object is a node of the graph and represented by an JInternalFrame in the JDesktopPane. Now I want to layout the Frames correspondig to the graph. Diplaying the edges is not my problem, but to get proper positions for each Frame(Node).
Have you an advice for a good aproach for this? I tried already to build an graph with the JUNG library, let JUNG calculate positions of nodes and transfere them to my swing components. But I am not satisfied with the solution as there result is kind of random.
br
Tobias

A: I can understand your pain here . I also do the same . ie. in my java application i take various inputs and combine it to produce a graph . The challenge remains to output the graph on the screen so that it can be meaningfully understood by the user of the application . My graphs can be extremely big . Here is what i do :
1 . I use Graphiz dot library to generate my graph . In case you are unfamiliar with Graphiz, it is a very popular graph layouting tool . It essentially does the same thing as the JUNG library . But since i have never used JUNG i will not speak about it . The Graphiz dot engine computes the position of the vertex and edges for you .
2 . I have created a Graphical editor that can parse the (x,y) co-ordinates specified in the .dot file( output file generated by Graphiz ) and show on the screen . Only the parsing part is tricky as the editor takes care of most of the visualization aspects ( like zooming , drag and drop edges and vertex , etc ) . You can check out the editor here Jgraphx . Download their source code and have a look at the GraphEditor example . Run that example and see . Let me know if you want me any more help .
I think you have achieved 1 and you need to achieve 2 . Hope my answer helps.


text:
Q: Cauchy Problem (PDE)
Find the solution to the Cauchy data problem
$$\frac{\partial u}{\partial t} − u\frac{\partial u}{\partial x} = −2u$$
where $u(x, 0) = x$.

I know how to solve homogeneous Cauchy problems. However, I am struggling to understand non-homogeneous equations like this one. Can somebody please give a detailed solution?

A: By characteristics, examining the pde along a curve $U(t)=u(x(t),t)$ where
$$
x'(t)=-U(t)\\
U'(t)=-2U(t)
$$
solving the second, we find
$$
U(t)=U_0e^{-2t}
$$
and setting initial conditions to be $x_0=x(0)$ and using the Cauchy data
$$
U(0)=x_0
$$
we have
$$
U(t)=x_0e^{-2t}
$$
giving
$$
x'(t)=-x_0e^{-2t}\implies x=x_0(\frac{1}{2}e^{-2t}+\frac{1}{2})
$$
and solving for $x_0$ and plugging in the expression for $U(t)$ we find
$$
U(t)=u(x,t)=e^{-2t}\frac{x}{\frac{1}{2}+\frac{1}{2}e^{-2t}}=\frac{2x}{e^{2t}+1}
$$

A: $$\frac{\partial u}{\partial t} − u\frac{\partial u}{\partial x} = −2u$$
System of characteristic ODEs : $\quad \frac{dt}{1}=\frac{dx}{-u}=\frac{du}{-2u}$
A first family of characteristic curves comes from $\quad \frac{dx}{-u}=\frac{du}{-2u} \quad\to\quad du-2dx=0$
$$u-2x=c_1$$
A second family of characteristic curves comes from $\quad \frac{dt}{1}=\frac{du}{-2u} \quad\to\quad \ln|u|=-2t+$constant.
$$e^{2t}u=c_2$$
The general solution of the PDE is obtained on the form of implicit equation :
$$\Phi\left((u-2x)\:,\:(e^{2t}u) \right)=0$$
where $\Phi$ is an arbitrary function of two variables, to be determined according to the initial condition.
Or equivalently :
$$u-2x=F(e^{2t}u)$$
where $F$ is an arbitrary function, to be determined according to the initial condition.
CONDITION : $\quad u(x,0)=x$ to be put into the above general solution.
$$x-2x=F(e^{2(0)}x) \quad\to\quad F(x)=-x$$
So, the function $F$ is determined : $\quad F(X)=-X\quad$ any $X$.
Putting it into the above general solution where $\quad X=e^{2t}u\quad$ leads to :
$$u-2x=-(e^{2t}u)$$
$$u=\frac{2x}{1+e^{2t}}$$


text:
Q: Persisting django channels groups when deploying to production using multiple server instances I am deploying my django application that uses web sockets (django channels 2) to production. Using load balancer and two application instances with nginx/gunicorn has been working fine so far but I am wondering about the scalability of the websockets part.
How can I build scalable web sockets architecture that will share the django channels groups among different server instances?
I am using websockets for the live chat functionality so I have to make sure that users added to a specific group will be able to send/receive message from all other users in the same chat room no matter to which server instance the load balancer will point them.
My first thought was to simply use a separate remote server just for redis but I am aware that the vertical scalability will eventually come to an end. What happens when I will need to scale redis servers horizontally?
I've been already using the gunicorn + daphne setup but only with low/dev-testing traffic. I have not tried scaling django channels horizontally yet.


text:
Q: Make a matrix full-ranked? How can I turn a regular matrix into a matrix full-ranked in R? Is there an available method for that?
I have a matrix that may have linearly dependent columns and I need to
pass it to a function that requires its argument to be a matrix with
full rank. Since linearly dependent columns are not of interest
anyway, I am looking for a function that removes such columns until
the matrix is full rank. There may be several solutions of course, but
any one of them should be fine.
Right now I am just constructing the matrix column by column and only
add a column if its the resulting matrix is still fullrank, but it
feels like there should be a better way to do this.

A: Another approach is to minimize |y - Ax|2 + c |x|2,
by tacking an identity matrix on to A and zeros to y.
The parameter c (a.k.a. λ)
trades off fitting y - Ax, and keeping |x| small.
Then run a second fit with the r largest components of x,
r = rank(A) (or any number you please).


text:
Q: Error when i try to install android Platform at ionic I got the below error when trying to add Android platform to Ionic framework. I tried uninstalling and reinstalling Cordova, but the problem persists.

A: as you're obviously working on Windows:
Is your issue possibly related to this post?
EDIT: this at last solved the issue:
Add JAVA_OPTS as a system variable:
JAVA_OPTS="-Xms256m -Xmx512m"

After that, head over to your CMD and run the following command:
SET JAVA_OPTS="-Xms256m -Xmx512m"

Try again. ;)


text:
Q: Is there a way to disable a form from submitting on pressing the "enter" key? I am creating a simple program in JavaScript for school that randomizes numbers between 1 and a value submitted by the user through a simple form.
On submitting the value, I hide the form through jQuery and dynamically append a text prompt with the randomizer result and a reset button in its place.
At this point, I'm having problems getting around the use of the enter key, as the form (as opposed to the reset button) still responds to the press of the enter key, creating havoc, as my reset button is set to trigger on a click.
So is there any way to disable the enter key from triggering the submit event?

A: Should look like
<form name="" id="" action="" onsubmit="javascript:return false;">
</form>

A: This is how you can disable form submitting with jQuery:
$('form').submit(function(event){ // on form submisson
    event.preventDefault(); // prevent default action
});

edit: the code in jsFiddle

A: if (window.event.keyCode) = 13; return false
to disable the return key
Disable keyboard <enter> key
-You will get better answers if you try a few things first, if not just so people can get a better understanding of what are you trying to do


text:
Q: What lines should be uncommented and why, inheritance I have a code-snippet, and I should determine what line I should un-comment so it will compile.
Question: Why only lines 9,13 and 10,14 works? Why wont 9,14 work for example? I'm a bit confused. help is highly appreciated! (Btw, the options are only un-commenting two lines of code)
1. // Question 3.1
2. class Car {
3.  private Car() { }
4.  protected Car(int x) { }
5. }
6. public class MG extends Car {
7.   // MG(int x) { }
8.   // MG(int x) { super(); }
9.   // MG(int x) { super(x); }
10.  // private MG(int x) { super(x); }
11.  // MG() { }
12.  // MG() { this(); }
13.  // MG() { this(6); }
14.  // MG() { super(7); }
15.  public static void main(String[] args) {
16.    new MG(7);
17.    new MG();
18. } }

I believe the lack of understand comes from not enough familiarity of private constructor and protected access modifier, so I'm reading on that and I will also continue trying figuring it out.
Edit: Well I almost got it now, first of all line 8 cant be called so options with 8 and 11-14 are gone. line 7 - why can't it be called for e.g. with line 11? I believe MG(){} will be called but first the private car() has to be called, error. with line 12 not possible, because than I need line 11, with line 13 no idea why, with line 14 no idea why..

A: I wrote it on Ideone, because i was pretty sure that line 9 and 14 should work and they do!
Check it here (code)
The only important thing to remember in this example is, that if you do not invoke parent constructor, Java will invoke it in that manner "super()". Since your parent class non-parameter constructor is private, it won't compile.
That's why lines 7,8,11 are plain wrong.

A: Inheritance
Subclass by default get the access of all parent class methods, variables, constructor.
When you are going to create object of child class  then (jvm calls zero parameter constructor implicitly)first parent class constructor executed and then child class constructor.
In your case you are calling super class constructor explicitly.
Use print statement in constructor you will get clear idea ...

A: First of all Few things to notice:
First get some idea about access modifiers:

About private constructor:
prevent subclassing (extending). If you make only a private constructor(only have one constructor), no class can extend your class, because it can't call the super() constructor. read more
And little bit about constructor:

*

*Constructors are never inherited - they are specific to the class in
which they are defined.

*If no constructor implemented, default constructor will added by the
compiler implicitly.

*In subclasses did not call the super() compiler automatically add those to all the constructors.

*When a new object that is a subclass is constructed, the constructor
for the superclass is always called first.

*Constructor invocation maybe implicit or explicit.

*

*explicit call to a constructor of superclass: super() - has to be the first statement in the subclass constructor.

Without any constructor in MG:
In this line public class MG extends Car { eclipse show error:

Implicit super constructor Car() is not visible for default
  constructor. Must define an explicit constructor.

Because of inheritance you need to pass values to parent class constructor.
And for this new MG(7);:

The constructor MG(int) is undefined

Because you donot have any parameterized constructor in MG class.
UPDATE:
You said in your question you only want to know about line number 7, 11, 12, 13 and 14. But I will answer for all the lines. Then others who looking for answer also can understand
If you uncomment line number 7:
When we create an object of a child class always the constructor of the parent get completed and the constructor of the child runs later.
When you run the program, First in the main method new MG(7); object looking for matching constructor in the MG, which is MG(int x) {}. Inside this has super() which is compiler added one. Then compiler look for default constructor in parent class, It cannot find since default constructor is private.
To fix this: MG(int x) {super(x);}
If you uncomment line number 8:
When you run the program, First in the main method new MG(7); object looking for matching constructor in the MG, which is found.
MG(int x) {super()}

If you added super() or not compiler will add this. There is no different between these two:
MG(int x) {}
MG(int x) {super()}

If you uncomment line number 9:
This line is fine(no errors). First compiler looking for constructor(MG(int x) { super(x); } for object(new MG(7);). Then inside the constructor have called super(x) which is have one argument and it is match with the parent class constructor. As I mentioned before, parent class constructor execute first, Then child class constructor execute.
If you uncomment line number 10:
private MG(int x) { super(x); }

Access modifier is not affected because this class is a subclass and it is not a parent class for any class. And we can create object from calling private constructor. read more about private constructor.
If you uncomment line number 11:
MG() { }

It is match with the new MG(); object. Compiler have added super() but no matching constructor found in the parent class.
If you uncomment line number 12:
MG() { this(); }

First, lets look at what is this():

*

*this can be used inside the Method or constructor of Class.

*this works as a reference to the current Object whose Method or
constructor is being invoked.

*The this keyword can be used to refer to any member of the current
object from within an instance Method or a constructor.

*this() keyword can be used inside the constructor to call another
overloaded constructor in the same Class.

*This is also called the Explicit Constructor Invocation.

*And this() and super() both cannot use in one constructor.

So this line is unnecessary because you don't have any other MG() constructors. learn more about this.
If you uncomment line number 13:
MG() { this(6); }

This is also unnecessary or cannot be called unless you have another MG() constructor. If you do like this:
MG(){
    this(6);
}
MG(int x){
    super(x);
}

What happen here is when you run the program new MG(); object find the default constructor and in it call the parameterized constructor(MG(int x){}). Then in the this constructor take the value and send it to the parent class.
If you uncomment line number 14:
MG() { super(7); }

new MG(); is matched with the costructor and in it you have passed value 7 to the parent class parameterized constructor.
Done.


text:
Q: How can I make sure that OpenMP threads are running in parallel? I am working on some OpenMP program and I have the following code:
   #pragma omp parallel sections shared(a, b, r1, r2)
   {
        #pragma omp section
        {
           a = 1;
           r1 = b;
        }

        #pragma omp section
        {
           b = 1;
           r2 = a;
        }
   }

The main thing I want to observe here is that r1 = 1or r2 = 1 (this is allowed by the specification) but I have run this code snippet for more than 1000000 times and I cannot observe it. The only result I got is r1 = 0, r2 = 1 (I was expecting at least some of them will be r1 = 1, r2 = 0. I am wondering if the implementation is serialising my program. I used omp_set_num_threads(2); to force two threads, but how I can be sure that the two threads are actually run on two physical cores (I am using a dual-core Macbook pro, and I am using gcc-4.9 installed by homebrew).

A: Your example is perfectly fine. The problem is the minimal workload for the two threads. Section 1 is scheduled to thread #0 and Section 2 to thread #1. However, thread #0 finished his work before the thread #1 has started. It just look like sequential execution of your sections.
I modified your example:
#include <iostream>
#include <unistd.h>
int main()
{
    int a, b, r1=0, r2=0;
    #pragma omp parallel sections shared(a, b, r1, r2)
    {
        #pragma omp section
        {
            a = 1;
            sleep(10);
            std::cout << "section #1" << std::endl;
            r1 = b;
        }
        #pragma omp section
        {
            b = 1;
            sleep(5);
            std::cout << "section #2 "<< std::endl;
            r2 = a;
        }
   }
   std::cout << r1 << r2 << std::endl;
}

The output shows

section #2
section #1
11

Just as you might have expected.


text:
Q: what is the difference between java-1.7.0-openjdk-i386 and java-7-openjdk-i386 when i install netbeans it gives me the option to select the java environment, i have 3 options, the oracle java and these two (java-1.7.0-openjdk-i386 and java-7-openjdk-i386). what is the difference between these two?The os if ubuntu.

A: The two OpenJDK are same. However OpenJDK is slightly different from Oracle JDK. Read this post for more clarification.
The reason why you are getting two options for OpenJDK is PROBABLY that you have two copies of OpenJDK installed (or two different references to the same directory on your system.)
For further investigation, try to ls -lh /usr/lib/jvm. The /usr/lib/jvm is usually the directory where Java gets installed. Check if one of them is a symbolic link. Also, check in netbeans the location of the two JDK and see if in fact you have two versions or references of Java on the system.
For example, here is the output of ls -lh on my system:
ls -lh
total 24K
lrwxrwxrwx 1 root  root    26 Sep 10 13:41 default-java -> /usr/lib/jvm/java-7-oracle
lrwxrwxrwx 1 root  root    18 Mar 13  2012 java-1.5.0-gcj -> java-1.5.0-gcj-4.6
drwxr-xr-x 7 root  root  4.0K Aug 22  2012 java-1.5.0-gcj-4.6
lrwxrwxrwx 1 root  root    19 Jun 26  2012 java-1.6.0-openjdk-i386 -> java-6-openjdk-i386
drwxr-xr-x 3 root  root  4.0K Feb 15 10:52 java-6-openjdk-common
drwxr-xr-x 7 root  root  4.0K Feb 15 10:52 java-6-openjdk-i386
drwxr-xr-x 8 ankit ankit 4.0K Jun  6  2012 java-6-sun
drwxr-xr-x 5 root  root  4.0K Aug 22  2012 java-7-openjdk-i386
drwxr-xr-x 8 root  root  4.0K Feb 20 10:40 java-7-oracle
lrwxrwxrwx 1 root  root    12 Mar 13  2012 java-gcj -> java-gcj-4.6
lrwxrwxrwx 1 root  root    18 Apr 16  2012 java-gcj-4.6 -> java-1.5.0-gcj-4.6

As you can see java-1.6.0-openjdk-i386 is just a symbolic link/reference to another directory named java-6-openjdk-i386

A: You installed it twice
From openjdk, following instructions from here
sudo apt-get install openjdk-7-jdk

From Stackoverflow, following instructions from here
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

Would recommend the second one and remvong the first one by typing
sudo apt-get remove openjdk-7-jdk.


text:
Q: Catering for devices running Jelly bean as well as versions later than Jelly bean when obtaining application data usage I would like to cater for devices running on jelly bean version and below as well as versions above Jelly Bean.
My method is supposed to get app usage/traffic for all applications based on the application ID. Please take note
of this line rx = Long.parseLong(String.valueOf(id)); on the first if clause which caters for devices running versions less than or equal to Jelly Bean.
The data usage of an installed application based on its ID is obtained using using TrafficStats.getUidTxBytes(uid) but that only returns a value of 0 in 4.3  however, the else clause using TrafficStats.getUidTxBytes(uid) retrieves app usage per app accurately in versions above 5.
I am particularly concerned about the if clause which caters for device running android version lower than 5 for example in this case 4.3 (Jelly Bean)
public void recordSnapshot(Context context)
{
  TinyDB settings = new TinyDB(context);
  int boot_id = settings.getInt(AppPreferences.BOOT_ID);
  PackageManager pm = context.getPackageManager();

  for (ApplicationInfo app : pm.getInstalledApplications(0))
  {
     String androidOS = Build.VERSION.RELEASE;
     int currentapiVersion = android.os.Build.VERSION.SDK_INT;

     long tx = 0;
     long rx = 0;
     int uid = app.uid;

     if(currentapiVersion <= Build.VERSION_CODES.JELLY_BEAN)
     {
        File dir = new File("/proc/uid_stat/");
        String[] children = dir.list();
        List<Integer> uids = new ArrayList<Integer>();

           for (int i = 0; i < children.length; i++) {
              uid = Integer.parseInt(children[i]);
              String uidString = String.valueOf(uid);
              File uidFileDir = new File("/proc/uid_stat/" + uidString);
              File uidActualFile = new File(uidFileDir, "tcp_rcv");
              StringBuilder text = new StringBuilder();

              try {
                 BufferedReader br = new BufferedReader(new FileReader(uidActualFile));
                 String line;

                 while ((line = br.readLine()) != null) {
                    Log.d(String.valueOf(uid), line);//this returns the amount of data received for the particular uid
                    rx = Long.parseLong(String.valueOf(uid));
                    text.append(line);

                    text.append('\n');
                 }
              } catch (IOException e) {
                 //handle this
              }

              uids.add(id);
           }
     }
     else {
        tx = TrafficStats.getUidTxBytes(uid);
        rx = TrafficStats.getUidRxBytes(uid);
     }
}

Entire Method
public void recordSnapshot(Context context)
    {
        TinyDB settings = new TinyDB(context);
        int boot_id = settings.getInt(AppPreferences.BOOT_ID);
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        int networkType = NetworkState.GetNetworkState(context, info, "DataUsageRecorder"); // wifi, data, data roaming

        // Get all apps
        PackageManager pm = context.getPackageManager();
        for (ApplicationInfo app : pm.getInstalledApplications(0))
        {

            String androidOS = Build.VERSION.RELEASE;
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            long tx = 0;
            long rx = 0;
            int uid = app.uid;

            if(currentapiVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2)
            {

                File dir = new File("/proc/uid_stat/");
                String[] children = dir.list();
                List<Integer> uids = new ArrayList<Integer>();

                for (int i = 0; i < children.length; i++) {
                    uid = Integer.parseInt(children[i]);
                    String uidString = String.valueOf(uid);
                    File uidFileDir = new File("/proc/uid_stat/" + uidString);
                    File uidActualFile = new File(uidFileDir, "tcp_rcv");
                    StringBuilder text = new StringBuilder();

                    try {
                        BufferedReader br = new BufferedReader(new FileReader(uidActualFile));
                        String line;

                        while ((line = br.readLine()) != null) {
                            Log.d(String.valueOf(uid), line);//this returns the amount of data received for the particular uid
                            rx = Long.parseLong(String.valueOf(uid));
                            //text.append(line);

                            //text.append('\n');
                        }
                    } catch (IOException e) {
                        //handle this
                    }

                    uids.add(uid);
                }
            }

              else
            {

                 tx = TrafficStats.getUidTxBytes(uid);
                 rx = TrafficStats.getUidRxBytes(uid);
            }

            if ((tx == 0 || rx == 0))
            {
                // Skip inactive items
                continue;
            }
            else if (Globals.DEBUG && (tx < DEBUG_5MB && rx < DEBUG_5MB)) {
                // Let's skip all the BS for quick testing
                continue;
            }

            // Get package name
            String package_name;
            try {
                CharSequence name = pm.getApplicationLabel(app);
                package_name = name != null ? name.toString() : "";
            } catch (Exception e) {
                e.printStackTrace();
                package_name = "";
            }

            AppUsage totals;
            AppUsage appUsage;

            // Get current data entry for app
            //appUsage = appUsageDao.queryBuilder().where(AppUsageDao.Properties.App_uid.eq(uid), AppUsageDao.Properties.Type.eq(networkType), AppUsageDao.Properties.Boot_id.eq(boot_id)).limit(1).unique();

            // Get last recorded totals since device boot
            totals = appUsageDao.queryBuilder().where(AppUsageDao.Properties.App_uid.eq(uid), AppUsageDao.Properties.Type.eq(NetworkState.ALL), AppUsageDao.Properties.Boot_id.eq(boot_id)).limit(1).unique();

            long tx_diff = tx;
            long rx_diff = rx;

            if (totals != null)
            {
                // Get difference, and update
                tx_diff -= totals.getTx();
                rx_diff -= totals.getRx();

                totals.setTx(tx);
                totals.setRx(rx);
            }
            else
            {
                // add new master
                totals = new AppUsage(null, new Date(), uid, package_name, NetworkState.ALL, tx_diff, rx_diff, 0, 0, boot_id);
            }

            // add new app
            appUsage = new AppUsage(null, new Date(), uid, package_name, networkType, tx_diff, rx_diff, 0, 0, boot_id);

         /*if (appUsage == null)
         {
            // Create new
            appUsage = new AppUsage(null, new Date(), uid, package_name, networkType, tx, rx, 0, 0, boot_id);
         }
         else
         {
            // Update
            appUsage.setTx(tx);
            appUsage.setRx(rx);
         }*/

            try {
                // master
                appUsageDao.insertOrReplace(totals);
            } catch (DaoException e) {
                e.printStackTrace();
            }

            try {
                appUsageDao.insertOrReplace(appUsage);
            } catch (DaoException e) {
                e.printStackTrace();
            }

            //apps.put(app.uid, new DataUsageItem(app.uid, app.packageName, pm.getApplicationLabel(app).toString()));
        }
    }

A: despite what the documentation says traffic stats doesnt seem to work well on 4.3 in the sense that in some instances it works for some app id and not for some , therefore I would bypass the whole trafficstats class and create two custom methods pointing to the native c file that contains app usage data to retrieve tx(transmitted data) and Rx(received data) within the same class
   long tx = yourClass.getUidTxBytes(uid);
    long rx = yourClass.getUidRxBytes(uid);

Then for RX
public static Long getUidRxBytes(int uid) {
        BufferedReader reader;
        Long rxBytes = 0L;
        try {
            reader = new BufferedReader(new FileReader("/proc/uid_stat/" + uid
                    + "/tcp_rcv"));
            rxBytes = Long.parseLong(reader.readLine());
            reader.close();
        }
        catch (FileNotFoundException e) {
            rxBytes = TrafficStats.getUidRxBytes(uid);
            //e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return rxBytes;
    }**

Then for TX
 public static Long getUidTxBytes(int uid) {
        BufferedReader reader;
        Long txBytes = 0L;
        try {
            reader = new BufferedReader(new FileReader("/proc/uid_stat/" + uid
                    + "/tcp_snd"));
            txBytes = Long.parseLong(reader.readLine());
            reader.close();
        }
        catch (FileNotFoundException e) {
            txBytes = TrafficStats.getUidTxBytes(uid);
            //e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return txBytes;
    }


text:
Q: Getting the count of rows from a web table -SELENID I am working with Selenide, however, I need to count the number of rows in the table to write tests. The table has the functionality of displaying the number of rows, I want to check that when selecting, for example, 15 rows, 15 is displayed in the table. However, I do not understand exactly how to count them using selenide.

A: You can count the number of rows in the table using Selenide by finding all elements with the class "srringtable" and then using the .size() method.
int rowCount = $$(".srringtable").size();

A: JQuery will be easy.

let rowCount = $(".srringtable").length;
$("input#count").val(rowCount);

<input id="count">


text: Q: Alert based on GCP logs with MQL So, from my understanding MQL is used for advanced metrics and not something simple like Log based alert but is it possible to Alert from GCP log. The log comes as output of cronjob running in Kubernetes.


text:
Q: CMDeviceMotion stops updating when the app is brought back to foreground from background I start device motion updates in the foreground. When I put the app to background by locking the phone, I continue to get updates but when I unlock my phone, device motion stops updating. Accelerometer,gyroscope and location updates are working fine both in background and when I bring it back to foreground.
I am using CMMotionManager for getting accelerometer,gyroscope and device motion.
I am reading the pitch, roll and yaw values from Device Motion.

A: Try SOMotionDetector. This is very helpful library. This will work on both cases foreground & background.
https://github.com/SocialObjects-Software/SOMotionDetector


text:
Q: How to declare array in method I am currently having to write a method that takes in two parameters: an array of integers called data and an integer called num.  The purpose of this method is to count the amount of times that number shows up in the array.  I am having trouble figuring out how to declare the array in the method.  I was wondering if there was any easier way that I did below:
Method
public static void countNumbers( int data[], int num ) {
        int count = 0;

        for(int i = 0; i < data.length; i++) {
            if(data[i] == num)
                count++;
        }
        if (count == 0)
            System.out.println("There are no " + num + "'s in the array.");
        if (count == 1)
            System.out.println("There is one " + num + " in the array.");
        if (count > 1)
            System.out.println("There are: " + count + " " + num + "'s in the array.");
}

Main Class
public static void main(String args[]) {
        int firstArray[] = {1,2,3,4,5};
        Methods.countNumbers(firstArray, 2);
    }

So I was wondering if you could directly declare the array within the countNumbers(data,num) any help would be appreciated!

A: Is that what you are looking for?
public static void main(String args[]) {
    Methods.countNumbers(new int[] {1,2,3,4,5}, 2);
}


text:
Q: border-bottom on hover issue and text auto center I have a header in which a table menu is placed, however I run into some issues when trying to make a border-bottom appear when you hover over the specific td's, the border-bottom will appear when you hover over it, but the border will stay when you hover to another part of the page. (The border appears a couple of pixels above the bottom border of the header as well.)*I already resolved this issue myself, forgot to remove a calc() statement earlier
Also I'm wondering why the text in the td's gets automatically vertically centered. Maybe I'm overlooking something, please help?

* {
  padding: 0;
  margin: 0 auto;
}
header {
  position: fixed;
  width: 100%;
  left: 0;
  right: 0;
  margin-left: 0 auto;
  margin-right: 0 auto;
  height: 80px;
  background-color: rgb(50, 50, 50);
}
#header_container {
  width: 100%;
  height: 100%;
  max-width: 1000px;
  border: 0px solid black;
}
#menu_container {
  border-collapse: collapse;
  width: 100%;
  height: 100%;
}
#menu_container tr {
  width: 100%;
  height: 100%;
}
#menu_container td {
  height: 100%;
  width: 25%;
  text-align: center;
  color: rgb(203, 207, 218);
  font-family: Signika;
  font-size: 30px;
}
.menuItem {
  padding-top: 14px;
  border: 0;
}
.menuItem:hover {
  border-bottom: 1px solid blue;
}
#logo {
  width: 50%;
  height: auto;
}

        Home
        Over
        Contact

A: The logo image size disturbing safari browser,which has been fixed with
#logo {
  max-width: 100%;
  height: auto;
}

Hope this solution fine for you :)

* {
  padding: 0;
  margin: 0 auto;
}
header {
  position: fixed;
  width: 100%;
  left: 0;
  right: 0;
  margin-left: 0 auto;
  margin-right: 0 auto;
  height: 80px;
  background-color: rgb(50, 50, 50);
}
#header_container {
  width: 100%;
  height: 100%;
  max-width: 1000px;
  border: 0px solid black;
}
#menu_container {
  border-collapse: collapse;
  width: 100%;
  height: 100%;
}
#menu_container tr {
  width: 100%;
  height: 100%;
}
#menu_container td {
  height: 100%;
  width: 25%;
  text-align: center;
  color: rgb(203, 207, 218);
  font-family: Signika;
  font-size: 30px;
}
.menuItem {
  padding-top: 14px;
  border: 0;
  border-bottom: 1px solid  rgb(50, 50, 50);
  box-sizing: border-box;
}
.menuItem:hover {
  border-bottom-color: blue;
}
#logo {
  max-width: 100%;
  height: auto;
}

        Home
        Over
        Contact


text:
Q: using function from different module as decorator in python I have read few pages on the usage of decorators in python and was trying out few examples on how to use it. I was able to get it right when i try to have the decorator function and the orignal function all in the same script.
I am trying 2 set of codes here where i have specific intentions to be performed. Kindly help me in understanding what mistake i am making.
1.In this example, i have written by decorator function in script "dec1.py" and i am trying to import this in my second script "script.py", where i am getting TypeError "wrapper1() takes no arguments (1 given)"
###########dec1.py#####################
def setup (setup_funct):
    def wrapper1():
        print "******Test Section setup******"
        return setup_funct()
    return wrapper1
###########script.py################
import dec1

class setup(object):
    @dec1.setup
    def tc_setup():
        print "Configure X"
c1=setup()
c1.tc_setup()

2.Is it possible to have a method defined under a class to be used as a decorator function?. Here is what i am trying to run but it gives me the same TypeError "TypeError: wrapper1() takes no arguments (1 given)"
class Common(object):
    def setup (setup_funct):
        def wrapper1():
            print "******Test Section setup******"
            return setup_funct()
        return wrapper1

c1=Common()

@c1.setup()
def tc_setup():
    print "Configure X"

tc_setup()


text:
Q: how to remove gap from generated report in php I have a generated report from sql query in php, the output is:
The Query is:

SELECT 'S. J. & G. FAZUL ELLAHIE (PVT) LTD.' AS CompanyName,'E - 46, S.I.T.E., KARACHI - 75700' AS CompanyAddress,'admin' login_user,'Invoice_49161' selpdfFileName,'SP_DeliveryChallan' seltoprint,'crm.sjg.local' selhost,'admin' sellogin,'SI' selrptType,'false' selisTP,'Transfer to Stock' seldeliveryChallanTitle,'1494' seldocId,* FROM SP_Order(1494)

A: Thanks for your consideration. I got the solution, the problem was actually in the crystal reports. It was a formatting error, the joints of lines were not connected to each other.
Thanks Again.


text:
Q: run scripts sequentially which are watching for changes I have a package.json file like below with scripts tag.
{
  "name": "name",
  "version": "1.0.1",
  "license": "MIT",
  "scripts": {
    "cmd1": "cd packages/apis/ && yarn start",
    "cmd2": "cd packages/utils/ && yarn start",
    "cmd3": "cd packages/components/ && yarn start",
    "cmd4": "cd services/ad/ && yarn dev",
    "start": "yarn cmd1 && yarn cmd2 && yarn cmd3 && yarn cmd4"
  },
  "dependencies": {
    // dependencies listed here
  }
}

Above command run each command sequentially but what happens is that it is waiting for the previous command to complete execution before it executes the next command in line. But the problem is that each of above commands are watching different services for changes in file and then compiles them accordingly. So that means that above start command only runs the first command i.e. cmd1 and watching it and does not run the rest of the commands.
I tried using concurrently package but it runs all commands in parallel. I also looked at npm-run-all package but it seems to have an issue when trying to stop the process with ctrl + c key combination because it does not stop the process so I have to close the terminal.
Is there any other way to make them run sequentially while watching all the cmds?

A: You may write your own Node.js script to do that. Maybe check if the first command emits a string you are looking for (e.g. "Server started on http://localhost:8000/") then execute the next command.
EDIT:
Maybe this is helpful:
#!/usr/bin/env node

/**
 * Usage:
 *  ./runMany.js --command COMMAND1 [AWAITED_OUTPUT_REGEX1] [--command COMMAND2 ...] ...
 */

const { exec } = require('child_process');
const args = process.argv.slice(2);

async function main() {
  /** @type {{ command: string; awaitedOutput?: RegExp }[]} */
  const commands = [];

  for (let i = 0; i < args.length; i++) {
    const el = args[i];
    if (el === '--command') {
      ++i;
      const command = args[i + 1] || '';
      const awaitedOutput =
        args[i + 2] === undefined || args[i + 2] === '--command'
          ? undefined
          : (++i, new RegExp(args[i + 2]));

      commands.push({ command, awaitedOutput });
    }
  }

  console.table(commands);

  let i = 0;
  for (const command of commands) {
    console.info(`Executing: command ${i}`);
    await execute(command);
    console.info(`Done: command ${i++}`);
  }
}

main();

/** @type {(options: {command: string, awaitedOutput?: RegExp}) => Promise<void>} */
function execute({ command, awaitedOutput }) {
  const child = exec(command);

  return new Promise((resolve) => {
    awaitedOutput ? console.info(`Waiting for output that matches: ${awaitedOutput}`) : resolve();

    child.stdout.on('data', (data) => {
      const output = data.toString();

      if (awaitedOutput?.test(output)) {
        resolve();
      }

      process.stdout.write(output);
    });

    child.stderr.on('data', (data) => {
      const output = data.toString();
      process.stderr.write(output);
    });

    child.on('exit', (code) => {
      // if there was an error, exit
      if (code) {
        process.exit(code);
      }

      resolve();
    });
  });
}

Paste it in runMany.js then use it as:
node runMany.js --command 'yarn cmd1' 'THE OUTPUT YOU ARE WAITING FOR FROM cmd1' --command 'yarn cmd2' 'THE OUTPUT YOU ARE WAITING FOR FROM cmd2' --command 'yarn cmd3' 'THE OUTPUT YOU ARE WAITING FOR FROM cmd3' --command 'yarn cmd4' 'THE OUTPUT YOU ARE WAITING FOR FROM cmd4'

A: You just need to change the start command from:
"start": "yarn cmd1 && yarn cmd2 && yarn cmd3 && yarn cmd4"

to
"start": "yarn cmd1 & yarn cmd2 & yarn cmd3 & yarn cmd4 &"

This should run commands without waiting for previous command to finish.
The running jobs can be found with command "jobs". Those can be brought forward with the command "fg" if you need to kill them one by one before it is finished.
Hope it worksout.
The package npm-run-all seems to have a what you are looking for.
npm-run-all with --parallel flag
npm-run-all --parallel cmd1 cmd2 cmd3

Documentation says all running parallel commands are killed if one command is single CTRL+C.
Refer following links to set up each "yarn cmd" with a name.
https://github.com/mysticatea/npm-run-all/blob/HEAD/docs/npm-run-all.md#npm-scripts
Also see "nohup" command if you need to return to terminal without waiting for commands to finish.


text:
Q: ArcGIS Desktop from GetCapabilities to GetMap When making a GetCapabilities request from ArcGis Desktop, how does it get the information needed for making the GetMap request and how is the GetMap request handled by their "sample server"?
For example (taken from their own resource center http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//005300000046000000):
If I use their own sample server and make the following GetCapabilities request:
http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer?version=1.3.0&request=GetCapabilities&service=WMS
But how does it get the information needed for making the following GetMap request?:
http:/sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer?version=1.3.0&request=GetMap&CRS=CRS:84&bbox=-178.217598,18.924782,-66.969271,71.406235&width=760&height=360&layers=0&styles=default&format=image/png
Is it only taken from the GetCapabilities response XML or am I missing something here? It's difficult for me to understand how ArcGis Desktop creates the GetMap request and receives the images when I'm only inputting the GetCapabilities request. Is there some documentation I'm missing somewhere? And is there some kind of guideline as to how their "sample server" might be handling the incoming requests?

A: GetMap URL is automatically built using the response of GetCapabilities.
Here you see, where do GetMap parameteres come from in the GetCapabilities Xml Document:

*

*CRS=CRS:84  => This is the coordinate system of all layers. Just try to search the xml file for CRS:84.

*bbox=-178.217598,18.924782,-66.969271,71.406235 => Search for EX_GeographicBoundingBox in xml and you will see the bounding box of all layers and bounding box of each layer separately.

*width=760&height=360 = > just search for MaxWidth or MaxHeight and you will see two numbers. You can specify any number less than or equal to these numbers

*layers=0 => Look for the tags Layer. In your sample GetCapabilities xml, there a group layer at top, with 3 layers underneath that layer. You can query each layer with their numbers. valid values are 0,1,2

*styles=default  => look for style in the GetCapabilities xml

*format=image/png  => look for format in the GetCapabilities xml
All WMS (web mapping service) services support GetMap request by default, if you haven't disabled it, you can use the same server url but with different request parameter. Pay attention to your both URLs. They are exactly the same until the request part:
http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer?version=1.3.0
From here you can set the request parameter to either GetCapabilities or GetMap. For example:
http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer?version=1.3.0&request=GetMap


text:
Q: Handling overflow in Matlab with exponential and imaginary error functions With Matlab, I want to verify numerically whether the following inequality holds

$$\exp(-27^2)\text{erfi}(27)<\frac{21}{1000}.$$

However, I obtain "Inf" with Matlab. The reason is due to overflow, which lead to results too large to represent as conventional floating-point values.
My question is: Is there some trick to compute the LHS with Matlab?
Thanks for any help!

A: So we want to prove that
$$ \frac{2}{\sqrt{\pi}}\int_{0}^{27} e^{x^2-27^2}\,dx < \frac{21}{1000}\tag{1} $$
but plenty of continued fraction representations for the Dawson function are already known.
For instance, for any $x\geq 2$
$$ \text{erfi}(x)e^{-x^2} \leq \frac{2x}{\sqrt{\pi}}\cdot\frac{1}{1+2x^2-\frac{4x^2}{2x^2-1}}\tag{2} $$
holds, and the evaluation at $x=27$ leads to
$$ \frac{2}{\sqrt{\pi}}\int_{0}^{27} e^{x^2-27^2}\,dx=\frac{2}{\sqrt{\pi}}\int_{0}^{27}e^{x^2-54x}\,dx \leq 0.02092.\tag{3} $$
The middle representation is best suited for numerical purposes: $e^{x^2-54x}$ takes values $\geq 10^{-20}$ only over $[0,1]$, and $\int_{0}^{\color{red}{1}}e^{x^2-54x}\,dx $ is straightforward to approximate through Maclaurin series, convexity inequalities like $e^{x^2}\leq 1+x^2+(e-2)x^4$, Cauchy-Schwarz etc.


text:
Q: Combine visitors in VisitorPattern I implemented the visitor pattern according to cpppaterns.com to traverse a tree and apply specific actions based on the node types. I always need to traverse the tree in the same order, hence I moved the logic which determines which child to visit next, into the base class Visitor. The individual visitors perform specific operations on the tree nodes and then call the visit method in the base Visitor. This works pretty well so far.
In some cases it is needed to perform actions implemented among multiple visitors (e.g., VisitorRewriteX, VisitorPrintX) on one tree. The naive way is to just execute the visitors sequentially. However, this requires traversing the tree multiple times which is inefficient.
Of course, I could also create a new visitor (e.g., VisitorRewritePrintX) which just calls the other two visitors—but I think that's not clean code and not flexible. Is there some more generic way (e.g., a pattern) which could help me to somehow allow 'stacking' of the actions implemented in the different visitors?

A: There are various ways how you can do it, one way would be to have a general-purpose, visitor for which you can register handlers that are called for each visit:
struct visitor {

    visitor(std::initializer_list<std::function<void(int)>> cbs) : callbacks(cbs) {

    }

    void visit(int val) {
        for( auto &cb: callbacks ) {
            cb(val);
        }
    }

    std::vector<std::function<void(val)>> callbacks;
};

As you have visit function for different elements, you might need to change that to a class that has the corresponding member function instead of using std::function
Another way would be to utilize variadic template arguments:
struct handler_a {
    static void visit(int val) {
        std::cout << "handler_a: " << val << std::endl;
    }
};

struct handler_b {
    static void visit(int val) {
        std::cout << "handler_b: " << val << std::endl;
    }
};

template <class ...Handlers>
struct visitor {

    void visit(int val) {
        (Handlers::visit(val), ...);
    }
};

int main() {
    visitor<handler_a,handler_b> v;
    v.visit(10);
    return 0;
}

The variadic approach has the advantage that there is no loop because the compiler creates the code for the calls at compile time. But it has the downside that you cannot save temporary information with those handlers while traversing, as those are static functions. But you could maybe solve that with a context object you pass along with the traversed object.
And if you want you can alias your visitor sets with using visitor_a_b = visitor<handler_a,handler_b>.
I left out the inheritance to keep the code minimal, so you need to add them back to get virtual void accept(visitor& v) override working.

A: Basically, I would do something like:
struct IVisitor
{
    virtual ~IVisitor() = default;

    virtual void visit(NodeA&) = 0;
    virtual void visit(NodeB&) = 0;
    // ...
};

struct ITraversal : IVisitor
{
    // Traversal logic
    void visit(NodeA& n) final { visit(n.left); action(n); visit(n.right); }
    void visit(NodeB& n) final { action(n); visit(n.next); }
    // Actions
    virtual void action(NodeA&) = 0;
    virtual void action(NodeB&) = 0;

// ...
};

struct VisitorRewriteX : ITraversal
{
    void action(NodeA&) override;
    void action(NodeB&) override;
    // ...
};
struct VisitorPrintX : ITraversal
{
    void action(NodeA&) override;
    void action(NodeB&) override;
    // ...
};

// To allow type T with generic action
template <typename T>
struct VisitorT : ITraversal
{
    VisitorT() = default;
    VisitorT(const T& t) : t(t) {}

    void action(NodeA& n) override { t.action(n); }
    void action(NodeB& n) override { t.action(n); }
    // ...
    T t;
};

template <typename ... Ts>
struct Combine
{
    Combine() = default;
    Combine(Ts... args) : visitors{args...} {}

    template <typename Node>
    void action(Node& n) override {
        std::apply([&](auto&...visitor){ (visitor.action(n), ...); }, visitors);
    }
private:
    std::tuple<Ts...> visitors;
};

and then use either
VisitorRewriteX, VisitorPrintX or VisitorT<Combine<VisitorRewriteX, VisitorPrintX>>


text:
Q: In Tensorflow, how can I access my model's weights when computing loss? I'm implementing a model described in a research paper (https://ieeexplore.ieee.org/document/9897541 for those with access to IEEEExplore, although not necessary to understand this question) which proposes a loss function.
This loss function is computed in part from the weights matrix from one of the layers in the model (a fully-connected layer which is a Keras Dense layer object in my code).
I've got a class subclassed from Keras.Model which has a custom implementation of train_step().
In the with tf.GradientTape() as tape: block, I calculate the loss, which involves calling M = self.fc_layer.get_weights()[0], which returns a NumPy array. As this datatype is not a Tensorflow datatype, it appears that it is unable to associate the loss generated on the gradient tape with the trainable weights, as I'm getting the following error:
ValueError: No gradients provided for any variable: (['conv1_conv/kernel:0', 'conv1_conv/bias:0', 'conv1_bn/gamma:0', 'conv1_bn/beta:0', 'conv2_block1_1_conv/kernel:0', 'conv2_block1_1_conv/bias:0', 'conv2_block1_1_bn/gamma:0', 'conv2_block1_1_bn/beta:0', 'conv2_block1_2_conv/kernel:0', 'conv2_block1_2_conv/bias:0', 'conv2_block1_2_bn/gamma:0', 'conv2_block1_2_bn/beta:0', 'conv2_block1_0_conv/kernel:0', 'conv2_block1_0_conv/bias:0', 'conv2_block1_3_conv/kernel:0', 'conv2_block1_3_conv/bias:0', 'conv2_block1_0_bn/gamma:0', 'conv2_block1_0_bn/beta:0', 'conv2_block1_3_bn/gamma:0', 'conv2_block1_3_bn/beta:0', 'conv2_block2_1_conv/kernel:0', 'conv2_block2_1_conv/bias:0', 'conv2_block2_1_bn/gamma:0', 'conv2_block2_1_bn/beta:0', 'conv2_block2_2_conv/kernel:0', 'conv2_block2_2_conv/bias:0',
etc.

If I'm correct in thinking that this is the problem, how could I access the weights of self.fc_layer without breaking away from the requirements of the Tensorflow graph? I've got Eager Execution enabled just to get this far, which I'm assuming is a clear indicator that my current code is not graph-compatible for that reason.
Extra information if you're interested:
The reason the weights are needed in the loss function is because one row of the weights matrix represents a class centre, from which cosine similarity between that and the centre is computed, to maximise inter-class difference in an embedding generated for a vehicle re-identification task.

A: I would suggest building your own fully connected layer. A basic dense layer, taking into account the new class viewpoint $$M \in \mathbb{R}^{d\times C\times V}$$, is:
import tensorflow as tf

class DenseCustom(tf.keras.layers.Layer):

    def __init__(self,C,V,activation=None,activity_regularizer=None,kernel_initializer="GlorotUniform",trainable=True,seed=None,**kwargs):
        # pylint: enable=g-doc-args
        super(DenseCustom, self).__init__(
                activity_regularizer=activity_regularizer,
                **kwargs)

        self.C=C
        self.V=V
        self.activation_fn=activation
        if(self.activation_fn is None):
            self.activation_fn="linear"
        self.kernel_initializer=kernel_initializer
        self.trainable=trainable
        self.seed = seed

    def build(self, input_shape):
        assert len(input_shape)==2#only for batch, features rank

        last_dim=input_shape[-1]

        input_shape = tf.TensorShape(input_shape)

        kernel_initializer=self.kernel_initializer

        if(type(kernel_initializer) is str):
            kernel_initializer=getattr(tf.keras.initializers, kernel_initializer)()

        self.kernel = self.add_weight('kernel',shape=[self.C, self.V, last_dim],initializer=kernel_initializer,dtype=tf.float32,trainable=self.trainable)

        self.built = True

You do not need to access the weights of the network at learning time in the loss. You only need to make the output of the network the necessary to plug in the loss. The output should be $$\phi=\frac{M\cdot x_i}{||M||\cdot ||x_i||}$$. The call function would take the form:
    @tf.function
    def call(self, X):

        M=self.kernel

        norm_M=tf.expand_dims(tf.norm(M, ord=2,axis=2), axis=-1)
        norm_X=tf.norm(X, ord=2)

        #L_R reunion loss
        self.add_loss(lambda : tf.reduce_sum((-2/(self.V*(self.V-1)))*tf.einsum("CVD, CVD-> D", M/norm_M, M/norm_M)) )

        return tf.einsum("BD,CVD->BCV",X/norm_X, M/norm_M,)

Now you can implement directly the loss of equation (3), being the output of this network $$\phi$$.
If you execute this code you get a tensor with the desired shape:
C=5
V=7

view_layer=DenseCustom(C,V)

x = tf.ones((10,4))

view_layer(x).shape

Output:
TensorShape([10, 5, 7])


text:
Q: finding the dp state ZUMA spoj i am trying to solve this spoj problem
http://www.spoj.pl/problems/ZUMA
i am unable to find a possible dp state .
can someone guide me what would be a possible dp state for this problem.

A: I already accepted that problem in SPOJ.
My state is, from position i to j with p equals elements. For transition you should consider two case:

*

*Insert how many piece in position i like you need to exploit that piece, then we will have the same problem but consider i+1 to j

*Let's say q is the position of an ahead element equal to the piece in i. We should consider solving the problem from i to q-1 and then from q to j for every q.


text:
Q: Aweber form not collecting leads because of simple jquery code I have a signup form that is having trouble to pass the input fiel data to aweber list.
submission takes place in same window without reloading the page, and I can see in the bottom of the browser window how the server is connecting to aweber url but the data is not passing through:
html form code that I am currently using:

<form method="post" action="http://www.aweber.com/scripts/addlead.pl" class="firstFom" target="AweberFormSubmitFrame" id="formularioaweber">
    <input type="hidden" name="meta_web_form_id" value="79676xxxx"/>
    <input type="hidden" name="meta_split_id" value=""/>
    <input type="hidden" name="listname" value="tizona_prosp"/>
    <input type="hidden" name="redirect" value="#" id="redirect_060b3473249d14423a8ed1bb376cdca8"/>
    <input type="hidden" name="meta_adtracking" value="Tizona_Joyas_Prospectos"/>
    <input type="hidden" name="meta_message" value="1"/>
    <input type="hidden" value="email"/>
    <input type="hidden" name="meta_tooltip" value=""/>

        <input type="email" value="" name="email" id="awf_field-44988808" placeholder="Ingrese Su Email" required>

        <input type="submit" value="enviar" id="enviar">

</form>

Now, this is the code that is changing some styling after the form is submitted:
$(function (){
    $( "#formularioaweber" ).submit(function( event ) {
        //alert( "Handler for .submit() called." );
        //alert($('input#awf_field-44988808').val());
        var a = $('#awf_field-44988808').val();
        $("#success-message").removeClass('display-none');
        // alert(a);
        $('#awf_field-44988808').val('');
        $('#enviar').css({"background-color": "grey"});
        $('#enviar').val('PROCESADO');
        $('#enviar').attr('disabled','disabled');
        $('#awf_field-44988808').attr('placeholder', 'Catalogo enviado a '+a);
        $("#awf_field-44988808").attr('disabled','disabled');
    });
});

I believe this happens because the form fields get reseted before the connection is stablished with aweber.com, this is just my guess.
Note: if I omit the jquery code, the form works fine.


text:
Q: Preventing reverse-engineering of a Java game source code using client server model I'm looking to find ways to prevent a Java made game such as runescape from being hacked by using the client server model for keeping the important source code in the server and sending the data to the client. My question is how would it be possible to make something like this, any information links or articles would be helpful.
I'm also wondering what kind of information can someone send from a server that can also be rendered in a 3d graphics engine, or how is it done?

A: You can't do much about the client being decompiled - you can obfuscate your source code to make it more difficult to reverse-engineer. This will make getting readable source code slightly more difficult, but not impossible. A determined and skilled user could stil reverse-engineer the client.
However you can do a lot of work on the server where the source code can't be recovered. For example you could code the artifical intelligence for NPCs, and all physics calculations on the server and just send the results to the clients.
In fact these sorts of calculations should be done on the server anyway to keep the game consistent and to prevent clients from cheating.
The client will typically do most of the presentation such as 3D rendering. This is usually done locally for performance reasons, so that the rendering can take full advantage of the graphics card in the client.

A:
I'm also wondering what kind of
  information can someone send from a
  server that can also be rendered in a
  3d graphics engine, or how is it done?

While I am not a game/3d developer myself, I found this article illuminating (browse their wiki for more!)
Source Multiplayer Networking [valvesoftware.com]

A: Every program, given sufficient manpower and time, can be reverse engineered. If you can give a team of testers/developers the program to use for a while, they are going to be able to mimic its functionality. A great example is the MMORPG games out there (think about Ultima Online and the plethora of open source Shards that mimic it and work with the UO client).
You can obfuscate the code, and make it hard to decompile etc.,  but at the beginning of a project that is beyond overkill. Make something people will be willing to pay for, take the very basic source-code protection precautions and then rely on copyright law to shield you from reserve engineering (its not perfect, but nothing is).

A: The client server model in theory could prevent many forms of cheating by only sending specific information between the two, notably input from the player and the players view of the game from the server.
However in practice this is rarely done.  Lag prevents a real time game from playing adequately without having the client handle at least part of the positioning and physics work.  This means a player has copies of information stored locally that they shouldn't have in the game.
The client server model also does little for hacks with macro actions.  Players can hack their clients to repeat actions or assist actions (such as aiming).  Certain other information can recreated on a hacked client from the information the server provides.
Rendering the 3d scene itself falls into three camps.

*

*Each client can render it however
they feel.  It doesn't matter if you
use sword swing A or sword swing B
if they don't interact differently
with the environment.

*Clients can make a best guess, and have to reconcile if wrong.  I lose connection for 2 seconds.  My character keeps running on your screen because your client assumes that's what I would be doing.  I reconnect, but I had told the client to turn.  Either I jump on your screen or mine.

*The server decides.  The server says a barrel falls along algorithmic path C.  This is most common when the falling barrel interacts with the environment i.e. it can hit and damage other things.


text:
Q: Counting Sort - Why go in reverse order during the insertion? I was looking at the code for Counting Sort on GeeksForGeeks and during the final stage of the algorithm where the elements from the original array are inserted into their final locations in the sorted array (the second-to-last for loop), the input array is traversed in reverse order.
I can't seem to understand why you can't just go from the beginning of the input array to the end, like so :
for i in range(len(arr)):
        output_arr[count_arr[arr[i] - min_element] - 1] = arr[i]
        count_arr[arr[i] - min_element] -= 1

Is there some subtle reason for going in reverse order that I'm missing? Apologies if this is a very obvious question. I saw Counting Sort implemented in the same style here as well.
Any comments would be helpful, thank you!

A: Stability. With your way, the order of equal-valued elements gets reversed instead of preserved. Going over the input backwards cancels out the backwards copying (that -= 1 thing).

A: To process an array in forward order, the count / index array either needs to be one element larger so that the starting index is 0 or two local variables can be used. Example for integer array:
def countSort(arr):
    output = [0 for i in range(len(arr))]
    count = [0 for i in range(257)]         # change
    for i in arr:
        count[i+1] += 1                     # change
    for i in range(256):
        count[i+1] += count[i]              # change
    for i in range(len(arr)):
        output[count[arr[i]]] = arr[i]      # change
        count[arr[i]] += 1                  # change
    return output

arr = [4,3,0,1,3,7,0,2,6,3,5]
ans = countSort(arr)
print(ans)

or using two variables, s to hold the running sum, c to hold the current count:
def countSort(arr):
    output = [0 for i in range(len(arr))]
    count = [0 for i in range(256)]
    for i in arr:
        count[i] += 1
    s = 0
    for i in range(256):
        c = count[i]
        count[i] = s
        s = s + c
    for i in range(len(arr)):
        output[count[arr[i]]] = arr[i]
        count[arr[i]] += 1
    return output

arr = [4,3,0,1,3,7,0,2,6,3,5]
ans = countSort(arr)
print(ans)

A: Here We are Considering Stable Sort --> which is actually considering the Elements position by position.
For eg if we have array like
arr--> 5 ,8 ,3, 1, 1, 2, 6
     0 1 2 3 4 5 6 7 8

count-> 0 2 1 1 0 1 1 0 1
Now we take cummulative sum of all frequencies
     0 1 2 3 4 5 6 7 8

count->  0 2 3 4 4 5 6 6 7
After Traversing the Original array , we prefer from last Since
we want to add Elements on their proper position so when we subtract the index , the Element will be added to lateral position.
But if we start traversing from beginning , then there will be no meaning for taking the cummulative sum since we are not adding according to the Elements placed. We are adding hap -hazardly which can be done even if we not take their cummulative sum.


text:
Q: Equal height columns jQuery not working in webkit browsers I tried to use both of these two solutions
1)
jQuery.fn.equalHeights = function() {
return this.height(Math.max.apply(null,
this.map(function() {
return jQuery(this).height()
}).get()
));
};

2)
jQuery.fn.equalHeights = function () {
var height = 0,
reset = jQuery.browser.msie ? "1%" : "auto";
return this.css("height", reset).each(function () {
height = Math.max(height, this.offsetHeight);
}).css("height", height).each(function () {
    var h = this.offsetHeight;
    if (h > height) {
        jQuery(this).css("height", height - (h - height));
    }
});
};

to have equal height columns, but I have problems in webkit browsers only.
Here is a screenshot, with the content of the left column overflowing. The columns have actually the same height, but they are all too short...
This is my jQuery call, in the footer:
jQuery(document).ready(

function() {

//Equal columns
jQuery('#center_column, #right_column,#left_column').equalHeights();
}
);

It looks like it is executed before the DOM is completely ready for some reason...
Any suggestion?

A: I've had problems in the past with Webkit browsers not being able to see the image dimensions until after the document.ready event. To get around this, you can specify the height and width in the  tag:
<img src="foo.jpg" alt="Foo" width="500" height="500" />

And if that doesn't work, you might find you need to do a little bit of a hack, using the window.load event rather than $(document).ready.


text:
Q: problem with changing the color and size of same text in javafx This is my code for building a text editor. Everything works fine but the thing is when I change the font size of the selected text and after it want to change the color of the same text, it changes the size of the text back to the default. I want to know how can I fix this issue.
Some people suggested defining a hashmap where we save each character that entered in the textarea and save it with its style. But I couldn't figure it out.
sample.FXML
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.collections.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<?import org.fxmisc.richtext.InlineCssTextArea?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity"
        prefHeight="564.0" prefWidth="790.0"
        xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
        fx:controller="sample.Controller">
  <center>
    <InlineCssTextArea  fx:id="textArea" BorderPane.alignment="CENTER"
        onKeyTyped="#handleTextAreaAction">
      <BorderPane.margin>
        <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
      </BorderPane.margin>
      <padding>
        <Insets bottom="1.0" left="1.0" right="1.0" top="1.0" />
      </padding>
    </InlineCssTextArea>
  </center>
  <top>
    <HBox BorderPane.alignment="CENTER">
      <children>
        <Button mnemonicParsing="false" onAction="#UploadButtonClicked"
            text="Upload">
          <HBox.margin>
            <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
          </HBox.margin>
        </Button>
        <ComboBox fx:id="familyComboBox" onAction="#familyOnAction"
            promptText="Font Theme">
          <HBox.margin>
            <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
          </HBox.margin>
          <items>
            <FXCollections fx:factory="observableArrayList">
              <String fx:value="Arial" />
              <String fx:value="Times new Roman" />
              <String fx:value="Calibri"/>
            </FXCollections>
          </items>
        </ComboBox>
        <ComboBox fx:id="sizeComboBox" layoutX="62.0" layoutY="10.0"
             onAction="#sizeOnAction" promptText="Font Size">
          <HBox.margin>
            <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
          </HBox.margin>
          <items>
            <FXCollections fx:factory="observableArrayList">
              <String fx:value="11" />
              <String fx:value="12" />
              <String fx:value="14" />
              <String fx:value="18" />
              <String fx:value="24" />
            </FXCollections>
          </items>
        </ComboBox>
        <ComboBox fx:id="ColorBoxColor" layoutX="180.0" layoutY="12.0"
            onAction="#colorOnAction" promptText="Font Color">
          <HBox.margin>
            <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
          </HBox.margin>
          <items>
            <FXCollections fx:factory="observableArrayList">
              <String fx:value="Red" />
              <String fx:value="Black" />
              <String fx:value="Green" />
              <String fx:value="Blue" />
            </FXCollections>
          </items>
        </ComboBox>
        <Button fx:id="bold" layoutX="10.0" layoutY="10.0"
            mnemonicParsing="false" onAction="#boldOnAction" text="Bold">
          <HBox.margin>
            <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
          </HBox.margin>
        </Button>
        <Button fx:id="italic" layoutX="487.0" layoutY="10.0"
             mnemonicParsing="false" onAction="#italicOnAction" text="Italic">
          <HBox.margin>
            <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
          </HBox.margin>
        </Button>
      </children>
    </HBox>
  </top>
</BorderPane>

Controller.java:
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.IndexRange;
import javafx.scene.input.KeyEvent;
import javafx.scene.control.TextArea;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import org.fxmisc.richtext.InlineCssTextArea;
import java.awt.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class Controller {
    Map<Integer,String> list = new HashMap<>();

    @FXML private ComboBox ColorBoxColor;
    @FXML private InlineCssTextArea textArea ;
    @FXML private ComboBox sizeComboBox;
    @FXML private ComboBox familyComboBox;

    String fontType ;
    int fontSize;

    CharacterStyle style = new CharacterStyle();
    @FXML
    public void handleTextAreaAction(KeyEvent key) {

    }

    public void italicOnAction(ActionEvent event) {

    }

    public void boldOnAction(ActionEvent event) {
    }
    @FXML
    public void colorOnAction(ActionEvent event) {

        try {
            int last = (textArea.getText().lastIndexOf(textArea.getSelectedText()))+textArea.getSelectedText().length();
            int start = last - textArea.getSelectedText().length();

            if (ColorBoxColor.getValue().equals("Red")) {
                textArea.setStyle(start,last,"-fx-fill: "+style.getColor("red"));
            }
            else if (ColorBoxColor.getValue().equals("Black")){
                textArea.setStyle(start,last,"-fx-fill: "+style.getColor("black"));
            }
            else if (ColorBoxColor.getValue().equals("Green")) {
                textArea.setStyle(start,last,"-fx-fill: " +style.getColor("green"));
            }else{
                textArea.setStyle(start,last,"-fx-fill: "+ style.getColor("blue"));
            }
        }catch (Exception ex) {
            System.out.println("Error");
        }
    }
    @FXML
    public void sizeOnAction(ActionEvent event) {

        try {
            int last = (textArea.getText().lastIndexOf(textArea.getSelectedText()))+textArea.getSelectedText().length();
            int start = last - textArea.getSelectedText().length();

            if (sizeComboBox.getValue().equals("11"))
                fontSize = style.getSize(11);
            else if (sizeComboBox.getValue().equals("12"))
                fontSize = style.getSize(12);
            else if (sizeComboBox.getValue().equals("14"))
                fontSize = style.getSize(14);
            else if (sizeComboBox.getValue().equals("16"))
                fontSize = style.getSize(16);
            else if (sizeComboBox.getValue().equals("18"))
                fontSize = style.getSize(18);
            else
                fontSize = style.getSize(24);

            textArea.setStyle(start,last,"-fx-font-size: " + style.getSize(fontSize));

        } catch (Exception ex) {

            System.out.println("Error");
        }
    }

    public void familyOnAction(ActionEvent event) {
        try {
            int last = (textArea.getText().lastIndexOf(textArea.getSelectedText()))+textArea.getSelectedText().length();
            int start = last - textArea.getSelectedText().length();

            if (familyComboBox.getValue().equals("Times New Roman")) {
                fontType = style.getFont("Times New Roman");
            } else if(familyComboBox.getValue().equals("Arial")) {
                fontType = style.getFont("Arial");
            }
            else
                fontType = style.getFont(("Calibri"));

            textArea.setStyle(start,last,"-fx-font-family: " +fontType);

        } catch (Exception ex) {
            System.out.println("Error");
        }
    }

    public void UploadButtonClicked(ActionEvent event) {
    }
}

I want to find out what did I miss so it wont get back to default when I apply more than one style on a specific text.