Q: How to make a successful batch commit when some of the docs could've been deleted? Suppose i have a structure like this:
items: {
  id1: {
    likes: 123
  },
  id2: {
    likes: 456
  },
  id3: {
    sourceId: 'id1',
    likes: 123
  },
  id4: {
    sourceId: 'id1',
    likes: 123
  }
  [,...]
}

where any item can either be a source item or an item that references a source item. The purpose of referencing the source item is to keep counters consistent across all items that share the same sourceId.
Therefore, when i change a counter on a source item, i want to batch write that counter's value to all the items that have that item as their sourceId.
My concern
Suppose I read in the docs referencing some sourceId, then i commit the changes in a batch to all of them. What if a very small subset of the docs in the batch were deleted in the small window of time since the documents were read in, or a rare but possible write-rate conflict occurs? Do none of the counters get updated because 1 or 2 documents failed to be updated?
Is it possible to submit a batch that writes the changes to each of its documents independently, such that if one fails, it has no impact on if the others get written?
Or maybe for this scenario it might be better to read in the documents referencing some sourceId and then write the changes to each document in parallel such that write independence is achieved. I don't like this approach since the number of requests would be the size of the batch.
What are your thoughts?

A: Take a careful read of the API docs for BatchWrite.  It will answer your questions.  Since you're not showing your batch code (are you using set? update?), we have to look at the API docs to assess the failure cases:

create()
This will fail the batch if a document exists at its location.

It sounds like you're probably not using create(), but this is the failure case.

set()
If the document does not exist yet, it will be created.

So, a set will not fail if the documented was deleted before the batch got committed.

update()
If the document doesn't yet exist, the update fails and the entire
  batch will be rejected.

So, if you try to update a nonexistent document, the batch will fail.
If you want to decide what to do with each document, depending on its existence and contents, then control the failure cases, use a transaction.

A: If I understand your question, I had a similar scenario and here's how I did it. First, I use generated universal ID's, uid's, for all my item keys/id's. Then, what you do is on the grandchildren, simply write the uid of the parent it is associated with. Each grandchild could be associated with more than one parent.
As you create new items, you have to recursively update the parent with the uid of the item so the parent has record of all its associated child items.
    fetchPromise = [];
    fetchArray = [];
    if(!selectIsEmpty("order-panel-one-series-select") || !selectIsUnselected(orderPanelOneSeriesSelect)){
        orderPanelOneTitle.innerHTML = "Select " + orderPanelOneSeriesSelect.value.toString().toUpperCase() + " Option";
    }
    //on change we need to populate option select based on this value
    //now we need to get the particular series doc and fill get array then prmise all to get all options

    familyuid = getRecordFromList(doc.getElementById("order-panel-one-family-select"),orderPanelOneFamilySelect.selectedIndex);
    seriesuid = getRecordFromList(doc.getElementById("order-panel-one-series-select"),orderPanelOneSeriesSelect.selectedIndex);
    optionuid = getRecordFromList(doc.getElementById("order-panel-one-option-select"),orderPanelOneOptionsSelect.selectedIndex);
    optionRef = db.collection("products").doc(familyuid).collection("option");
    itemRef = db.collection("products").doc(familyuid).collection("item");
    targetRef = db.collection("products").doc(familyuid).collection("option").doc(optionuid);
    try {
        targetRef.get().then(function(snap) {
            if (snap.exists) {
                for (var key in snap.data()) {
                    if (snap.data().hasOwnProperty(key)) {
                        fetchPromise = itemRef.doc(key).get();
                        fetchArray.push(fetchPromise);
                    }
                }
                Promise.all(fetchArray).then(function(values) {
                    populateSelectFromQueryValues(values,"order-panel-one-item-select");
                    if(!selectIsEmpty("order-panel-one-item-select")){
                        enableSelect("order-panel-one-item-select");
                    }
                    targetRef.get().then(function(snap){
                        if(snap.data().name){
                            var str = snap.data().name.toString();
                            orderAsideInfo.innerHTML = "Select " + capitalizeFirstLetter(str) + " item.";
                        }
                    });
                });
            }
        }).catch(function(error) {
            toast("error check console");
            console.log("Error getting document:", error);
        });
    }


Q: Quartz CronTrigger expression between two dates Is there a way to write a Quartz CronTrigger expression that runs every day between two dates, for example starts at 11am 5th of Sep 2011 and ends at 11am 10th of June 2012?

A: Use an expression that means every day at 11:00am  e.g.  "0 0 11 * * ?".
Then set the startTime of the trigger to 5th of Sep 2011 10:59 am, and set the endTime of the trigger to 10th of June 2012  11:01 am.

A: Another solution I found is to specify a route policy (SimpleScheduledRoutePolicy) for the scheduled route and set the RouteStartDate and setRouteStopDate for this policy object.

A: A single cron expression doesn't facilitate running different schedules for the same period type, no matter which period is concerned, your differing schedule being the year period.
However other than your year difference all other periods have the same schedule. So... using these cron expressions:
cron1 = "0 0 23 5/1 SEP-DEC ? 2012"
cron2 = "0 0 23 1/1 JAN-JUN ? 2013"
you can switch the scheduler from using cron1 to cron2 sometime after 11:00.00 PM on 12/31/2012 but before 10:59.99 PM on 1/1/2013, though I wouldn't cut it so close as shown here. If you scheduler is reading its cron expression from the database or a configuration somewhere then just have it read in a new schedule every day at 11:30 PM. If you are storing your cron expressions in a database you could schedule to have a scheduler swap out the cron expression for your particular task using this chron3 below:
cron3 = "0 0 0 1 JAN ? 2013"
Silly me :o) today's date is Mar 13, 2013 so I'm sure this answer is a bit late for you!


Q: C# Console not writing object string I'm trying to get the console to write a string that is part of a object, however the console leaves the string portion blank.
This is how i am getting the information:
Console.WriteLine("Please Enter an Agent Name: ");
agent1 = (Console.ReadLine());

Console.WriteLine("Please Enter " + agent1 + "'s Number of Customers: ");
ID1 = int.Parse(Console.ReadLine());

Then passing the variable agent 1 into a class i created:
Insurance Agent1 = new Insurance(agent1, ID1);

Then im tryting to tell the console to write out the agent's name and customer number:
Console.WriteLine("Agent 1 Name: "+ Agent1.Agent +" , Agent 1 Number of Customers: " + Agent1.Customers +".");

However, the console writes the customer number, which is an int, but not the string agent.

Please Enter an Agent Name: Test Please Enter Test's Number of
  Customers: 12
Agent 1 Name:  , Agent 1 Number of Customers: 12.

Any idea on how to get this to work?
EDIT:
This is the insurance class for reference:
class Insurance
{
    private string _Agent; //String for _Agent because it will be a series of letters
    private int _Customers; //Int for _Customers because it will be a whole number

    public Insurance (string Agent, int Customers)
    {
        this.Agent = Agent;
        this.Customers = Customers;
    }

    public string Agent
    {
        get { return _Agent; }
        set { _Agent = Agent; }
    }

    public int Customers
    {
        get { return _Customers; }
        set //Only set _Customers if the value is larger or equal to zero, if less than zero (negative) set to zero
        {
            if (value >= 0)
            {
                _Customers = value;
            } else if (value < 0) {
                _Customers = 0;
            }
        }
    }
}

A: Your "set" accessor is setup incorrectly. It's setting the value of _Agent to Agent, which calls the "get" on the property itself. The "getter" for Agent returns the _Agent field which is null.
Use value instead:
public string Agent
{
    get { return _Agent; }
    set { _Agent = value; }
}

Also, if I may, here's a few other suggestions on trimming down that class. But take it with a grain of salt, especially if you're just learning.
class Insurance
{
    private int customers;

    public Insurance(string agent, int customers)
    {
        Agent = Agent;
        Customers = Customers;
    }

    public string Agent { get; set; }

    public int Customers
    {
        get { return customers; }
        set { customers = Math.Max(value, 0); }
    }
}


Q: python Discord Bot how to send messages from one channel to another async def on_message(message):
    if message.channel == (720020927668289588):
        await Bot.get_channel(703707652710072515).send(f"{message.author.name}: {message}")
    await Bot.process_commands(message)

I am trying to have the bot to when someone sends a msg in channel 1 it will send the message to channel 2
I When i type into channel 1 nothing happens and no msg is send to channel 2 and there is no errors in the console
I have got it sorted

A: message.channel returns a channel object, you're trying to get the id. You can replace message.channel with message.channel.id to get the channel id. Then the code will work.


Q: custom iOS PWA background color instead of splash screen I don't want to show any custom splash screen for every device. Instead I'd like to just change the default ios black background to my custom background color (e.g. #89CFF0) and show it on every device without long list of links <link rel="apple-touch-startup-image" media="screen and (device-width: 810px) and (device-height: 1080px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" href="/assets/splash_screens/10.2_iPad_portrait.png"> ....
How can I get it?


Q: Why is my random number generator becoming an unused assignment when using it to input values for 2d array? I have been making a basic game of battleship and to get the CPU to choose ship locations on a 2d array I am making two random number generators to pick values from 1 to 8 on a separate method. For some reason, the random generators show up as unused and I don't know why. so far this is what I have. If anyone knows what I'm doing wrong please let me know.
//calls method
board3 = CPUship(board3);
//displays result of method
for (int i = 0; i < board3.length; i++) {
    for (int j = 0; j < board3.length; j++) {
        System.out.print(board3[i][j]);
    }
    System.out.println("");
}

public static String[][] CPUship(String[][] board3) {
    int rowGenerate;
    int colGenerate;
    boolean valid2 = false;
    for (int CPUships = 0; CPUships < 6; CPUships++) {
        while (!valid2) {
            rowGenerate = (int) (9 * Math.random() + 0);
            colGenerate = (int) (9 * Math.random() + 0);
            if (!board3[rowGenerate][colGenerate].equalsIgnoreCase("#")) {
                board3[rowGenerate][colGenerate] = "#";
                valid2 = true;
            }
        }
        valid2 = false;
    }
    return board3;
}

A: Here should be a complete code
public static String[][] CPUship(String[][]board3){
    int rowGenerate;
    int colGenerate;

    for (int CPUships = 0; CPUships < 6; CPUships++) {
        boolean valid2=false;
        while (!valid2){ //instead of valid = false "
            rowGenerate = (int) ( 9* Math.random() + 0);
            colGenerate = (int) ( 9* Math.random() + 0);
            if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){
                board3[rowGenerate][colGenerate]="#";
                valid2=true;
            }
            //removed the valid2=false, it does not "reset" automatically
            //removed the CPUships++ ... already done by the for loop
        }
    }
    return board3;
}

