text:
Q: How do I fix this npx create-react-app error? This is How it looks

When I gave "npx create-react-app my-app" this is what I faced.
Could'nt figure out any measures.
"yarn create-react-app my-app" - this didn't work either.
Creating a new React app in C:\mern-stack-project\my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

> core-js@2.6.11 postinstall C:\mern-stack-project\my-app\node_modules\babel-runtime\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"

> core-js@3.6.5 postinstall C:\mern-stack-project\my-app\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"

> core-js-pure@3.6.5 postinstall C:\mern-stack-project\my-app\node_modules\core-js-pure
> node -e "try{require('./postinstall')}catch(e){}"

+ cra-template@1.0.3
+ react-scripts@3.4.1
+ react-dom@16.13.1
+ react@16.13.1
added 1613 packages from 750 contributors in 216.578s

58 packages are looking for funding
  run `npm fund` for details

And my prompt had these comments for hours.
I'll attach my screens.
My console stays like this and I had to open another window to execute "npm start"

And this is what I get after running "npm start"

A: I don't know what's wrong, here are some troubleshooting steps you can follow to see if it helps:

*

*Delete your node install

*Install again, but from the official website. Don't google random pages about installing node, only official site.

*Make sure your Node and NPM version are 12+ and 5+ respectively

*Get rid of your client/ directory

*Finally try again running npx create-react-app client
There isn't anything extraordinary with these steps, I just don't know what have you done to achieve your current error, so I'm sort of giving you a baseline of steps to do.

A: I think that your command prompt was suspended. Go to the Resource Monitor and right click on the suspended cmd process and click on resume process. Do this 2 times. This resumes the installation of the packages.


