text:
Q: (Python) Alternating inputs from a binary tree? So I've just begun the meat and potatoes of my degree and I'm learning Python. One of our assignments this week was to use a binary tree and add guests, allowing the tree to alternate left and right, then print the names of left and right aisle guests.
Our professor gave us some sample code to work with, and I made a few changes to have it do what I wanted to do with it. Here's what I have:
guestnumber = 0
class Node:
    def __init__(self):
        self.left = None
        self.right = None
        self.data = list()

def guestadd(root, Guest):
    if Guest <= root.data[0]:
        if root.left == None:
            root.left = Node()
            root.left.data.append(Guest)
        else:
            guestadd(root.left, Guest)
    else:
        if Guest >= root.data[0]:
            if root.right == None:
                root.right = Node()
                root.right.data.append(Guest)
            else:
                guestadd(root.right, Guest)

def printlist(root):
    if root == None:
        return
    print(root.data)
    printlist(root.left)
    printlist(root.right)

print("Enter guest names for seating arrangements. (Max = 50)")
guestnumber = int(input("How many guests are attending?"))
root = Node()
root.data.append("Guest")
for i in range (0,guestnumber):
    guestadd (root, input("Name:"))

print("Left Aisle:")
printlist(root.left)
print("Right Aisle:")
printlist(root.right)

At first glance, everything works as intended, but I noticed I was given inconsistent results where it didn't split the names evenly. After sleeping on it, I did some more troubleshooting and discovered that, no matter what order I put the data in, it would always put 0-9, A-G, and a handful of special characters on the left node, and H-Z, a-z, and another handful of special characters on the right side.
I've already handed in what I have, along with several screenshots of my discoveries, so I'm sure I'll be given full credit, given that's it's an introductory course. But it's bugging me that I can't get get it to do what I want consistently.
My best guess is that it has something to do with where the characters lie on an ASCII chart. Everything from 0-71 was on the left,  and 72-127 on the right. How would I go about getting my program to treat the strings as just that and not thinking of it in ASCII?
NOTE: If I was given this task to separate guests, I wouldn't use a tree. I'd probably use something that just adds names to an list, then use a [::2] and [1::2] slice to alternate sides. However, since the assignment was to learn how to use a binary tree, I wanted to stay with the constraints of the lesson

A: You have nothing in your code about alternating left and right. You've built a binary search tree with "Guest" at the root. Anyone whose name comes before "Guest" in Unicode-lexicographic order goes on the left, and anyone whose name comes after "Guest" in Unicode-lexicographic order goes on the right.


text:
Q: unity c# countdown timer for dynamic times I've worked out how to make a countdown timer. I would like to make a timer that counts minutes and seconds that I specify in the inspector. when I click an object the timer gets reduced by a few minutes and/or seconds. I will decide a little later. below is my code. Thanks!
using UnityEngine;
using System.Collections;

public class controllerScript : MonoBehaviour {

    public GUIText timerText;
    public float minutes;

    void Start(){
        timerText.text = "";
    }

    void Update(){
        if (Input.GetMouseButtonDown(0)){
            Debug.Log("pressed left click, casting ray");
            CastRay();
        }

        minutes -= Time.deltaTime;
        timerText.text = minutes.ToString("f0") + "";
    }

    void CastRay(){
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);

        //start statements for what happens when Objects are clicked
        if (hit.collider.gameObject.name == "target01"){
            Debug.Log("you've click obj 1, good work.");

        }
        if (hit.collider.gameObject.name == "target02"){
            Debug.Log("well that's obj 2, even better!");
        }
    }

}

A: Dont know, what exact is your question,
but you should realize, that Time.deltaTime is time in seconds and not in minutes.
So you should change the line
minutes -= Time.deltaTime;

to
minutes -= Time.deltaTime / 60.0;

redpajama_set_name: RedPajamaStackExchange


text:
Q: docker-compose lock my local folder when installing wordpress I am trying to install wordpress using docker-compose, everything runs perfectly but I have a lock issue for the current folder on my machine when I mount it using docker-compose..
here is my docker-compose.yaml
version: '3.3'

services:
db:
 image: mysql:5.7
 volumes:
   - db_data:/var/lib/mysql
 restart: always
 environment:
   MYSQL_ROOT_PASSWORD: somewordpress
   MYSQL_DATABASE: wordpress
   MYSQL_USER: wordpress
   MYSQL_PASSWORD: wordpress

 wordpress:
 depends_on:
   - db
 image: wordpress:latest
 ports:
   - "8000:80"
 restart: always
 environment:
   WORDPRESS_DB_HOST: db:3306
   WORDPRESS_DB_USER: wordpress
   WORDPRESS_DB_PASSWORD: wordpress
 volumes:
  - ./wp-content:/var/www/html/wp-content
volumes:
  db_data:

and here is how the folder is locked

The owner of wp-content is not the root, this happened because it's created using the docker-compose, I tried to change the owner but the connection to db failed!

A: as you can see there is a shared volume between the container and the folder:
 volumes:
  - ./wp-content:/var/www/html/wp-content

you can stop the container in order to change folders contents

A: After you stop container:
sudo chown -R <username>:<username> folder_name/

A: We run the docker compose file that adds the volume data in your local folder with the owner of the content being systemadmin. So, this folder is locked. Please, change the owner of the folder and then you can access the content. Remove the lock symbol too.
sudo chown -R hostname:hostname folder_name