or use break instead of the valid boolean
public static String[][] CPUship(String[][]board3){
    int rowGenerate;
    int colGenerate;

    for (int CPUships = 0; CPUships < 6; CPUships++) {
        while (true){ //instead of valid = false "
            rowGenerate = (int) ( 9* Math.random() + 0);
            colGenerate = (int) ( 9* Math.random() + 0);
            if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){
                board3[rowGenerate][colGenerate]="#";
                break;
            }
            //removed the valid2=false, it does not "reset" automatically
            //removed the CPUships++ ... already done by the for loop
        }
    }
    return board3;
}


Q: Can I use Environment.Username and MYSQL to verify log in?         private void btnSubmitt_Click(object sender, RoutedEventArgs e)
        {
        try
        {
            i = 0;
            MySqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select * from users where  TX_EMPLOYEE='"; (Environment.UserName) & "'";
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);

            i = Convert.ToInt32(dt.Rows.Count.ToString());
        }
        catch
        {
            MessageBox.Show("Database connection is not available at this time. Please contact your database administrator ");
        }
        finally
        {
            con.Close();
        }

I would like to authenticate the user with their computer login name and the exact match that is listed in the MYSQL data table. However Environment.Username is not a valid syntax in this SQL statement.

A: This line is very very wrong:
cmd.CommandText = "Select * from users where  TX_EMPLOYEE='"; (Environment.UserName) & "'";

It should be this:
cmd.CommandText = "Select * from users where  TX_EMPLOYEE='" + Environment.UserName + "'";

Except, it shouldn't be like that because of SQL injection. If I could make Environment.UserName into ' or 1 = 1 or TX_EMPLOYEE = ' then your final query would become this:
Select * from users where  TX_EMPLOYEE='' or 1 = 1 or TX_EMPLOYEE = ''

Which clearly isn't what you want - somebody with no credentials being able to access this. You should instead use SQL parameters:
cmd.CommandText = "Select * from users where  TX_EMPLOYEE=?userName";
cmd.Parameters.AddWithValue("?userName", Environment.UserName);

On a separate note, I'm confused by this code:
i = Convert.ToInt32(dt.Rows.Count.ToString());

DataTable.Rows.Count is already an int, so you're converting a number to a string to a number. Why?


Q: What is "special" about PostgreSQL update vs delete+insert My understanding is that an update locks a tuple, marks it as deleted, and then adds a new tuple.
In other words, update = delete + insert.
Or so I had believe. But it appears there something fundamentally different about update from delete+insert in MVCC.

Setup:
CREATE TABLE example (a int PRIMARY KEY, b int);
INSERT INTO example VALUES (1, 1);

Method 1: Update
-- session A                          session B
BEGIN;
UPDATE example SET b = 2 WHERE a = 1;
                                      DELETE FROM example WHERE a = 1;
COMMIT;
-- now there are 0 rows in table example (1 row was deleted by session B)

Method 2: Delete and insert
-- session A                          session B
BEGIN;
DELETE FROM example WHERE a = 1;
INSERT INTO example VALUES (1, 2);
                                      DELETE FROM example WHERE a = 1;
COMMIT;
-- now there is 1 row in table example (0 rows deleted by session B)

Thus
UPDATE example SET b = 2 WHERE a = 1;

is different from
DELETE FROM example WHERE a = 1;
INSERT INTO example VALUES (1, 2);

How am I to understand the MVCC nature of update? Does the tuple has some sort of MVCC "identity" that is preserved during the update? What is it?

A: Yes, there is a difference between UPDATE and DELETE + INSERT.
Let's use the pageinspect extension to look at the tuples and the tuple headers.
If you want to repeat my experiment, you have to drop and re-create the table in between. Also, there may be additional flags (hint bits) if you selected the rows before examining them.
The meaning of infomask2 and infomask can be found in src/include/access/htup_details.h, see the quotations at the end of the answer.
After the UPDATE:
SELECT lp, t_xmin, t_xmax, t_ctid, t_infomask2, t_infomask, t_attrs
FROM heap_page_item_attrs(get_raw_page('example', 0), 'example');

 lp | t_xmin | t_xmax | t_ctid | t_infomask2 | t_infomask |            t_attrs
----+--------+--------+--------+-------------+------------+-------------------------------
  1 | 380943 | 380944 | (0,2)  |       16386 |        256 | {"\\x01000000","\\x02000000"}
  2 | 380944 |      0 | (0,2)  |       32770 |      10240 | {"\\x01000000","\\x02000000"}
(2 rows)

*

*The first tuple is the dead one. Its t_ctid has been changed to point to the updated version.
This is one of the key points, so let me expand on this: the ctid of a tuple is the combination of the block number and the “line pointer” (lp in the query result. t_ctid is normally redundant, but in this case it is used to point to the new row version. This is the link between the original tuple and the updated version.
t_infomask2 is 2 (the number of columns) plus HEAP_HOT_UPDATED, so this row received a HOT update (there was enough space in the block, and there is no index). t_infomask is HEAP_XMIN_COMMITTED (a hint bit).

*The second tuple is the new version.
t_infomask2 is 2 plus HEAP_ONLY_TUPLE, so this is  “heap-only tuple” that is only reachable via the updated ctid of the old version. t_infomask is HEAP_XMAX_INVALID (true, it is 0) plus HEAP_UPDATED (this is the updated version).
After the DELETE + INSERT:
SELECT lp, t_xmin, t_xmax, t_ctid, t_infomask2, t_infomask, t_attrs
FROM heap_page_item_attrs(get_raw_page('example', 0), 'example');

 lp | t_xmin | t_xmax | t_ctid | t_infomask2 | t_infomask |            t_attrs
----+--------+--------+--------+-------------+------------+-------------------------------
  1 | 380958 | 380961 | (0,1)  |        8194 |        256 | {"\\x01000000","\\x02000000"}
  2 | 380961 |      0 | (0,2)  |           2 |       2048 | {"\\x01000000","\\x02000000"}
(2 rows)

*

*Again, the first tuple is the dead one.
t_infomask2 is 2 plus HEAP_KEYS_UPDATED (this is a deleted or updated tuple), and t_infomask is HEAP_XMIN_COMMITTED (the tuple was valid before it was deleted).

*The second tuple is the inserted one:
t_infomask2 is 2 plus, and t_infomask is HEAP_XMAX_INVALID (it is 0), so this is a new tuple.
Explanation of the observed difference:
In READ COMMITTED isolation level, a transaction always sees the latest committed version of a row. The DELETE in session B has to lock the row and is blocked by the UPDATE or DELETE in session A.
The documentation explains what happens when the lock is released:

UPDATE, DELETE, SELECT FOR UPDATE, and SELECT FOR SHARE commands behave the same as SELECT in terms of searching for target rows: they will only find target rows that were committed as of the command start time. However, such a target row might have already been updated (or deleted or locked) by another concurrent transaction by the time it is found. In this case, the would-be updater will wait for the first updating transaction to commit or roll back (if it is still in progress). If the first updater rolls back, then its effects are negated and the second updater can proceed with updating the originally found row. If the first updater commits, the second updater will ignore the row if the first updater deleted it, otherwise it will attempt to apply its operation to the updated version of the row. The search condition of the command (the WHERE clause) is re-evaluated to see if the updated version of the row still matches the search condition. If so, the second updater proceeds with its operation using the updated version of the row.

In the case of the UPDATE there is a link between the old and the new row version, so PostgreSQL locks and deletes the new row version, while in the case of DELETE + INSERT there is no valid version of the row after the lock is gone, and nothing is deleted.
So while in many respects UPDATE and DELETE + INSERT are quite similar in PostgreSQL, they are not the same: in the second case, there is no connection between the deleted and the inserted row.
Appendix: the meaning of infomask and infomask2
t_infomask:
/*
 * information stored in t_infomask:
 */
#define HEAP_HASNULL            0x0001  /* has null attribute(s) */
#define HEAP_HASVARWIDTH        0x0002  /* has variable-width attribute(s) */
#define HEAP_HASEXTERNAL        0x0004  /* has external stored attribute(s) */
#define HEAP_HASOID             0x0008  /* has an object-id field */
#define HEAP_XMAX_KEYSHR_LOCK   0x0010  /* xmax is a key-shared locker */
#define HEAP_COMBOCID           0x0020  /* t_cid is a combo cid */
#define HEAP_XMAX_EXCL_LOCK     0x0040  /* xmax is exclusive locker */
#define HEAP_XMAX_LOCK_ONLY     0x0080  /* xmax, if valid, is only a locker */

 /* xmax is a shared locker */
#define HEAP_XMAX_SHR_LOCK  (HEAP_XMAX_EXCL_LOCK | HEAP_XMAX_KEYSHR_LOCK)

#define HEAP_LOCK_MASK  (HEAP_XMAX_SHR_LOCK | HEAP_XMAX_EXCL_LOCK | \
                         HEAP_XMAX_KEYSHR_LOCK)
#define HEAP_XMIN_COMMITTED     0x0100  /* t_xmin committed */
#define HEAP_XMIN_INVALID       0x0200  /* t_xmin invalid/aborted */
#define HEAP_XMIN_FROZEN        (HEAP_XMIN_COMMITTED|HEAP_XMIN_INVALID)
#define HEAP_XMAX_COMMITTED     0x0400  /* t_xmax committed */
#define HEAP_XMAX_INVALID       0x0800  /* t_xmax invalid/aborted */
#define HEAP_XMAX_IS_MULTI      0x1000  /* t_xmax is a MultiXactId */
#define HEAP_UPDATED            0x2000  /* this is UPDATEd version of row */
#define HEAP_MOVED_OFF          0x4000  /* moved to another place by pre-9.0
                                         * VACUUM FULL; kept for binary
                                         * upgrade support */
#define HEAP_MOVED_IN           0x8000  /* moved from another place by pre-9.0
                                         * VACUUM FULL; kept for binary
                                         * upgrade support */
#define HEAP_MOVED (HEAP_MOVED_OFF | HEAP_MOVED_IN)

#define HEAP_XACT_MASK          0xFFF0  /* visibility-related bits */

t_infomask2:
/*
 * information stored in t_infomask2:
 */
#define HEAP_NATTS_MASK         0x07FF  /* 11 bits for number of attributes */
/* bits 0x1800 are available */
#define HEAP_KEYS_UPDATED       0x2000  /* tuple was updated and key cols
                                         * modified, or tuple deleted */
#define HEAP_HOT_UPDATED        0x4000  /* tuple was HOT-updated */
#define HEAP_ONLY_TUPLE         0x8000  /* this is heap-only tuple */

#define HEAP2_XACT_MASK         0xE000  /* visibility-related bits */


Q: SQL Sum with non unique date I'm trying to write a SQL query that will sum total production from the following two example tables:
Table: CaseLots
DateProduced        kgProduced
October 1, 2013     10000
October 1, 2013     10000
October 2, 2013     10000

Table: Budget
OperatingDate       BudgetHours
October 1, 2013     24
October 2, 2013     24