text:
Q: Custom jQuery Mobile Theme won't apply Wordpress I'm trying to apply my own Theme made with jQuery Mobile Themeroller to my Wordpress Theme. But somehow it won't apply.
Here is my header.php code
<!DOCTYPE html>
<html>
    <head>
    <title>
        <?php
            if (function_exists('is_tag') && is_tag()) {
                single_tag_title("Tag Archive for ""); echo '" - '; }
            elseif (is_archive()) {
                wp_title(''); echo ' Archive - '; }
            elseif (is_search()) {
                echo 'Search for "'.wp_specialchars($s).'" - '; }
            elseif (!(is_404()) && (is_single()) || (is_page())) {
                wp_title(''); echo ' - '; }
            elseif (is_404()) {
                echo 'Not Found - '; }
            if (is_home()) {
                bloginfo('name'); echo ' - '; bloginfo('description'); }
            else {
                bloginfo('name'); }
            if ($paged>1) {
                echo ' - page '. $paged; }
        ?>
    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="apple-mobile-web-app-capable" content="yes" />

    <link rel="apple-touch-icon-precomposed" href="<?php bloginfo('template_url'); ?>/img/icon.png" />
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="<?php bloginfo('template_url'); ?>/img/icon-ipad.png" />
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="<?php bloginfo('template_url'); ?>/img/icon-iphone4.png" />

    <link rel="apple-touch-startup-image" href="<?php bloginfo('template_url'); ?>/img/splash.png" />
    <link rel="apple-touch-startup-image" sizes="640x920" href="<?php bloginfo('template_url'); ?>/img/splash-iphone4.png" />

    <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<link rel="stylesheet" href="themes/CustomTheme.min.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>

    <?php
    wp_head();
?>
</head>

<body <?php body_class(); ?>>

Also tried the the custom css before the jQM CSS and the code that is given with Theme.zip when you download it at themeroller
<link rel="stylesheet" href="themes/CustomTheme.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile.structure-1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>

can you see any problems why it won't apply?

redpajama_set_name: RedPajamaStackExchange


text:
Q: TFS 2012 work item ui window refresh I've created Server side Event Handler on TFS 2012 Server. After saving work item, i put some logic, what calculate data from few fields and show in another one. The problem is, that after saving work item element ( by clik 'save' button ), i've havent my changes - becous they begin to calculate only AFTER saving, and i want to refresh UI Window with Work Item, but not know how to. Any suggestions?
P.S. In Visual Studio and in Web Access.

A: Sadly this is not possible, at least directly from TFS API. You will have to create your on plugin for Team Explorer and Web Access.


text:
Q: python-crontab Как удалить определенное задание Всем привет, я создаю задания с помощью python скрипта, вот так:
from crontab import CronTab

cron = CronTab('name')
job = cron.new(command=f'python3 /home/name/PycharmProjects/vkbot/posting_script.py {token} {idg} "{text}"')
job.minute.every(interval)
cron.write()

И все работает отлично, но мне нужно как-то удалить одно задание из списка.
К примеру создал я 3 задания, а по запросу пользователя мне нужно удалить 2-е.
Подскажите пожалуйста, как мне определить какое именно мне нужно удалить задание(по идентификатору может какому-то) и как его удалить c помощью питон скрипта?


text:
Q: JavaScript: recreate/order Document Fragment. Remove formatting from fragment I am building a block-based editor but have hit a wall on how to proceed.
I do not want to use execCommand to do things such as bold text because I want my editor to be able to wrap selected text in anything custom, as well as because execCommand works differently across browsers.
My issue is undoing fragmented markup.
For example, if we have text like this.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

and wanted to simply unbold a word or two, that's easy.
But what if we have something like this where formatting is nested:
The Lost City of Atlantis is a myth and legend that has fascinated generations and captured the imagination for countless storytellers since the great philosopher Plato first introduced it to the masses ~360BC.

and I wanted to unbold the word countless?
Assuming I already have a created document fragment that contains all of the current nodes, and added a class selectionNode to the node that contains the text we want to unbold, what is the best way to go about unraveling everything to get the desired output?

Can anyone help point me in the right direction? Or am I doing this the "hard" way and there is a better solution to this all together?


text:
Q: Should I add a owner component on every entity that has parent? Should I add a owner component on every entity that has parent? if yes, what is the right term for that component. Currently I am using AttachmentComponent that consist of owner Entity, and use it like in the below code.
AttachmentComponent ...
ItemComponent ...

entity.add(attachment);
entity.add(item);

A: If your entities can be hierarchical in nature, why introduce a component to represent the parent entity but instead represent it as an attribute on the entity itself?
public class Entity {
  private Set<Component> components;
  private Entity owner;

  public final boolean hasOwner() {
    return owner != null;
  }

  public void setOwner(Entity owner) {
    this.owner = owner;
  }
}

You could also maintain a list on each Entity with all its relevant children should you need to traverse the entity hierarchy from top-down rather than bottom-up.


text:
Q: Isomorphism Gaussian and Polynomial Quotients How does $$\mathbb{Z}[i]/(2+i) \cong \mathbb{Z}[x]/(x^2+1,2+x)$$ follow formally from the fact that $$\mathbb{Z}[i] \cong \mathbb{Z}[x]/(x^2+1)?$$

A: $\newcommand{\ZZ}{{\mathbb Z}}$
$\newcommand{\ideal}[1]{{\mathfrak #1}}$
It can be transformed
$$
\begin{multline}
\ZZ[i]/(2+i)\ZZ[i] = (\ZZ[x]/(x^2+1))/((2+\bar{x})\ZZ[x]/(x^2+1)) =  \\ =(\ZZ[x]/(x^2+1))/((2+x) \ZZ[x]/(x^2+1)) = (\ZZ[x]/(x^2+1))/((2+x,x^2+1)/(x^2+1)) = \\
 = \ZZ[x]/(2+x,x^2+1)
\end{multline}
$$
using $(M/P)/(N/P) = M/N$ for $A$-modules $M \supseteq N \supseteq P$ (Noether isomorphism theorem) and $\ideal{a} (A/\ideal{b}) = (\ideal{a} + \ideal{b})/\ideal{b}$ for $\ideal{a}, \ideal{b} \subseteq A$ two ideals of $A$.


text:
Q: Database design question (unknown number of columns?) I am just starting my journey into learning databases/SQL and the like.  I decided to make some databases for one of the companies I work for as practice and to help us organize a little.
One of the tables will simply contain all of the individual parts we have in our inventory with columns like: PartNumber, Description, and StockQty.
The other table would contain all of the hardware kits we make.  All of which are made up of a combination of parts we have in our inventory.
My initial thought was to have columns such as: PartNumber, KitName, Part1Number, Part1Qty, ... PartNnumber, PartNQty etc. The numbers in the parts columns would be part numbers of items in the first table.
So since not all kits have the same number of parts I would just have to know how many parts are in the largest kit and make that many Parts columns.  But then what if I have to add a new kit with more parts?
Is there a better way to do this?
Any suggestions would be greatly appreciated!
Thanks!

A: This is a very basic question in relational DB design. The solution is easy: Invent a 3rd table containing the relationships between table A and B.
Table A products:

*

*ID 1, name "car"

*ID 2, name "bicycle"

Table B parts:

*

*ID 1, name "wheel"

*ID 2, name "seat"

Table C relationships:

*

*ID 1, product 1, part 1, quantity 4

*ID 2, product 2, part 1, quantity 2

*ID 3, product 1, part 2, quantity 4

*ID 4, product 2, part 2, quantity 1

I hope you can understand the example. Go on with SQL and have fun learning! I can recommend buying a good book which introduces basic SQL knowledge and you'll speed up your success with SQL.

A: ++ For the answers above.
You should start thinking about the keys of these tables now. Each table should have something that will serve to uniquely identify a row -- done sensibly this will ensure that you can't get duplicate rows which would mess up your data.
Here's a really simple example.
CREATE TABLE Parts (
    [PartNumber] INT
    , [PartDescription] VARCHAR(50)
)

The PartNumber column would make a really good PRIMARY KEY (Assuming that no two parts thet you will ever have would have the same PartNumber) A property that uniquely defines a row and has meaning in and of itself is an example of a NATURAL KEY
CREATE TABLE Kits (
    [KitNumber] INT
    , [KitDescription] VARCHAR(50)
)

Again -- KitNumber would be a good primary key. If there wasn't a NATURAL KEY for kits then you would probably make the KitNumber a simple Auto Incrementing SURROGATE KEY.
Now to the more complicated table. The one that models the link between Parts and Kits. (Kits are made of parts).
CREATE TABLE KitParts (
    [KitNumber] INT
    , [PartNumber] INT
    )

So the only information this table contains is the links between Kits and Parts. What should the PRIMARY KEY be?
If you think about the thing that uniquely identifies a row is the COMBINATION of the two columns. Therefore the NATURAL KEY is both ([KitNumber] and [PartNumber]). This is called a COMPOSITE KEY.
Also this table should add some FOREIGN KEY Constraints. For example, [KitNumber] should never contain a value that doesn't exist in the Kits table.......
Good luck. Welcome to SQL Development.

A: You should break up your second table into two new ones, one for kits, and one for parts belonging to kits.
Tables needed:
PARTS(PartNumber, Description, StockQty)
KITS(KitNumber, KitName)
KITSPARTS(KitNumber, PartNumber, PartQty)

This way, you add an entry to the KITSPARTS table per unique part belonging to a kit.
Sample data:
PARTS
1, "Apple", 1
2, "Orange", 2

KITS
1, "Salad"

KITSPARTS
1, 1, 1
1, 2, 1

The sample data models a single kit, "Salad", with two parts; 1 "Apple" and 1 "Orange".

A: As others have said you need to normalize your design.


text:
Q: NodeJS writing response First of all: I am a beginner at nodeJS!
My Problem is that i have an html-file, which is complex, and i want to write an individual response in it. For example
index.js
var express = require('express');
var app = express();

var server = app.listen(3000, function () {
console.log('Listening at port 3000');
});

app.use(express.static('public'));

app.get('/', function(req, res){
res.sendFile(__dirname + 'index.html');
//
// what to write here when i want to modify the index.html before sending?
//
});

index.html
<!DOCTYPE HTML>
<html>
    <div id="writehere">
    <!--I would like to modify the page here-->
    </div>
</html>

I hope you can help me and understood my question!


text:
Q: Django - How to check if id contains in a table column? guys.
I want to check in my django template, if request.user exists in some row of column user in my table LeagueMember. The way I found is not working.
views.py
@login_required(login_url='login/')
def search_leagues(request):
if request.method == 'POST':
    return redirect('join_league')

leagues = League.objects.all()
return render(request, 'search_leagues.html', { 'allleagues': leagues })

model.py
class League(models.Model):
    league_owner = models.ForeignKey('auth.User')
    league_name = models.CharField(max_length=30)
    creation_date = models.DateTimeField()

    def is_member(self):
        member = LeagueMember.objects.get(league=self)
        if member:
            return True
        else:
            return False

class LeagueMember(models.Model):
    league = models.ForeignKey('League', related_name='leaguemember_league')
    user = models.ForeignKey('auth.User')

search_leagues.html

{% for league in allleagues %}

   {{ league.league_name }}
   {{ league.leaguemember_league.count}}/{{ league.leaguesettings_league.league_number_teams }}
   {{ league.leaguesettings_league.league_eligibility }}
   {{ league.leaguesettings_league.league_lifetime }}
   {% if request.user in league.leaguemember_league.user %}
   DO SOMETHING!!!
   {% else %}
   {% if league.leaguemember_league.count < league.leaguesettings_league.league_number_teams %}
   {% if league.leaguesettings_league.league_eligibility == "Private" %}
   <form method="post" action="{% url 'joinleague' pk=league.id %}">
      Soliticar
   </form>
   {% elif league.leaguesettings_league.league_eligibility == "Public" %}
   <form method="post" action="{% url 'joinleague' pk=league.id %}">
      Entrar
   </form>
   {% endif %}
   {% endif %}
   {% endif %}

{% endfor %}

This error is in this line:
{% if request.user in league.leaguemember_league.user %}

Always goes to ELSE block
Thank you all

A: league.leaguemember_league will not give you a LeagueMember object but a RelatedManager object (so you cannot find a user property in it, therefore your template logic will not work).
What you are trying to do is go two levels deep in your relationship (League -> LeagueMember -> User). You can't easily do this kind of logic in your template and probably need to do it in your view code instead. For example:
league_data = []
for league in League.objects.all():
    league_data.append({
        'league': league,
        'users': User.objects.filter(leaguemember__league=league) # This gives you all the users that are related to this league
    })

 return render(request, 'search_leagues.html', { 'allleagues': league_data})

You then need to modify all your template logic to use this new structure:
{% for league_data in allleagues %}
# Replace league with league_data.league in all the template logic below this

In the if block you can then do:
{% if request.user in league_data.users %}

Note that this querying may not be very efficient if you have a large number of users/leagues - in which case you may need to rethink your model design.


text:
Q: Swift: Recursive Value Type I have a structure in which I want to have a global variable of type Struct?. This example is essentially a briefer version of the structure I am actually creating.
struct SplitString { //splits a string into parts before and after the first "/"

    var preSlash: String = String()
    var postSlash: SplitString? = nil

    init(_ str: String) {
        var arr = Array(str)
        var x = 0
        for ; x < arr.count && arr[x] != "/"; x++ { preSlash.append(arr[x]) }
        if x + 1 < arr.count { //if there is a slash
            var postSlashStr = String()
            for x++; x < arr.count; x++ {
                postSlashStr.append(arr[x])
            }
            postSlash = SplitString(postSlashStr)
        }
    }

}

However, it throws the error:
Recursive value type 'SplitString' is not allowed

Is there any way to get around this? Any help would be great. Thanks :)
Edit:
In case it is relevant, I am programming on iOS, not OSX.
Edit:
If I have:
var split = SplitString("first/second/third")

I would expect split to be:
{preSlash = "first", postSlash = {preSlash = "second", postSlash = {preSlash = "third",
postSlash = nil}}}

A: I imagine this is because an Optional behaves like a value type.
So what you have is a value type of a value type. A value type.
In order to do layout for a value type, you need to know the size of things involved.
So you have (simplified):
sizeof(SplitString) = sizeof(String) + sizeof(SplitString?)

with
sizeof(SplitString?) > sizeof(SplitString)

since you need to store the fact that the value is or is not present (and, no, a pattern of sizeof(SplitString) zeros is not a valid representation for that as it would be for a class type - why? imagine Int? = 0)
So, now you have
sizeof(SplitString?) > sizeof(String) + sizeof(SplitString?)

but all quantities involved are definitely > 0. Rather the absurd, right?

A: TL;DR:
What you are trying to achieve is easily accomplished using split:
for s in split("first/second/third", { c in c == "/" } ) {
    println("\(s)")
}

Discussion:
It seems like you are trying to write a linked list of value types.  The problem is that Swift couples the concepts of copy semantics with value / reference access. (unlike say C++ which allows you to create the same object on the stack or heap).  The solution would seem to be wrapping it in a reference container aka class.
class SplitString { //splits a string into parts before and after the first "/"

    var preSlash: String = String()
    var postSlash: Wrapped? = nil

    init(_ str: String) {
        var arr = Array(str)
        var x = 0
        for ; x < arr.count && arr[x] != "/"; x++ { preSlash.append(arr[x]) }
        if x + 1 < arr.count { //if there is a slash
            var postSlashStr = String()
            for x++; x < arr.count; x++ {
                postSlashStr.append(arr[x])
            }
            postSlash = Wrapped(postSlashStr)
        }
    }

}

class Wrapped {
    var split:SplitString

    init(var _ str:String) {
        split = SplitString(str)
    }
}

Note that this code compiles as a proof of concept but I haven't delved into your algorithm or tested it.
Edit:
In response to your edits above, this code will exercise your code above and yield the splits you want:
for (var s:SplitString? = split; s != nil; s = s?.postSlash?.split) {
    println("\(s!.preSlash)")
}

Obviously having turtles all the way down doesn't make sense, per the discussion above, so you need to break the cycle, as was the case with the class containing your struct.
Note that I have been trying to answer the question that you posted, not the problem that you have.  The solution to the problem that you have, is to use SequenceOf and GeneratorOf to create a sequence wrapped generator that iterates through the slashes and returns the substrings between.  This is actually done for you via the split function:
for s in split("first/second/third", { c in c == "/" } ) {
    println("\(s)")
}


text:
Q: Bit order in python's struct.pack When packing bytes with python's struct.pack, I was surprised that although my byte order is little-endian, my bit order appears to be big-endian. My most significant bytes appear on the right side in the output below, but the most significant bits of each byte appear on the left. (I'm using BitArray from bitstring to display the bits.)
In[23]: BitArray(struct.pack('B', 1)).bin
Out[23]:'00000001'
In[24]: BitArray(struct.pack('H', 1)).bin
Out[24]:'0000000100000000'
In[25]: sys.byteorder
Out[25]:'little'

This surprises me because I read here that "Bit order usually follows the same endianness as the byte order for a given computer system. That is, in a big endian system the most significant bit is stored at the lowest bit address; in a little endian system, the least significant bit is stored at the lowest bit address."
Am I interpreting it correctly that my bit order is the reverse of my byte order here?
Also, I know you can change the byte order using the > and <, but I guess there is no way to change the bit order?
Edit: For context, right now I'm writing a python implementation of TCP communication with an ATI NetFT sensor based on the protocol description starting on page B - 76 here. But, this same question comes up frequently in my work implementing serial and network communications with all sorts of sensors. In this case, the protocol description says things like: set bit 2 of byte 16 to 1 to bias the sensor, and I've been finding that bit 0 in python does not correspond to the bit 0 that controls the bias -- the bit order in the byte seems to be flipped.

A: No, Python supplies no way to reverse the bit order - but you don't need to.  The article made you overly paranoid ;-)
The endianness of byte order is normally invisible to software.  If, e.g., you read a 2-byte short in C, the underlying hardware delivers a big-endian result regardless of the physical storage convention.  Store 258 (0x0102) and you read 258 back, regardless of the storage's physical byte order.  The only way you can tell the difference is to read (or write) part of an N-byte value in a chunk of less than N bytes.  That's common enough in network protocols and portable storage formats, but rare outside those.
Similarly, the only way you could detect the endianness of physical bit order is if the machine were bit-addressable, so you could read one bit at a time directly.  I don't know of any current machine that supports bit addressing, and even if there were such a beast C supports no direct bit-level access anyway.  If you read a byte at time, the hardware will deliver the bytes in big-endian bit order again regardless of the physical bit storage order.
If, e.g., you're poking a bit at a time into a bit-level serial port, then you'll need to know the convention the specific hardware requires.  But in that case struct.pack() is useless anyway - the smallest unit struct.pack() manipulates is a byte, and at that level hardware bit-level ordering is invisible.  For example, your struct.pack('B', 1) will unpack as 1 regardless of the bit-level endianness of the machine you run it on.
Bits of Code
Since "general principles" don't seem to be enough here, and there was no specific code presented to work with, here are bits of code that may be useful.
As mentioned in a comment, if you want to reverse a byte's bit order, the simplest and fastest way is to precompute a list with 256 items, mapping a byte to its bit-reversed value:
br = [int("{:08b}".format(i)[::-1], 2) for i in range(256)]
assert sorted(br) == list(range(256))

Then, e.g.,
>>> br[0], br[1], br[2], br[254], br[255]
(0, 128, 64, 127, 255)

If you're working with bytes objects, the .translate() method can use this table (after converting it to a bytes object) to convert the whole object with one call:
reverse_table = bytes(br)

and then, e.g.,
>>> original = bytes([0, 1, 2, 3, 254, 255])
>>> print([i for i in original.translate(reverse_table)])
[0, 128, 64, 192, 127, 255]

If instead you're building bytes a bit at a time (as in "set bit 2 of byte 16 to 1"), you can build them in "reversed order" (when appropriate) from the start.  To build a byte in LSB 0 order, "setting bit i" means
byte |= 1 << i

To build a byte in MSB 0 order instead, it's
byte |= 1 << (7-i)

But without knowing the precise details of the API(s) you're using, and how you like to work, it's really not possible to guess at the precise code you need.


text:
Q: How do I display the current date and time in a specific format? On the original Sky EPG, the date and time shows on all pages like this:
View Image
I want this to show on my Web EPG, but I'm not sure how to do it. Here's what I've got so far:
function startTime() {
    var today = new Date();
    var day = today.getDay();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    day = checkTime(day);
    document.getElementById('txt').innerHTML =
        h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (day = Monday) { Monday = Mon };
    if (day = Tuesday) { Tuesday = Tue };
    if (day = Wednesday) { Wednesday = Wed };

    if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
    return i;
}

This is how it would show on Monday 3rd October at 12:58 for example: 12:58pm Mon 3 Oct

A: You can use something like that
 const date = new Date()
 var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
 var months = ['Jan', 'Feb','Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']

const myDate = date.getHours()+':'+date.getMinutes()+' pm '+days[date.getDay()]+'    '+date.getDate()+' '+months[date.getMonth()]


text:
Q: XSL count() within a choose element I have a kind of scoreboard and want to calculate the winning team. But unfortunately i cannot count the number of appearances of the id value. Here is the example xml document:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="winner.xsl" ?>
<wm>
    <game>
        <team id='de' />
        <team id='fr' />
        <result>4:2</result>
    </game>
    <game>
        <team id='us' />
        <team id='de' />
        <result>4:2</result>
    </game>
    <game>
        <team id='de' />
        <team id='fr' />
        <result>3:2</result>
    </game>
    <game>
        <team id='de' />
        <team id='fr' />
        <result>1:3</result>
    </game>
</wm>

and the xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template match="wm/game/result">
<xsl:variable name="tore1" select="substring-before(.,':')"/>
<xsl:variable name="tore2" select="substring-after(.,':')"/>

 <xsl:choose>
     <xsl:when test="$tore1 > $tore2">
         <xsl:value-of select="../team[1]/@id"/>

     </xsl:when>
     <xsl:otherwise>
         <xsl:value-of select="../team[2]/@id"/>

     </xsl:otherwise>
 </xsl:choose>

I set the winner of a game by comparing the goals of the result and select the team[1] or team[2]. The output is:
de
us
de
fr

But now I am stuck with the counting of the appearances of the countries. If I set the count() on the XPath expression like
<xsl:value-of select="count(../team[1]/@id)" />

it results in:
1
1
1
1

Also
<xsl:value-of select="count(../team[@id = 'de'])"/>

outside the choose statement did the same output. I would like to have the following output
2 de
1 us
1 fr

Thanks for your help.

A: Counting the number of wins of a known team is easy. Consider the following example:
<xsl:template match="/wm">
    <xsl:variable name="id" select="'de'"/>
    <xsl:variable name="home-wins" select="count(game[team[1]/@id=$id][substring-before(result, ':') > substring-after(result, ':')])"/>
    <xsl:variable name="away-wins" select="count(game[team[2]/@id=$id][substring-after(result, ':') > substring-before(result, ':')])"/>
    <xsl:value-of select="$home-wins + $away-wins"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="$id"/>
</xsl:template>

Result
2 de

A: Thanks. The answer of @michael.hor257k works fine. I tried also to apply the Meunchian grouping. I think I got it. Thanks for your help.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:key name="teamsByID" match="game/team" use="@id"/>

<xsl:template match="wm">

  <xsl:for-each select="game/team[count(. | key('teamsByID', @id)[1]) = 1]">
    <xsl:variable name="id" select="@id"/>
    <xsl:variable name="tore1" select="count(../../game[team[1]/@id=$id][substring-before(result,':') > substring-after(result, ':')])" />
    <xsl:variable name="tore2" select="count(../../game[team[2]/@id=$id][substring-after(result,':') > substring-before(result, ':')])" />
    <xsl:value-of select="$tore1 + $tore2"/>  -  <xsl:value-of select="@id"/>

  </xsl:for-each>

</xsl:template>


text:
Q: Firebase Database issue I want to query to my firabse database which is having data like below image.

I would like to authenticate user on the basis of userEmail and password.
How can I make a query here?

A: you should use firebase authentication. it will handle that for you. You can
also use security rules to give permissions to certain type of accounts only https://firebase.google.com/docs/auth/

A: For handling authentication, you should use FirebaseAuth. Refer docs
For querying data once, you can use this
FirebaseDatabase.getInstance().getReference().child("users")
 .addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // This listens for the data only once and gives it to you in dataSnapshot.
        // Use this code to get the userEmail.
        // String userEmail = String.valueOf(dataSnapshot.child("userEmail"));
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

A: To query according to the userType, then try the following:
FirebaseDatabase.getInstance().getReference().child("users").orderByChild("userType").equalTo("Child").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
 public void onDataChange(DataSnapshot dataSnapshot) {

  String id=dataSnapshot.child("id").getValue().toString();
}
@Override
public void onCancelled(DatabaseError databaseError) {

   }
});

Using the query orderByChild you will be able to retrieve the data related to the result of that query.

A: To solve this, you should definitely implement Firebase Authentication and change your database structure a little bit by adding the uid as unique identifier between users. So your database structure should look like this:
Firebase-root
   |
   --- users
         |
         --- uid
              |
              --- userEmail: "mayank@gmail.com"
              |
              --- userPassword: "123456"
              |
              --- userType: "Child"

If you don't use a database structure like this, you'll end up overriding one user after another. To get the uid, you simply need to use the following line of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

And in the end, to query your database, you should use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("users").orderByChild("userType").equalTo("Child");
query.addListenerForSingleValueEvent(/* ... */);

The result of the query, will be all the children from your database.


text:
Q: Interpreting Aristotle's law of motion $\vec F = R\vec v$
The Aristotle's law of motion, which is incorrect, states that
The velocity of an object $\vec v$ is directly proportional to the force $\vec F$ acting on it
or $\vec F \propto \vec v$
or $\vec F = R\vec v$,
where $R$ is the constant of proportionality which is the resistance to motion.

I want to know how can we interpret this equation $\vec F = R\vec v$  ? Does this equation imply that $\vec F$ and $\vec v$ have the same direction? If it does, then how do we know this through this equation? Does equality mean that they have the same direction?
The book in which I actually saw this equation, wrote this equation in this way:
$$\vec v = \frac {\vec F}{R}. $$

A: The equation implies that if I push on an object with force $\vec F$, it will start moving at velocity $\vec v = \vec F / R$.
You are correct when you say that having vectors on either side of the equal sign means they will be in the same direction. If I push an object away from me, this equation says it will move in the direction I pushed it. It also says that stronger input forces give faster output velocities. If I just give a small push, the object will move not so quickly, but a big push means fast motion. So far it sounds pretty reasonable, right?
There are several ways this equation doesn't accurately describe motion, though. I will take one illustrative example.
Say an object is sitting in front of me (in space, so there isn't any gravity or friction). I give this object a little push and it starts moving. After my push is done, I'm not imparting any more force to the object. What does this equation say should happen, and what really happens?
This equation says that when my hand is in contact and I am pushing the object, it will move with velocity $\vec v$. But as soon as I take my hand away, the force goes to $0$, therefore the object's velocity goes to $0$ as well. That means the object only moves when I push it and immediately stops dead when I am done pushing.
Of course, we know that in reality if I push an object it will continue moving after the push is done. And in my example, in space with no gravity and no friction, the object will continue moving at a constant velocity forever. That's because in the real world, forces don't cause velocities, forces change velocities; no force, no velocity change.

A: Presumably $R$ is intended to be a scalar, and multiplying a vector by a scalar just changes the magnitude of the vector without changing it's direction. So yes, $\vec{F}$ and $\vec{v}$ would have the same direction.
In the real world $R$ might be a tensor, and in that case $\vec{F}$ and $\vec{v}$ are not guaranteed to point in the same direction. This isn't as complicated as it sounds. Suppose you push a railway train at an angle to the direction of the rails. The train will move along the rails, which is a different direction to the one you're pushing in. This is a somewhat contrived example, but you get similar affects in materials that are anisotropic.

A: There is a sense wherein Aristotle was correct (at least in Newtonian physics). Namely, if $\vec{F}_{aristotle}$ is the vector quantity we call impulse that measures the total "shove" you give an object to set it going. It's quite intuitive: the harder you shove a shopping trolley, the swiftlier it runs away from you.
In Newton's terms:
$$\vec{F}_{aristotle} = \int_{t_0}^{t_1} \vec{F}_{newton} \,{\rm d} t = m \vec{v}\qquad(1)$$
and then the quantity $R$ in your equation is what we call the object's inertia or mass: $\vec{F}_{aristotle} = m\,\vec{v}$, where $\vec{v}$ is the vector velocity of a body, which is stationary relative to us to begin with, after we have given it a "shove" $\vec{F}_{aristotle}$.
We don't know exactly what Aristotle had in mind to be the force. Where we know he was wrong was that he said that his concept of the force had to be applied continuously, without letting up, to keep a body moving, but this mistake was not needfuly embodied in his $\vec{F} = R \vec{v}$ law. Newton's insight that corrected Aristotle was to understand that bodies without interaction with the outside World do not change their state of motion.  Aristotle overlooked that, once you get a body going with a "shove", things like air resistance and friction have their own "shove" back and that, with most everyday things we don't often see objects that truly do not interact with the outside World. Once you have this understanding, i.e. the grasping of Newton's first law, then it makes much more sense to define "interaction" as the time rate of change of the acted upon body i.e. it makes sense to focus on acceleration as measuring the instantaneous interaction as opposed to the velocity change which measures the "smeared out" interaction over time. Especially so when you were the one who invented differential calculus and had derived the fundamental theorem of calculus. So Newton simply took the time derivative of the Aristotlean version (1):
$$\vec{F}_{newton} = {\rm d}_t(m\,\vec{v})\qquad(2)$$
I'd argue that Newton's first law is the crucial insight and its negation is what defines interaction; once you gasp this, then the second law becomes really a definition of nett force on a body. As I have argued, the second law is not needfully incompatible with Aristotle's (1) (if indeed he did mean impulse); it is the first law that Aristotle got wrong. See for instance my answer to "Explaining Newton's Laws of motion to a 6 year old".


text:
Q: Android: Draw Canvas on Webview I am using a WebView to display an image that is in my resources, using a WebView because I need it to be zoomable. Dynamically I need to be able to draw points on the image, it is a map. To do this I am trying to put a canvas on top of the loaded image. The canvas would have the points drawn on it.
mWebView = (WebView)findViewById(R.id.webview);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl("file:///android_res/drawable/map.png");

Canvas c = new Canvas();
c.drawARGB(10, 0, 100, 12);//This is just random. It is where I would draw the points
mWebView.draw(c);

The last 3 lines in the code do not appear to do anything.
Is there a better way to go about drawing on top of a WebView? Is it even possible this way?

A: In you last line, you are giving it a new canvas (which will not have map.png loaded).
What you should do is:

*

*Create a new class which extends WebView

*override its onDraw() method, like:
public class MyWebView extends WebView{

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawPoint(yourPoint);
   }
}

Make its variable:
        MyWebView mWebView = new MyWebView(this);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.loadUrl("file:///android_res/drawable/map.png");

add this view to your Main View of your layout.
       myMainView.add(wv);

Done!


text:
Q: Trouble deploying from Eclipse - test and code classes I am new to this community and using eclipse but have gotten the basics down. I am trying to create a button on our lead page to go the next record in the list and have found this post stating how:https://developer.salesforce.com/page/The_Get_Next_Button.
I am now having issues trying to deploy the Apex Code in Eclipse, if I paste all the apex code into a new class and try to run it I get an error saying 'Test methods must be in test class' which I understand(I also tried putting @istest where the tests began and got the same thing if it matters).
So the next thing I tried was to cut all the tests which start at line 83 down to the bottom and also making sure to fix up the }. Put this into a new apex class called 'TestRetrieveNextUtils' and want to deploy this before the actual class, this is when I ran into more errors.
The first error I got was 'unexpected token: Group', I then called one of my friends who knew some code and had used eclipse before. I was told to put in 'public class TestRetrieveNextUtils {' before everything in the test  which worked but new error.
The next error is what caused a lot of confusion for my friend as he isn't familiar with Force.com. The next error was: "Method does not exist or incorrect signature:retrieveNextLead(Id)'. This seems to be that its calling on the method that is in the actual class and not in the test itself but we couldn't keep them in the same class because of the first error we got. He and I couldn't understand why Salesforce have written this code all in one section when you can't actually deploy the code in such a manner in eclipse. If anyone could help or shed some light that would be great thanks. I have attached some pictures of errors and pastebins of the class all as one and just the test.
These are the pastebin files but I cant post more than 2 links which ive used for errors.
/pMLd1Vm4
/4kWGNRHb

A: *

*You need to create the Test in a separate class to the actual code.

*You need to deploy the test class and the code class at the same time. This can be done in eclipse (https://developer.salesforce.com/page/Deploy_Force.com_Applications_Faster), you just need to select the multiple items within the same deploy.

Assuming you are using a sandbox and a production org, I would personally prefer to use change-sets to deploy as it is considered better practice and once you have setup the change-set you can redeploy easily. See here for info on change-sets: https://help.salesforce.com/HTViewHelpDoc?id=changesets_about_outbound.htm&language=en_US


text:
Q: How to fix Jest encountered an unexpected token I configured all my jest with babael, but I can't run the tests, it always shows the same error.
I'm using nextJs and typescript with styled-components.
FAIL  src/components/Main/main.spec.tsx
● Test suite failed to run
Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

C:\teste next\mks-sistemas\public\assets\cartImage.png:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){�PNG

SyntaxError: Invalid or unexpected token

  1 | import React from "react";
  2 | import * as S from "./styles";
> 3 | import iconCart from "../../../public/assets/cartImage.png";
    | ^
  4 | import Image from "next/image";

Snapshots:   0 total
Time:        3.841 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.enter image description here
I already followed several configuration tutorials but none of them worked, I believe that jest should only do the test in the folder that I set but it is getting errors from other pages with svg.

A: Try to set your jest.config like below and install necessary packages
npm i jest-environment-jsdom tsconfig-paths-jest

const nextJest = require('next/jest');
const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
});