text:
Q: Is Octavian making a huge mistake [spoilers for First Lord's Fury] At the end of First Lord's Fury, Octavian asks Alera (basically a manifestation of the spirits of the land) how to change the way furycrafting works.  Specifically, he asks for two changes:

*

*That one be able to increase one's furycrafting strength via will and practice, instead of being strongly controlled by birth

*That the other races of Carna -- Icemen, Marat, Canem -- be able to develop conscious crafting
I get point 1, this is a pretty decent egalitarian move.  But point two strikes me as ... counterproductive in a number of ways.  Furycrafting was one of humanity's key levelers against these other races which are stronger and longer-lived than humans.  I understand that he wants to make friends with the other peoples of Carna, but isn't this a bit much?
Especially the Canem; they can live for centuries, now they can increase their furycrafting strength over all that time.  Octavian may have created our new wolf-sorceror overlords here.
What am I overlooking here?  What is the benefit of point 2 besides weakening Alerans relative to other races?

A: No—in fact, this move is both fair and exceedingly shrewd
First of all, it's easy to see why someone would want to make such a move on purely egalitarian grounds. Why not grant the same opportunities to each species, to whatever extent possible? That very principle is the foundation of many modern societies. Tavi can't make humans live as long as the Canim, but he can at least give everyone an even playing field as far as furycrafting is concerned.
Besides, I see no reason to conclude from the text that someone's furycrafting can continue growing without bound for centuries. There's probably still a limit; it's just that now everyone can theoretically reach it.
Finally, I think it's implied that, until the vord invasion, the Canim really did always have the numbers to conquer Alera, but simply didn't do it due to internal reasons. Their continent was enormous and had huge cities. So what else is new, even if the Canim can become more powerful?
But there are certainly very practical reasons to support such a plan.
Quid Pro Quo
Tavi believes that if the various races of Carna share what they know with each other, all will benefit. He believes that the Canim have something to give humans, as the Marat did.

"I cannot say the same," Alera responded. "For which I find myself…
  somewhat grateful. It would be awkward." She inhaled slowly, then
  nodded. "Are you sure you wish to continue on the path you have
  begun?"
"Well. You say I introduced you to Kitai, without realizing it,
  because of our bond. That's why you can speak to her."
"Indeed."
"Then you should trust me. Interaction with the other Marat will be
  just as rewarding, on some level. As it will with the Canim. And the
  Icemen are already watercrafting, whether they realize it or not. It's
  hardly any change at all."

He's probably right, too: the Canim and Icemen have their own sorcery, which the humans can benefit from learning. As with trade in the real world, though some may suffer, and certainly some will benefit disproportionately, there's generally a net benefit to both parties. And links with the Marat offer their own possibilities.
Who wants to die?
The Vord are going to come to Alera. As Alera herself says:

"You have a century and a half, by my estimation. Perhaps two. And
  then the Canean vord queen will come for you."
Tavi nodded. "Then I'll make us ready. Or get us part of the way
  there, at least."

The Canem vord queen won't have the furycrafting prowess of her counterpart, but she'll have numbers beyond anything Alera has seen before. The Canem continent and its resources were enormous.
When an existential threat is knocking on your door, do you want more furycrafters, or fewer? It's what is colloquially called "a no-brainer."
Besides, if the humans give their sorcery to the Canim and others, they buy goodwill, and (in keeping with the above points), are more likely to be granted the Canim and Icemen and Marat's secrets.
And then everyone wins. Or at least doesn't get assimilated by the vord. And honestly, that's what they're aiming for at this point.

A: Tavi's strategy is trying to create a stronger Alera.  There are two components you should consider, the past, and the future -

*

*Holding furycrafting for Aleran humans only did not keep Alera unified or strong. The kingdom was already falling apart quite well with humans - specifically, certain families - having the reins of ultimate power.  The lack of change and lack of any dire threat once the bulk of the continent was secure let multiple High Lords ambitions fester until Kalare cracked the nation.  If that hadn't happened, Alera might have stood against the Vord without losing over half their cities and countless lives.  Tavi needs to redistribute the power of furycrafting, or the Aleran nation will simply repeat old patterns.

*He needs Alerans to have enemies - in the Canim fashion - or they won't learn.  Tavi's greatest strength is learning and adapting - and recruiting - his enemies.  It's something the Canim truly appreciate, an enemy that is strong enough to beat you but honors and respects you.  This is just what the Canim bring to the table of ideas - the Marat and Icemen have plenty to teach Alerans too.  What Tavi is doing is applying his method of learning to the entire nation.  Alerans under this new system will be working side-by-side - and competing - with races that will force humans to learn from them or be left behind.  Alerans need to relearn skill, like Tavi did, not just power... and now skill is power.
All of this is for the inevitable return of the Vord.  The Canea Vord will eventually come, and will have the resources of a much larger continent to draw from.  This is how Tavi has beaten every enemy bigger than him to date - endure, outhink, outmaneuver, conquer.  Learn and apply every possible advantage, even from your enemies.  He is just trying to apply the conditions that taught him this to his new alliance.


text:
Q: Matlab toolbox, same name function I installed the SPRT toolbox in matlab but can't use the pca() function because there's a function with the same name in Matlab and it has priority. Working on mac (intel).
Thanks in advance.


text:
Q: `when` reserved word in erlang I started off this morning trying to work out what the 'when' statement is used for in erlang. I know the below example is wrong:
do_larger() ->
    io:format("Larger~n").

do_smaller() ->
    io:format("Smaller~n").

when_version(Size) ->
    when Size > 10 -> do_larger(),
    when Size < 10 -> do_smaller().

I decided to look at its implementation in Haskell to see if this would help and I ended up getting even more confused.
Is anyone able to point me at a tutorial (or explain to me) what the when statement is used for and how it's used in haskell and/ or erlang?

A: The when in Erlang is a guard on a clause.  This regards the pattern matching built into Erlang.  Your example must be:
when_version(Size) when Size > 10 ->
    do_larger();
when_version(Size) when Size < 10 ->
    do_smaller().

See Guard Sequences and Function Declaration Syntax in the reference.
For a tutorial read Guards, Guards! in Learn You Some Erlang for Great Good which is a great online Erlang tutorial BTW.


text:
Q: Count consequitive numbers in a string C# I have a string {101110111010001111} I'm searching for the total number of all sequences of equal bits with an exact length of 3 bits. In above string the answer willbe 3 (please note that the last one "1111" doesn't count as it has more than 3 equal bits.
Any suggestions how to do this?

A: If you don't want a simple solution, try this:
string s = "1101110111010001111";
var regex = new Regex(@"(.)\1+");
var matches = regex.Matches(s);
int count = matches.Cast<Match>().Where(x => x.Length == 3).Count();

Explanation:

*

*The regex finds sets of 2 or more identical characters (not limited to 0's and 1's)

*Then only sets of exactly 3 characters are counted

A: Is it that you  need? Sometimes the simplest solutions are the best:
public static int Count(string txt)
{
    // TODO validation etc
    var result = 0;
    char lstChr = txt[0];
    int lastChrCnt = 1;

    for (var i = 1; i < txt.Length; i++)
    {
        if (txt[i] == lstChr)
        {
            lastChrCnt += 1;
        }
        else
        {
            if (lastChrCnt == 3)
            {
                result += 1;
            }

            lstChr = txt[i];
            lastChrCnt = 1;
        }
    }

    return lastChrCnt == 3 ? result + 1 : result;
}

A: You can use a regular expression:
Regex.Matches(s, @"((?<=0)|^)111((?=0)|$)|((?<=1)|^)000((?=1)|$)");

Here's the same expression with comments:
Regex.Matches(s, @"
    (
        (?<=0)           # is preceeded by a 0
        |                # or
        ^                # is at start
    )
    111                  # 3 1's
    (
        (?=0)            # is followed by a 0
        |                # or
        $                # is at start
    )
    |                    # - or -
    (
        (?<=1)           # is preceeded by a 1
        |                # or
        ^                # is at start
    )
    000                  # 3 0's
    (
        (?=1)            # followed by a 1
        |                # or
        $                # is at end
    )", RegexOptions.IgnorePatternWhitespace).Dump();

A: You can split the string by "111" to get an array. You can then simply count the lines that not begins with "1" with the linq.
See the sample:
using System;
using System.Linq;

namespace experiment
{
    class Program
    {
        static void Main(string[] args)
        {
            string data = "{101110111010001111}";
            string[] sequences = data.Split(new string[] {"111"}, StringSplitOptions.None);
            int validCounts = sequences.Count(i => i.Substring(0, 1) != "1");
            Console.WriteLine("Count of sequences: {0}", validCounts);
            // See the splited array
            foreach (string item in sequences) {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}

A: Yet another approach: Since you are only counting bits, you can split the string by "1" and "0" and then count all elements with lenght 3:
string inputstring = "101110111010001111";
string[] str1 = inputstring.Split('0');
string[] str2 = inputstring.Split('1');
int result = str1.Where(s => s.Length == 3).Count() + str2.Where(s => s.Length == 3).Count();
return result

A: An algorithmic solution. Checks for any n consecutive characters. But this is not completely tested for all negative scenarios.
public static int GetConsecutiveCharacterCount(this string input, int n)
{
   // Does not contain expected number of characters
   if (input.Length < n || n < 1)
      return 0;

   return Enumerable.Range(0, input.Length - (n - 1)) // Last n-1 characters will be covered in the last but one iteration.
                    .Where(x => Enumerable.Range(x, n).All(y => input[x] == input[y]) && // Check whether n consecutive characters match
                                ((x - 1) > -1 ? input[x] != input[x - 1] : true) && // Compare the previous character where applicable
                                ((x + n) < input.Length ? input[x] != input[x + n] : true) // Compare the next character where applicable
                     )
                    .Count();
}


text:
Q: setting dns cache to give internal address responses to my domain requests for my externally accessible server I'm having trouble trying to find anything on the internet explaining how to do this...
I'm running Ubuntu 14.04 with repository current Bind9
I have a authoritative DNS server hosting my domain and my web/mail server on my network behind a single static external IP address that is shared by all the other computers in the building.
I have a DNS caching setup on a 2nd machine for all my out going DNS requests and I would like  it so that when I type www.my.domain, the DNS cache will give the internal IP of the web-server instead of the external IP.
I haven't been about to find any information on how to do this, but I don't think I'm searching for the correct terminology.
i tried just adding the addresses to the /etc/hosts file and this doesn't work for the rest of the network.
i don't know where to look from here, can anyone point me in the correct direction.
thanks.

A: The search term you're looking for is "split DNS" or "split views". It's generally regarded as a bad idea due to the management headaches that end up being created by it in the long term.
You may wish to consider creating a privately forwarded subdomain that is not exposed on the internet.  (i.e. int.example.com, something under a domain you own) Put your DNS records for private IP addresses in this domain. It will not solve the problem of making www.example.com selectively return the private IP -- this should usually be solved on individual systems -- but it will at least give you dedicated DNS records for your private network.

A: You can use Unbound which supports exactly what you want to do. It would replace BIND, and your configuration would look something like this;
local-zone: "example.com." transparent
local-data: "server1.example.com. IN A 192.168.0.10"
local-data: "server2.example.com. IN A 192.168.0.11"
local-data: "serverN.example.com. IN A 192.168.0.12"

What this does;

*

*Define the zone 'example.com'.

*transparent refers to a mode that will pass through to external/forwarder nameservers if it doesn't have a local-data record that matches.

*local-data defines the records you'd like to override internally. server1.example.com could have an external IP address of 1.2.3.4, but to any clients using this DNS server, it would appear to them as 192.168.0.10.

I've used this several times before on large office networks, and it works flawlessly. You can also define many local-zone definitions to override as many domains as you would like.


text:
Q: is UNC S.M.A.R.T. Error serious? need to take action? I have a 300G Western Digital Raptor, recently showing UNC SMART, wondering anyone who has experience knows should I replace it and get warranty form WD?
Details of smartctl -a as follows:
smartctl 5.41 2011-06-09 r3365 [FreeBSD 8.2-RELEASE-p6 amd64] (local build)
Copyright (C) 2002-11 by Bruce Allen, http://smartmontools.sourceforge.net

=== START OF INFORMATION SECTION ===
Model Family:     Western Digital VelociRaptor
Device Model:     WDC WD3000HLFS-01G6U0
Serial Number:    WD-WXD0C79C8807
LU WWN Device Id: 5 0014ee 0ac3cfaf0
Firmware Version: 04.04V01
User Capacity:    300,069,052,416 bytes [300 GB]
Sector Size:      512 bytes logical/physical
Device is:        In smartctl database [for details use: -P show]
ATA Version is:   8
ATA Standard is:  Exact ATA specification draft version not indicated
Local Time is:    Thu Apr 19 16:03:33 2012 CST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x84) Offline data collection activity
                    was suspended by an interrupting command from host.
                    Auto Offline Data Collection: Enabled.
Self-test execution status:      (   0) The previous self-test routine completed
                    without error or no self-test has ever
                    been run.
Total time to complete Offline
data collection:        ( 4800) seconds.
Offline data collection
capabilities:            (0x7b) SMART execute Offline immediate.
                    Auto Offline data collection on/off support.
                    Suspend Offline collection upon new
                    command.
                    Offline surface scan supported.
                    Self-test supported.
                    Conveyance Self-test supported.
                    Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                    power-saving mode.
                    Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                    General Purpose Logging supported.
Short self-test routine
recommended polling time:    (   2) minutes.
Extended self-test routine
recommended polling time:    (  59) minutes.
Conveyance self-test routine
recommended polling time:    (   5) minutes.
SCT capabilities:          (0x303f) SCT Status supported.
                    SCT Error Recovery Control supported.
                    SCT Feature Control supported.
                    SCT Data Table supported.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x000f   195   195   051    Pre-fail  Always       -       49036
  3 Spin_Up_Time            0x0003   199   196   021    Pre-fail  Always       -       3008
  4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       425
  5 Reallocated_Sector_Ct   0x0033   200   200   140    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x000e   200   200   000    Old_age   Always       -       0
  9 Power_On_Hours          0x0032   086   086   000    Old_age   Always       -       10292
 10 Spin_Retry_Count        0x0012   100   100   000    Old_age   Always       -       0
 11 Calibration_Retry_Count 0x0012   100   100   000    Old_age   Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       404
192 Power-Off_Retract_Count 0x0032   200   200   000    Old_age   Always       -       268
193 Load_Cycle_Count        0x0032   200   200   000    Old_age   Always       -       426
194 Temperature_Celsius     0x0022   117   100   000    Old_age   Always       -       30
196 Reallocated_Event_Count 0x0032   200   200   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0012   200   200   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0010   200   200   000    Old_age   Offline      -       4
200 Multi_Zone_Error_Rate   0x0008   200   200   000    Old_age   Offline      -       1

SMART Error Log Version: 1
ATA Error Count: 749 (device log contains only the most recent five errors)
    CR = Command Register [HEX]
    FR = Features Register [HEX]
    SC = Sector Count Register [HEX]
    SN = Sector Number Register [HEX]
    CL = Cylinder Low Register [HEX]
    CH = Cylinder High Register [HEX]
    DH = Device/Head Register [HEX]
    DC = Device Command Register [HEX]
    ER = Error register [HEX]
    ST = Status register [HEX]
Powered_Up_Time is measured from power on, and printed as
DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,
SS=sec, and sss=millisec. It "wraps" after 49.710 days.

Error 749 occurred at disk power-on lifetime: 6972 hours (290 days + 12 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 51 00 44 cb 53 40  Error: UNC at LBA = 0x0053cb44 = 5491524

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 40 10 a6 4e 58 01 08      00:16:23.812  READ FPDMA QUEUED
  60 08 10 9e 32 5b 00 08      00:16:17.646  READ FPDMA QUEUED
  60 08 10 9e 32 5b 00 08      00:16:17.645  READ FPDMA QUEUED
  ef 02 00 00 00 00 00 08      00:16:17.645  SET FEATURES [Enable write cache]
  60 08 10 9e 32 5b 00 08      00:16:11.412  READ FPDMA QUEUED

Error 748 occurred at disk power-on lifetime: 6972 hours (290 days + 12 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 51 00 44 cb 53 40  Error: UNC at LBA = 0x0053cb44 = 5491524

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 08 10 9e 32 5b 00 08      00:16:11.412  READ FPDMA QUEUED
  60 08 10 9e 32 5b 00 08      00:16:11.412  READ FPDMA QUEUED
  ef 02 00 00 00 00 00 08      00:16:11.412  SET FEATURES [Enable write cache]
  60 00 30 1e cb 53 06 08      00:16:05.199  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:16:05.180  READ FPDMA QUEUED

Error 747 occurred at disk power-on lifetime: 6972 hours (290 days + 12 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 51 00 44 cb 53 40  Error: UNC at LBA = 0x0053cb44 = 5491524

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 00 30 1e cb 53 06 08      00:16:05.199  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:16:05.180  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:16:05.178  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:16:05.178  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:16:05.178  READ FPDMA QUEUED

Error 746 occurred at disk power-on lifetime: 6972 hours (290 days + 12 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 51 00 44 cb 53 40  Error: UNC at LBA = 0x0053cb44 = 5491524

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 00 30 1e cb 53 06 08      00:15:58.945  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:15:58.945  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:15:58.945  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:15:58.945  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:15:58.944  READ FPDMA QUEUED

Error 745 occurred at disk power-on lifetime: 6972 hours (290 days + 12 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 51 00 44 cb 53 40  Error: UNC at LBA = 0x0053cb44 = 5491524

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 00 30 1e cb 53 06 08      00:15:52.727  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:15:52.727  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:15:52.727  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:15:52.727  READ FPDMA QUEUED
  60 00 30 1e cb 53 06 08      00:15:52.726  READ FPDMA QUEUED

SMART Self-test log structure revision number 1
No self-tests have been logged.  [To run self-tests, use: smartctl -t]

SMART Selective self-test log data structure revision number 1
 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
    1        0        0  Not_testing
    2        0        0  Not_testing
    3        0        0  Not_testing
    4        0        0  Not_testing
    5        0        0  Not_testing
Selective self-test flags (0x0):
  After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.

A: Read errors can be caused by something as simple as losing power during a write operation. Alone, they don't suggest any hardware issues with the drive.

A: Do the replace if you can.
On the other hand these are 'only' read errors which is not that bad. If you write to that sector then you can be only sure if it has defects.
I would run the vendors utility to check (they also run smart tests) if it has problems. They usually make bootable cds available.
You can and should run a self test which you can do from linux by issuing
smartctl -t long /dev/your-device

wait a couple of hours (it will show an estimate). Then check again with
smartctl -a /dev/your-device

If it says Completed without errors you are fine. If not go for the vendors utility to check the drive.


text:
Q: Hibernate self join exception: No row with the given identifier exists I have a table as following
CREATE TABLE labour_no_pk (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  name varchar(255) DEFAULT NULL,
  labour_id bigint(20) NOT NULL,
  contractor_id bigint(20) DEFAULT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY labour_id_UNIQUE (labour_id),
  KEY FK_SELF_idx (contractor_id),
  CONSTRAINT FK_SELF FOREIGN KEY (contractor_id) REFERENCES labour_no_pk (labour_id) ON DELETE CASCADE ON UPDATE CASCADE
);
Class as
@Entity
@Table(name = "LABOUR_NO_PK")
public class LabourNoPK {
    @Id
    @Column(name = "id")
    @GeneratedValue
    private Long id;

    @Column(name = "firstname")
    private String firstName;

    @ManyToOne(cascade = { CascadeType.ALL })
    @JoinColumn(name = "labour_id")
    private LabourNoPK contractor;

    @OneToMany(mappedBy = "contractor")
    private Set<LabourNoPK> subordinates = new HashSet<LabourNoPK>();
}

DAO as
public static List<LabourNoPK> getLabours(Session session) {
        List<LabourNoPK> labours = null;
        try {
            Query query = session.createQuery("FROM LabourNoPK where contractor_id is null");
            labours = query.list();
            for (LabourNoPK labour : labours) {
                System.out.println("parent=" + labour.toString());
                if (null != labour.getSubordinates() && !labour.getSubordinates().isEmpty()) {
                    for (LabourNoPK subordinate : labour.getSubordinates()) {
                        System.out.println("Sub=" + subordinate.toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return labours;
    }

I have data as

when I run the program, i am getting org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [LabourNoPK#100] but there's a record available in DB.
I understood (from exception message) my model class pointing to id instead of contractor_id. How should I map to get the results all parents with childs?
What exactly i am missing?
thanks in advance

A: After a lot of reading and trials I am able achieve what I want. So posting if somebody needs the same way.
@Entity
@Table(name = "LABOUR_NO_PK")
public class LabourNoPK implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue
    private Long id;

    @Column(name = "labour_id")
    @NaturalId
    private Long labourId;

    @Column(name = "firstname")
    private String firstName;

    @OneToMany(mappedBy="labour")
    private Set<LabourNoPK> subordinates = new HashSet<>();

    @ManyToOne
    @JoinColumn(name = "contractor_id", referencedColumnName = "labour_id")
    /* child (subordinate) contractor_id will be matched with parent (labour) labour_id*/
    private LabourNoPK labour;

}


text:
Q: Android listview firstscreen's item animation no effect I have a listview in an activity, each listview item have a viewswitcher and there are two child view in viewswitcher. I set the viewswitcher's android:inAnimation and android:outAnimation property in layout xml. When I run the app, I find that the listview's fristscreen have no animation effect when the viewswitcher switch its child view , but the other item witch no in the fristscreen have animation effect .
What cause this problem? How to fix it?


text:
Q: Store Hive output as textfile I am creating a external table as follows
SET hive.exec.dynamic.partition = true;
SET hive.exec.dynamic.partition.mode = nonstrict;
SET hive.exec.compress.output=false;

CREATE EXTERNAL TABLE IF NOT EXISTS result_table (uid STRING) partitioned by (pub_year STRING, edition_code STRING)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '|'
STORED AS TEXTFILE
LOCATION 's3://bucket_name/output_new/';

insert overwrite table result_table partition (pub_year, edition_code) select uid, pub_year, edition_code from combined_union_table;

The "Type" in s3browser is "File" and not "txt".
but when i describe the table it says
"OutputFormat:           org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat"
The result files are used by shell scripts which cant read part files,
How can i get the final results stored in ".txt" format?
Note: hive version = Hive 2.1.0-amzn-0


text:
Q: Automatic UTF-8 encoding in Node.js HTTP client There I am trying to load XML content from a remote host using Node.js.
The problem is that German "umlaute" like "ä" are broken. Like in the browser this usually is a simple encoding problem. But since the XML content on the remote host is encoded in iso-8859-2" I had no success getting the letters back to work.
The functionality is very simple. I simply use the default HTTP client integrated in Node.js to connect to a remote host with a simple get request.
Some environment facts:

*

*The remote system uses "iso-8859-2" encoding.

*The encoding is currently set in the response header.

*The characters are unrecoverable broken in the data (chunk) received by response.onData(chunk)
Node.js is running on version 0.2 on da default Debian server.
The code is based on the default httpClient like described in the Node.js documentation.
I tried the following:
response.defaultAsciiEncoding true/false
response.encoding = UFT-8/ascii

I used a UTF-8 encoder/decoder to encode/decode the chunk. After this failed I tried to encode/decode the whole response body.
I am not very familiar with using buffers, and I guess the problem must be in that direction. Or Node.js (or the httpClient) simply can't handle other encoding types by default witch is my second guess. In this case I need to write my own HTTP client using the net lib I think. I just want to make sure I don't walk into the wrong direction :)

A: Try setting the encoding parameter in the XML declaration:
<?xml version="1.0" encoding="iso-8859-2" ?>
<xml>
  <!-- whatever -->
</xml>

XML files default to UTF-8 unless you explicitly declare their encoding.

A: It seems to me that Node.js can't work with encoding other than UTF-8. Maybe using something like node-iconv should work.

A: I had a quick poke around the Node.js source and it seems like svick is right: Node.js doesn't support the ISO encoding. You can, however, get at the response as a binary stream and then either return it to the browser with your own encoding or use node-iconv (again as svick suggested).
Here's a little example: http://gist.github.com/576884


text:
Q: Use Handler To Post In To UI Thread I am working on an android application, that fetches image from Internet and show in the user interface. I am using RecyclerView for showing the image. I am planning to download the image using a separate thread. and update RecyclerView via the handler. I dont know wether this concept is correct or not, (I know AsyncTask, but for learning purpose I am trying to implement Handler.)
    So I coded for the same as below
private void loadNewsThumbnailImage(ArrayList<DataItem> dataList) {
    for (DataItem item : DataList) { //DataItem is the model class
        loadThumbnailFromInternet(item);
        }
}

private void loadThumbnailFromInternet(final DataItem dataItem) {

        Thread imageDowloaderThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                try {
                    bitmap = getDataItemBitmap(dataItem.getmImageUrl());
                    dataItem.setmThumbnail(bitmap);
                    new Handler().post(new Runnable() { // Tried new Handler(Looper.myLopper()) also
                        @Override
                        public void run() {
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        imageDowloaderThread.start();

    }

I have executed this code but I am getting error, and application is terminated, I don't know why this is happening . please any one help me to sort it out. and explain what is the problem for the current code.
(Please do not suggest to use AsyncTask (I have tried that and it works fine))
UPDATE
Error getting :java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

A: Your application is getting terminated because you are calling notifyDataSetChanged() from a non UI Thread.
Replace:
 new Handler().post(new Runnable() { // Tried new Handler(Looper.myLopper()) also
                        @Override
                        public void run() {
                            mAdapter.notifyDataSetChanged();
                        }
                    });

With this:
new Handler(Looper.getMainLooper()).post(new Runnable() { // Tried new Handler(Looper.myLopper()) also
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                    }
                });

A: The thread you defined does not have a Looper, and no message queue,so you can not send message in this thread. AsyncTask has its own Looper which you can find it in its source code. This is handler defined in AsyncTask:
private static class InternalHandler extends Handler {
    public InternalHandler() {
        super(Looper.getMainLooper());
    }

    @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
    @Override
    public void handleMessage(Message msg) {
        AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
        switch (msg.what) {
            case MESSAGE_POST_RESULT:
                // There is only one result
                result.mTask.finish(result.mData[0]);
                break;
            case MESSAGE_POST_PROGRESS:
                result.mTask.onProgressUpdate(result.mData);
                break;
        }
    }
}


text:
Q: Modular maths: How do I find the remainder? How do I find the remainder of $5^{22} \pmod{25}$?
And also how do I find the remainder of $3^{16} + 7 \pmod{5}$?

A: I these situations you can apply Fermat's little theorem. It states that if $p$ is a prime that is coprime to $a$, then $a^{p - 1} \equiv 1 \mod p$. For example, in your first case this means $5^{22} = 5^{16} 5^6 \equiv 5^{16} \pmod{7}$.
If you apply this rule multiple times, you can significantly reduce the complexity of this problem. If you apply euclidean division to the exponent and the modulus, you can simplify this to a single step. I hope you can take t from here.

A: Try to see which power of $5$ can give $1$ or $-1$ modulo $7$. This will reduce your computations quite significantly. For example, $5^2 \equiv 4 \pmod{7}$ so $5^3 \equiv 20 \equiv 6 \equiv -1 \pmod{7}$. Thus
$$5^{22} \equiv 5^{21} \cdot 5 \equiv (5^{3})^7 \cdot 5 \equiv -5 \equiv 2 \pmod{7}$$

A: $$5^{22}=5\cdot 5^{21}=5\cdot (5^3)^7\equiv 5\cdot (-1)^7\equiv -5\equiv 2 (mod7).$$
Do the second in a similar way.

A: Well $5^3 = 125 \equiv -1 \pmod {7}$   because $7 \mid 125 - (-1)$
And since ${5}^{3} \equiv -1 \pmod {7}$ then ${(5^3)}^{7} \equiv (-1)^7 \pmod{7}$ and so $5^{21} \equiv -1 \pmod{7}$ and so $5^{22} \equiv -5 \pmod 7$. But since $-5 \equiv 2 \pmod 7$ then $5^{22} \equiv 2 \pmod 7$ as well


text:
Q: Is it possible to use => to define objects? I'm trying to use the arrow-constructor to create an object:
var Countable = (data) => {
    return data;
}

But when creating an object:
new Countable(newSubscriptions)

I get the error
Uncaught TypeError: (data) => {
    return data;
} is not a constructor

I get the expected output by doing
var Countable = function(data) {
    return data;
}

A: Yes, you can use an arrow function to create new objects:
var Countable = () => {
    return {}; // This function returns a new object
};
var o = Countable();

However, you can't instantiate an arrow function, because it doesn't have the [[Construct]] internal method. So using new will throw.


text:
Q: jQuery: Show/Hide based on Radio Boxes from an array I setup two arrays: 1) the class names and the value names 2) the HTML fields that are being effected: such as li, divs etc...
Basically I setup everything to use classes instead of ID's because the # is a coldfusion veriable/function marker which throws up a CFML error. I put everything into arrays to recude the number of $.change(functions) I had to write.
First issue: only 2 fields are getting hidden.
Second issue: when you click on a radio box, nothing shows up.
Any suggestions?
Code:
                <!--- An array of the radio boxes |
                    It's a collection of the class="" of the radio boxes
                    and their values. We're going to loop over this to
                    show/hide fields for the array below.
                 --->
                var classArray = new Array(
                    "appliedWorkedYes",
                    "workStudyYes",
                    "workHistoryYes",
                    "workWeekEndsYes",
                    "cprYes",
                    "aedYes",
                    "aidYes"
                    );
                <!--- An array of the radio boxes extra fields, these will be hidden
                    It's a collection of HTML elements such as span or li that have the
                    class name of each in the array. the idea is on load they will be hidden
                    when you select yes on a radio box they will appear with their extra details.
                 --->
                var classFieldArray = new Array(
                    "appliedWorkedYesHide",
                    "workStudyYesHide",
                    "workHistoryYesHide",
                    "workWeekEndsYesHide",
                    "cprYesHide",
                    "aedYesHide",
                    "aidYesHide"
                    )

        $(document).ready(function() {
                // looping over the class name
                for(var i = 0; i < classArray.length; i++){
                    var fName = classFieldArray[i];
                    var cName = classArray[i];

                        // hiding the fields until selected
                        $("."+fName).css("display","none");
                        // the jQuery fu that shows the fields
                        $("radio[@name=''+cName]").change(function(){
                            if ($("radio[@name=''+cName]:checked").val() == ''+cName)
                                $('.'+fName).show("fast");
                            });
                    }
        });

A: It doesn't look like you are concatinating the cName correctly. Also @ in front of attributes is no longer used. ie:
$("radio[@name=''+cName]")

should be
$("radio[name='"+cName+"']")


text:
Q: Compiling gtk from sources I'm tring to compile gtk+-3.2.0 but I get an error message from ./configure:
checking for GLIB - version >= 2.29.14...
*** 'pkg-config --modversion glib-2.0' returned 2.32.4, but GLIB (2.34.0)
*** was found! If pkg-config was correct, then it is best
*** to remove the old version of GLib. You may also be able to fix the error
*** by modifying your LD_LIBRARY_PATH enviroment variable, or by editing
*** /etc/ld.so.conf. Make sure you have run ldconfig if that is
*** required on your system.
*** If pkg-config was wrong, set the environment variable PKG_CONFIG_PATH
*** to point to the correct configuration files
no
configure: error:
*** GLIB 2.29.14 or better is required. The latest version of
*** GLIB is always available from ftp://ftp.gtk.org/pub/gtk/.

I really have GLIB 2.34.0 (which I have compiled from sources too) but I don't know how to do gtk know the library. I have changed  PKG_CONFIG_PATH to points to path where is the new glib installation and after a ldconfig but makes no difference. by modifing /etc/ld.so.conf I really have no idea how to do.

A: PKG_CONFIG_PATH should contain the path to the directory where the .pc file for the GLib version you want to use is.
Otherwise, use your package manager to detect which package has installed the .pc file that you don't want to use. And remove that package. For example, on an rpm-based distro, run:
strace -eopen pkg-config --modversion glib-2.0 2>&1 | grep "\.pc"

It will return where is located the .pc file detected by pkg-config.
open("/usr/lib64/pkgconfig/glib-2.0.pc", O_RDONLY) = 3

Then detect to which package this file belongs:
rpm -qf /usr/lib64/pkgconfig/glib-2.0.pc

Here's the result on my Mageia 2 system:
lib64glib2.0-devel-2.32.4-1.1.mga2

Removing this package will remove the .pc that gets in the way. However, you should prefer the PKG_CONFIG_PATH method in the case removing the package also tries to remove other dependencies you still want to use.


text:
Q: fill webview2 site getting information in .NET I have a program that I made for myself, in which it helps me in my work in speeding up, but I had problems with a time in filling information on a website https://venus.maringa.pr.gov.br/laudosnew/requerimentos.php, still newbie at this part, but my problem is as follows, on this site I try the data, using code
Dim CNPJ As String = "document.getElementByName('cnpj_empresa').value = '" & FrmAlvara.CNPJMaskedTextBox.Text & "'"
WebView21.ExecuteScriptAsync(CNPJ)

but when running on the site it does not fill in the location, and it seems that the site does not have the "value" when using in VB.net and Web2, in this how can it fill the site automatically?


text:
Q: How to change a column name when the current name is NaT in Pandas I have a data frame df1 with two column Names as NaT
Index    NaT     Nat     2019-01-01 00:00:00
 1        A       B        1
 2        C       D        2

How can I change the name of the NaT columns to "Name1" and "Name2"
Index    Name1    Name2     2019-01-01 00:00:00
 1        A       B        1
 2        C       D        2

I tried the following statements:
df1.rename(columns = {0:'Name1', 1: 'Name2'}) #(doesn't work)

df1.columns.values[0] = 'Name1' #(doesn't work)
df1.columns.values[1] = 'Name2' #(doesn't work)

A: I was having an issue where
df.rename(columns={"NaT": "new_column_name"}, inplace=True) would not work because the column header NaT was actually a value (pd.NaT) and not a string.
In this case, the following code worked.
df.rename(columns={pd.NaT: "new_column_name"}, inplace=True)

A: you could just reassign directly the name of columns:
df1.columns = ['Name1','Name2']

A: You can assign new list from columns names - first from original, next by list and next columns from 4. to last one:
df.columns = df.columns[:1].tolist() + ['Name1', 'Name2'] + df.columns[3:].tolist()
print (df)
   Index Name1 Name2  2019-01-01 00:00:00
0      1     A     B                    1
1      2     C     D                    2

Or if first column is index then reassing list with columns from 3. to last one:
df.columns = ['Name1', 'Name2'] + df.columns[2:].tolist()
print (df)
      Name1 Name2  2019-01-01 00:00:00
Index
1         A     B                    1
2         C     D                    2

A: You can use set_axis like this:
df_out = df.set_axis(['Name1','Name2',df.columns[-1]], axis=1, inplace=False)
df_out

Output:
  Name1 Name2  2019-01-03 00:00:00
1     A     B                    1
2     C     D                    2

Edit to answer comment, use slicing of the column header like this:
df = pd.DataFrame(np.arange(100).reshape(10,-1), columns=[*'ABCDEFGHIJ'])

df = df.set_axis(['Name1']+['Name2']+df.columns[-8:].tolist(), axis=1, inplace=False)

Output:
   Name1  Name2   C   D   E   F   G   H   I   J
0      0      1   2   3   4   5   6   7   8   9
1     10     11  12  13  14  15  16  17  18  19
2     20     21  22  23  24  25  26  27  28  29
3     30     31  32  33  34  35  36  37  38  39
4     40     41  42  43  44  45  46  47  48  49
5     50     51  52  53  54  55  56  57  58  59
6     60     61  62  63  64  65  66  67  68  69
7     70     71  72  73  74  75  76  77  78  79
8     80     81  82  83  84  85  86  87  88  89
9     90     91  92  93  94  95  96  97  98  99

A: Edit your  first code to this :
df1.rename(columns = {'NaT':'Name1', 'Nat': 'Name2'})


text:
Q: How to display nested routes in different pages using React Hooks..? React Routing V5 --
Hi, In this Nested react routing, I want to display the 2nd nesting inside Resources page separately when i click the corresponding links. Right now it's displaying inside the Products Id page. Also, I'm using the { match } for some components, is it fine or it needs to be updated.. maybe by using the useParams, but don't know how to do it as i'm lagging knowledge on it. Also, i want to know how to navigate inside the page.. is it done by using Navlink..? I would be thankful for upgrade to any of the codes below. A CodeSandbox would really help.
Link to -> Sandbox
My Code as below:
       //DATA STRUCTURE
          const Data = [
                {
                 name: "LIGHT FITTINGS",
                 id: "1",

                  resources: [
                               {
                                id: "1a",
                                title: "Bulb",
                                specification: "9W",
                                price: 29.9584,
                                countInStock: 19
                                 },
                                 {
                               id: "2a",
                       title: "Tube light",
                       specification: "9W",
                   price: 39.56,
                   countInStock: 24
                    }
                ]
        },
    {
         name: "SWITCH & SOCKETS",
         id: "2",
             resources: [
                          {
                           id: "1b",
                   title: "Switch",
                   specification: "6A",
                   price: 16,
                   countInStock: 15
                },
              {
            id: "2b",
            title: "Socket",
                specification: "16A",
                price: 39.56,
                countInStock: 24
                }
                  ]
    }
       ];
        export default Data;

   //App.jsx

        import React from "react";
        import { BrowserRouter, Route, Switch } from "react-router-dom";
        import HomeScreen from "../screens/HomeScreen";
        import Products from "../screens/Products";

        function App() {
         return (
            <BrowserRouter>

                  <Route path={"/product/:productId"} component={ProductId}/>
                  <Route path="/products" component={Products} />
                  <Route exact path="/" component={HomeScreen} />

            </BrowserRouter>
            );
            }

        export default App;

   //Product
      import React from "react";
      import Data from "../Data";
      import { Link } from "react-router-dom";

      export default function Products() {
        return (

First page

                    {Data.map(({ name, id }) => (

                       <Link to={`/product/${id}`}>{name}</Link>

                    ))}

                 );
             }

   //Product ID page
    import React from "react";
    import Data from "../Data";
    import { Link, Route, useRouteMatch, Switch } from "react-router-dom";
    import Resource from "./Resource";

    export default function ProductId({ match }) {
        let { path, url } = useRouteMatch();

     const productItem = Data.find(({ id }) => id === match.params.productId);
        return (

ProductId page

{productItem.name}

                    {productItem.resources.map((sub) => (

                        <Link to={`${url}/${sub.id}`}>{sub.title}</Link>

                ))}

                <Route path={`${path}/:subId`} component={Resource} />

         );
         }

    //Resource Page

        import React from "react";
        import Data from "../Data";
        //import { useParams, useRouteMatch } from "react-router-dom";

            export default function Resource({ match }) {
             //let match = useRouteMatch();
            //let { subId } = useParams();

        const productItem = Data.find(({ id }) => id === match.params.productId)
                    .resources.find(({ id }) => id === match.params.subId);

        return (

Resource Page

{productItem.title}

{productItem.price}

                         More Info.

            );
            }

A: Solution

*

*Add exact in the Route for productId so that all sub routes can be handled separately.
 <Route exact path={"/product/:productId"} component={ProductId}/>

*Create a new Route pointing to subId.
 <Route path="/product/:productId/:subId" component={Resource} />

This should solve your issue.
Below is the modified codesandbox with working solution.

https://codesandbox.io/s/routing-test-2-forked-k8p64?file=/src/components/App.jsx


text:
Q: how to take an iterable object as a function parameter? (Typescript) example:
function foo(iterable) {
    for (let i of iterable) {}
}

What type could iterable be here asides from any?
other examples include Array.from and most of the other iterable data structure constructors.

A: Iterable is an ES6 feature, so setting your tsc target to "es6" lets you take in an Iterable as a parameter, e.g.
function foo<T>(iterable: Iterable<T>) {
    for (let i of iterable) {}
}

A: You should tell typescript the type of your parameter, so it could compile:
function foo(iterable:Array<any>) {
    for (let i of iterable) {}
}

Types could iterate


text:
Q: gRPC response headers based on the incoming value I need to send the response headers for the gRPC request based on the incoming value. The way of doing this is by using ServerInterceptor. But here I'm a bit stuck. I'm able to intercept the incoming value using ForwardingServerCallListener.SimpleForwardingServerCallListener#onMessage, but I don't see the way to put this value into the context and read it in the ForwardingServerCall.SimpleForwardingServerCall#sendHeaders.
Here is my code:
public class FooInterceptor implements ServerInterceptor {

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
        var serverCall = new ForwardingServerCall.SimpleForwardingServerCall<>(call) {
            @Override
            public void sendHeaders(Metadata headers) {
                //Here I should get the value from the context and add it to the headers
                //var foo = CONTEXT_KEY.get("foo");
                //headers.put(METADATA_KEY, foo);
                super.sendHeaders(headers);
            }
        }
        ServerCall.Listener<ReqT> listenerWithContext = Contexts
                .interceptCall(Context.current(), serverCall, headers, next);
        return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(listenerWithContext) {
            @Override
            public void onMessage(ReqT message) {
                if (message instanceof FooRequest) {
                    var foo = ((FooRequest) message).getFoo();
                    //How to add it to context?
                }
                super.onMessage(message);
            }
        };
    }
}

So the problem is in the method ForwardingServerCallListener.SimpleForwardingServerCallListener#onMessage I'm able to get the value from the message, but I'm not able to rewrite the context there with the new value.
Any ideas/suggestions would be appreciated very much!

A: I found a workaround, it's not the most elegant solution, but it seems to work. Will post it here since there are no other answers yet.
I've managed to pass the value using the requests headers.
So, in ForwardingServerCallListener.SimpleForwardingServerCallListener#onMessage I'm setting the value to the request headers and inside the ForwardingServerCall.SimpleForwardingServerCall#sendHeaders I write it the value from the request headers and write it to the response headers.
Here is the code:
public class FooInterceptor implements ServerInterceptor {

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
        var serverCall = new ForwardingServerCall.SimpleForwardingServerCall<>(call) {
            @Override
            public void sendHeaders(Metadata responseHeaders) {
                var foo = headers.get(Metadata.Key.of("x-value"), Metadata.ASCII_STRING_MARSHALLER));
                responseHeaders.put(Metadata.Key.of("x-value"), Metadata.ASCII_STRING_MARSHALLER), foo);
                super.sendHeaders(responseHeaders);
            }
        }
        ServerCall.Listener<ReqT> listenerWithContext = Contexts
                .interceptCall(Context.current(), serverCall, headers, next);
        return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(listenerWithContext) {
            @Override
            public void onMessage(ReqT message) {
                if (message instanceof FooRequest) {
                    var foo = ((FooRequest) message).getFoo();
                    headers.put(Metadata.Key.of("x-value"), Metadata.ASCII_STRING_MARSHALLER), foo);
                }
                super.onMessage(message);
            }
        };
    }
}


text:
Q: Getting information about multiple URLs in one request from Facebook, Twitter, Google+, and LinkedIn With Facebook, you can do this:
http://api.facebook.com/method/fql.query?format=json&query=SELECT total_count FROM link_stat WHERE url="http://stackoverflow.com OR url="http://stackexchange.com" OR url="http://example.com"

However, with Twitter, Google, and LinkedIn, I can only figure out how to get information about one URL at a time. Here are the URLs (took me a while to find):
http://urls.api.twitter.com/1/urls/count.json?url=http://example.com

https://clients6.google.com/rpc (Google uses a POST request)

http://www.linkedin.com/cws/share-count?url=http://example.com

How can I get information about multiple URLs in one request from Twitter, Google+, and LinkedIn

A: One HTTP request is directed at only 1 url.  How else would an HTTP request get routed to the correct place if it couldn't figure out the IP address of where to send the request?
You do have a solution.  Write a web service on your server such as http://www.example.com/ajax/GetAllAtOnce.asmx.  In your server-side code, you create four web requests, gather back the information and send it back to the client.


text:
Q: RandomForest factor with too many levels I have a model with about 200,000 training observations, where I am regressing, with 4 factors and 2 continuous variables.  One of my features has 927 levels, which is causing the R implementation of randomForest to fail (it has a limit of 32 levels for any feature).  Unfortunately, I don't see a simple way to avoid using this factor, or to decompose it into a series of continuous variables.  Since my predictors are a mix of categorical and continuous, I thought of trees.  Can anyone suggest a different implementation (package or language), ML approach, or a better way to pre-process or massage my inputs?

A: I'm not an R user, but some general comments about random forest
Discrete features can be treated two ways depending on their property

*

*if they have a clear ordering, eg year, (bad/med/good) result, then you can just treat them as continuous.

*if they can't, eg gender,company name, then they should be dummy'd.

A: You might try representing that one column differently. You could represent the same data as a sparse dataframe with dummy variables.
Minimum viable code;
example <- as.data.frame(c("A", "A", "B", "F", "C", "G", "C", "D", "E", "F"))
names(example) <- "strcol"

for(level in unique(example$strcol)){
      example[paste("dummy", level, sep = "_")] <- ifelse(example$strcol == level,     1, 0)
}

A: Have you tried cforest in party package? I know it can handle more than 30-40 levels but I am not sure about 900 levels.
http://www.inside-r.org/packages/cran/party/docs/cforest

A: You can use sklearn (python) and use OneHotEncoding.
OneHotEncoder basically creates one column per each level for a categorical variable (927 in your case). There created columns can take only 0 or 1 as values. This method by definition puts no limit on the number of levels. However, it does not capture the interaction between levels the same way as R does. The reason cforest doesn't allow you to have more than 30 levels is the huge number of permutations (~2^30).
Sklearn aside, I suggest finding a way to reduce your number of levels.


text:
Q: Magento order data not getting using observer event from admin I want item's data in observer from particullar order which order place from admin.
following config.xml
<adminhtml>
    <events>
        <sales_order_place_after>
            <observers>
                <test_module_after_order>
                    <class>Test_Module_Model_Observer</class>
                    <method>orderAfterAdmin</method>
                </test_module_after_order>
            </observers>
        </sales_order_place_after>
    </events>
</adminhtml>

following Observer.php
public function orderAfterAdmin($observer)
{
    Mage::log("orderAfterAdmin");
    try
    {
        $order = $observer->getEvent()->getOrder();
        $productIds = array();
        Mage::log("In orderAfterAdmin");
        Mage::log($observer);
    }
    catch(Exception $e)
    {
        Mage:log($e->getMessage());
    }
}

When I placed order from admin panel at that time I got

User Error: Some transactions have not been committed or rolled back
  in ..\lib\Varien\Db\Adapter\Pdo\Mysql.php on line 3937

error massege when Mage::log($observer) occur. system.log print In orderAfterAdmin but not next step.


text:
Q: Is it possible to profile only certain packages using GHC's profiler? Is it possible to only generate cost-centres for functions defined in certain packages? I'm not sure if this question actually makes sense from a technical viewpoint, in that case please enlighten me. What I'm interested in, essentially, is to get profiler output that only shows cost-centres for bindings in my own packages. Is this possible?
Alternatively I'd like to be able exclude cost-centres from some packages. Is this possible?


text:
Q: How to handle ajax call in laravel controller functions I perform an ajax call to a laravel controller, but it seems not working. What can I do?
public function postSubmit($id) {//Gelen geornal id'si

    header('Content-Type: application/json');

    $uploaded = [];
    $allowed = ['jpg', 'png'];

    $succeeded = [];
    $failed = [];

    if(!empty($_FILES['dosya'])) {

           // It seems not entering here.. I want to save file here.

    }

When I write that in controller:
$allFiles = Input::all();
return $allFiles;

I get this in my console:
Object {ajax: "true", file: Array[1]}

How can I get my file in controller?
This is the script:
<script>

    document.getElementById('submit-button').addEventListener('click', function(e) {
        e.preventDefault();

        var f = document.getElementById('file_input'),

        app.uploader({
            files: f,
            processor: "{{ URL::route('category/post', array($category->id)) }}",

        });

    });

</script>

And I have getFormData and ajax function to get FormData and for a XMLHttpRequest.


text:
Q: How to optimize this Google Apps Script? All it does is read and write data but it takes forever I have (what I think is) a simple Google Apps Script that takes parameters from the URL and uses them to write data to a spreadsheet based on whether two of the cells in a row match two of the parameters:
function doGet(e) {
  var email = e.parameter.email;
  var originalTitle = e.parameter.originalTitle;
  var newTitle = e.parameter.newTitle;
  var newAdditionalAuthors = e.parameter.newAdditionalAuthors;
  var newTechnicalSessions = e.parameter.newTechnicalSessions;
  var newApproval = e.parameter.newApproval;

  var sh = SpreadsheetApp.openById("18vghxzzt27FcBOvoG8kIFFtswMB7XTsMRg60DJ6_-QM").getSheetByName("Responses");
  var data = sh.getDataRange().getValues(); // read all data in the sheet

  for (n=0;n<data.length;++n){
    if (data[n][2] == email && data[n][3] == originalTitle){ //Find all rows where the email matches the submitter's and the title matches the original
      data[n][3] = newTitle;
      data[n][31] = newAdditionalAuthors;
      data[n][33] = newTechnicalSessions;
      data[n][34] = newApproval;
    };
    sh.getRange(1,1,data.length,data[0].length).setValues(data); // write back to the sheet
  }

  return ContentService.createTextOutput("Success. You may close this tab.");
}

However, it seems to take a rather ridiculous amount of time for the script to run, and it just gets worse the more entries I have in the sheet. Can someone tell me what I'm doing wrong?


text:
Q: Sql - getting sum of a value in table for a specific id I have 2 tables
X
-----------------
id      | value
1       |    10
2       |    20

Y
----------------
id     |    value
2      |      30

then the output should be
result
-----------------
id     |   value
1      |     10
2      |     50     (20 + 30) from both the tables

I have to do it in hive.

A: This looks like a left join:
select x.id, (x.value + coalesce(y.value, 0)) as value
from x left join
     y
     on x.id = y.id

A: You can try this below option with UNION ALL and GROUP BY-
SELECT id, SUM(value) Value
FROM
(
    SELECT id, value FROM X
    UNION ALL
    SELECT id, value FROM Y
) A
GROUP BY id

A: If both the tables have mismatching list of ids, we can use full outer join to get the results. Please consider the below query:
select x.id,NVL(x.value,0)+NVL(y.value,0) value from x full outer join y on x.id=y.id;


text:
Q: How to get a derive 'N' Date Rows from a single record with From / To date columns? Title sounds confusing but let me please explain:
I have a table that has two columns that provide a date range, and one column that provides a value. I need to query that table and "detail" the data such as this

Is it possible to do only using TSQL?
Additional Info
The table in question is about 2-3million records long (and growing)

A: Assuming the range of dates is fairly narrow, an alternative is to use a recursive CTE to create a list of all dates in the range and then join interpolate to it:
WITH LastDay AS
(
  SELECT MAX(Date_To) AS MaxDate
  FROM MyTable
),
Days AS
(
  SELECT MIN(Date_From) AS TheDate
  FROM MyTable

  UNION ALL

  SELECT DATEADD(d, 1, TheDate) AS TheDate
  FROM Days CROSS JOIN LastDay
  WHERE TheDate <= LastDay.MaxDate
)
SELECT mt.Item_ID, mt.Cost_Of_Item, d.TheDate
FROM MyTable mt
INNER JOIN Days d
ON d.TheDate BETWEEN mt.Date_From AND mt.Date_To;

I've also assumed an that date from and date to represent an inclusive range (i.e. includes both edges) - it is unusual to use inclusive BETWEEN on dates.
SqlFiddle here
Edit
The default MAXRECURSION on a recursive CTE in Sql Server is 100, which will limit the date range in the query to a span of 100 days. You can adjust this to a maximum of 32767.
Also, if you are filtering just a smaller range of dates in your large table, you can adjust the CTE to limit the number of days in the range:
WITH DateRange AS
(
  SELECT CAST('2014-01-01' AS DATE) AS MinDate,
         CAST('2014-02-16' AS DATE) AS MaxDate
),
Days AS
(
  SELECT MinDate AS TheDate
  FROM DateRange

  UNION ALL

  SELECT DATEADD(d, 1, TheDate) AS TheDate
  FROM Days CROSS APPLY DateRange
  WHERE TheDate <= DateRange.MaxDate
)
SELECT mt.Item_ID, mt.Cost_Of_Item, d.TheDate
FROM MyTable mt
INNER JOIN Days d
ON d.TheDate BETWEEN mt.Date_From AND mt.Date_To
OPTION (MAXRECURSION 0);

Update Fiddle

A: This can be achieved using Cursors.
I've simulated the test data provided and created another table with the name "DesiredTable" to store the data inside, and created the following cusror which achieved exactly what you are looking for:
SET NOCOUNT ON;

DECLARE @ITEM_ID int, @COST_OF_ITEM Money,
        @DATE_FROM date, @DATE_TO date;

DECLARE @DateDiff INT; -- holds number of days between from & to columns
DECLARE @counter INT = 0; -- for loop counter

PRINT '-------- Begin the Date Expanding Cursor --------';

-- defining the cursor target statement
DECLARE Date_Expanding_Cursor CURSOR FOR
SELECT [ITEM_ID]
      ,[COST_OF_ITEM]
      ,[DATE_FROM]
      ,[DATE_TO]
  FROM [dbo].[OriginalTable]

-- openning the cursor
OPEN Date_Expanding_Cursor

-- fetching next row data into the declared variables
FETCH NEXT FROM Date_Expanding_Cursor
INTO @ITEM_ID, @COST_OF_ITEM, @DATE_FROM, @DATE_TO

-- if next row is found
WHILE @@FETCH_STATUS = 0
BEGIN

-- calculate the number of days in between the date columns
SELECT @DateDiff = DATEDIFF(day,@DATE_FROM,@DATE_TO)

-- reset the counter to 0 for the next loop
set @counter = 0;

WHILE @counter <= @DateDiff
BEGIN

-- inserting rows inside the new table
insert into DesiredTable
Values (@COST_OF_ITEM, DATEADD(day,@counter,@DATE_FROM))

set @counter = @counter +1
END

-- fetching next row
FETCH NEXT FROM Date_Expanding_Cursor
INTO @ITEM_ID, @COST_OF_ITEM, @DATE_FROM, @DATE_TO
END

-- cleanup code
CLOSE Date_Expanding_Cursor;
DEALLOCATE Date_Expanding_Cursor;

The code fetches every row from your original table, then it calculates the number of days between DATE_FROM and DATE_TO columns, then using this number the script will create identical rows to be inserted inside the new table DesiredTable.
give it a try and let me know of the results.

A: You can generate an increment table and join it to your date From:

Query:

With inc(n) as (
    Select ROW_NUMBER() over (order by (select 1)) -1 From (
        Select 1 From (values(1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) as x1(n)
        Cross Join (values(1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) as x2(n)
    ) as x(n)
)
Select item_id, cost, DATEADD(day, n, dateFrom), n From @dates d
Inner Join inc i on n <= DATEDIFF(day, dateFrom, dateTo)
Order by item_id

Output:

item_id cost    Date                        n
1       100     2014-01-01 00:00:00.000     0
1       100     2014-01-02 00:00:00.000     1
1       100     2014-01-03 00:00:00.000     2
2       105     2014-01-08 00:00:00.000     2
2       105     2014-01-07 00:00:00.000     1
2       105     2014-01-06 00:00:00.000     0
2       105     2014-01-09 00:00:00.000     3
3       102     2014-02-14 00:00:00.000     3
3       102     2014-02-15 00:00:00.000     4
3       102     2014-02-16 00:00:00.000     5
3       102     2014-02-11 00:00:00.000     0
3       102     2014-02-12 00:00:00.000     1
3       102     2014-02-13 00:00:00.000     2

Sample Data:

declare @dates table(item_id int, cost int, dateFrom datetime, dateTo datetime);
insert into @dates(item_id, cost, dateFrom, dateTo) values
(1, 100, '20140101', '20140103')
, (2, 105, '20140106', '20140109')
, (3, 102, '20140211', '20140216');

A: Yet another way is to create and maintain calendar table, containing all dates for many years (in our app we have table for 30 years or so, extending every year). Then you can just link to calendar:
select <whatever you need>, calendar.day
from <your tables> inner join calendar on calendar.day between <min date> and <max date>

This approach allows to include additional information (holidays etc) in calendar table - sometimes very helpful.


text:
Q: Loading GeoJSON with polygon in OpenLayers I am trying to load GeoJSON in OpenLayers, however, the polygon isn't visible on the map. What am I doing wrong?
<!doctype html>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css" type="text/css">

    <title>Gminy</title>


text:
Q: Left join without returning NA values I am using R and the library dplyr.
I want to join a larger database with a smaller database (in terms of rows).
I use left join because I want to have a final database that has the same number of rows as the larger one.
This naturally returns NA values when the smaller database does not have a value corresponding to the joining key.
What I want to achieve is sort of copying the previous values of the smaller database into the rows where NA is returned by the left join.
In other words:
if is.na(columnvalue[j]) == TRUE then
    columnvalue[j] = columnvalue[j-1]

where columnvalue is a joined column from the smaller database and j = 1,..., nrow(largerdataset).
A loop with that if statement should work, but it is a bit cumbersome. Is there any other smarter solution?
Thank you.

A: If you update with some sample data, I could provide full code for this. The general solution is to use fill from tidyr package, possibly with a group_by the key if needed. You would just write it as:
library(tidyverse)

data %>%
  # group_by(key) %>%
  tidyr::fill(var1, var2, var3, .direction = "up")


text:
Q: Java DateTimeFormatter can't format its own parsed TemporalAccessor I'm creating a simply DateTimeFormatter, but it can't seem to read it's own output. The reason I need to use the DateTimeFormatter directly and not LocalDate.format or YearMonth.format is that the code needs to be generic enough to handle different instances of DateTimeFormatter with completely different fields. The code below fails with: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
DateTimeFormatter yearMonthFormatter = DateTimeFormatter.ofPattern("yyyyMM");
TemporalAccessor yearMonthTemp = yearMonthFormatter.parse("200102");
String formatted = yearMonthFormatter.format(yearMonthTemp); //fails here trying to format its own output

Is there any way to accomplish the above without having to know the contents of the datetime pattern? i.e. the string "yyyyMM" is not static, it will be passed as a parameter.
Edit: Dang, asked and solved in 40 minutes, on a Saturday.

A: What is happening here is that when you parse the string, an additional resolution phase happens, and turns the yyyy format specifier representing the "Year Of Era" temporal field into a "Year" temporal field in the returned TemporalAccessor, and you end up with (yearMonthTemp.toString()):
{Year=2001, MonthOfYear=2},ISO

When you format, the yyyy format specifier expects to format a "Year Of Era" temporal field, but the temporal accessor doesn't have it, as you can clearly see above.

If one needed to change the format of a Temporal without knowing the formats head of time, eg from yyyyMM to MMM-yyyy, you would need two different DateTimeFormatters. The formatters would be completely compatible in terms of the fields that they parse and the temporal objects they produce.

If all you want to do is changing formats, you can set the resolver style to STRICT (by default this is SMART):
DateTimeFormatter.ofPattern("yyyyMM")
    .withResolverStyle(ResolverStyle.STRICT);

Though I cannot find documentation for this, I have found that this will prevent it from automatically changing "Year Of Era" to "Year" (which is typically denoted uuuu). From my testing, every parsed temporal field will be present in the result. Assuming that you have the same format specifiers in the formatting DateFormatter, it will get the same temporal fields successfully.
Note that this also means that you cannot easily get something like a YearMonth from this DateTimeFormatter, because YearMonth.parse/YearMonth.from expects a "Year". not "Year Of Era".
// does not work
System.out.println(YearMonth.from(yearMonthTemp));


text:
Q: django-password-reset - how to set attributes I am trying to use django-password-reset (https://pypi.python.org/pypi/django-password-reset/0.2) to allow users recovering their passwords.
django-password-reset provides a form where the user can enter their username or email address, and tries to find one of those in the database.
In my project, the user has no username field - only the email field.
Thus, I need to make it search users by the 'email' field only, and not by the 'username' field, which does not exist in my system.
The projects documentation says there are attributes to change this behavior:
http://django-password-reset.readthedocs.org/en/latest/views.html.
However, I simply cannot find out how to set these attributes.
Can someone help?

A: Just override Recover view like so:
class MyRecover(Recover):
    search_fields = ['email']

myrecover = MyRecover.as_view()

because there are two recover urls, you need to pass the one with signature first and then the overridden one and then the included one, seems not very DRY, but it's the only way to make the urls be dispatched correctly:
url(r'^recover/(?P<signature>.+)/$', 'password_reset_recover.views.recover_done',
    name='password_reset_sent'),
# next we override our url, assuming your app name is called 'core'
url(r'^recover/$', 'core.views.myrecover', name='password_reset_recover'),
url(r'^/', include('password_reset.urls')),

A: The documentation for django-password-reset says that it uses django.contrib.auth.models.User (the django built in User model) to search for username or email.  So here a username would exist.
If you want to change the functionality of the django-password-reset you can go into the forms.py file and change the form's search_fields variable (and other logic) so that it only searches by email.
Here is the hyperlink to the forms.py:
https://github.com/brutasse/django-password-reset/blob/master/password_reset/forms.py
I'd start with changing the PasswordRecoveryForm


text:
Q: How to use Keystore to connect to SSL enabled IBM MQ using NodeJS I need to connect to IBM MQ on cloud which is SSL enabled with mutual authentication from NodeJS. Because of some restrictions at MQ side I am unable to connect to this IBM MQ using Native keydb approach. When i try to connect i get error. My client confirmed that I wont be able to connect to MQ using keydb(native approach)
MQ call failed in CONNX: MQCC = MQCC_FAILED [2] MQRC = MQRC_HOST_NOT_AVAILABLE [2538]

I saw official documentation of ibmmq node library which mentions that MQI based client like Node, Python etc  needs to use keydb. I am able to connect to this IBM MQ using Java (Keystore).
I would like to know if there is a way to connect to IBM MQ from NodeJS using keystore which i used to connect from Java.

A: You can't directly use the jks file with the ibmmq node library.
You can convert the jks to a kdb using these commands:
runmqckm -keydb -convert -db key.jks -new_format kdb
runmqckm -keydb -stashpw -db key.kdb

The first command will create two files:
key.kdb
key.rdb

The second command will create the stash file:
key.sth

Both commands will prompt you for the jks password.


text:
Q: how to compile linux 0.01? as i came across recompiling the linux kernel, i got a bit interested in the topic. so to go more deep and observe the output, i downloaded the linux kernel 0.01 from github (https://github.com/liudonghua123/linux-0.01). when i run make (with no extra parameters). i get errors:-
$ cd 'linux_kernel(0.01)-source_code'
$ make
gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -fno-stack-protector  \
-nostdinc -Iinclude -c -o init/main.o init/main.c
In file included from include/sys/stat.h:5,
                 from include/unistd.h:53,
                 from init/main.c:2:
include/stdint.h:153: warning: "__INT64_C" redefined
  153 | #  define __INT64_C(c) c ## LL
      |
<built-in>: note: this is the location of the previous definition
In file included from include/sys/stat.h:5,
                 from include/unistd.h:53,
                 from init/main.c:2:
include/stdint.h:154: warning: "__UINT64_C" redefined
  154 | #  define __UINT64_C(c) c ## ULL
      |
<built-in>: note: this is the location of the previous definition
In file included from init/main.c:3:
include/time.h:39:8: warning: conflicting types for built-in function 'strftime'; expected 'long unsigned int(char *, long unsigned int,  const char *, const void *)' [-Wbuiltin-declaration-mismatch]
   39 | size_t strftime(char * s, size_t smax, const char * fmt, const struct tm * tp);
      |        ^~~~~~~~
include/time.h:1:1: note: 'strftime' is declared in header '<time.h>'
  +++ |+#include <time.h>
    1 | #ifndef _TIME_H
init/main.c: In function 'printf':
init/main.c:114:45: warning: passing argument 3 of 'vsprintf' from incompatible pointer type [-Wincompatible-pointer-types]
  114 |  write(1,printbuf,i=vsprintf(printbuf, fmt, args));
      |                                             ^~~~
      |                                             |
      |                                             va_list {aka char *}
init/main.c:38:12: note: expected '__va_list_tag *' but argument is of type 'va_list' {aka 'char *'}
   38 | extern int vsprintf();
      |            ^~~~~~~~
init/main.c: Assembler messages:
init/main.c:93: Error: invalid instruction suffix for `push'
init/main.c:94: Error: invalid instruction suffix for `push'
init/main.c:95: Error: invalid instruction suffix for `pushf'
init/main.c:96: Error: invalid instruction suffix for `push'
init/main.c:97: Error: invalid instruction suffix for `push'
make: *** [Makefile:27: init/main.o] Error 1
$

(i've copied the exact words from the shell)
how to fix?

A: The 0.01 kernel can't be built for 64-bit x86; on x86, you should target 32-bit instead. On top of that, recent linker changes mean that the code can't be linked; we can fix that by allowing multiple definitions.
There are a couple of remaining issues, which can be fixed by editing kernel/console.c so that columns and attr are exported:
static unsigned long lines=LINES;
unsigned long columns=COLUMNS;
static unsigned long state=0;
static unsigned long npar,par[NPAR];
static unsigned long ques=0;
unsigned char attr=0x07;

With that,
make CC="gcc -m32" AS="as --32" LD="ld -melf_i386 --allow-multiple-definition" clean Image

will complete successfully (assuming you have the appropriate GCC and binutils, and Bruce Evans' as86 and ld86), at least with GCC 10. I haven't tried booting the resulting kernel; I'm not sure an ELF kernel will work at all.

A: Check this repo out where changes has been made to be able to compile on Ubuntu 18.04 64 and 32 bit versions. It also has a make command to run on qemu.
https://github.com/mariuz/linux-0.01


text:
Q: Decode a java serialized .dat file in C Is it possible to decode a java serialized .dat file in C?
I have a file in a java project which I read as follows in java project:
FileInputStream in = new FileInputStream(.dat file path);
ObjectInputStream si = new ObjectInputStream(in);
si.readUTF();

si.readBoolean()
int num=si.readInt();

How can I convert this code to C? I know the first character is a utf character, the second one is boolean and the third is int.
unsigned char buf[16];
FILE *fp = fopen((const char*)[filePath UTF8String], "rb");
fread(buf, 4, 1, fp); // read 4 bytes
printf("%s", buf);

A: The official Javadocs for the DataInput interface specify exactly what readUTF, readBoolean, and readInt read from the stream. Just implement those in C, following the descriptions exactly, and you'll be fine.
I see you're using Objective-C; for readUTF in particular you can construct NSString after you've read the appropriate number of bytes using [[NSString alloc] initWithBytes:byteArray length:length encoding:NSUTF8StringEncoding].
By the way, your Java code is being wasteful: it is using an ObjectInputStream when it really only needs a DataInputStream, which is much simpler and provides the same methods you're using. (This came to my notice in particular because if you had been using the intended functionality of ObjectInputStream, i.e. reading serialized Java objects, then it would be much harder to write decoding in C, because the format is much more complex and designed for use by systems which include the Java standard libraries.)


text:
Q: Strange batch loss in keras Im training a Bidirectional RNN with keras.losses.MSE and have my dataset shuffled before training. I manually split it into validation and train data. However when i start training loss follows some strange pattern like the one on the picture with batch loss having drops at the epoch end.

Secondly, sometimes loss has this pattern: gradually decreasing batch loss, then huge drop at validation loss at the epoch end, and after this  new epoch batch losses start with the last validation loss, but not the last batch loss, just like my NN learned something during validation data testing.

Also,  i have some concerns about MSE loss, which increases proportionally to the batch size. It is MEAN square error, so should not it be independent from the batch size?

A: First question - loss curve:
Usually loss curves are plotted based on epoch-loss, but you are displaying the loss of every single mini-batch and I think (correct me if I'm wrong) that the loss you are showing is not the mean of but the sum of it.
The last mini-batch that passes thru your model is probably very small (it is the remainder of the what is left after dividing the full dataset into batches of equal size), so it results in a smaller summed-loss, if you would display the mean loss, it will stop happening.
Second question - loss updates:
The training loss that Keras calculates during the epoch is accumulated and estimated online. So it includes the loss from the model after different weight updates.
While the loss of the validation is for the weights at the end of the epoch.
This is the reason that there are big changes between training losses of different epochs.
Let we clarify with an easy case: assume for a second that the model is only improving (every weight update results in better accuracy and loss), and that each epoch contains 2 weight updates (each min-batch is half the training dataset).
At epoch X, the first mini-batch is processed and the result is a loss score 2.0. After updating the weights, the model runs its second mini-batch which results in a loss score of 1.0 (for just the mini-batch). however you will see a loss of 2.0 change to 1.5 (average over all the dataset).
Now we start epoch X+1, but it happens after another weight update which leads to a loss of 0.8 over the first mini-batch, which is shown to you. And so on and on...
The same thing happens during your training, only that obviously, not all changes are positive.


text:
Q: Installing virtualenvwrapper-powershell in Windows 8.1, import-module failing I'm trying to follow the guide here, and I'm stuck at Import-Module virtualenvwrapper, where PowerShell keeps giving me the error:

import-module : The specified module 'virtualenvwrapper' was not
  loaded because no valid module file was found in any module directory.
At line:1 char:1

*

*import-module virtualenvwrapper

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

*

*CategoryInfo          : ResourceUnavailable: (virtualenvwrapper:String) [Import-Module], FileNotFoundException

*FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

I'm at a real loss at what to do here, because as far as I can tell from this guide and others this step should be rather straight-forward. Googling this problem hasn't really helped me here since I can't find anyone else with this problem.

A: Thank you for coming back with a solution. This helped me today. I would also like to add that I had to do an extra step to make it work on Windows 10.
I was getting an error trying to run:

Import-Module virtualenvwrapper

"Get-Content : Cannot find path 'Function:\TabExpansion' because it does not exist."
The solution that I found, was to edit VirtualenvWrapperTabExpansion.psm1 on line 15 from this:
$_oldTabExpansion = Get-Content Function:TabExpansion

to this:
$_oldTabExpansion = Get-Content Function:TabExpansion2

A: Well, I've actually figured my way around this issue. I guess the pip install never placed the files in a correct module directory for PowerShell. I created a WindowsPowerShell\Modules folder in my documents folder, which did not exist but was listed in my PowerShell modules path. I then took the VirtualEnvWrapper directory from the virtualenvwrapper-powershell bitbucket and copied it into the Modules folder I just created.
Then I had to use Set-ExecutionPolicy Unrestricted instead of Set-ExecutionPolicy RemoteSigned as shown in the guide, but I was then able to do the import-module and use everything needed. I'm not sure why I had to all of this manually instead of pip having done it, but I just hope this can somehow help someone else.


text:
Q: Subsonic 3 - No Fetch, FetchAll, or Scaffolding Control? I'm fairly new to SubSonic, and downloaded the latest version which only contained a zip file with the folders Binaries, Examples and T4 Templates.  Upon further reading I was looking forward to trying the Scaffolding control, however the DLL contains no tools to add to the VS2008 toolbox.
I'm also unable to use .Fetch, .FetchByID, etc.
I'm using the ActiveRecord pattern, and all table entities are created in ActiveRecord.cs.
I can grab data using the following:

        var qry = from s in tbl_Geo_State.All()
                  select new
                  {
                      s.State
                  };

        GridView1.DataSource = qry;
        GridView1.DataBind();

Is there a different installation file for 3.0.x.x or should I use an older install version (if so, which), and simply add the new directories to the installation to get the tools and missing methods?
Thanks.

A: Didn't need to update the Scaffold - it works great the way it is :). I will be splitting out the "web stuff" into separate DLLs when I have a chance - but for now you can use both 3 and 2 in the same project if you want that control.
RE Fetch and FetchByID - these are static factory methods on the class:
Product.SingleOrDefault(...)
Product.Find(...)
Product.All().Where()...

etc.


text:
Q: Spring @Bean configs and java polymorphism I've been making increasingly heavy use of the new @Bean configuration style in Spring 3, as a more type-safe alternative to XML bean definition files.  Occasionally, though, this type-safety can prevent you do what should be valid things, due to a combination of Java's lack of type expressiveness, and Spring scoped proxies.
A full unit test which demonstrates the problem is below, but briefly put I have a class ServiceBean, which implements interfaces ServiceA and ServiceB. This bean is a scoped proxy (session-scoped in this case). I also have beans ClientA and ClientB, which are injected with objects of type ServiceA and ServiceB respectively.
In Spring XML config, there's no problem with this. Spring generates a JDK-proxy for the ServiceBean, which implements both interfaces, and both are injected into the client beans. It's all reflective, and the types are fine at runtime.
Try this in @Bean-style, though, and you have problems.  Here's the demonstrative test.
Firstly, the services:
public interface ServiceA {}

public interface ServiceB {}

public class ServiceBean implements ServiceA, ServiceB {}

Now, the clients:
public class ClientA {
    public ClientA(ServiceA service) {}
}

public class ClientB {
    public ClientB(ServiceB service) {}
}

Now, the Spring bean definitions:
@Configuration
public class ScopedProxyConfig {

    @Bean @Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode=ScopedProxyMode.INTERFACES)
    public ServiceBean services() {
        return new ServiceBean();
    }

    @Bean
    public ClientA clientA() {
        return new ClientA(services());
    }

    @Bean
    public ClientB clientB() {
        return new ClientB(services());
    }
}

And finally, the unit test and support context:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ScopedProxyTest {

    private @Resource ClientA clientA;
    private @Resource ClientB clientB;

    public @Test void test() {
        assertThat(clientA, is(notNullValue()));
        assertThat(clientB, is(notNullValue()));
    }
}

<beans>
    <context:annotation-config/>
    <bean class="test.ScopedProxyConfig"/>
</beans>

(XML namespaces omitted for clarity).
This all compiles nicely. Run the test, though, and you get a type casting runtime exception:

Caused by: java.lang.ClassCastException: $Proxy11 cannot be cast to test.ServiceBean
      at test.ScopedProxyConfig$$EnhancerByCGLIB$$d293ecc3.services()
      at test.ScopedProxyConfig.clientA(ScopedProxyConfig.java:26)

It's not clear to me exactly what this is telling me, but it appears to be a clash between the JDK proxy (which implements ServiceA and ServiceB) and the ServiceBean object.
I've tried getting clever with generics:
@Bean @Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode=ScopedProxyMode.INTERFACES)
public <T extends ServiceA & ServiceB> T services() {
    return (T)new ServiceBean();
}

But that doesn't even compile.
This isn't an especially exotic situation, I think, and I've run into it a few times before. In the past, the workaround has been to use TARGET_CLASS proxying instead of interface proxying, but that's not an option for me here.
Can anyone figure out how to make this work?

A: I think you'll have to go for a more interface-based solution:
create an interface ServiceC:
public interface ServiceC extends ServiceA, ServiceB {}

and let ServiceBean implement that interface
public class ServiceBean implements ServiceC{}

And in your ScopedProxyConfig:
@Bean @Scope(value=WebApplicationContext.SCOPE_SESSION,
             proxyMode=ScopedProxyMode.INTERFACES)
public ServiceC services() {
    return new ServiceBean();
}

Consistent use of interfaces should let Spring work with JDK proxies.

A: This one at least compiles, perhaps it will work:
@Bean @Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode=ScopedProxyMode.INTERFACES)
public <T extends ServiceA & ServiceB> T services() {
    return (T)new ServiceBean();
}

@Bean
public ClientA clientA() {
    return new ClientA(this.<ServiceBean>services());
}

@Bean
public ClientB clientB() {
    return new ClientB(this.<ServiceBean>services());
}


text:
Q: How to run docker inside android chroot I have debian stretch installed in arm64 android phone in chrooted environment. I have installed docker-ce following these steps from here.
On starting docker :: systemctl start docker
returns this error :: Running in chroot, ignoring request.
Checking using service docker status shows  [FAIL] Docker is not running ... failed!
How can I run it inside chroot on my android phone ?

A: Try starting the daemon manually with dockerd (rather than using systemctl).


text:
Q: Where can I found Services creation in JBPM How do I integrate other applications into my application using service task in JBPM?.Really appreciated if any one shared the code for that in JBPM.

A: I suppose a custom work handler is what you looking for. You can find the tutorial on how to create one here.
I hope it will give you some idea on how to apply it to your scenario.


text:
Q: Can Project Navigator show target membership in Xcode 4.5? In older versions of Xcode, if I remember correctly you could show extra columns in the Project Navigator (kind of like the version control icons) to show things like current target membership, etc.  I can't find that in Xcode 4.5.  Anyone know how to get at that now?  I just want to see the list of checkboxes showing which files are part of the target.
Note
Yes, I know you can click the target, navigate to the 'Build Phases', then check the relevant sections there to see them all at once, but there you lose the context of your group hierarchies.
You used to be able to just click the checkboxes right down the side of Project Navigator (or whatever it used to be called.)
I googled around and saw someone else said it was removed from Xcode 4.x so maybe that's why I can't find it.  That's crazy if that's the case though, but Apple has done stranger things.

A: It's there in the Utilities > File inspector tab. You can show/hide it using Option + Command + 0 or navigating to View > Utilities > Show Utilitites.