I would like to output a table as follows:
TotalProduction   TotalBudgetHours
30000                   48

Here is what I have for code so far:
SELECT
Sum(kgProduced) AS TotalProduction, Sum(BudgetHours) AS TotalBudgetHours
FROM
dbo.CaseLots INNER JOIN dbo.Budget ON dbo.CaseLots.DateProduced = dbo.Budget.OperatingDate
WHERE
dbo.Budget.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'

It seems that the query is double summing the budget hour in instances where more than one case lot is produced in a day. The table I'm getting is as follows:
Total Production     BudgetHours
30000                72

How do I fix this?

A: Think about what the INNER JOIN is doing.
For every row in CaseLot, its finding any row in Budget that has a matching date.
If you were to remove your aggregation statements in SQL, and just show the inner join, you would see the following result set:
DateProduced    kgProduced    OperatingDate BudgetHours
October 1, 2013    10000    October 1, 2013    24
October 1, 2013    10000    October 1, 2013    24
October 2, 2013    10000    October 2, 2013    24
(dammit StackOverflow, why don't you have Markdown for tables :( )
Running your aggregation on top of that it is easy to see how you get the 72 hours in your result.
The correct query needs to aggregate the CaseLots table first, then join onto the Budget table.
SELECT DateProduced, TotalKgProduced, SUM(BudgetHours) AS TotalBudgetHours
FROM
(
    SELECT DateProduced, SUM(kgProduced) AS TotalKgProduced
    FROM CaseLots
    GROUP BY DateProduced
) AS TotalKgProducedByDay
INNER JOIN
Budget
ON TotalKgProducedByDay.DateProduced = Budget.OperatingDate
WHERE DateProduced BETWEEN '1 Oct 2013' AND '2 Oct 2013'
GROUP BY DateProduced

A: The problem is in the INNER JOIN produces a 3 row table since the keys match on all. So there is three '24's with a sum of 72.
To fix this, it would probably be easier to split this into two queries.
SELECT Sum(kgProduced) AS TotalProduction
FROM dbo.CaseLots
WHERE dbo.CaseLots.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'

LEFT JOIN

SELECT Sum(BudgetHours) AS TotalBudgetHours
FROM dbo.Budget
WHERE dbo.Budget.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'

A: This could be easily achieved by this:
SELECT
   (SELECT SUM(kgProduced) FROM dbo.CaseLots WHERE DateProduced BETWEEN '2013-10-01' AND '2013-10-02') AS TotalProduction,
   (SELECT SUM(BudgetHours) FROM dbo.Budget WHERE OperatingDate BETWEEN '2013-10-01' AND '2013-10-02') AS TotalBudgetHours

There's no need for joining the two tables.

A: Try this:
select DateProduced,TotalProduction,TotalBudgetHours from
  (select DateProduced,sum(kgProduced) as TotalProduction
  from CaseLots group by DateProduced) p
  join
  (select OperatingDate,sum(BudgetHours) as TotalBudgetHours
  from Budget group by OperatingDate) b
  on (p.DateProduced=b.OperatingDate)
where p.DateProduced between '2013-10-01' AND '2013-10-02'

A: The other answers are simpler for this particular case. However if you needed to SUM 10 different values on the CaseLots table, you'd need 10 different subqueries. The following is a general, more scaleable solution:
SELECT
    SUM(DayKgProduced) AS TotalProduction,
    SUM(BudgetHours) AS TotalBudgetHours
FROM (
    SELECT
        DateProduced,
        SUM(kgProduced) AS DayKgProduced,
    FROM dbo.CaseLots
    WHERE DateProduced BETWEEN '2013-10-01' AND '2013-10-02'
    GROUP BY DateProduced
) DailyTotals
INNER JOIN dbo.Budget b ON DailyTotals.DateProduced = b.OperatingDate

First you SUM the production of each CaseLot without having to SUM the BudgetHours. If you used a SELECT * FROM in the query above you'd see:
Date        DayKgProduced  BudgetHours
2013-10-01  20000          24
2013-10-02  10000          24

But you want the overall total, so we SUM those daily values, correctly producing:
TotalProduction  TotalBudgetHours
30000            48


Q: ngx-translate if a key is missing in one of the json file replace with other json file same key I have a scenario, I have two languages files en.json & es.json I have a key in en.json file which is missed in es.json file, however, I want to replace this missing key with the en.json key how would I achieve this.
I know the way we use MissingTranslationHandler for missing keys, but I do not want to show a default text for missing keys, Although I'm doing this for a missed key from both files, in my scenario its different.
Any help would be greatly appreciated, thanks in advance!

A: Inside your app module constructor, you can tell what is the default language which you're interested in
export class AppModule {

    constructor(translate: TranslateService) {
        translate.setDefaultLang('en');
        translate.use('en');
    }
}


Q: Transfer data from aprs server to symfony database I would like to connect symfony to an "aprs-is" server.
My data are received by the "aprs" server and i would like to insert them in the database i have created in the doctrine of symfony. My entities are ready but i can't figure out how to do that.
I can make an up-link on "aprs" server to redirect the data but i don't know how to architect all that link on both side.
Here is the link of aprs-is server archi: http://he.fi/aprsc/
The informations about the aprs uplink:
    $ sudo netstat -anp|grep aprsc
tcp        0      0 192.168.5.56:50002      0.0.0.0:*               LISTEN      21864/aprsc
tcp        0      0 127.0.0.1:10151         0.0.0.0:*               LISTEN      21864/aprsc
tcp        0      0 127.0.0.1:10151         127.0.0.1:46962         ESTABLISHED 21864/aprsc
tcp        0      0 192.168.5.56:50002      192.168.5.54:34070      ESTABLISHED 21864/aprsc
tcp6       0      0 :::50002                :::*                    LISTEN      21864/aprsc
unix  3      [ ]         STREAM     CONNECTE      865809   21864/aprsc
unix  3      [ ]         STREAM     CONNECTE      864810   21864/aprsc
unix  3      [ ]         STREAM     CONNECTE      864811   21864/aprsc

The information about apache listener
    $ sudo netstat -anp|grep apache2
tcp6       0      0 :::10150                :::*                    LISTEN      21582/apache2

The log connection on aprs:
2018/07/31 14:32:49.091674 aprsc[21864:7f5c008b1700] INFO: HTTP thread ready.
2018/07/31 14:32:49.091682 aprsc[21864:7f5bfd55f700] INFO: Uplink: 1 uplinks configured, 0 are connected, need to pick new
2018/07/31 14:32:49.091688 aprsc[21864:7f5bfd55f700] DEBUG: Uplink: trying Http (127.0.0.1:10150)
2018/07/31 14:32:49.091755 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: Connecting to 127.0.0.1:10150 (127.0.0.1:10150) [link 0, addr 1/1]
2018/07/31 14:32:49.091832 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: poll after connect returned 1, revents 4
2018/07/31 14:32:49.091840 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: successful connect
2018/07/31 14:32:49.091858 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: 127.0.0.1:10150: Connection established on fd 13 using source address 127.0.0.1:58630
2018/07/31 14:32:49.091865 aprsc[21864:7f5bfd55f700] DEBUG: pass_client_to_worker: client on fd 13 to thread 0 with 0 users
2018/07/31 14:32:49.091870 aprsc[21864:7f5bfd55f700] INFO: status: setting error flag no_uplink ttl 3600
2018/07/31 14:32:49.121688 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): closing all existing peergroup peers
2018/07/31 14:32:49.121776 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): added fd 13 to polling list, xfd 0x7f5c00a02000
2018/07/31 14:32:49.121795 aprsc[21864:7f5c00890700] DEBUG: Worker 0 accepted 1 new clients, 1 new connections, now total 1 clients
2018/07/31 14:32:50.989005 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink server software: HTTP/1.1 400 Bad Request
2018/07/31 14:32:50.989070 aprsc[21864:7f5c00890700] ERROR: 127.0.0.1:10150: Uplink's welcome message is not recognized: no # in beginning
2018/07/31 14:32:50.989098 aprsc[21864:7f5c00890700] INFO: Uplink TCP 127.0.0.1:10150 (Http) closed after 2 s: Uplink server protocol error, tx/rx 70/483 bytes 0/0 pkts, dropped 0, fd 13, worker 0
2018/07/31 14:32:50.989228 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink [0] has been closed: Uplink server protocol error
2018/07/31 14:32:50.989255 aprsc[21864:7f5c00890700] DEBUG: found the link to disconnect
2018/07/31 14:32:53.096709 aprsc[21864:7f5bfd55f700] INFO: Uplink: 1 uplinks configured, 0 are connected, need to pick new
2018/07/31 14:32:53.096795 aprsc[21864:7f5bfd55f700] DEBUG: Uplink: trying Http (127.0.0.1:10150)
2018/07/31 14:32:53.096970 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: Connecting to 127.0.0.1:10150 (127.0.0.1:10150) [link 0, addr 1/1]
2018/07/31 14:32:53.097139 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: poll after connect returned 1, revents 4
2018/07/31 14:32:53.097177 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: successful connect
2018/07/31 14:32:53.097275 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: 127.0.0.1:10150: Connection established on fd 13 using source address 127.0.0.1:58632
2018/07/31 14:32:53.097305 aprsc[21864:7f5bfd55f700] DEBUG: pass_client_to_worker: client on fd 13 to thread 0 with 0 users
2018/07/31 14:32:53.097324 aprsc[21864:7f5bfd55f700] INFO: status: setting error flag no_uplink ttl 3600
2018/07/31 14:32:53.126840 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): added fd 13 to polling list, xfd 0x7f5c00a02030
2018/07/31 14:32:53.126950 aprsc[21864:7f5c00890700] DEBUG: Worker 0 accepted 1 new clients, 1 new connections, now total 1 clients
2018/07/31 14:32:53.663743 aprsc[21864:7f5c008b1700] DEBUG: http status [127.0.0.1] request /status.json
2018/07/31 14:32:53.664754 aprsc[21864:7f5c008b1700] DEBUG: http_compress_gzip: compressed 7656 bytes to 1743 bytes: 22.8 %
2018/07/31 14:32:54.994428 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink server software: HTTP/1.1 400 Bad Request

$ sudo service aprsc status
● aprsc.service - LSB: start and stop aprsc
Loaded: loaded (/etc/init.d/aprsc; generated; vendor preset: enabled)
Active: active (running) since Tue 2018-07-31 16:32:48 CEST; 20min ago
Docs: man:systemd-sysv-generator(8)
Process: 21831 ExecStop=/etc/init.d/aprsc stop (code=exited, status=0/SUCCESS)
Process: 21844 ExecStart=/etc/init.d/aprsc start (code=exited, status=0/SUCCESS)
Tasks: 8 (limit: 4915)
CGroup: /system.slice/aprsc.service
       └─21864 /opt/aprsc/sbin/aprsc -u aprsc -t /opt/aprsc -f test -e             debug -o file -r logs -c /etc/aprsc.conf