// Add any custom config to be passed to Jest
const customJestConfig = {

  setupFilesAfterEnv: ['<rootDir>/setupTests.ts'],

  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  bail: true,
  logHeapUsage: true,
  testTimeout: 120000,
  forceExit: true,
  collectCoverage: true,

  coverageProvider: 'v8',
  collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
  moduleNameMapper,

};

module.exports = createJestConfig(customJestConfig);


text:
Q: TYPO3 auto deleting item from object storage I have TYPO3 version 7.6.18. I have some model video. video has object storage field comments mm relation table. And in BE I can delete comment from general list. I want set auto deleting comment from object storage and from mm table when I delete comment. I hope you understand my problem. Help  me please, I really need it very much and I have not any ideas (

A: Add the @cascade remove to your video model, like it is mentioned here: https://docs.typo3.org/typo3cms/ExtbaseFluidBook/singlehtml/#implementing-relationships-between-domain-objects


text:
Q: Showing the set defined as $\{(x,y) \in \mathbb R^2 : x \text{ not an integer}\}$ is open. I am trying to prove that if $S =  \{ (x,y) \in \mathbb{R}^2 \mid x \notin \mathbb{Z}\}$, then $S$ is open.
My approach was to realize that this can be rewritten as $\{ (x,y) \in \mathbb{R}^2 \mid k < x < k + 1\}$ for all $k$ in he integers.
Let $p \in s$ such that $p = (p_x, p_y)$ and $p_x \notin \mathbb{Z}$. More importantly $p_x$ is in $k < x < k + 1$ for an arbitrary integer $k$.
Define an open ball $B(r, p)$ such that $\{y \in \mathbb{R}^2 : d(y,p) < r\}$.
Now let $q \in B(r,p)$, ie: $d(q,p) < r$.
NEED TO SHOW: $q \in S$.
I proceed by triangle inequality.
$$|q_x - p_x| \leq \|q - p\| \lt r$$
$$-r \lt q_x - p_x \lt r$$
$$-r + p_x \lt q_x \lt r + p_x$$
So I've reached the stage where I need to pick an $r$, but I can't figure out how to determine what $r$ to pick (without just guessing) so I can get rid of the $px$'s and get involved a $k$. Is this even the correct approach? Perhaps, I thought, I should use the fact that I know $k < p_x < k + 1$? But I couldn't figure out how either. I also should be keeping in mind that this new $r$ should be a smaller "value", correct?
In a general situation, what's the best strategy (algebraic or otherwise) for determining your radius $r$?
EDIT: So I used the fact that it looks like $p_x - r = k$ and $p_x + r = k + 1$ but I have no rigorous way of showing this. If I can do this I can simply bring it into my inequality. How can I better show this?

A: Draw a picture of $S$ (actually it is easier to draw its complement, $\mathbb{R}^2 \smallsetminus S$). You should see a bunch of vertical lines, one for each integer. Pick any point $(x,y)$ in $S$. What's the biggest ball centered on this point that you can draw, that is contained in $S$ (i.e. doesn't cross any lines)? What is its radius? (Hint: Label the lines corresponding to $k$ and $k+1$. The radius depends on which line it is closest to.)