systemd[1]: Starting LSB: start and stop aprsc...
aprsc[21844]:  * Preparing chroot for APRS-IS server: aprsc chroot
aprsc[21844]:    ...done.
aprsc[21844]:  *   Checking configuration 'aprsc'
aprsc[21844]:  * Starting APRS-IS server: aprsc
aprsc[21844]:  *   Starting 'aprsc'
aprsc[21844]:    ...done.
systemd[1]: Started LSB: start and stop aprsc.

A: I have progressed a little on that subject:
What's happening is the format sent from apache to aprs-is as response is badly interpreted by aprs. The apache server send a response with a header configured in apache2.conf:
ServerTokens will return HTTP/1.1 with the version of apache after that ( the verbose depending on the option next to Servertoken )
But i can't figure out how change the value "HTTP/1.1" by "#APRS"
I've tried to change it in mod_header.c but the only file i have found is mod_header.so  ...


Q: Unfortunately, AndroidFirst has stopped I am a beginner in android application & just started building first "HelloWorld" app. i followed official tutorial and designed emulator. But when i run it, the emulator says "Unfortunately, AndroidFirst has stopped". I looked around on SO but different solutions didn't help. I am a very beginner for Android, hence can't find the bug or something like wrong/error.
following is logCat:
08-29 05:16:58.629: W/dalvikvm(1934): VFY: unable to resolve static field 1864 (ActionBarWindow) in Landroid/support/v7/appcompat/R$styleable;
08-29 05:16:58.629: D/dalvikvm(1934): VFY: replacing opcode 0x62 at 0x0004
08-29 05:16:58.649: D/AndroidRuntime(1934): Shutting down VM
08-29 05:16:58.649: W/dalvikvm(1934): threadid=1: thread exiting with uncaught exception (group=0xb1daece8)
08-29 05:16:58.669: E/AndroidRuntime(1934): FATAL EXCEPTION: main
08-29 05:16:58.669: E/AndroidRuntime(1934): Process: com.example.androidfirst, PID: 1934
08-29 05:16:58.669: E/AndroidRuntime(1934): java.lang.NoClassDefFoundError: android.support.v7.appcompat.R$styleable
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:106)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.support.v7.app.ActionBarActivityDelegateICS.onCreate(ActionBarActivityDelegateICS.java:57)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:99)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at com.example.androidfirst.MainActivity.onCreate(MainActivity.java:13)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.Activity.performCreate(Activity.java:5242)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2258)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread.access$800(ActivityThread.java:138)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1209)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.os.Looper.loop(Looper.java:136)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread.main(ActivityThread.java:5026)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at java.lang.reflect.Method.invokeNative(Native Method)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at java.lang.reflect.Method.invoke(Method.java:515)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at dalvik.system.NativeStart.main(Native Method)
08-29 05:21:58.843: I/Process(1934): Sending signal. PID: 1934 SIG: 9

MainActivity.java Code:
package com.example.androidfirst;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidfirst"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I would be very thankful to you people!

A: For that Android Support library is required
See this image:

Then just import the v7 compact library project into your work space and add it as a library to your project
you can find it in sdk\extras\android\support\v7\appcompat where your SDK is present in directory.
After importing, select your project right click ->Properties-> Android->Add->Select app compact
click ok.

A: The problem resolve when i downloaded API-19 & re-created the AVD. On a very first attempt, the AVD shows "Hello World" the default text on emulator.


Q: reset infinite scroll with ajax content I am using the ajax infinite scroll with a comment system.  It works fine until a user posts a new comment - this breaks the infinite scroll, the 'load more items' link is still there but nothing happens when you click it.
I have seen this question: Reset / disable infinite scroll after AJAX call
I have tried to implement the destroy and bind into my success method but the loadmoreitems link is unreponsive.  How can I reset the infinite scroll after a user posts a comment with the code below?
ajax:
<script>
$(document).ready(function(){
$('#commentform').on('submit',function(e) {

$.ajax({
    url:'ajaxrequest.php',
    data:$(this).serialize(),
    type:'POST',
    dataType: 'HTML',
    success:function(data, response){

ias.destroy();

$("#posts").fadeOut(300);
$('#posts').html(data)
$("#posts").fadeIn(500);
$('html, body').animate({ scrollTop: $('#posts').offset().top - 100 }, 'fast');

ias.bind();

 jQuery.ias({
  container: "#posts",
  item: ".post",
  pagination: "#pagination",
  next: ".next a"
});
    },
    error:function(data){
        $("#error").show().fadeOut(5000);
    }
    });

e.preventDefault();
return false;

});
});
</script>

A: When you initialize the scroll on load make sure you have stored it in a variable called ias. Something like this
var ias = jQuery.ias({
  container: "#posts",
  item: ".post",
  pagination: "#pagination",
  next: ".next a"
});

And in success method call just the ias.destroy(); and ias.bind(); methods as you have done before.
Remove the initialization that is done again in your code i.e
jQuery.ias({
  container: "#posts",
  item: ".post",
  pagination: "#pagination",
  next: ".next a"
});


Q: React stop other events on that element I have a volume element that shows the volume bar when the user hovers over it. This all works great in desktop. However to get the same functionality on mobile, the user has clicks on the volume element which also toggles the mute click event.
I am wanting to stop that mute event when the user clicks (i.e taps) on that element on mobile.
I don't want to modify the Mute or VolumeBar classes to fix this because these are generic classes in my library that the developer uses.
https://jsfiddle.net/jwm6k66c/2145/

*

*Actual: The mute click event gets fired and the volume bar opens.

*Expected: The mute click event doesn't gets fired and the volume bar opens.

Open the console -> go into mobile view (CTRL + SHIFT + M on chrome) -> click the volume button and observe the console logs.
What I have tried:
Using volumeControlOnClick to stop propogation when the volume bar's height is 0 (i.e not visible), this does not cancel the onClick though.
What I want:
To cancel the mute click event if the user clicks on the volume icon for the first time in mobile. Instead it should only show the volume bar.
const volumeControlOnClick = (e) => {
  const volumeBarContainer =
    e.currentTarget.nextElementSibling.querySelector('.jp-volume-bar-container');
  /* Stop propogation is for mobiles to stop
    triggering mute when showing volume bar */
  if (volumeBarContainer.clientHeight === 0) {
    e.stopPropagation();
    console.log("stop propogation")
  }
};

class Volume extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
  }
    render() {
    return (

        <Mute onTouchStart={volumeControlOnClick}></Mute>

            <VolumeBar />

    );
  }
};

class Mute extends React.Component {
    render() {
    return (
      <button className="jp-mute" onClick={() => console.log("mute toggled")} onTouchStart={this.props.onTouchStart}>
        {this.props.children}
      </button>
    );
  }
};

class VolumeBar extends React.Component {
    render() {
    return (

 console.log("bar moved")}>
        {this.props.children}

    );
  }
};

React.render(<Volume />, document.getElementById('container'));

A: Here's what I ended up with. It works because onTouchStart is always calld before onClick if it's a touch event and if not's then the custom logic gets called anyway. It also fires before the hover has happened. This preserves the :hover event. e.preventDefault() did not.
let isVolumeBarVisible;

const onTouchStartMute = e => (
  isVolumeBarVisible = e.currentTarget.nextElementSibling
    .querySelector('.jp-volume-bar-container').clientHeight > 0
);

const onClickMute = () => () => {
  if (isVolumeBarVisible !== false) {
    // Do custom mute logic
  }
  isVolumeBarVisible = undefined;
};

<Mute
  aria-haspopup onTouchStart={onTouchStartMute}
  onClick={onClickMute}
>
  {/* Icon set in css*/}
</Mute>

A: What you can do is use a flag to indicate you were in a touch event before being in your mouse event, as long as you are using bubble phase. So attach a listener to your container element like this:
let isTouch = false;

const handleContainerClick = () => isTouch = false;

const handleMuteClick = () => {
  if (isTouch == false) {
    console.log("mute toggled");
  }
};

const volumeControlOnClick = () => {
  isTouch = true;
};

class Volume extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  render() {
    return (

        <Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}></Mute>

            <VolumeBar />

    );
  }
};

class Mute extends React.Component {
  render() {
    return (
      <button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>
        {this.props.children}
      </button>
    );
  }
};

class VolumeBar extends React.Component {
  render() {
    return (

 console.log("bar moved")}>
        {this.props.children}

    );
  }
};

render(<Volume />, document.getElementById('container'));

If you are not using bubble phase so you can register a timeout of 100ms with the same logic above, where after 100ms you make your flag variable false again. Just add to your touchStart handler:
setTimeout(() => {isTouch = false}, 100);

EDIT: Even though touch events are supposed to be passive by default in Chrome 56, you call preventDefault() from a touchEnd event to prevent the click handler from firing. So, if you can't modify the click handler of your Mute class in any way, but you can add a touchEnd event, than you could do:
const handleTouchEnd = (e) => e.preventDefault();

const volumeControlOnClick = () => console.log("volumeControlOnClick");

class Volume extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  render() {
    return (

        <Mute onTouchStart={volumeControlOnClick} onTouchEnd={handleTouchEnd}></Mute>

            <VolumeBar />

    );
  }
};

class Mute extends React.Component {
  render() {
    return (
      <button className="jp-mute" onTouchStart={this.props.onTouchStart} onTouchEnd={this.props.onTouchEnd} onClick={() => console.log("mute toggled")}>
        {this.props.children}
      </button>
    );
  }
};

class VolumeBar extends React.Component {
  render() {
    return (

 console.log("bar moved")}>
        {this.props.children}

    );
  }
};

render(<Volume />, document.getElementById('container'));

A: Try this
 render() {
        return (

        <Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}></Mute>

            <VolumeBar />

    );
  }
};

class Mute extends React.Component {
  render() {
    return (
      <button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>
        {this.props.children}
      </button>
    );
  }
};

class VolumeBar extends React.Component {
  render() {
    return (

 console.log("bar moved")}>
        {this.props.children}

    );
  }
};

render(<Volume />, document.getElementById('container'));


Q: Remove the Duplicate value item from 2 same format JSON objects in Java I'm looking for a way to remove the duplicate item from two JSON objects that both have the same value.
e.g.
First object:
{
 "a":true,
 "b":true,
 "c":true,
 "d":{"i":true,"ii":true,"iii":true}
}

Second object
{
 "a":false,
 "b":true,
 "c":true,
 "d":{"i":true,"ii":true,"iii":false}
}

And after removing the duplicate, I'd like to get
First object
{
 "a":true,
 "d":{"iii":true}
}

Second object
{
 "a":false,
 "d":{"iii":false}
}

I wonder if there's a tool already provides this function
(If that couldn't detect the duplicates inside the nested value, it's ok.)

A: Found way myself, I convert the json to map and then compare to remove the duplicates. Then convert the reduced map back to json


Q: Use rvest to extract html table I am a new learner for R, I am interested in using rvest to extract html table and submit html forms.
Now, I want to get some useful information from a Chinese Website.  The url is:
http://caipiao.163.com/award/cqssc/20160513.html
I am using Windows 10 Professional with RStudio Version 0.99.896, I use Google Chrome as the web browser with XPATH helper addon.
I want to extract the main html table from the Chinese site, it contains 120 groups of information about the lottery winning number.  The first one (001) is: 98446 and  the last one (120) is: 01798; I want to extract only the numbers (001) to (120) and the winning numbers: 98446 to 01798.
I used XPATH helper and Chrome web development to get the XPATH.
I think the XPATH for the information I want is:
//html/body/article[@class='docBody clearfix']/section[@id='mainArea']/div[@class='lottery-results']/table[@class='awardList']/*[@id="mainArea"]/div[1]/table/tbody/tr[2]/td[1]

But when I run the following code in RStudio, I can not get the result I want.
The following is my code:
> library(rvest)
Loading required package: xml2
> url <- "http://caipiao.163.com/award/cqssc/20160513.html"
> xp <- "//html/body/article[@class='docBody clearfix']/section    [@id='mainArea']/div[@class='lottery-results']/table[@class='awardList']/*[@id='mainArea']/div[1]/table/tbody/tr[2]/td[1]"
>
> x <- read_html(url)
> y <- x %>% html_nodes(xpath=xp)
> y
{xml_nodeset (0)}

>

Please take a look at my code and let me know if I made any mistakes.  You can simply ignore those unknown Chinese characters, they are not important, I just want to get the numbers.
Thanks!
John

A: It's not necessary to use such a precise target selector since there's only one table element (as the other answerer also pointed out). But you don't need to leave rvest behind:
library(rvest)

URL <- "http://caipiao.163.com/award/cqssc/20160513.html"

pg <- read_html(URL)
tab <- html_table(pg, fill=TRUE)[[1]]

str(tab)

## 'data.frame': 40 obs. of  39 variables:
##  $ 期号    : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ 开奖号码: chr  "9 8 4 4 6" "1 8 3 1 6" "2 9 3 5 6" "1 4 5 8 0" ...
##  ....

(SO is interpreting some of the unicode glyphs as spam so I had to remove the other columns).
The second column gets compressed via post-page-load javascript actions, so you'll need to clean that up a bit if that's the one you're going for.

A: I would use the function readHTMLTable from package XML to get the whole table, as in your website there is only one <table> element:
install.packages("XML)
library(XML)
url <- "http://caipiao.163.com/award/cqssc/20160513.html"
lotteryResults <- as.data.frame(readHTMLTable(url))

Then you can just do some cleansing procedures, subsetting and using rbind to get a data.frame with 2 columns and 120 observations.


Q: Using AWS Cloudfront, should I use apache gzip module to compress files or Cloudfront itself? I'm trying to get cloudfront straight on my site.
I want to know if I should you apache module to enable gzip on my site or set Cloudfront to compress the cached files?


Q: Looking for pure Java 3D library I have a very simple scenario: given are bare 3d points and I need to connect all these points and draw a surface. And for this case I need a very basic and really pure Java library without any dependencies.
Do you know such a library?

A: Do you know (or test) Java 3D API ?
Useful link : Java 3D API or Java net link
There is also another library : jmathplot (to draw diagram or others) --> it's easier than java 3d API.
It's two diferent philosophy. With the first you have to "draw point by point", with the second (jmathplot) you can use predefined elements and mathematical functions.

A: I think Java Surface Plot might be what you're looking for.
http://javasurfaceplot.sourceforge.net/

A: In order to communicate with the hardware just about any Java 3d library is going to have some dependencies.
You might try this:
http://www.mediafire.com/download/8ui3uwduw17bnx9/OpenGL.rar
There is a video tutorial set available for it. Just drawing a surface shouldn't be a problem.
http://www.youtube.com/watch?v=V1EvbHFtjCE
If you really want to get into Java 3D I would just search around for as much info on the various competing libraries and pick one for what you want to do with it.
edit:
The surface library fron other answer looks promising. I also found https://jogamp.org/jogl/www/ the JOGL or The Java API for OpenGL.


Q: contains function for int in flutter what is the best way to figure out what number the integer contains
for example:
i have a int that is 96 and i want to see if it has 9 return something and if it has not return something else

A: // this will return true if your int contains the pattern
bool intContains(myInt,pattern){
   return myInt.toString().contains(pattern.toString());
}


Q: WPF - XAML - Call an animation in a nested style from the parent style I'm trying to modify an ItemsControl to have a watermark to indicate the behavior of content dropped into it.
I'm using a Label inside a VisualBrush to show the word "OR" as the background to the ItemsControl (The control will contain property filters which will be Or'd together). The change in background is triggered by IsMouseOver on the ItemsControl.
The problem is this: I can get my VisualBrush (see xaml) to appear/disappear if I set the opacity directly in the Label but I cannot get the Opacity to animate if I try to use the nested style for the label. I have tried several approaches without success and so any pointers as to my mistake would be gratefully received.
I have included (one commented out) both animations I have tried. I also tried setting the Foreground on the Label with a ColorAnimation without success.
Many thanks
Ian Carson
<ItemsControl x:Name="OrFilterItemsTarget"
              ItemsSource="{Binding Assets.OrFilters}"
              ItemTemplateSelector="{StaticResource FilterTargetTemplateSelector}"
              ItemContainerStyle="{StaticResource DraggableItemStyle}"
              BorderThickness="0,0,0,0.5"
              BorderBrush="DimGray"
              AllowDrop="True"
              IsHitTestVisible="True"
              Margin="0,2.95,15.934,77"
              HorizontalAlignment="Right"
              Width="105">
    <ItemsControl.Style>
        <Style TargetType="{x:Type ItemsControl}">
            <Style.Resources>
                <Style x:Key="LabelStyle"
                       TargetType="{x:Type Label}">
                    <Style.Resources>
                        <Storyboard x:Key="FadeUp">
                            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                                          Storyboard.TargetProperty="Opacity"
                                                          FillBehavior="HoldEnd">
                                <SplineDoubleKeyFrame KeyTime="00:00:2"
                                                     Value="0.5" />
                            </DoubleAnimationUsingKeyFrames>
                            <!--<DoubleAnimation Storyboard.TargetProperty="Opacity"
                                             From="0" To="0.5"
                                             Duration="0:0:2" />-->
                        </Storyboard>
                        <Storyboard x:Key="FadeDown">
                            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                                           Storyboard.TargetProperty="Opacity"
                                                           FillBehavior="Stop">
                                <SplineDoubleKeyFrame KeyTime="00:00:2"
                                                      Value="0" />
                            </DoubleAnimationUsingKeyFrames>
                            <!--<DoubleAnimation Storyboard.TargetProperty="Opacity"
                                             From="0.5" To="0"
                                             Duration="0:0:2" />-->
                        </Storyboard>
                    </Style.Resources>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsMouseOver, ElementName=OrFilterItemsTarget}"
                                     Value="True">
                            <DataTrigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource FadeUp}" />
                            </DataTrigger.EnterActions>
                        </DataTrigger>
                        <DataTrigger  Binding="{Binding Path=IsMouseOver, ElementName=OrFilterItemsTarget}"
                                      Value="False">
                            <DataTrigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource FadeDown}" />
                            </DataTrigger.EnterActions>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
                <VisualBrush x:Key="FilterContentType"
                             AlignmentX="Center"
                             AlignmentY="Center"
                             Stretch="None">
                    <VisualBrush.Visual>
                        <Label Content="OR"
                               Foreground="DarkGray"
                               Style="{StaticResource LabelStyle}">
                        </Label>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Style.Resources>
            <Style.Triggers>
                <Trigger Property="IsMouseOver"
                         Value="True">
                    <Setter Property="Background"
                            Value="{StaticResource FilterContentType}" />
                </Trigger>
                <Trigger Property="IsMouseOver"
                         Value="False">
                    <Setter Property="Background"
                            Value="Transparent" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ItemsControl.Style>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal"
                       Background="Transparent">
                <i:Interaction.Behaviors>
                    <ei:FluidMoveBehavior AppliesTo="Children"
                                          Duration="0:0:0.3">
                        <ei:FluidMoveBehavior.EaseY>
                            <BackEase EasingMode="EaseIn"
                                      Amplitude="0.1" />
                        </ei:FluidMoveBehavior.EaseY>
                    </ei:FluidMoveBehavior>
                </i:Interaction.Behaviors>
            </WrapPanel>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

A: In the end I realized I was over-thinking the problem. Nested styles were unnecessary. The solution was to set the background as the VisualBrush (with its content set up as the desired final appearance) inside its own tag within the ItemsControl and then animate the opacity of the VisualBrush using EventTriggers directly on the ItemsControl. Note the various events to manage both mouse and dragging user activity.
Thanks to anyone who was thinking about this problem. The final XAML looks like this and hopefully will be useful to someone.
 <ItemsControl x:Name="OrFilterItemsTarget"
               ItemsSource="{Binding Assets.OrFilters}"
               ItemTemplateSelector="{StaticResource FilterTargetTemplateSelector}"
               ItemContainerStyle="{StaticResource DraggableItemStyle}"
               BorderThickness="0,0,0,0.5"
               BorderBrush="DimGray"
               AllowDrop="True"
               IsHitTestVisible="True"
               Margin="0,2.95,15.934,77"
               HorizontalAlignment="Right"
               Width="105">
     <ItemsControl.Background>
         <VisualBrush x:Name="OrFilterContentType"
                      AlignmentX="Center"
                      AlignmentY="Center"
                      Stretch="None"
                      Opacity="0">
             <VisualBrush.Visual>
                 <Label Content="OR"
                        Foreground="DarkGray"
                        Opacity="0.5" />
             </VisualBrush.Visual>
         </VisualBrush>
     </ItemsControl.Background>
     <ItemsControl.Triggers>
         <EventTrigger RoutedEvent="ItemsControl.MouseEnter">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="0" To="1"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
         <EventTrigger RoutedEvent="ItemsControl.DragEnter">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="0"
                                          To="1"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
         <EventTrigger RoutedEvent="ItemsControl.MouseLeave">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="1" To="0"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
         <EventTrigger RoutedEvent="ItemsControl.DragLeave">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="1"
                                          To="0"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
         <EventTrigger RoutedEvent="ItemsControl.Drop">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="1"
                                          To="0"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
     </ItemsControl.Triggers>
     <ItemsControl.ItemsPanel>
         <ItemsPanelTemplate>
             <WrapPanel Orientation="Horizontal"
                        Background="Transparent">
                 <i:Interaction.Behaviors>
                     <ei:FluidMoveBehavior AppliesTo="Children"
                                           Duration="0:0:0.3">
                         <ei:FluidMoveBehavior.EaseY>
                             <BackEase EasingMode="EaseIn"
                                       Amplitude="0.1" />
                         </ei:FluidMoveBehavior.EaseY>
                     </ei:FluidMoveBehavior>
                 </i:Interaction.Behaviors>
             </WrapPanel>
         </ItemsPanelTemplate>
     </ItemsControl.ItemsPanel>
 </ItemsControl>