text:
Q: XSL-FO tags not supported in Java I'm trying to edit an XSL-FO document to be processed in Java via Apache FOP.   Are there any tags that might not be supported or that have become depreciated?
I didn't write the original XSL-FO.  It was originally a WordML document that I converted via Word2FO, and I've gotten rid of junk characters and made sure all the tags are closed properly, so the only thing I can think of is that some of these tags might not be supported.  Particularly:

*

*Tags with Microsoft-related properites, including fonts like Arial-Word-Unicode, references to Microsoft-Office Smarttags, and other word-related properties

*SVG tags

*External graphics tags with huge streams of nonsense text to represent an image.

I've been looking online for a list of these unsupported tags, but I can't seem to find anything.

A: I have found what I am looking for on this page.
http://xmlgraphics.apache.org/fop/compliance.html
Very useful for looking up what is/isn't supported.
I should really stop finding these solutions after asking these questions.
This question is answered, and the above link will probably help anyone who needs it answered too. Sorry to bother the rest of you.


text:
Q: LiteDB import a csv I don't know how I can import a Csv to LiteDB.
I searched a lot but don't get a solution. I'm using asp.net core 3.1 razor pages to build a one page website and I store my data in LiteDB. Now I have data to import, but I don't know how.

A: Simple way
var json = JsonSerializer.Serialize(new BsonArray(db.Engine.Find("mycol")));

db.Engine.Insert("mycol", JsonSerializer.Deserialize(json).AsArray.ToArray());


text:
Q: Get total count of last seven days for top 5 countries of all time I have a table called events which looks like this:
 id |    date    | country |  event | count
---------------------------------------------
 1  | 2018-03-16 |   RS    | views  | 33577
 2  | 2018-03-21 |   US    | plays  | 232712
 3  | 2018-03-14 |   AR    | clicks | 469159
 4  | 2018-03-18 |   US    | plays  | 415732
 5  | 2018-03-26 |   US    | views  | 442159
 6  | 2018-03-22 |   BA    | plays  | 181610
 7  | 2018-03-21 |   UK    | plays  | 57899
 8  | 2018-03-17 |   CZ    | views  | 64605
 9  | 2018-03-17 |   BA    | plays  | 375444
 10 | 2018-03-22 |   US    | plays  | 148073
 11 | 2018-03-23 |   BA    | views  | 181644
 12 | 2018-03-22 |   CZ    | clicks | 411953
 13 | 2018-03-15 |   AR    | views  | 329597
 14 | 2018-03-18 |   BA    | clicks | 480834
 15 | 2018-03-17 |   CZ    | plays  | 279060
 16 | 2018-03-19 |   MN    | views  | 611975
 17 | 2018-03-26 |   MN    | clicks | 227115
 18 | 2018-03-24 |   BA    | plays  | 176248
 19 | 2018-03-14 |   UK    | views  | 288072
 20 | 2018-03-18 |   UK    | plays  | 598980

I need to get sum of counts of each event for the last seven days of the top 5 countries of all times.
Currently, I have a query that does that:
SELECT
    `c`.`country`,
    `event`,
    SUM(`count`) AS `total`
FROM
    `eem_events` `a`
INNER JOIN(
    SELECT
        `country`
    FROM
        `eem_events` `b`
    GROUP BY
        `country`
    ORDER BY
        SUM(`count`)
    DESC
LIMIT 5
) AS `c`
WHERE
    `date` > DATE_SUB(NOW(), INTERVAL 7 DAY)
GROUP BY
    `c`.`country`,
    `event`

This query returns this:
 country | event  | count
-----------------------------
   AR    | views  | 43084323
   AR    | plays  | 46487773
   AR    | clicks | 44581794
   BA    | views  | 43084323
   BA    | plays  | 46487773
   BA    | clicks | 44581794
   DE    | views  | 43084323
   DE    | plays  | 46487773
   DE    | clicks | 44581794
   MN    | views  | 43084323
   MN    | plays  | 46487773
   MN    | clicks | 44581794
   UK    | views  | 43084323
   UK    | plays  | 46487773
   UK    | clicks | 44581794

What I would like to get is following:
 country |   views   |   plays   |  clicks
-----------------------------------------------
   AR    | 43084323  | 46487773  | 44581794
   BA    | 43084323  | 46487773  | 44581794
   DE    | 43084323  | 46487773  | 44581794
   MN    | 43084323  | 46487773  | 44581794
   UK    | 43084323  | 46487773  | 44581794

I am trying to do this for like 12 hours now and I don't have any more ideas. You can see that for views, plays and clicks there are same values. Could you please help me with refactoring my SQL query to get this result?
I am using MySQL / MariaDB.

A: You only need add conditional SUM()
SELECT
    `c`.`country`,
    SUM(CASE WHEN event = 'views'  THEN `count` ELSE 0 END) AS `views`,
    SUM(CASE WHEN event = 'plays'  THEN `count` ELSE 0 END) AS `plays`,
    SUM(CASE WHEN event = 'clicks' THEN `count` ELSE 0 END) AS `clicks`