Q: How to change from annual year end to annual mid year in SAS I currently work in SAS and utilise arrays in this way:
Data Test;
input Payment2018-Payment2021;
datalines;

10 10 10 10
20 20 20 20
30 30 30 30
;
run;

In my opinion this automatically assumes a limit, either the start of the year or the end of the year (Correct me if i'm wrong please)
So, if I wanted to say that this is June data and payments are set to increase every 9 months by 50% I'm looking for a way for my code to recognise that my years go from end of June to the next end of june
For example, if I wanted to say
Data Payment_Pct;
set test;

lastpayrise = "31Jul2018";

array payment:
array Pay_Inc(2018:2021) Pay_Inc: ;

Pay_Inc2018 = 0;
Pay_Inc2019 = 2; /*2 because there are two increments in 2019*/
Pay_Inc2020 = 1;
Pay_Inc2021 = 1;

do I = 2018 to 2021;

    if i = year(pay_inc) then payrise(i) * 50% * Pay_Inc(i);

end;

run;

It's all well and good for me to manually do this for one entry but for my uni project, I'll need the algorithm to work these out for themselves and I am currently reading into intck but any help would be appreciated!
P.s. It would be great to have an algorithm that creates the following
Pay_Inc2019 Pay_Inc2020 Pay_Inc2021
1           2           1

OR, it would be great to know how the SAS works in setting the array for 2018:2021 , does it assume end of year or can you set it to mid year or?

A: This is a wonderful use case of the intnx() function. intnx() will be your best friend when it comes to aligning dates.
In the traditional calendar, the year starts on 01JAN. In your calendar, the year starts in 01JUN. The difference between these two dates is exactly 6 months. We want to shift our date so that the year starts on 01JUN. This will allow you to take the year part of the date and determine what year you are on in the new calendar.
data want;
    format current_cal_year
           current_new_year year4.
    ;

    current_cal_year = intnx('year', '01JUN2018'd, 0, 'B');
    current_new_year = intnx('year.6', '01JUN2018'd, 1, 'B');
run;

Note that we shifted current_new_year by one year. To illustrate why, let's see what happens if we don't shift it by one year.
data want;
    format current_cal_year
           current_new_year year4.
    ;

    current_cal_year = intnx('year', '01JUN2018'd, 0, 'B');
    current_new_year = intnx('year.6', '01JUN2018'd, 0, 'B');
run;

current_new_year shows 2018, but we really are in 2019. For 5 months out of the year, this value will be correct. From June-December, the year value will be incorrect. By shifting it one year, we will always have the correct year associated with this date value. Look at it with different months of the year and you will see that the year part remains correct throughout time.
data want;
    format cal_month date9.
           cal_year
           new_year year4.
    ;

    do i = 0 to 24;
        cal_month = intnx('month', '01JAN2016'd, i, 'B');
        cal_year = intnx('year', cal_month, i, 'B');
        new_year = intnx('year.6', cal_month, i+1, 'B');
        year_not_same = (year(cal_year) NE year(new_year) );
        output;
    end;

    drop i;
run;

A: Regarding input Payment2018-Payment2021; there is no automatic assumption of yearness or calendaring. The numbers 2018 and 2021 are the bounds for a numbered range list

In a numbered range list, you can begin with any number and end with any number as long as you do not violate the rules for user-supplied names and the numbers are consecutive.

The meaning of the numbers 2018 to 2021 is up to the programmer.  You state the variables correspond to the June payment in the numbered year.
You would have to iterate a date using 9-month steps and increment a counter based on the year in which the date falls.
Sample code
Dynamically adapts to the variable names that are arrayed.
data _null_;

  array payments payment2018-payment2021;
  array Pay_Incs pay_inc2018-pay_inc2021; * must be same range numbers as payments;

  * obtain variable names of first and last element in the payments array;
  lower_varname = vname(payments(1));
  upper_varname = vname(payments(dim(payments)));

  * determine position of the range name numbers in those variable names;
  lower_year_position = prxmatch('/\d+\s*$/', lower_varname);
  upper_year_position = prxmatch('/\d+\s*$/', upper_varname);

  * extract range name numbers from the variable names;
  lower_year = input(substr(lower_varname,lower_year_position),12.);
  upper_year = input(substr(upper_varname,upper_year_position),12.);

  * prepare iteration of a date over the years that should be the name range numbers;
  date = mdy(06,01,lower_year); * june 1 of year corresponding to first variable in array;

  format date yymmdd10.;

  do _n_ = 1 by 1; * repurpose _n_ for an infinite do loop with interior leave;
    * increment by 9-months;
    date = intnx('month', date, 9);

    year = year(date);
    if year > upper_year then leave;

    * increment counter for year in which iterating date falls within;
    Pay_Incs( year - lower_year + 1 ) + 1;
  end;

  put Pay_Incs(*)=;
run;

Increment counter notes
There is a lot to unpack in this statement
    Pay_Incs( year - lower_year + 1 ) + 1;

*

*+ 1 at the end of the statement increments the addressed array element by 1, and is the syntax for the SUM Statement

variable + expression The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here:
  retain variable 0;
  variable=sum(variable,expression);

*year - lower_year + 1 computes the array base-1 index, 1..N, that addresses the corresponding variable in the named range list pay_inc<lower_year>-pay_inc<upper_year>

*Pay_Incs( <computed index> ) selects the variable of the SUM statement


Q: Make for loop continue until a goal is accomplished I need to be able to find 5 sequential bits of EEPROM memory, ideally closest to 2 (as I have bit #1 & 2 associated with other data and want things to be kept organized). I developed this code which works, but the for loop continues after it has found a good set of numbers.
Serial.println("got to assignment number finder");
for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
  Serial.println("Finding a good assignment number " + String(AssignCheck));
  if (EEPROM.read(AssignCheck) == 255){          //Looks for a blank space which can be used to store the new card
    if (EEPROM.read(AssignCheck + 1) == 255){
      if (EEPROM.read(AssignCheck + 2) == 255){
        if (EEPROM.read(AssignCheck + 3) == 255){
          if (EEPROM.read(AssignCheck + 4) == 255){
            Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ".  Scanner value = " + String(Scanner));
            int StoreValue = AssignCheck;
          }
        }
      }
    }
  }
}

I then thought I could put a while loop around it, and have the while loop stop once a variable is set to 0 as opposed to 1, so I wrote this: (notice the introduction of the while loop, the variable and the Scanner = 0 line in the middle).
Serial.println("got to assignment number finder");
int Scanner = 1;
while (Scanner == 1){
  for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
    Serial.println("Finding a good assignment number " + String(AssignCheck) + ".  Scanner value = " + String(Scanner));
    if (EEPROM.read(AssignCheck) == 255){          //Looks for a blank space which can be used to store the new card
      if (EEPROM.read(AssignCheck + 1) == 255){
        if (EEPROM.read(AssignCheck + 2) == 255){
          if (EEPROM.read(AssignCheck + 3) == 255){
            if (EEPROM.read(AssignCheck + 4) == 255){
              Scanner = 0;
              Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ".  Scanner value = " + String(Scanner));
              int StoreValue = AssignCheck;
            }
          }
        }
      }
    }
  }
}

It correctly identifies and sets the variable to 0 when I want, but the while loop doesn't seem to have an impact and the loop continues to produce sets of numbers which could work.
As a novice coder myself, I'm not sure what I could try next.
Any advice would be greatly appreciated.

A: In these case you can use the instruction break:
Serial.println("got to assignment number finder");
for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
  Serial.println("Finding a good assignment number " + String(AssignCheck));
  if (EEPROM.read(AssignCheck) == 255){          //Looks for a blank space which can be used to store the new card
    if (EEPROM.read(AssignCheck + 1) == 255){
      if (EEPROM.read(AssignCheck + 2) == 255){
        if (EEPROM.read(AssignCheck + 3) == 255){
          if (EEPROM.read(AssignCheck + 4) == 255){
            Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ".  Scanner value = " + String(Scanner));
            int StoreValue = AssignCheck;
            break;
          }
        }
      }
    }
  }
}

As you can read here, it does exactly what you want.
Please note that your second attempt doesn't work because the for loop is inside the while: it completes before the whole for loop and, after, it compare the "scanner" variable of the while loop
You can correct it in this way:
Serial.println("got to assignment number finder");
int Scanner = 1;
for (int AssignCheck = 2; (AssignCheck < 250) && (Scanner == 1); AssignCheck++){
  Serial.println("Finding a good assignment number " + String(AssignCheck) + ".  Scanner value = " + String(Scanner));
  if (EEPROM.read(AssignCheck) == 255){          //Looks for a blank space which can be used to store the new card
    if (EEPROM.read(AssignCheck + 1) == 255){
      if (EEPROM.read(AssignCheck + 2) == 255){
        if (EEPROM.read(AssignCheck + 3) == 255){
          if (EEPROM.read(AssignCheck + 4) == 255){
            Scanner = 0;
            Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ".  Scanner value = " + String(Scanner));
            int StoreValue = AssignCheck;
          }
        }
      }
    }
  }
}

A: Reading EEPROM is expensive, please consider this:
Serial.println("got to assignment number finder");
int Scanner = 1;
char rollingBuffer[5];
rollingBuffer[0] = EEPROM.read(2 + 0);
rollingBuffer[1] = EEPROM.read(2 + 1);
rollingBuffer[2] = EEPROM.read(2 + 2);
rollingBuffer[3] = EEPROM.read(2 + 3);
rollingBuffer[4] = EEPROM.read(2 + 4);
pointRoll = 0;
for (int AssignCheck = 7; (AssignCheck < 255); AssignCheck++)
{
    if ((rollingBuffer[0] == 255) && (rollingBuffer[1] == 255) && (rollingBuffer[2] == 255) && (rollingBuffer[3] == 255) && (rollingBuffer[4] == 255))
    {
        Serial.println("Found assignment numbers " + String(AssignCheck-5) + " through to " + String(int(AssignCheck-1)) + ".  Scanner value = " + String(Scanner));
        int StoreValue = AssignCheck;
        break;
    }
    rollingBuffer[pointRoll] = EEPROM.read(AssignCheck);
    pointRoll++;
    if (pointRoll > 4) pointRoll = 0;
}