FROM
    `eem_events` `a`
INNER JOIN(
    SELECT    `country`
    FROM      `eem_events` `b`
    GROUP BY  `country`
    ORDER BY   SUM(`count`) DESC
    LIMIT 5
) AS `c`
  ON `a`.`country` = `c`.`country`
WHERE
    `date` > DATE_SUB(NOW(), INTERVAL 7 DAY)
GROUP BY
    `c`.`country`


text:
Q: Save byte[] to image with FileOutputStream I send with my Android device a picture to my Java server. I do this with a byte[]. Then I want to store it at my server. But this doesn't work right. The file has the right size, but when I want to open it, windows says: The file can't be opened. What's wrong?
     FileOutputStream fos = new FileOutputStream("./images/"+IDfromPost+".png");
     fos.write(buffer);
     fos.close();

buffer is my byte[], IDfromPost an integer.
By the way. I display the length of the byte array at my phone and the server and both are the same.

A: It's not a problems with Android, you have to check how you decode the byte[] in your server to convert it to a ImageFile.
If you want more help, you have to update the post with the specification of you server.
Regards.


text: Q: Retry on SocketTimeoutException leads to multiple cloud function executions I'm calling a parse cloud function from android. On the cloud code, I receive upto 4 requests and my data is getting corrupt because of this as I'm creating an object in each call to that function. I get a parse exception with error "SocketTimeoutException" only after the function has been executed 4 times on the cloud. Is there any way I can control the retry logic or the timeout duration for parse as I'd like to declare a failure only after 1st failure or increase the timeout duration.


text:
Q: Detect When Soft Keyboard is in Use abd Run a JS Function? I have a site that opens a modal upon click that contains a form. I noticed on my iPad that when the soft keyboard is open it covers several fields of the form, and as I am near the bottom of the screen, I cannot scroll to reveal those hidden fields.
In researching this issue I came across this answer which includes code from this answer. However, neither of these answers seem to work when tested on iOS 8.3.
Here is what I would like to achieve:

*

*Detect when the keyboard is opened.

*Find the height of the keyboard.

*Add padding to the bottom of the footer to accommodate the height of the keyboard.

*When the keyboard is dismissed or closed, the padding is removed.

There are a few things to note:

*

*If someone is using a connected keyboard (including bluetooth keyboards) don't do anything as the soft keyboard shouldn't appear

*jQuery is okay to use.

*A solution must run via client side code.

*I prefer a solution that covers iOS and Android. Preferably, any device that can use a soft keyboard.

How could I achieve a solution that will increase the padding in my footer, that will work on the majority of devices, when someone is using a soft keyboard as a means of filling out a form in a modal?

A: I bumped into a problem similar to this not too long ago and I found a small solution to this, when a mobile or tablet is being used and a keyboard is activated it triggers a resize event of the screen so you could use that to trigger a function.
var lastHeight = $(window).height(); //  store the intial height.
var lastWidth = $(window).width(); //  store the intial width.
var keyboardIsOn = false;

$(window).resize(function () {
    if ($("input").is(":focus")) {
        keyboardIsOn =
           ((lastWidth == $(window).width()) && (lastHeight > $(window).height()));
    }
    if(keyboardIsOn){
        var keyboardHeight = lastHeight - $(window).height();
        $("footer").css("padding", keyboardHeight+"px");
    } else{
        $("footer").removeAttr("style");

        //or if you just want to remove the padding
        //$("footer").css("padding", 0);
    }
});

//An alternative solution is by checking if the height of the screen
//change on input/textarea focus.

$('input, textarea').focus(function() {
     keyboardIsOn =
           ((lastWidth == $(window).width()) && (lastHeight > $(window).height()));
     if(keyboardIsOn){
        var keyboardHeight = lastHeight - $(window).height();
        $("footer").css("padding", keyboardHeight+"px");
    } else{
        $("footer").removeAttr("style");

        //or if you just want to remove the padding
        //$("footer").css("padding", 0);
    }
});


text:
Q: Receiving "NoneType Object is not Callable" error when calling function via .trace() Okay, so I'm trying to put together a really simple app that essentially just takes a scanned barcode value, which is tied to an image file, and goes into a dictionary of images, finds the image whose key matches the barcode value, and displays that image in the Tkinter window.
I actually got it working consistently when just using a raw input() value, but when I tried to incorporate an Entry box into the window to take the barcode value, that's when I ran into problems.
I want the Entry widget to kick off a function whenever it's edited, so that all that needs to be done is scan the barcode and the image will appear. I looked up solutions to this and the most common one I found was to use a StringVar, tie it to the Entry widget, and then use .trace() to kick off the desired function whenever the value in the Entry widget is altered.
The snag is that whenever I scan the barcode into the Entry box, I get the following error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "c:\program files\python37\Lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
TypeError: 'NoneType' object is not callable

This is my full code. I tried to comment out and explain the process as best I could. Naturally, it won't be able to grab the image files and populate the dictionary with them, but hopefully just looking at it, you'll be able to tell me where I went wrong.
from PIL import Image
from PIL import ImageTk as itk
import tkinter as tk
import cv2
import glob
import os, os.path

# INITIALIZE TKINTER WINDOW #
window = tk.Tk()
window.title('Projector Test')
#window.overrideredirect(1)

# Function to kick off whenever Tkinter Entry value is edited. Grabs value of StringVar and assigns it to variable 'barcode'. Checks to see if the barcode
# value is in 'images' dictionary. If so, grab image and display on Tkinter Canvas. If not, display Error message image.
def barcodeScanImage():
  barcode = str(sv.get())

  if barcode in images:
    image_file = images.get(barcode)
    scanImage = itk.PhotoImage(image_file)
    width, height = image_file.size
    canvas.create_image(0, 0, image = scanImage, anchor = tk.NW)

  else:
    image_file = images.get('error.gif')
    errorImage = itk.PhotoImage(image_file)
    width, height = image_file.size
    canvas.create_image(0, 0, image = errorImage, anchor = tk.NW)

# Create Dictionary 'images' to store image files in. #
images = {}

# Iterate through projectorImages folder in directory and store each image found there in the 'images' dictionary, with its Key as its filename. #
for filename in os.listdir('projectorImages\\'):
  image = Image.open(os.path.join('projectorImages\\', filename))
  images[filename] = image

# Create startImage variable. Use .size function to get its width and height, which will be plugged into the tk.Canvas width and height arguments.
# This ensures the displayed image will be displayed in its entirety.
startImage = images.get('start.gif')
width, height = startImage.size
canvas = tk.Canvas(master = window, width = width, height = height)

# Create startImageReady variable reference to the same image file, using the itk.PhotoImage function to convert it into a readable format for Tkinter.
# Then, use canvas.create_image to actually display the image in the Tkinter canvas.
startImageReady = itk.PhotoImage(images.get('start.gif'))
canvas.pack()
canvas.create_image(0, 0, image = startImageReady, anchor = tk.NW)

sv = tk.StringVar()
entry = tk.Entry(master = window, textvariable = sv)
sv.trace("w", callback = barcodeScanImage())
entry.pack()

window.mainloop()

Thanks much for your time. I've been trying to figure out what's causing this issue, but I'm at the end of my beginner's rope! Lol

A: Consider this line of code:
sv.trace("w", callback = barcodeScanImage())

It is functionally identical to this code:
result = barcodeScanImage()
sv.trace("w", callback=result)

Since barcodeScanImage() returns None, it's the same as this:
sv.trace("w", callback=None)

When you call trace, you must give it a reference to a function (note the missing ()):
sv.trace("w", callback=barcodeScanImage)

However, when you set up a trace, tkinter will pass some additional arguments to the function which you need to be prepared to accept. Since you're not using them, you can just ignore them:
def barcodeScanImage(*args):
   ...

For more information on the arguments that are passed in, see this question: What are the arguments to Tkinter variable trace method callbacks?


text:
Q: I want to make a graphic in python from csv documents,but it can only show one pair numbers, how can i make it complete? import os
from matplotlib import pyplot as pyplot
from collections import defaultdict
import numpy as np
import csv
path = r'C:/Users/AK6PRAKT'
dirs = os.listdir(path)
s = []
for i in dirs:
    if os.path.splitext(i)[1] == ".csv":
        f = open(path+"/"+i)
        iter_f = iter(f);
        str = ""
        for line in iter_f:
              str = str + line
        s.append(str)
        with open(path+"/"+i,'r') as r:
            lines=r.readlines()
        with open(path+"/"+i,'w') as w:
            for row in lines:
                if 'Date' not in row:
                    w.write(row)
        from collections import defaultdict
        columns = defaultdict(list)
        import csv
        with open(path+"/"+i) as f:
            reader = csv.reader(f)
            for row in reader:
                for (i,v) in enumerate(row):
                    columns[i].append(v)
        print(columns[0],columns[1])
fig = pyplot.figure()
ax1 = fig.add_subplot(1,1,1)
pyplot.plot(columns[0],columns[1])
pyplot.show()

actually i there are over 40000 csv files in my computer and first of all, i select 2 series of numbers in the specific positions, one is about the time and the other one is about the battery condition, then I want to make a graphic about the 2 series, one as x-axis and one as y-axis.but the result shows only the last pair of the series, but I want to see the complete graphic in python.

A: you seem to be doing a lot of unnecessary work…  as far as I can tell, the important bits are just:
from glob import glob
import csv

c1 = []
c2 = []

for path in glob('C:/Users/AK6PRAKT/**/*.csv', recursive=True):
  with open(path) as fd:
    rows = csv.reader(fd)
    # ignore header (I presume this is what your "'Date' not in row" is about)
    next(rows)
    for cols in rows:
      c1.append(cols[0])
      c2.append(cols[1])


text:
Q: What does $\bigotimes$ and $X^*$ mean? Can someone explain / link me to a linear algebra worked problem where I can see how these work. I've searched and given their statistics and matrix specialty uses, can't find any ready examples.

A: $\bigotimes$ is the Kronecker product of two matrices. In this post I used the Kronecker product to understand the model matrices in mixed effects models.
$A^* = A^H = \bar A^T$ is the Hermitian or conjugate transpose of a matrix $A$.
A good example of the use of Hermitian matrices is in obtaining the inverse of a Fourier matrix in the Fast Fourier Transform (FFT). For an $n \times n$ Fourier matrix, $F_n$, the inverse is going to be the Hermitian conjugate, such that $\frac{1}{n}\,F_n^H\,F_n = I.$
For example, a $4\times4$ Fourier matrix ($n=4$) would be:
$$\large \begin{bmatrix}
1 & 1 & 1 & 1\\
1 & W & W^2 & W^3\\
1 & W^2 & W^4 & W^6 \\
1 & W^3 & W^6 & W^9
\end{bmatrix} =
\begin{bmatrix}
1 & 1 & 1 & 1 \\
1 & e^{i\,\frac{2\pi}{4}} & e^{i\,2\frac{2\pi}{4}} & e^{i\,3\frac{2\pi}{4}}\\
1 & e^{i\,2\frac{2\pi}{4}} & e^{i\,4\frac{2\pi}{4}} & e^{i\,6\frac{2\pi}{4}} \\
1 & e^{i\,3\frac{2\pi}{4}} & e^{i\,6\frac{2\pi}{4}} & e^{i\,9\frac{2\pi}{4}}
\end{bmatrix}=
\begin{bmatrix}
1 & 1 & 1 & 1 \\
1 & i & -1 & -i\\
1 & -1 & 1 & -1 \\
1 & -i & -1 & i
\end{bmatrix}
$$
And the Hermitian of this matrix:
$$F_4=\begin{bmatrix}
1 & 1 & 1 & 1 \\
1 & i & -1 & -i\\
1 & -1 & 1 & -1 \\
1 & -i & -1 & i
\end{bmatrix}\implies F_4^H =
\begin{bmatrix}
1 & 1 & 1 & 1 \\
1 & -i & -1 & i\\
1 & -1 & 1 & -1 \\
1 & i & -1 & -i
\end{bmatrix}
$$