Q: Disk Usage Analysys.. On my virtual Ubuntu Desktop (HD: 300 GB), Disk usage analyzer shows:

and the df-l command shows:

This is strange! If the root consumes only 59.6 GB, How the filesystem capacity says it uses 227.4 GB ?!

A: The program tallies both files that you do not have read access to. The 59.6 GB probably only refers to the actual amount of data you can READ. The 227.4 GB is the total space used on the hard drive, readable or not.


Q: Laravel back() doesn't use _previous Trying to use
return back();

In one of my controllers however it always seems to return back to the home page if I however use
return Redirect::to($request->session->get('_previous')['url']);

It does work so it seems that for some reason the back() function isn't grabbing _previous correctly. Any way to fix this? I've noticed it in other controllers as well.


Q: Chinese Chewing input method does not work on Ubuntu 22.04 I apt-ge installed ibus-chewing and reboot the machine. Now I can type Chewing in Ubuntu search bar, but not else where.
I tried LibreOffice writer,Firefox browser,and gedit. I can only type English in them.

UPDATE:
So I checked out this https://lintut.com/how-to-set-up-system-locale-on-ubuntu-18-04/ and it says Locales defines language and country specific setting for your programs and shell session.
I ran sudo locale-gen zh_TW.UTF-8, and it only updated the file in /etc/default/locale, which is not the locale used by the system

Then, I tried sudo dpkg-reconfigure locales. It reconfigure the font types.

Then I tried update-locale to update /usr/bin/locale, but to no avail.

UPDATE2:
I realized I didn't tick the Plain Zhuyin Mode in preference in Chewing.
I can type Chinese in LibreOffice now, but the character selection is horrible, which was always the case.


Q: Confused in Dependency Injection I am new to MVC and dependency injection. Please help me to understand how that should work. I use Ninject. Here is my code:
in Global.asax file:
private void RegisterDependencyResolver()
    {
        var kernel = new StandardKernel();
        kernel.Bind<IDbAccessLayer>().To<DAL>();
        // DAL - is a Data Access Layer that comes from separated class library
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

protected void Application_Start()
    {
        RegisterDependencyResolver();
    }

IDbAccessLayer implementation is very simple:
public interface IDbAccessLayer
{
  DataContext Data { get; }
  IEnumerable<User> GetUsers();
}

now in a Controller I need to create a constructor that gets IDbAccessLayer param. And that just works.
Now I don't know how to pass a connection string to DAL. if I try to replace DAL's constructor with something that accepts a parameter, it doesn't work. Throws an exception with message No parameterless constructor defined for this object

A: You could specify constructor parameters:
kernel
    .Bind<IDbAccessLayer>()
    .To<DAL>()
    .WithConstructorArgument("connectionString", "YOUR CONNECTION STRING HERE");

And instead of hardcoding the connection string in your Global.asax you could read it from your web.config using:
ConfigurationManager.ConnectionStrings["CNName"].ConnectionString

and now your DAL class could take the connection string as parameter:
public class DAL: IDbAccessLayer
{
    private readonly string _connectionString;
    public DAL(string connectionString)
    {
        _connectionString = connectionString;
    }

    ... implementation of the IDbAccessLayer methods
}

A: Create a parameter-less constructor that calls the one-parameter constructor with a default connection string.
public DAL() : this("default connection string") {

}

public DAL(string connectionString) {
    // do something with connection string
}

A: I've not worked with ninject, just a bit with Unity.  But all the IOC containers seem to gravitate towards you making your own factory class that takes your stateful parameters (your connection string), which returns your real object.  For example, if you had a Person class which requires a "name" and "age" for the constructor, then you must make a factory which would interact with Unity rather like this:
IPerson foo = container.Resolve<IPersonFactory>().Create("George", 25);

This is one of the things I don't like about IOC containers, but it's generally where it goes...

A: Just stupid idea having no knowledge of ninject:
kernel.Bind<IMyConnectionString>().To<MyConnectionString>();

And to your DAL constructor accepting IMyConnectionString


Q: O que é granularidade de serviços? O que é granularidade de serviços em SOA?
Qual a diferença entre granularidade fina e grossa?

A: A "granularidade de serviços" é utilizada para mensurar a profundidade de abstração
que foi aplicado nos serviços.
A granularidade pode ser dividida em duas partes, sendo:

*

*Granularidade fina (fine-grained):
Determina que precisamos de muitos "grãos".
Teremos serviços com poucas operações, mas dividiremos essas operações por vários serviços.

Exemplo: Dividir operações de um CRUD de clientes via serviço WCF em dois serviços
ServicoCadastroCliente com operações/métodos CriarCliente(), AtualizarCliente() e ExcluirCliente()
ServicoValidarCadastroCliente com operações/métodos ValidarCliente(), ValidarAtualizacaoCliente() e ValidarExclusaoCliente

*

*Granularidade grossa (coarse-grained):
Determina que teremos poucos "grãos", bem maiores.
Teremos poucos serviços, mas cada um deles conterá uma porção bem maior de operações.

Exemplo: Definir apenas um serviço para as operações de um CRUD de clientes via serviço WCF
ServicoCadastroCliente com operações/métodos CriarCliente(), AtualizarCliente(), ExcluirCliente(), ValidarCliente(), ValidarAtualizacaoCliente() e ValidarExclusaoCliente


Q: Change App name dynamically based on user input I want to change the name of the app and the form title based on the user input. I know to do those changes in the manifest and styles, but how to make it dynamic. Please suggest me how to do it?. What are the changes to be done.

A: Did you try this?
myActivity.setTitle(userInput); //Where userInput is new title given by user

Hope this helps.

A: You can simply call the setTitle() function from within your Activity. It takes either an int (resource ID) or a CharSequence as a parameter.
or
this.setTitle("New Title Here");

or change in manifest file

A: If you just want to change the string in the Title bar, you can use setTitle as @android_beginner or @Mystic Magic suggested.
If you intend on changing the name of the app as it appears in the Android desktop, I'm afraid that's not possible.


Q: How to replace table name in sql query with regex in Java? I want to replace table name in a sql query string. I only want to change table name. How can I do that in java with regex?
I do not want to use any dependencies.
For example,
Input:
select ... from table1 where/etc ....

expected output:
select ... from UPDATED_TABLE_NAME where/etc ....

A: If you mutate the query explicitly you open yourself to SQL injection. What you could do is use a PreparedStatement with a parameterized query to provide the table name safely.
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM ?")) {
    statement.setString(1, "my_table");

    try (ResultSet results = statement.executeQuery()) {

    }
}

If you're insistent on using regex you can just use the query above and replace ? with the table name. I would not do this in a production environment.
String query = "SELECT * FROM ?";

String queryWithTable = query.replaceAll("?", "my_table");


Q: Get Azure Webjob History - 403 Token invalid I am trying to retrieve the web job history of an Azure web job via REST using a .NET backend and the OAuth2 credentials flow (as described here
https://learn.microsoft.com/en-us/rest/api/appservice/web-apps/get-triggered-web-job-history-slot)
How do I need to authenticate correctly?
I retrieve the token as follows:
POST https://login.microsoftonline.com/{MySubscription}/oauth2/v2.0/token
client_id={MyApp}
&grant_type=client_credentials
&scope=https://management.azure.com/.default
&client_secret={myclient_secret}

I get a token back, however I get a 403 error message when I try to retrieve the resource:
GET https://management.azure.com/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}/history?api-version=2021-02-01
Authorization: Bearer {MyToken}

Client '{MyApp}' with object ID '{MyApp}' is not
authorized to perform the action
'Microsoft.Web/sites/slots/triggeredwebjobs/history/read' using the
scope
'/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}'
or the scope is invalid. If access was granted recently, please update
your credentials.

What am I doing wrong?
I already added the API-Permission

A: The "403 Token invalid" error usually occurs if you missed giving permissions to particular scope (Azure Service Management).
By giving this scope it enables you to access https://management.azure.com
To resolve this error, please follow below steps:
Go to Azure Ad ->your application -> API permissions -> Add permission -> Azure Service Management -> delegated permissions ->User impersonation -> Add

After giving these permissions try to retrieve the resource again, there won't be any error.

A: Since I didn't find a solution that worked with OAuth2 and the Credentials flow, I got it working with Basic Authentication. The username (userName) and password (userPWD) can be taken from the publishing profile of the respective app service.
GET https://{appservicename}.scm.azurewebsites.net/api/triggeredwebjobs/{jobName}/history
Authorization Basic ....


Q: Meteor loginWithFacebook permissions not being asked I am using Meteor.loginWithFacebook:
 Meteor.loginWithFacebook({
      // https://developers.facebook.com/docs/reference/fql/permissions/
      requestPermissions: ['read_friendlists','user_about_me','user_birthday',
      'user_education_history', 'user_friends', 'user_likes', 'user_photos',
      'user_religion_politics', 'user_work_history'],
      loginStyle: "popup"
    }, function (err,res) {
      if(err)  alert(err)
      else console.log(res)
    });

But when my actual login box pops up, thought the user is logged in and I get access to all their publicly availabe information, it doesn't actually request any of the specified permissions (and I therefore don't have access to them). Is there something in my code I need to change in order to have the permissions actually be requested?

A: @kittyminky you right
the solution is
Accounts.ui.config({ requestPermissions: { facebook: [the_permissons_you_want] } });

A: on my case using Accounts.ui.config yields an error since i only have Accounts defined, Accounts.ui isn't defined for me.
Perhaps because i didn't add that package, but must be a way without using the .ui ?


Q: How to save All excel Charts in one pdf then Email it I would greatly appreciate it if you could help me with this, I am creating a dynamic excel sheet and I managed so far to create excel charts using Excel vba.
However, I am struggling with exporting all of the charts and one additional sheet to one pdf. I have around 15 excel charts and one excel sheet that I need to put in one pdf. And I need the excel sheet to be the first page in the pdf. Then email this pdf (all using vba).
Could you please help me on this! Your help is much appreciated. Thank you in advance!

A: Well you could Publish the workbook to PDF, just make sure your fist page is the first sheet
Option Explicit
Sub PDF_And_Mail()
    Dim FileName As String

    '// Call the function with the correct arguments
    FileName = Create_PDF(Source:=ActiveWorkbook, _
                              OverwriteIfFileExist:=True, _
                              OpenPDFAfterPublish:=False)

    If FileName <> "" Then
        Mail_PDF FileNamePDF:=FileName
    End If

End Sub