text:
Q: how to get the image which is taken from mysql as backround in body?
Possible Duplicate:
How to display a repeated image stored in database on background as on Twitter?

I want to display an image on background (by using CSS repeat thing) the same way as on twitter but the problem is that i am retrieving it from a MySql database and CSS cannot handle src tag on background i have usedfollowing code and links
body{
    background:url(<?php $lastid=$_SESSION['lastid']; echo "get_test.php?id=$lastid";?>)     repeat;

   }

http://www.webdeveloper.com/forum/showthread.php?210964-Set-CSS-Background-Image-with-PHP
http://net.tutsplus.com/tutorials/php/supercharge-your-css-with-php-under-the-hood/
my whole code on the main site
<html>
<head>
<?php
$temp = tmpfile();
?>
<style>
  body{
    background:url(<?php $lastid=$_SESSION['lastid']; echo "get_test.php?id=$lastid"; ?>) repeat;

   }

</style>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
File:<br>
<input type="file" name="image">

<input type="submit" name="submit" value="Upload">

</form>

<?php

mysql_connect("host", "nam", "database") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

$file= $_FILES['image']['tmp_name'];

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = addslashes(getimagesize($_FILES['image']['tmp_name']));

if($image_size==FALSE)
{
echo "thats not an image";
}

else
{

mysql_query("INSERT INTO image_store VALUES ('','$image_name','$image')") or die(mysql_error());
 $lastid=mysql_insert_id();

$_SESSION['lastid']=$lastid;
 echo "the image is"."<image src=get_test.php?id=$lastid>";

}

?>
</body>

and the code on get_test.php is
<?php
mysql_connect("host", "nam", "database") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

$id = addslashes($_REQUEST['id']);

$image=mysql_query("SELECT * FROM image_store WHERE id=$id ");
$image = mysql_fetch_assoc($image);
$image = $image['image'];

header("Content-Type: image/jpeg");
echo $image;

?>

A: To answer this:
1: Add a space after the last semi-colon. This has caused issues with people before.
2: To stop the background from repeating, use the background-repeat property, and set it to no-repeat, like this:
background-repeat: no-repeat;

A: In order to set/use a $_SESSION variable (ie $_SESSION['lastid'], you need to start a session on each page-
<?php
session_start();
?>
<html>
<head>
<?php
$temp = tmpfile();
?>
<style>
  body{
    background:url(<?php $lastid=$_SESSION['lastid']; echo "get_test.php?id=$lastid"; ?>) repeat;
   }
</style>
</head>
<body>
...
</body>


text:
Q: The CDO message is not sent and the message's attached file is not free to delete I am trying to send a message with attachment using CDO object. When the SMTP Server is available and all the information is correct, the message is correctly sent with the attachment.
However, if the SMTP Server is incorrect the message is not sent (as expected), but it seems to be "stuck" somewhere. I am using:
Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2

I've searched over the Internet, and found that this option would give a 60 second timeout. But the file I attached to the message is never available.
The test that I've done is to send a message with an attached file and using an invalid SMTP Server. Then, I wait for a few minutes and try to delete the file I had attached. However, when I try do it, I have a permission problem. When I kill the sending email program, I am able to delete the file.
I want to know how to configure the timeout to make sure it gives up sending the message, how I "detach" the file when the message is not sent and how to make the program wait for the message to be sent (I want to send the message and then erase the attached file from the computer. So I need to know when the message was really sent or when it was timedout).

A: CDO is hopelessly obsolete, you really need to consider switching to System.Net.Mail.  The specific problem sounds like a file locking issue.  Quacks like a bug in CDO, it would open the attachment to compose the email message but forgets to close the file when the SMTP server balks.
This bug is probably exacerbated by the way .NET deals with COM servers, like CDO.  The COM object doesn't get released until the garbage collector runs.  Which can take a while, especially when your program doesn't do anything significant after trying to send the email.  A workaround for that is calling Marshal.ReleaseComObject() on the CDO object.  Tends to not work when you have other CDO interface references in your program, those references tend to be hidden.  GC.Collect() + GC.WaitForPendingFinalizers() is the big hammer, after you nulled any object reference.
But, really, use System.Net.Mail.


text:
Q: Cellular Automata Neighborhood as Node connections Can I use the CellularAutomation[] function where the neighborhood is defined by the connections between nodes?
For example, if 1 -> 2, 1 -> 3, 1 -> 8, 1 ->1, then the neighborhood of node 1 is the nodes 2,3,8,1.
Here is what I have to start with:
Manipulate[
nodes = Sort@Flatten@Table[Range@n, {k}];
rand = RandomInteger[{1, n}, n*k];
rules = MapThread[Rule, {nodes, rand}];
colors = RandomInteger[{0, 1}, n] /. {0 -> Black, 1 -> Red};
GraphPlot3D[rules,
 VertexRenderingFunction -> ({colors[[#2]], EdgeForm[Black],
 Sphere[#, .1], If[colors[[#2]] === Black, Yellow, White],
 Style[Text[#2, #1], FontWeight -> Bold, FontSize -> 12]} &)],
 {n, 1, 20, 1}, {k, 1, 8, 1}, {step, 0, 100, 1}]

A: No, the CelluluarAutomaton command works is specifically designed to model cellular automata on grids.  It's certainly feasible to roll your own, though.
Your example using GraphPlot3D
I generated the following graph using your code.
rules = {1 -> 5, 1 -> 1, 1 -> 8, 1 -> 6, 1 -> 2, 2 -> 5, 2 -> 2,
  2 -> 7, 2 -> 7, 2 -> 5, 3 -> 7, 3 -> 8, 3 -> 2, 3 -> 1, 3 -> 4,
  4 -> 3, 4 -> 5, 4 -> 3, 4 -> 2, 4 -> 8, 5 -> 4, 5 -> 2, 5 -> 3,
  5 -> 4, 5 -> 1, 6 -> 5, 6 -> 1, 6 -> 8, 6 -> 3, 6 -> 7, 7 -> 7,
  7 -> 6, 7 -> 8, 7 -> 2, 7 -> 3, 8 -> 2, 8 -> 5, 8 -> 2, 8 -> 2,
  8 -> 5};
GraphPlot3D[rules, VertexRenderingFunction -> ({Sphere[#, .1],
  Style[Text[#2, #1], FontWeight -> Bold, FontSize -> 12]} &)]

Now, let's set up an initial state from which to evolve.  Note that I store the state (either 1 or 2) of vertex v at time 0 in value[0,v].
Clear[value];
SeedRandom[1];
n = Max[Sequence @@@ rules];
Do[value[0, v] = RandomChoice[Range[2]], {v, 1, n}];
color[1] = Yellow;
color[2] = Lighter@Red;
GraphPlot3D[rules,
  VertexRenderingFunction -> ({{color[value[0, #2]], Sphere[#, .1]},
  Style[Text[#2, #1], FontWeight -> Bold, FontSize -> 12]} &)]

Now, I'll write a function step that accepts a vertex u, computes the new value, and stores that value in value[gen,u], where gen is global variable indicating our generation number.  Specifically, we simply sum the values of all the adjacent vertices and set the new value to 1, if the sum is even, and set the new value to 2, if the sum is odd.
Clear[adjacentVertices]
adjacentVertices[v_] := adjacentVertices[v] = Last /@ Select[rules, First[#] == v &]
adjacentVertices /@ Range[n];
step[u_] := value[gen, u] =
   Mod[Total[Table[value[gen - 1, v], {v, adjacentVertices[u]}]], 2, 1];

Note that adjacentVertices[v] takes direction and multiplicity into account and allows for self-loops.  For example, adjacentVertices[2] contains 7 twice, as well as 2 itself, while adjacentVertices[7] contains 2 only once.
Let's do it!
gen = 0;
Do[
  gen = gen + 1;
  step /@ Range[n],
 {100}]

And visualize:
ListAnimate[Table[
  GraphPlot3D[rules,
    VertexRenderingFunction -> ({{color[value[k, #2]], Sphere[#, .1]},
      Style[Text[#2, #1], FontWeight -> Bold, FontSize -> 12]} &)],
  {k, 0, 100}]]

Another example
I'm honestly not sure how neat that example is, so here's another one that I rather like.  Note that there is nothing about running a CA on a graph that is intrinsically three dimensional, apart from the visualization.  For this example, I'll use the newer Graph object, rather than the GraphPlot3D function.  So, here's a pretty fun graph:
allEdges = UndirectedEdge @@@ {
      {1, 2}, {1, 15}, {1, 30}, {1, 33}, {1, 43}, {2, 37}, {2, 30},
      {3, 18}, {3, 13}, {3, 41}, {3, 35}, {3, 40}, {4, 20}, {4, 22},
      {4, 26}, {4, 6}, {5, 19}, {5, 36}, {5, 12}, {5, 48}, {6, 38},
      {6, 46}, {6, 22}, {6, 26}, {7, 22}, {7, 25}, {7, 35}, {7, 41},
      {7, 46}, {8, 15}, {8, 29}, {8, 10}, {8, 11}, {9, 16}, {9, 31},
      {9, 34}, {9, 39}, {9, 44}, {10, 15}, {10, 21}, {10, 29}, {10, 12},
      {10, 48}, {11, 14}, {11, 15}, {11, 29}, {11, 33}, {11, 42},
      {12, 21}, {12, 27}, {12, 36}, {12, 48}, {13, 18}, {13, 28},
      {13, 41}, {14, 23}, {14, 28}, {14, 29}, {14, 41}, {14, 42},
      {15, 33}, {15, 43}, {15, 48}, {16, 34}, {16, 39}, {17, 25},
      {17, 32}, {17, 38}, {19, 30}, {19, 37}, {19, 43}, {19, 45},
      {19, 48}, {20, 22}, {20, 29}, {20, 21}, {20, 47}, {21, 27},
      {21, 29}, {21, 47}, {22, 29}, {22, 41}, {22, 46}, {23, 28},
      {23, 42}, {24, 31}, {25, 38}, {25, 46}, {26, 47}, {26, 27},
      {27, 36}, {27, 47}, {28, 41}, {29, 41}, {30, 37}, {30, 43},
      {31, 44}, {32, 34}, {32, 38}, {33, 42}, {33, 43}, {34, 44},
      {34, 38}, {34, 39}, {35, 40}, {35, 41}, {37, 45}, {38, 46},
      {43, 48}
  };
coords = {
  {-111.67, 34.33}, {-119.65, 37.28}, {-83.46, 32.66}, {-86.29, 39.91},
  {-109.65, 47.04}, {-82.79, 40.28}, {-78.92, 37.51}, {-98.37, 38.49},
  {-71.79, 42.25}, {-99.81, 41.53}, {-97.51, 35.59}, {-100.23, 44.43},
  {-86.83, 32.78}, {-92.44, 34.90}, {-105.55, 39.00}, {-72.70, 41.60},
  {-75.50, 38.96}, {-82.52, 28.66}, {-114.66, 44.40}, {-89.20, 40.07},
  {-93.49, 42.08}, {-85.28, 37.53}, {-92.00, 31.05}, {-69.26, 45.36},
  {-76.77, 39.02}, {-84.62, 43.46}, {-94.29, 46.32}, {-89.67, 32.74},
  {-92.47, 38.37}, {-116.66, 39.34}, {-71.59, 43.67}, {-74.68, 40.19},
  {-106.10, 34.43}, {-75.53, 42.96}, {-79.38, 35.53}, {-100.47, 47.44},
  {-120.57, 43.93}, {-77.80, 40.88}, {-71.59, 41.67}, {-80.90, 33.91},
  {-86.35, 35.85}, {-99.37, 31.48}, {-111.68, 39.32}, {-72.67, 44.07},
  {-120.42, 47.38}, {-80.60, 38.63}, {-90.02, 44.63}, {-107.55, 43.00}
};
G = Graph[Range[48], allEdges, VertexCoordinates -> coords,
  VertexSize -> 1]

This happens to be a fairly well known planar graph, although this particular embedding does have some edge crossings.  It should nonetheless be four-colorable, i.e. we can color the vertices in such a way that no two adjacent vertices share the same color.  Let's see if we can color it with a stochastic cellular automaton.  We'll start with a random coloring.
Clear[value];
SeedRandom[3];
Do[value[0, i] = RandomChoice[Range[4]], {i, 1, 48}];
color[1] = Red;
color[2] = Blue;
color[3] = Yellow;
color[4] = Green;
SetProperty[G,
 VertexStyle -> Table[i -> color[value[0, i]], {i, 1, 48}]]

The following step function implements the CA rules, which essentially say that, if the color of a vertex is different from all of it's neighbors, then leave it the same, otherwise change it with some randomness thrown in.  As a result, a four-coloring is a  fixed point.  The hope is that this fixed state might be attractive.
step[v_] :=
  Module[{neighbors, done, vxCoord, rightNeighbors, rightValues,leftValues},
   neighbors = AdjacencyList[G, v];
   Which[
    (* Case 1: all adjacent vertices are different colors - stay fixed *)
    Intersection[{value[gen - 1, v]},
      value[gen - 1, #] & /@ neighbors] == {},
    done = True;
    value[gen, v] = value[gen - 1, v],
    done = False;
    (* Case 2: There's a conflict to the right - try to avoid *)
    vxCoord = coords[[v, 1]];
    rightNeighbors = Select[neighbors, coords[[#, 1]] > vxCoord &];
    rightValues = value[gen - 1, #] & /@ rightNeighbors;
    Intersection[{value[gen - 1, v]}, rightValues] =!= {},
    If[RandomReal[] < 0.9,
     value[gen, v] = RandomChoice[{1, 2, 3, 4}],
     value[gen, v] = value[gen - 1, v]
     ],
    (* Case 3: There's a conflict to the left - try to avoid *)
    leftValues = value[gen - 1, #] & /@
      Complement[neighbors, rightNeighbors];
    Intersection[{value[gen - 1, v]}, leftValues] =!= {},
    If[RandomReal[] < 0.1,
     value[gen, v] = RandomChoice[{1, 2, 3, 4}],
     value[gen, v] = value[gen - 1, v]
     ]
    ];
   done
   ];

Now, let's run it and animate:
cnt = 0;
gen = 1;
While[cnt++ < 2500 && Count[step /@ Range[48], True] < 48,
  gen = gen + 1]
pics = Table[SetProperty[G,
  VertexStyle -> Table[i -> color[value[k, i]], {i, 1, 48}]],
 {k, 0, cnt}];
ListAnimate[pics]


text:
Q: "couldn't recognize data in image file ..." Why do I (sometimes) get this Error-message? I wanted to implement some images in my Python-Tkinter application. I used the PhotoImage instance of Tkinter for this. It all worked perfectly whith the first picture: "RR.gif, a GIF image made with MS Paint. The second image: "Tank.gif", unfortunately caused some troubles. This picture was made (also in MS Paint) immediately after the first one and was also stored in GIF format. The images are located in the same folder so I assume the path is correct for both of them. However, the second label, (which contains the second image) gives the following error:
_tkinter.TclError: couldn't recognize data in image file "Tank.gif"

Which I think is strange since both images files are very similar. Does anyone know why I am getting this error? and how to solve it?
This is the simplest code in which the problem occurs.
from Tkinter import *

root = Tk()

icon = PhotoImage(file="RR.gif")
tank = PhotoImage(file="Tank.gif")
label_ico = Label(root, image=icon)
label_tan = Label(root, image=tank)
label_ico.pack()
label_tan.pack()

root.mainloop()


text:
Q: Watson Assistant Upload file I have built a Chatbot using Watson Assistant, and I am looking for a way to enable the user to upload a pdf or an image in the chat, like using an Upload File button, or a Drag and drop or files here functionality.

A: Watson Assistant on IBM Cloud is a conversation service that can interact with other components of a solution. Depending on the type of Watson Assistant integration, uploading a file is possible, or not. You might want to check out custom integrations which would allow you to build such file uploading feature around the chatbot capability.
Note that the chatbot API is designed for driving dialogs by exchanging messages. The file upload would be on top.

A: File upload will be an additional feature of functionality that you will have to have in the custom UI and integrate it with the Orchestration/Integration Layer and then do whatever you want to do with that file and then send the required information from the file to Watson Assistant in a context variable.


text:
Q: getting arraylist size as ZERO while getting data from server? I am trying to show data on daynamic list view. I get data from server database. but the problem in my code is task_kist is a string type arraylist. As I execute
new TaskList().execute();

before
Log.i("Total size", String.valueOf(task_list.size()));

this line execute before "new TaskList().execute();" . In class TaskList the size or task_list is 11 but when i check total size as mentioned above, it is 0. Can anyone please suggest me the solution that why size of task_list is zero while I added some values in it.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tasklist);

     Bundle bundle = getIntent().getExtras();
        username = bundle.getString("username");

        Log.i("username from login", username);

        registerButtons();

        new TaskList().execute();
        Log.i("Totalllllll size", String.valueOf(task_list.size()));

        String str[] = new String[5];

        for(int i =0; i<5;i++) {
            str[i]=String.valueOf(task_list.size());
        }

        ArrayAdapter<String> ap = new ArrayAdapter<String>(this,android.R.layout.test_list_item,str);
        lv.setAdapter(ap);

        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {

                Toast.makeText(AllTask.this, "You have Selected : "+((TextView)arg1).getText(), Toast.LENGTH_SHORT).show();
            }
        });

  }
 /**
 * Background Async Task to Create new product
 * */
class TaskList extends AsyncTask<String, String, String> {

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));

        // getting JSON Object
        // Note that create product url accepts POST method
        json = jsonParser.makeHttpRequest(url_get_tasklist,
                "GET", params);

        // check log cat fro response
        Log.i("Create Response", json.toString());

        // check for success tag
        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                tasks = json.getJSONArray(TAG_NAME);

                // looping through All members
                for (int i = 0; i < tasks.length(); i++) {

                    JSONObject c = tasks.getJSONObject(i);

                    // Storing each json item in variable
                    tasklist = c.getString(TAG_TASKLIST);

                    task_list.add(tasklist);
                    Log.i("size", String.valueOf(task_list.size()));
                    Log.i("array", task_list.get(i));

                }

            } else {

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

}

A: This is because you are getting size in async task which run in background thread.And before completing the async task your log print value as 0
So track log in doInBackground for loop as
// looping through All members
                for (int i = 0; i < tasks.length(); i++) {
//your code
}
Log.i("Total size", String.valueOf(task_list.size()));  // track log here

Edit
Also you may track log onPostExecute in method as
@Override
        protected void onPostExecute(String result) {
            Log.i("Total size", String.valueOf(task_list.size()));  // track log here
}


text:
Q: (Retention) How to divide all values by value in first row across different categories of users in SQL? I have the following table:

Day
Category
Count

D1
A
10

D1
B
20

D2
A
8

D2
B
10

D3
A
6

D3
B
5

I'm trying to create a percentage column by dividing the values in the third column (Count) by the value for D1 across all categories in the second column (Category; in this case 10 and 20 for A and B respectively). This should output something like:

Day
Category
Count
Pct

D1
A
10
100%

D1
B
20
100%

D2
A
8
80%

D2
B
10
50%

D3
A
6
60%

D3
B
5
25%

The furthest I got is the code below, but I can't figure out how to do the division by category.
    SELECT
        day,
        category,
        count,
        count/(SELECT count FROM table WHERE day = 'D1')*100 AS pct
    FROM
        table
    ORDER BY 1
)

A: This is the same as Asgar's query but with the unnecessary table derivation removed -
SELECT
    `t1`.*,
    ROUND((`t1`.`count` / `t2`.`count`) * 100) `pct`
FROM `table` `t1`
JOIN `table` `t2`
    ON `t1`.`category` = `t2`.`category`
    AND `t2`.`day` = 'D1'
ORDER BY 1, 2;

A: this should do what you ask:
SELECT
        day,
        category,
        count,
        count/(SELECT count
                 FROM table as sub
                   WHERE day = 'D1'
                   AND sub.category = main.category)*100 AS pct
    FROM
        table as main

I assumed that the denominator will always just be based on "D1", and that combinations of day-category will always be unique.

A: This should word accurately for you:
SELECT
main.*,
ROUND(((main.Count/d2.Count)*100),2)
FROM
(SELECT *   FROM day_table d1) main
  JOIN day_table d2 ON d2.Category=main.Category AND d2.Day='D1'
  ORDER BY
  main.Day,
  main.Category


text:
Q: Avoid JOptionPane interference with action listeners I have noticed that all JOptionPane method "interfere" with ActionListeners.
I need ActionListener to remain active after a JOptionPane has been opened.
For example:
I have a JButton, I register the mouse being pressed and draw the button red. Upon being released, I draw it blue.

*

*If I just click it, the button will turn blue. Ok

*If I hold it clicked, the button will stay red. Ok

*If I click it and set it to open a JOptionPane dialog, it stays red, even though I have released the mouse. Not Ok
I haven't been able to find any documentation on this specific behaviour, can someone point me in the right direction?
I do really need to use JOptionPane.

A: One option -- queue the call to open the JOptionPane on the Swing event queue.  This will delay the opening of the modal JOptionPane just a little bit, allowing other button actions to be performed.
Another option is to extract the JDialog from the JOptionPane, and call it in a non-modal way.
For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TestOptionPane extends JPanel {
    private static final Color FOREGROUND = Color.RED;
    private static final Color PRESSED_FG = Color.BLUE;
    private JButton button1 = new JButton(new Button1Action());
    private JButton button2 = new JButton(new Button1Action());

    public TestOptionPane() {
        setPreferredSize(new Dimension(600, 450));
        button1.getModel().addChangeListener(new ButtonModelListener(button1));
        button1.setForeground(FOREGROUND);
        add(button1);
        button2.getModel().addChangeListener(new ButtonModelListener(button2));
        button2.setForeground(FOREGROUND);
        add(button2);
    }

    private class Button1Action extends AbstractAction {
        public Button1Action() {
            super("Queue JOptionPane on Swing event thread");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(TestOptionPane.this, "hello");
            });
        }
    }

    private class Button2Action extends AbstractAction {
        public Button2Action() {
            super("Show non-modal JOptionPane");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(() -> {
                Component parentComponent = TestOptionPane.this;
                JOptionPane optionPane = new JOptionPane("Hello", JOptionPane.PLAIN_MESSAGE);
                JDialog dialog = optionPane.createDialog(parentComponent, "Fubars Rule!");
                dialog.setModalityType(ModalityType.MODELESS);
                dialog.setLocationRelativeTo(parentComponent);
                dialog.setVisible(true);
            });
        }
    }

    private class ButtonModelListener implements ChangeListener {
        private JButton button;

        public ButtonModelListener(JButton button) {
            this.button = button;
        }

        @Override
        public void stateChanged(ChangeEvent e) {
            ButtonModel model = (ButtonModel) e.getSource();
            if (model.isPressed()) {
                button.setForeground(PRESSED_FG);
            } else {
                button.setForeground(FOREGROUND);
            }
        }

    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("TestOptionPane");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new TestOptionPane());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}


text:
Q: ¿Por qué un clasificador de red neural para problemas de clases múltiples clasifica sólo en una clase cuando un árbol de decisión es más preciso? Quiero crear un clasificador para un marco de datos que tiene cuatro clases. Tengo dos modelos predictivos: una red neuronal y un clasificador de árbol. Pero ponen a todos en una clase, durante el entrenamiento y por lo tanto durante las pruebas.
Red neuronal clasifica en una clase
El problema es que la clasificación de mi red neuronal es:

Llamo a la modelo aquí:
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.models import load_model

model = create_model(x_train.shape[1], y_train.shape[1])
epochs =  30
batch_sz = 64

print("Beginning model training with batch size {} and {} epochs".format(batch_sz, epochs))

checkpoint = ModelCheckpoint("lc_model.h5", monitor='val_acc', verbose=0, save_best_only=True, mode='auto', period=1)

# train the model
history = model.fit(x_train.to_numpy(),
                y_train.to_numpy(),
                validation_split=0.2,
                epochs=epochs,
                batch_size=batch_sz,
                verbose=2,
#                 class_weight = weights, # class_weight tells the model to "pay more attention" to samples from an under-represented grade class.
#                 callbacks=[checkpoint]
                   )

# revert to the best model encountered during training
model = load_model("lc_model.h5", compile=False)

Aquí está la arquitectura del modelo:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.constraints import MaxNorm
# from tensorflow.python.compiler.tensorrt import trt_convert as trt

def create_model(input_dim, output_dim):
    print(output_dim)
    # create model
    model = Sequential()
    print("sequential")
    # input layer
    model.add(Dense(100, input_dim=input_dim, activation='relu', kernel_constraint=MaxNorm(3)))
    model.add(Dropout(0.2))

    # hidden layer
    model.add(Dense(60, activation='relu', kernel_constraint=MaxNorm(3)))
    model.add(Dropout(0.2))

    # output layer
    model.add(Dense(output_dim, activation='softmax'))

    # Compile model
    model.compile(loss=focal_loss(alpha=1), loss_weights=None, optimizer='nadam', metrics=['accuracy'])

    return model

Aquí hay una parte de x_train.
id reg  0.0_x   1.0_x   17.0    21.0    30.0    40.0    50.0    60.0    70.0    Célibataire     Divorcé(e)  Marié et j'ai des enfants à charge  Marié et je n'ai pas encore d'enfants à charge  Refus de répondre   Veuf (ve)   1er cycle universitaire / Licence   2e cycle universtaire / Master  3e cycle universtaire / Doctorat    BTS     Je n'ai jamais été à l'école    Niveau collège  Niveau lycée    Niveau primaire     Autre. Merci de préciser :@NS$  Infirme     J'ai une société    Je ne travaille pas     Je suis commerçant  Je suis encore étudiant     Je suis independent     Je suis journalier, je travaille de temps à autre   Je suis retraité    Je travaille dans le secteur privé  Je travaille dans le secteur public     0.0_y   250.0   3750.0  7500.0  8750.0  11250.0     11500.0     18750.0     25000.0     35000.0     45000.0     50000.0     0.0_x.1     1.0_y   0.0_y.1     1.0_x.1     Je ne suis pas d'accord     Je suis d'accord    False_x     True_y  False_y     True_x  False_x.1   True_y.1    False_y.1   True_x.1    False_x.2   True_y.2    False_y.2   True_x.2    False_x.3   True_y.3    False_y.3   True_x.3    False_x.4   True_y.4    False_y.4   True_x.4    False_x.5   True_y.5    False_y.5   True_x.5    0.0_x.2     1.0_y.1     0.0_y.2     1.0_x.2     0.0_x.3     1.0_y.2     0.0_y.3     1.0
0   NaN     0   1   0   0   1   0   0   0   0   1   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0   1   0   0   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0   0   1   0   1   0   0   1   0   1   0   1   1   0   1   0   0   1   1   0   1   0   1   0   1   0   1   0   1   0   1   0   0   1   1   0   0   1   0   1
1   NaN     0   1   0   0   1   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0   0   1   0   0   0   0   0   0   0   1   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0   0   0   1   1   0   1   0   0   1   1   0   1   0   1   0   0   1   1   0   1   0   1   0   1   0   0   1   1   0   1   0   1   0   1   0   1   0   0   0
...

Y aquí está parte de y_train:
   Voting intention in 2021_Cast a blank vote   Voting intention in 2021_I know who I will be voting for in 2021    Voting intention in 2021_I won't vote   Voting intention in 2021_I'm going to vote in 2021 but don't know for who
0                0                                  1                                                                       0                                                                       0
1                0                                  0                                                                       0                                                                       1
...

Así que cuando intento probar este modelo no es mejor que el azar:
sequential
Beginning model training with batch size 64 and 30 epochs
WARNING:tensorflow:`period` argument is deprecated. Please use `save_freq` to specify the frequency in number of samples seen.
Train on 768 samples, validate on 192 samples
Epoch 1/30
768/768 - 1s - loss: -inf - acc: 0.2448 - val_loss: -inf - val_acc: 0.2708
Epoch 2/30
768/768 - 0s - loss: -inf - acc: 0.2409 - val_loss: -inf - val_acc: 0.2708
...
Epoch 30/30
768/768 - 0s - loss: -inf - acc: 0.2409 - val_loss: -inf - val_acc: 0.2708

De hecho, la precisión está justo por debajo del 25%, que es un resultado que habría esperado de la selección aleatoria de las clases. Y parece que nunca se aprende nada ya que la pérdida es siempre "-inf".
Así que calculo la precisión del modelo en el equipo de pruebas y es aún peor. De hecho, con el siguiente código:
import numpy as np
from sklearn.metrics import f1_score

y_pred = model.predict(x_test.to_numpy())

# Revert one-hot encoding to classes
y_pred_classes = pd.DataFrame((y_pred.argmax(1)[:,None] == np.arange(y_pred.shape[1])),
                              columns=y_test.columns,
                              index=y_test.index)

y_test_vals = y_test.idxmax(1)
y_pred_vals = y_pred_classes.idxmax(1)

# F1 score
# Use idxmax() to convert back from one-hot encoding
f1 = f1_score(y_test_vals, y_pred_vals, average='weighted')
print("Test Set Accuracy: {:.2%}   (But results would have been better if trained on the FULL dataset)".format(f1))

Obtengo: "Test Set Accuracy: 10.92%"
No lo entiendo, es una arquitectura que había logrado poner a trabajar en otro problema de clasificación de préstamos.
With weights:
Todas las modelizaciones anteriores no estaban ponderadas o no tenían pérdida focal.
Traté de hacer frente al desequilibrio de clase de manera diferente, como el remuestreo. Sin remuestreo lo hice con pesos:
weights = df_en2['Voting intention in 2021'].value_counts(normalize=True)
weights = weights.sort_index().tolist()
weights = {0: 1 / weights[0],
           1: 1 / weights[1],
           2: 1 / weights[2],
           3: 1 / weights[3]}

Donde dfen_2 es el dataframe que da x_train, y_train, x_test, y_test con la función spilt_data() que puedes encontrar aquí (Es básicamente la misma arquitectura pero para el problema de clasificación de préstamos).
Clasificador de árboles multiclase
En comparación, con un clasificador de árboles, si dejo max_depth a "ninguna", las hojas se expanden hasta que todas las hojas son puras o hasta que todas las hojas contienen menos de muestras divididas. Y obtengo una precisión promedio del 42%.
# importing necessary libraries
from sklearn import datasets
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split

# dividing X, y into train and test data
# X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0)

# training a DescisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier
dtree_model = DecisionTreeClassifier().fit(x_train, y_train)
dtree_predictions = dtree_model.predict(x_test)

# creating a confusion matrix
cm = confusion_matrix(y_test.values.argmax(axis = 1), dtree_predictions.argmax(axis = 1))

Y devuelve:
array([[0.19047619, 0.15873016, 0.45454545, 0.27118644],
       [0.15873016, 0.38095238, 0.2       , 0.30508475],
       [0.15873016, 0.15873016, 0.4       , 0.22033898],
       [0.19047619, 0.19047619, 0.21818182, 0.38983051]])


text:
Q: Tinymce textarea do not work while initializing using javascript I'm having a problem trying to use tinymce for my textarea. My textarea is kept hidden on pageload using javascript. I've used the following code to initialize tinymce & show it upon clicking a button.
$('#buttonID').click(function(){
    $('#textareaID').show();
    $('#textareaID').tinymce({
        //Settings here
    });
});

Upon clicking the button, the tinymce editor shows up for a fraction of sec after which the textarea falls back to the plain textarea.
The other solution I tried is to initialize tinymce using the following code & hide the textarea on pageload. Clicking a button can successfully show it but the input area is inactive & I can't enter any text. The same text area works perfectly fine if I don't hide it on pageload.
<script type="text/javascript">
tinyMCE.init({
    //settings here
});
</script>

Any help would be much appreciated. Thanks.