'// Create PDF
Function Create_PDF(Source As Object, OverwriteIfFileExist As Boolean, _
                                OpenPDFAfterPublish As Boolean) As String
    Dim FileFormatstr As String
    Dim Fname As Variant

    '// Test If the Microsoft Add-in is installed
    If Dir(Environ("commonprogramfiles") & "\Microsoft Shared\OFFICE" _
         & Format(Val(Application.Version), "00") & "\EXP_PDF.DLL") <> "" Then

            '// Open the GetSaveAsFilename dialog to enter a file name for the pdf
            FileFormatstr = "PDF Files (*.pdf), *.pdf"
            Fname = Application.GetSaveAsFilename("", filefilter:=FileFormatstr, _
                                                  Title:="Create PDF")

        '// If you cancel this dialog Exit the function
        If Fname = False Then
            Exit Function
        End If

        'If OverwriteIfFileExist = False we test if the PDF
        'already exist in the folder and Exit the function if that is True
        If OverwriteIfFileExist = False Then
            If Dir(Fname) <> "" Then Exit Function
        End If

        'Now the file name is correct we Publish to PDF
        Source.ExportAsFixedFormat _
                Type:=xlTypePDF, _
                FileName:=Fname, _
                Quality:=xlQualityStandard, _
                IncludeDocProperties:=True, _
                IgnorePrintAreas:=False, _
                OpenAfterPublish:=OpenPDFAfterPublish

        'If Publish is Ok the function will return the file name
        If Dir(Fname) <> "" Then
            Create_PDF = Fname
        End If
    End If
End Function

'// Email Created PDF
Function Mail_PDF(FileNamePDF As String)
    Dim GMsg As Object
    Dim gConf As Object
    Dim GmBody As String
    Dim Flds As Variant

    Set GMsg = CreateObject("CDO.Message")
    Set gConf = CreateObject("CDO.Configuration")

    gConf.Load -1    ' CDO Source Defaults
    Set Flds = gConf.Fields

    With Flds
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "GmailAddress@gmail.com"
        .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        .Update
    End With

    GmBody = "Hi there" & vbNewLine & vbNewLine

    With GMsg
        Set .Configuration = gConf
        .To = "recip@email.com"
        .CC = ""
        .BCC = ""
        .From = "Reply@something.com"
        .Subject = "Important message"
        .TextBody = GmBody
        .AddAttachment FileNamePDF
        .Send
    End With

End Function

Most codes from Ron de Bruin


Q: An inequality involving sums of squares and sums of cubes Assume that we have $m$ real numbers $x_1,x_2,...,x_m\in[0,1/4]$ satisfying the following equations:
$$ \sum_{i=1}^m x_i=a_1, \sum_{i=1}^mx_i^2=a_2,\sum_{i=1}^mx_i^3\geq a_3,$$
where $a_1,a_2,a_3$ are all positive. The aim is to obtain restrictions on $a_1,a_2,a_3$. We can consider the polynomial
$$f_b(x)=(x-1/4)(x+b)^2=x^3+(2b-1/4)x^2+(b^2-b/2)x-(1/4)b^2$$
 where $b\in\mathbb{R}$. Then
$$0\geq \sum_{i=1}^m f_b(x_i)\geq a_3+(2b-1/4)a_2+(b^2-b/2)a_1-(1/4)b^2m,$$ where the right hand side can be seen as a quadratic polynomial in variable $b$ and it is always less than or equal to 0. This will give us a restriction on $a_1,a_2,a_3$. I wonder whether there are other restrictions on $a_1,a_2,a_3$?

A: This is a partial answer. If it is correct, I can proceed.
Let $m \ge 3$ be a fixed positive integer. Let $\lfloor x\rfloor$
be the greatest integer less than or equal to $x$.
First, let us prove the following lemma.
Lemma 1: There exists $x_1, x_2, \cdots, x_m \in [0, \frac{1}{4}]$, not all zero, such
that $x_1 + x_2 + \cdots + x_m = a_1, \ x_1^2 + x_2^2 + \cdots + x_m^2 = a_2$ and $x_1^3+x_2^3 + \cdots + x_m^3
\ge a_3$,
if and only if,
\begin{equation}
0 < a_1 \le \frac{m}{4}, \qquad\qquad\qquad\qquad\qquad\qquad\qquad (1)
\end{equation}
\begin{equation}
\frac{a_1^2}{m} \le a_2 \le \frac{1}{16}\lfloor 4a_1\rfloor + \left(a_1 - \frac{1}{4}\lfloor 4a_1\rfloor\right)^2, \qquad (2)
\end{equation}
and
\begin{align}
a_3 \le F(a_1, a_2),\qquad\qquad\qquad\qquad\qquad\qquad\quad (3)
\end{align}
where
\begin{align}
F(a_1, a_2) =  &\max_{x_1, x_2, \cdots, x_m} \ x_1^3 + x_2^3 + \cdots + x_m^3\qquad\qquad\qquad\qquad\quad (4)\\
&\mathrm{s.t.}\quad x_i\in [0, \frac{1}{4}], \forall i; \ x_1 + x_2 + \cdots + x_m = a_1, \ x_1^2 + x_2^2 + \cdots + x_m^2 = a_2.\nonumber
\end{align}
Proof of Lemma 1: WLOG, assume that $x_1 \ge x_2\ge \cdots \ge x_m$.
(the "only if" part):
i) Clearly, $0 < a_1 \le \frac{m}{4}$.
ii) Given $0 < a_1 \le \frac{m}{4}$, the range of $a_2$ is $[g(a_1), f(a_1)]$ where
\begin{align*}
f(a_1) = &\max_{x_1, x_2, \cdots, x_m} \ x_1^2 + x_2^2 + \cdots + x_m^2\\
&\mathrm{s.t.}\quad x_i\in [0, \frac{1}{4}], \forall i; \ x_1 + x_2 + \cdots + x_m = a_1
\end{align*}
and
\begin{align*}
g(a_1) = &\min_{x_1, x_2, \cdots, x_m} \ x_1^2 + x_2^2 + \cdots + x_m^2\\
&\mathrm{s.t.}\quad x_i\in [0, \frac{1}{4}], \forall i; \ x_1 + x_2 + \cdots + x_m = a_1.
\end{align*}
It is easy to obtain $g(a_1) = \frac{a_1^2}{m}$ (the minimum is attained always when $x_1=x_2 = \cdots = x_m = \frac{a_1}{m}\in [0, \frac{1}{4}]$).
We have $f(a_1) = \frac{1}{16}\lfloor 4a_1\rfloor + \left(a_1 - \frac{1}{4}\lfloor 4a_1\rfloor\right)^2$ since
$h(x) = x_1^2 + x_2^2 + \cdots + x_n^2$ is convex, and (denote $K = \lfloor 4a_1\rfloor$)
$\big(\underbrace{\frac{1}{4}, \frac{1}{4}, \cdots, \frac{1}{4}}_{K}, a_1 - \frac{1}{4}K, 0, 0, \cdots, 0\big)$ majorizes $(x_1, x_2, \cdots, x_m)$ with
$x_i\in [0, \frac{1}{4}], \forall i; \ x_1 + x_2 + \cdots + x_m = a_1$.
iii) Clearly, (3) is true.
(the "if" part): It is clear according to the (the "only if" part). This completes the proof of Lemma 1.
Let us proceed. We want to find the explicit expression of $F(a_1, a_2)$.
Let $(x_1, \ x_2, \cdots, x_m)$ be the global maximizer of the optimization problem given in (4).
We claim that $|\{x_1, \ x_2, \cdots, x_m\}|\le 4$ where $|\cdot|$ is the cardinality of a set.
Proof of the claim: Assume, for the sake of contradiction, that $|\{x_1, \ x_2, \cdots, x_m\}| > 4$.
WLOG, assume that $0 < x_1 < x_2 < x_3 < \frac{1}{4}.$
Denote $D = 16(x_1^2+x_2^2+x_3^2) - 32(x_1x_2 + x_1x_3 + x_2x_3) + 8(x_1+x_2+x_3) -3.$
Remark: The proof of the inequalities in this part is simple and thus omitted.
1) If $D\le 0$, let
$$a = \frac{x_1+x_2+x_3}{3}-\frac{1}{3}\sqrt{x_1^2+x_2^2+x_3^2-x_1x_2-x_1x_3-x_2x_3}\, ,$$
$$b = \frac{x_1+x_2+x_3}{3}+\frac{2}{3}\sqrt{x_1^2+x_2^2+x_3^2-x_1x_2-x_1x_3-x_2x_3}\, .$$
We have $x_1+x_2+x_3 = a + a + b, \ x_1^2+x_2^2+x_3^2 = a^2 + a^2 + b^2$ and $0 \le a \le b\le \frac{1}{4}$.
Thus, $(a, a, b, x_4, x_5, \cdots, x_m)$ is a feasible point of the optimization problem given in (4).
We also have $a^3 + a^3 + b^3 > (x_1^3 + x_2^3 + x_3^2) \Longleftarrow (x_2-x_3)^2(x_1-x_3)^2(x_1-x_2)^2 > 0.$
Thus, we have $a^3 + a^3 + b^3 + x_4^3 + x_5^3 + \cdots + x_m^3 > x_1^3 + x_2^3 + x_3^3 + x_4^3 + x_5^3 + \cdots + x_m^3.$
Thus, $(a, a, b, x_4, x_5, \cdots, x_m)$ is strictly better than $(x_1, \ x_2, \cdots, x_m)$.
This contradicts the optimality of $(x_1, \ x_2, \cdots, x_m)$.
2) If $D > 0$, let
$$u = \frac{x_1+x_2+x_3}{2} - \frac{1}{8} + \frac{1}{8}\sqrt{D}\,,$$
$$v = \frac{x_1+x_2+x_3}{2} - \frac{1}{8} - \frac{1}{8}\sqrt{D}\,.$$
We have $x_1 + x_2 + x_3 = \frac{1}{4} + u + v, \ x_1^2+x_2^2+x_3^2 = (\frac{1}{4})^2 + u^2 + v^2.$
It follows from $D>0$ and $0 < x_1 < x_2 < x_3 < \frac{1}{4}$ that
$$x_1+x_2+x_3\ge \frac{1}{4},$$
$$x_1^2+x_2^2+x_3^2 \ge \frac{1}{16},$$
$$16(x_1x_2+x_1x_3+x_2x_3) - 4(x_1+x_2+x_3) + 1\ge 0,$$
$$16(x_1x_2 + x_1x_3 + x_2x_3) - 8(x_1+x_2+x_3) + 3 > 0,$$
$$-192x_1x_2x_3 + 48(x_1x_2+x_1x_3+x_2x_3) - 12(x_1+x_2+x_3) + 3 > 0.$$
With these facts, we have $0 \le v \le u \le \frac{1}{4}$ and $(\frac{1}{4})^3 + u^3 + v^3 > x_1^3 + x_2^3 + x_3^3.$
Thus, $(\frac{1}{4}, u, v, x_4, x_5, \cdots, x_m)$ is a feasible point of the optimization problem given in (4)
and is strictly better than $(x_1, \ x_2, \cdots, x_m)$.
This contradicts the optimality of $(x_1, \ x_2, \cdots, x_m)$. This completes the proof of the claim.