text:
Q: PHP: Image is not displaying from SQL datdabase I have checked out other questions of same topic on this site and tried to find the solution but unsuccessful. Images are stored in database and loaded in folder successfully but are not displayed
Here is my code:

        <form action="image.php" method="post" enctype="multipart/form-data">
            <input type="text" name="image_description" placeholder="Enter name" required>
            <input type="file" name="myfile">
            <input type="submit" name="upload" value="upload">
        </form>

<?php
include("db.php");
if(isset($_POST['upload'])) {
    $image_description = $_POST['image_description'];
    $name = $_FILES["myfile"]["name"];
    $type = $_FILES["myfile"]["type"];
    $size = $_FILES["myfile"]["size"];
    $temp = $_FILES["myfile"]["tmp_name"];
    $error = $_FILES["myfile"]["error"];

    $upload=move_uploaded_file($temp, "uploaded/" . $name);

    $query= "INSERT INTO image(image_description,image_name,image_type,image_size) VALUES ('$image_description','$name','$type','$size')";
    if(mysqli_query($conn,$query) && $upload) {
        echo "successfully uploaded";
    }
    else
       die(mysqli_error($conn));
}

$query = mysqli_query($conn,"SELECT * FROM image");
while($row = mysqli_fetch_array($query))
{?>
        <img style="width: 200px;height: 200px;" src="<?php echo 'uploaded/' .$row['image_name'] ?>">
<?php
    echo $row['image_description'] . "
";
}?>

Images are displayed as in picture

This is database table

A: The URL of your page is index.php/; notice the trailing slash.
A relative URL (e.g. src="uploaded/..") will resolve to index.php/uploaded/...
That folder obviously does not exist on your disk.

*

*Use root-relative URLs: src="/uploaded/.."

*or use relative URLs but go to the right folder: src="../uploaded/.."

*or fix your weird URL and make it index.php, from which even relative URLs will resolve correctly.


text:
Q: CGAffineTransformRotate : Detect rotation direction What I am trying to do :
I have an Image of a wheel and a scroll view. User can drag the wheel to rotate it in either direction.
By detecting the direction of rotation. I have to scroll the images placed over scroll view.
What I am doing is :
Following this tutorial
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchPoint = [touch locationInView:self];
    startTouch = touchPoint; // StartTouch is static varialbel
    float dx = touchPoint.x - container.center.x;
    float dy = touchPoint.y - container.center.y;
    deltaAngle = atan2(dy,dx);
    startTransform = container.transform;
    return YES;
}

- (BOOL)continueTrackingWithTouch:(UITouch*)touch withEvent:(UIEvent*)event
 {
    CGPoint pt = [touch locationInView:self];
    float dx = pt.x  - container.center.x;
    float dy = pt.y  - container.center.y;
    float ang = atan2(dy,dx);
    float angleDifference = deltaAngle - ang;
    container.transform = CGAffineTransformRotate(startTransform, -angleDifference);
    return YES;
}

Main Problem
I am not able to detect the Rotation Direction correctly. I am using the angleDifference varibale from method continueTrackingWithTouch to detect it.
if(angleDifference > 0){
// Positive value move in right direction.
}
else{
// Negative value move in left direction.
}

This is working ok for small drags of less than 360 dgrees, but after that it's not working properly.
Can anyone suggest me correct approach of Detecting the rotation Direction.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: using a variable to specify a column in a dataframe I am trying to access a column in a data frame using a variable , this variable wil be populated
in a loop
atr<-"yield_kgha"

so what i want is the second line below where $atr to act like it was $yield_kgha
I tried $get(atr) with no luck ... how do I get atr to be taken literally
meanis=MEAN = mean(zones[[zonename]]$yield_kgha , na.rm = TRUE) #get the mean yield_kgha in the zone
meanis=MEAN = mean(zones[[zonename]]$atr , na.rm = TRUE) #get the mean yield_kgha in the zone

A: If we want to use an object, then use [[ instead of $ similar to the 'zonename'
mean(zones[[zonename]][[atr]] , na.rm = TRUE) #


text:
Q: Open multiple txt files in python3 I have multiple txt files with similar names as follow:
item1.txt,
item2.txt,
item3.txt,
item700.txt
what is the best way to read these files' data in using python? Thank you in advance

A: Use range() function to iterate over the 700 integers:
import os
import io

work_dir = "path/to/workdir"

for index in range(1, 701):
    name = "item{index}.txt".format(index=index)
    path = os.path.join(work_dir, name)
    with io.open(path, mode="r", encoding="utf-8") as fd:
        content = fd.read()

A different way is to use glob.glob function to search for the text files:
for path in glob.glob(os.path.join(work_dir, "item*.txt")):
    with io.open(path, mode="r", encoding="utf-8") as fd:
        content = fd.read()

A:
Assuming all and only the text-files are in a Folder

import os

all_txt_files = os.listdir(file_dir)

for txt in all_txt_files:
    txt_dir = file_dir + txt
    with open(txt_dir, 'r') as txt_file:

    # read from a single Textfile whatever you want to

Note: Depending on your python version the Textfiles might not be sorted by os.listdir() prevent that by sorted(os.listdir())


text:
Q: Best parser to parse 1 GB xml data in java My Requirement is :
I have 1GB xml file and want to remove few nodes from xml file.Here removing xml nodes can be anything in entire file which is based on the input.What is the best parser in JAVA.
I'm Currently using DOM parser and it is working fine for 100MB files but it is throwing out of memory error :heap space for 1 GB file.
Can anyone suggest best approach for my code below:
    public static void main(String[] args) {
    DocumentBuilder docBuilder = null;
    File inputFile = new File("/scratch/bigfile/final.txt");
    // Parse the xml file using DOM parser
    try{
    DocumentBuilderFactory docBuilderFactory =DocumentBuilderFactory.newInstance();
    docBuilderFactory.setExpandEntityReferences(false);
    docBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    docBuilder = docBuilderFactory.newDocumentBuilder();
       Document doc= docBuilder.parse(inputFile);

       // Remove unwanted nodes from xml file
        Element element1 = (Element) doc.getElementsByTagName("G_SUMMARY_ROWSET").item(0);
        element1.getParentNode().removeChild(element1);
        Element element2 = (Element) doc.getElementsByTagName("G_JRNLSOURCE_ROWSET").item(0);
        element2.getParentNode().removeChild(element2);
        Element element3 = (Element) doc.getElementsByTagName("G_JRNLSOURCE_UNMATCHED_ROWSET").item(0);
        element3.getParentNode().removeChild(element3);
        Element element4 = (Element) doc.getElementsByTagName("G_JRNLDETAILS_UNMATCHED_ROWSET").item(0);
        element4.getParentNode().removeChild(element4);

        // Convbert Dom Document to Byte array
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
         StreamResult result=new StreamResult(bos);
         transformer.transform(source, result);
         byte []array=bos.toByteArray();
        System.out.println(array.length);

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

A: Consider using SAXParser. It is generally better to use a SAXParser for larger files because the data is not stored in memory and discards most elements after they have been processed. This would solve your issue of running out of memory.
This is contrasted with a DOM (Document Object Model) parser where the entire document is loaded into memory.


text:
Q: Navigation bar button image in iOS taking 15 seconds to load I am using storyboard to give an image to my navigation bar button item. However, it is taking 15 seconds to load on my iPhone 6! My image size is only 1kb, but the view controller does have a viewdidload and viewdidappear. What could be happening that my custom 3 lined image is taking so long to load on that nav bar button in iOS?
Update: I have even tried doing programmatically and there is still a delay.
 UIImage *backButtonImage = [[UIImage imageNamed:@"menu-icon.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 6)];
    [self.emaily setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

A: Deleting the storyboard element and then just doing it programmatically solved it.
 UIImage *backButtonImage = [UIImage imageNamed:@"menu-icon.png"];
    _emaily = [[UIBarButtonItem alloc] initWithImage:backButtonImage style:UIBarButtonItemStyleBordered target:self action:@selector(emailappcrea:)];
    self.navigationItem.rightBarButtonItem = _emaily;
    [_emaily release];


text:
Q: SQL AVG statement another table I'm having trouble with a SQL query. The goal is to see only the certain entries on a specific date (I got this already) which have an average score below 1 in their last 5 home games.
You can see the tables here:
http://dbup2date.uni-bayreuth.de/downloads/bundesliga/Klassendiagramm_Bundesliga.pdf
I have this code so far:
SELECT
    A.Spieltag, A.Datum, A.Uhrzeit, B.Name AS Heim
FROM
    Spiel AS A
JOIN
    Verein AS B ON A.Heim = B.V_ID AND B.Liga = 1
WHERE
    Spieltag = 5
HAVING
    AVG(SELECT Tore_Heim
        FROM Spiel AS A
        JOIN Verein AS B
        WHEN A.Heim = B.V_ID) < 1

Sorry for my bad English
Thank you

A: Make sure you group by any =fields that you are not aggregating on when you use HAVING. And you can simplify that HAVING clause since you are already referencing those exact tables in your FROM:
SELECT
    A.Spieltag, A.Datum, A.Uhrzeit, B.Name AS Heim
FROM
    Spiel AS A
JOIN
    Verein AS B ON A.Heim = B.V_ID AND B.Liga = 1
WHERE
    Spieltag = 5
GROUP BY A.Spieltag, A.Datum, A.Uhrzeit, B.Name
HAVING
    AVG(Tore_Heim) < 1


text:
Q: Azure In-Role cache ErrorCode : SubStatus There is a temporary failure. Please retry later I am experiencing a very strange issue trying to get an in-role cache working.  I've only got 1 web role in the current deployment, and have set up in-role caching according to the MSDN docs and blogs alike.  I've looked at all similar questions on SO regarding the same caching error however no solutions worked for me and my situation is a little different.  I've spent hours googling, testing, and nothing seems to be working.
The project works fine locally, and when I push it to Azure for the first time.  In fact, if I am the only one on the website, it seems to work fine (although be it slow).  I started noticing while QA'ing with my partner that after a short period of time when we're both browsing the site it crashes.  At first it appears to be stuck, just spinning there and never receiving a response.  But after a while, we'll eventually get the YSOD with the error listed above.  Once the error occurs, all subsequent requests bomb with the above error, until I kill the w3wp process.  Then the entire process repeats.  The data we are storing in the cache is incredibly small for right now (well under the 8mb limit).
It seemed pretty intermittent, but after using the tool loader.io to test concurrent users, it consistently gets "stuck" (meaning starts throwing the above error) after a few requests were made and for all requests thereafter.
I have the AFCacheSessionStateProvider and AFCacheOutputCacheProvider configured for session and output caching as well.
After hours of trying to get the DataCache code to work (I even implemented retry policy via the Microsoft Enterprise block), I finally tried switching the calls of the Get and Put [wrapper] to use HttpContext.Current.Session rather than the DataCache object.  Alas, no more appfabric caching errors.  Loader.io was able to complete successfully running 500 concurrent users without 1 bad/unsuccessful connection, and I assume it is correctly caching via the AFCacheSessionStateProvider.  Also, the website appears to run incredibly faster after making the switch to the Session object over DataCache.
To give some brief context, we are accessing the cache at the start of each request via an http module (PostAcquireRequestState event) to load user information [permission claims among other data] for the current authenticated identity.
Although it is working with the Session[] object, we would still like to leverage the AppFabric caching api and eventually move to the new caching data service that is still in preview.  Why is this not working?  Also, any explanation for the speed boost after switching off the DataCache object?


text:
Q: "E212: Can't open file for writing" when saving in gvim on Windows I opened a new file with :e ~\mypath\myfile.txt using gvim on Windows.
But when I try to save my file using :w I get this error message:

E212: Cannot open file for writing

How can I solve this?

A: gvim could obviously not create diretories for me, so it worked after I had created the mypath\ directory in my home directory.


text:
Q: moment generating function of a pmf A pmf is shown below along with its mgf. I was wondering how I would calculate moments for the marginal distributions. Would I let t1 = 0 to find the marginal distribution of y? Would I then differentiate that expression and evaluate it at 0 to find E(Y)?
Also, how would I find E(XY) and E(X|y)? For E(XY), would the easiest way to find it be to do a double summation of x and y for xy * the pmf? And for E(X|y), I am not sure at all how to go about finding that... Thanks for the help!

A: Let's first compute the moment generating function from the p.m.f.:
$$
  \begin{eqnarray}
  M(t_1, t_2) &=& \mathbb{E}( \exp( t_1 X + t_2 Y) ) =
     \sum_{x=0}^\infty \sum_{y=x}^\infty \mathrm{e}^{-2} \frac{\exp(t_1 x)}{x!} \frac{\exp(t_2 y)}{(y-x)!} \\ &=& \sum_{x=0}^\infty \sum_{y=0}^\infty \mathrm{e}^{-2} \frac{\exp(t_1 x)}{x!} \frac{\exp(t_2 (y+x))}{(y)!} = M_{\mathrm{Po}(1)}(t_1+t_2) M_{\mathrm{Po}(1)}(t_2)
  \end{eqnarray}
$$
where $M_{\mathrm{Po}(1)}(t) = \exp\left( \mathrm{e}^t - 1 \right)$. The factorization of $M(t_1, t_2)$ means that the random variable in question corresponds to vector $(X, Y) = (Z_1, Z_1+Z_2)$, where $Z_1$ and $Z_2$ are i.i.d. Poisson random variate with unit mean.
Thus $\mathbb{E}(X Y) = \mathbb{E}\left( Z_1(Z_1+Z_2) \right) = \mathbb{E}\left( Z_1^2 \right) + \mathbb{E}\left( Z_1 \right) \mathbb{E}\left( Z_2 \right) = (1^2 + 1) + 1 \times 1 = 3$. Using moment generating function
$$ \begin{eqnarray}
  \mathbb{E}(X Y) &=& \left. \frac{\mathrm{d}^2}{\mathrm{d} t_1 \mathrm{d} t_2} M(t_1, t_2) \right\vert_{t_1=0, t_2=0} = \left. \left( M(t_1,t_2) \mathrm{e}^{t_1+t_2}  \left(
  1 + \mathrm{e}^{t_1} + \mathrm{e}^{t_1+t_2} \right)\right)\right\vert_{t_1=0, t_2=0} \\&=& 1 \times 1 \times (1+1+1 ) = 3
  \end{eqnarray}
$$
Now, let's turn to $\mathbb{E}\left( X \vert Y=y \right)$. Doing computation directly:
$$
  \mathbb{E}(X \vert Y=y) = \frac{ \sum_{x=0}^\infty x \frac{1}{\mathrm{e}^2} \frac{1}{x!} \frac{1}{(y-x)!}}{\sum_{x=0}^\infty \frac{1}{\mathrm{e}^2} \frac{1}{x!} \frac{1}{(y-x)!}}
  = \frac{ \sum_{x=0}^y x \frac{1}{\mathrm{e}^2} \frac{1}{x!} \frac{1}{(y-x)!}}{\sum_{x=0}^y \frac{1}{\mathrm{e}^2} \frac{1}{x!} \frac{1}{(y-x)!}}
$$
Now the changing variables $x \mapsto y-x$ in the sum in the numerator:
$$
  \mathbb{E}(X \vert Y=y) = y - \mathbb{E}(X \vert Y=y) \qquad \implies \qquad
    \mathbb{E}(X \vert Y=y) = \frac{y}{2}
$$
In order to get the same result using mgf, one should remark, that for positive discrete r.v. the $M_{\mathrm{Po(1)}}(\log t)$ is the probability generating function of Poisson random variable with unit mean, indeed:
$$
   M(\log t) = \exp( t -1 ) = \sum_{x=0}^\infty \frac{\mathrm{e}^{-1}}{x!} t^x
$$
It would then follow that
$$
  \begin{eqnarray}
  \mathbb{E}(X \vert Y=y) &=& \frac{
   [t_2]^y \left. \frac{\mathrm{d}}{\mathrm{d} t_1} M\left( t_1, \log t_2 \right) \right\vert_{t_1=0}}{ [t_2]^y   M\left(0, \log t_2 \right)  } =
  \frac{[t_2]^y \left. \frac{\mathrm{d}}{\mathrm{d} t_1} \exp\left( \mathrm{e}^{t_1} t_2 + t_2 - 2 \right) \right\vert_{t_1=0}}{ [t_2]^y   M\left(0, \log t_2 \right)  }  \\
  &=& \frac{[t_2]^y \left. t_2 \exp\left( t_2 \mathrm{e}^{t_1} + t_2 + t_1 - 2 \right) \right\vert_{t_1=0}}{ [t_2]^y   \exp(2(t_2-1))  } =
  \frac{[t_2]^y \left( t_2 \exp\left( 2 (t_2 - 1) \right)   \right)}{
    [t_2]^y   \exp(2(t_2-1))
    } \\
  &=& \frac{ 2^{y-1} \mathrm{e}^{-2} /(y-1)! }{ 2^{y} \mathrm{e}^{-2} /(y)!} = \frac{y}{2}
  \end{eqnarray}
$$
Added As suggested by Didier Piau, the conditional expectation also follows by symmetry, using representation of $(X, Y)$ in terms of $Z_1$ and $Z_2$. Indeed:
$$
   \mathbb{E}(X \vert Y=y) = \mathbb{E}(Z_1 \vert Y=y) \stackrel{\text{symmetry}}{=} \frac{1}{2} \left( \mathbb{E}(Z_1 \vert Y=y) + \mathbb{E}(Z_2 \vert Y=y)) \right) = \frac{1}{2} \mathbb{E}(Z_1 +Z_2 \vert Y=y)= \frac{y}{2}
$$
Where the symmetry refers to the fact that, due to $Z_1$ and $Z_2$ being i.i.d., the following equation holds:
$$\mathbb{E}(Z_1 \vert Y=y) = \mathbb{E}(Z_1 \vert Z_1+Z_2 = y) = \mathbb{E}(Z_2 \vert Z_1+Z_2 = y) =  \mathbb{E}(Z_2 \vert Y=y).$$


text:
Q: I have a question about sending the value back to the main page [IOS] I have a question about Sending the value back to the main page
After login-> Page 1-> page2-> press home button -> page 1
When I go, there is no problem with the delivery. But I want to press the home button and return the value to page1
this out put on page 2
pShipmentDCBeforeLoad==>Optional("4505023274")
pPlanDateDCBeforeLoad==>Optional("20190119")
TruckIdDCBeforeLoad==>Optional("2")
ptruckNoDCBeforeLoad==>Optional("60-7624")
pShipmentDCBeforeLoad==>Optional("4505023274")

See from the picture

After login -> page 1 -> go to page 2
this code on page 2
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//      Check segue identifier
        if segue.identifier == "gotoAfterLoadingDC" {
//          Get SecondVC
            let destinationVC = segue.destination as! AfterLoadViewController
//          Pass text to SecondVC
            destinationVC.pShipmentDCAfterLoad = pShipmentDCBeforeLoad!
            destinationVC.pPlanDateDCAfterLoad = pPlanDateDCBeforeLoad!
            destinationVC.TruckIdDCAfterLoad = TruckIdDCBeforeLoad!
            destinationVC.ptruckNoDCAfterLoad = ptruckNoDCBeforeLoad
            destinationVC.PlanDetailIdDCAfterLoad = PlanDetailIdDCBeforeLoad!
        }
    }

press Home button on page 2 -> go to page 1
@IBAction func BacktoPlandata(_ sender: UIBarButtonItem) {
        DispatchQueue.main.async {
            //self.performSegue(withIdentifier: "BeforeloadBacktoplandata", sender: "self")
            func prepare(for segue: UIStoryboardSegue, sender: Any?) {
                //      Back to home
                if segue.identifier == "BeforeloadBacktoplandata" {
                    //Get SecondVC
                    let destinationVC = segue.destination as! PlanDataViewController
                    //Pass text to SecondVC
                    destinationVC.getpShipmentPickerView.text! = self.pShipmentDCBeforeLoad!
                    destinationVC.getpPlanDatePickerView.text! = self.pPlanDateDCBeforeLoad!
                    destinationVC.ptruckidDCPlanData = self.TruckIdDCBeforeLoad!
                    destinationVC.ptruckNoDCPlanData = self.ptruckNoDCBeforeLoad
                    destinationVC.pPlandDetailIdDCPlanData = self.PlanDetailIdDCBeforeLoad!

//                  Show log back to plandata
                    print("pShipmentDCBeforeLoad==>\(String(describing: self.pShipmentDCBeforeLoad))")
                    print("pPlanDateDCBeforeLoad==>\(String(describing: self.pPlanDateDCBeforeLoad))")
                    print("TruckIdDCBeforeLoad==>\(String(describing: self.TruckIdDCBeforeLoad))")
                    print("ptruckNoDCBeforeLoad==>\(String(describing: self.ptruckNoDCBeforeLoad))")
                    print("pShipmentDCBeforeLoad==>\(String(describing: self.pShipmentDCBeforeLoad))")

//                  call fuction
                    print("//////////////-getPlanDetail-BacktoPlandata-/////////////////")
                    self.getPlanDetailDCbeforeLoadingViewController(pshipment: self.pShipmentDCBeforeLoad!, pplanDate: self.pPlanDateDCBeforeLoad!)
                }
            }
        }
    }

A: Seems you can create method in Home screen with data you want to pass as a parameter and call it from Page 2.
In Home screen
func someData(param1: String, param2: String) { }

From Page 2
let destinationVC = segue.destination as! PlanDataViewController
destinationVC.someData(param1: "ABC", param2: "XYZ")

Also, you can pass data by creating property in home screen and passing data from Page2.

A: Instead of using segue you can use navigationController controller and it will get the same instance of page 1 (VC) that is already loaded into navigation controller. If you use the segue it will create new instance that will present on the top of page 2 (VC). So instead of using new instance use the same instance that is created already.
@IBAction func BacktoPlandata(_ sender: UIBarButtonItem) {

let n: Int! = self.navigationController?.viewControllers?.count
let destinationVC = self.navigationController?.viewControllers[n-1] as! UIViewController

destinationVC.getpShipmentPickerView.text! = self.pShipmentDCBeforeLoad!
destinationVC.getpPlanDatePickerView.text! = self.pPlanDateDCBeforeLoad!
destinationVC.ptruckidDCPlanData = self.TruckIdDCBeforeLoad!
destinationVC.ptruckNoDCPlanData = self.ptruckNoDCBeforeLoad
destinationVC.pPlandDetailIdDCPlanData = self.PlanDetailIdDCBeforeLoad!

self.navigationController.popViewController(animated: true)

}

A: You could try post notification which send your data once you click the home button,
NotificationCenter.default.post(name: Notification.Name(rawValue: "anyname"), object: ["TruckID": self.TruckIdDCBeforeLoad])

In the home controller add this in viewdidload,
NotificationCenter.default.addObserver(self, selector: #selector(refresh(_:)), name: NSNotification.Name(rawValue: "anyname"), object: nil)

https://www.hackingwithswift.com/example-code/system/how-to-post-messages-using-notificationcenter
https://learnappmaking.com/notification-center-how-to-swift/


text:
Q: Brief explanation of some input/outputs of RISC-V Core I am trying to analyze the code of fetch.v file from (https://github.com/ultraembedded/riscv/tree/master/core/riscv), but the designer has no documentation explaining anything and I am very beginner at the world of Verilog and digital design. What do these mean and do ?
,input           fetch_accept_i
,input           icache_accept_i
,input           icache_valid_i
,input           icache_error_i
,input  [ 31:0]  icache_inst_i
,input           icache_page_fault_i
,input           fetch_invalidate_i
,input           branch_request_i
,input  [ 31:0]  branch_pc_i
,input  [  1:0]  branch_priv_i

// Outputs
,output          fetch_valid_o
,output [ 31:0]  fetch_instr_o
,output [ 31:0]  fetch_pc_o
,output          fetch_fault_fetch_o
,output          fetch_fault_page_o
,output          icache_rd_o
,output          icache_flush_o
,output          icache_invalidate_o
,output [ 31:0]  icache_pc_o
,output [  1:0]  icache_priv_o
,output          squash_decode_o

The design is very complex. I wish there is a good resource I could read to understand his design

A: This is a file that describe the fetch unit of the core.
input means that's a input wire of the unit and output an output one.
The goal of this stage is to fetch instructions from the cache/memory and to send it to the decod unit.
Problem is that every implementation is different but basically :
,input           fetch_accept_i : fetch is accepted by fetch stage (signal come from decode)
,input           icache_accept_i : instruction cache accept the request from fetch unit
,input           icache_valid_i : icache answer is valid
,input           icache_error_i : icache answer made an error
,input  [ 31:0]  icache_inst_i : instruction fetch by the cache
,input           icache_page_fault_i : cache did a page fault exception\
,input           fetch_invalidate_i : fetch was invalid
,input           branch_request_i : fetch unit made a branch request
,input  [ 31:0]  branch_pc_i : branch address of pc
,input  [  1:0]  branch_priv_i : current priviledge of the core (M, S or U)

// Outputs
,output          fetch_valid_o : fetch request is valid
,output [ 31:0]  fetch_instr_o : ?
,output [ 31:0]  fetch_pc_o : current pc which is fetch
,output          fetch_fault_fetch_o : fetch did a fault
,output          fetch_fault_page_o : fault did a page fault
,output          icache_rd_o : ?
,output          icache_flush_o : flush request to the cache
,output          icache_invalidate_o : invalidate request to the cache
,output [ 31:0]  icache_pc_o : current pc
,output [  1:0]  icache_priv_o : priviledge mode
,output          squash_decode_o : ?

I'm not sure with my answer but according to the name of the signal i can do these assumptions


text:
Q: How to store my session array into my database How do I store my data in session array into my database ? Upon entering the product and its quantity, the user will be directed to a checkout page. In the checkout page, upon filling up the necessary information in a form, I am trying to use a button to submit the session array into my database.
My current code:
<?php
    session_start();
    $array = $_SESSION['shopping_cart'];
    $connect = mysqli_connect('localhost', 'root', '', 'table');
    ?>
    $sql = "INSERT INTO customer_order (productName, quantity, totalPrice, pax)";
    foreach($array as $product){
       $sql = "INSERT INTO p2_5.customer_order (productName, quantity, totalPrice, pax)";
       $sql .= " VALUES ('{$product['name']}', '{$product['quantity']}', '{$product['price']}', '{$product['pax']}')";
       if ($connect->query($sql)) {
          $errorMsg = "Connection failed: " . $connect->connect_error;
          $success = false;
   }
}

However, upon clicking on the button, I am able to store client information into my database, but I would have an PHP error message Undefined index: name, Undefined index: quantity, Undefined index: price, Undefined index: pax ?

A: You're passing elements from $array without referencing to their indexes, I mean without $array[0] or $array[1].
You need to add a loop like below:
foreach($array as $product){
   $sql = "INSERT INTO customer_order (productName, quantity, totalPrice, pax)";
   $sql .= " VALUES ('{$product['name']}', '{$product['quantity']}', '{$product['price']}', '{$product['pax']}')";
   if ($connect->query($sql)) {
       $errorMsg = "Connection failed: " . $connect->connect_error;
       $success = false;
   }
   if ($errorMsg != "Connection failed: ") {echo $errorMsg; $connect->close(); return;}
}

This will allow you to save each row data from shopping_cart.


text:
Q: Change comparison function for BST dynamically in Python I have made a binary search tree with the help of the following library. I have made a comparison function to determine where the nodes should go. The comparison function determines the current y value for each segment.
Look at the following example:

from sortedcontainers import SortedList

def findCurrentY(segment):
   #uses current_x to calculate value of y...

def compare(segment):
   position = findCurrentY(segment)
   return position

global current_x
myList = SortedList(key = compare)

segments = [segment1,segment2]

current_x = 1
for segment in segments:
   myList.add(segment)

print(MyList)

current_x = 2
print(MyList)

current_x = 3
print(MyList)

This is how my output looks like
For current_x = 1:
MyList = [segment2,segment1] #y value of segment1 is higher than segment2
For current_x = 2:
MyList = [segment2,segment1]
For current_x = 3:
MyList = [segment2,segment1]

It shows three times the same thing, as it only calculated the compare function ones. How can I dynamically change the compare function when my current_x changes without deleting each element and adding it again to my list?
So it needs to look like this.
For current_x = 1:
MyList = [segment2,segment1] #segment 1 has higher y value
For current_x = 2:
MyList = [segment2,segment1] #segment 1 has higher y value
For current_x = 3:
MyList = [segment1,segment2] #segment 1 has **lower** y value

A: Changing the value of current_x doesn't alter the list as intended. That's because the whole list needs to be updated again if we change the compare function (i.e., to be re-sorted according to the new y values generated) and this process is necessary for this data structure.
See the below example to see unexpected results brought by using a global variable here.
global current_x
current_x = 1

def key_func(val):
    return globals()['current_x'] * val

list = SortedList(key=compare)

>>> list.add(2)
>>> list.add(3)
>>> list.add(5)
>>> print(list)
SortedKeyList([2, 3, 5], key=<function compare at xxx>)
>>> current_x = -1
>>> list.add(5)
>>> list.add(4)
>>> print(list)
SortedKeyList([5, 4, 2, 3, 5], key=<function compare at xxx>)

Apparently, [5, 4, 2, 3, 5] isn't the result we're expecting. Therefore,  instead of changing the key function in-place, a safer approach is to copy the original list into a new SortedList.
# Return a function that gives the y value according to x
# Segments are expected to be functions representing expressions like y=x or y=-x+4
def get_key_func(x_value: int):
    return lambda segment: segment(x_value)

# Return a new sorted list based on the same list but with different x
def new_sorted(sl: SortedList, new_x_value):
    return SortedList(sl, key=get_key_func(new_x_value))

So, according to the graph you gave, we can define segment1 and segment2.
# define y = -x + 4
def expr_one(x):
    return -x + 4

# define y = x
def expr_two(x):
    return x

# The x of the current list is 0
myList = SortedList(key=get_key_func(0))
myList.add(expr_one)
myList.add(expr_two)

Then, we can try to create new list sorted by the resulting y different x.
for i in range(1, 4):
   print(f'For current_x = {i}:\nMyList = {new_sorted(myList, i)}')

The code above outputs:
For current_x = 1:
MyList = SortedKeyList([<function expr_two at xxx>, <function expr_one at xxx>], key=<...>)
For current_x = 2:
MyList = SortedKeyList([<function expr_two at xxx>, <function expr_one at xxx>], key=<...>)
For current_x = 3:
MyList = SortedKeyList([<function expr_one at xxx>, <function expr_two at xxx>], key=<...>)

However, if you insist to make the list dynamically sorted, you can implement a wrapper class in which self.list always refers to a list sorted as intended.
class DynamicSorted:
    def __init__(self, key_func):
        self.list = SortedList(key=key_func)

    def update_key_func(self, new_key_func):
        self.list = SortedList(self.list, key=new_key_func)


text:
Q: Store Form Selection and pass as hidden form field I have a table that allows users to make a selection from a list of items:

<form action="submitSelection.php" method="post" role="form">

      Code
      Description
      Select

        1234A
        Option A

          <button type="button" class="btn btn-success btn-sm">Select</button>

        45678B
        Option B

          <button type="button" class="btn btn-success btn-sm">Select</button>

        9988C
        Option C

          <button type="button" class="btn btn-success btn-sm">Select</button>

        4455D
        Option D

          <button type="button" class="btn btn-success btn-sm">Select</button>

    <button type="submit" name="buttonType" value="saveSelected" class="btn btn-success">Submit</button>

</form>

When they click the 'Select' button on a table row I would like to store the ID - I only need to track the last selection they made. I need this value to persist after they have made a selection, so it needs to be stored in some kind of global variable (still learning Javascript so not 100% familiar with the correct terminology here). I'll need to pass the selected ID in a hidden form input field when they submit the form.
I would then like to validate that they have indeed made a selection by making sure the global variable exists when they click the Submit button, and if not show a hidden alert (I'm using the Bootstrap theme).
I've got the script to the point where it gets the selected ID and I can log this in the Console but not sure how to store it somewhere whilst the user has the page open and before the click the Submit button, and also validate that it has been selected when they click Submit.
Here's my script:

$(document).ready(function() {
      $('button.btn-success').click(function() {
        // Remove the classes from all of the TR elements
        $(this).parents('table').find('tr').removeClass('success warning danger');
        var productID = $(this).closest('tr').attr('id');
        console.log(productID);
      });

A: Below code will help you.
var latest_id = null;
$(document).ready(function(){
  $(".btn.btn-sm").click(function(event){
    latest_id = $(this).parents('tr').attr('id');
  });
  $(".btn.btn-success[name=buttonType]").click(function(event){
    alert(latest_id);
    event.preventDefault();
  });
});

Here is demo https://jsbin.com/puyajomipi/edit?html,js,output

A: Here added one hidden field and on click of select button assign latest value to the hidden field and after that on click of submit button check if hidden field contains any value or not. If no value present then prevent submit button click.

$(document).ready(function() {
      $('button[type=button]').click(function() {

        $(this).parents('table').find('tr').removeClass('success warning danger');
        var productID = $(this).closest('tr').attr('id');
        //console.log(productID);
        $('#hdOptionId').val(productID); //add product id value to hidden field
        console.log($('#hdOptionId').val()); //check updated value of hidden field
      });

      $("button[type=submit]").click(function(e){
          if($('#hdOptionId').val() ==="") {
              console.log('false');
              e.preventDefault();
              return false;
          }
          else {
              console.log('true');
              return true;
          }
      });
  });

<form action="submitSelection.php" method="post" role="form">

      Code
      Description
      Select

        1234A
        Option A

          <button type="button" class="btn btn-success btn-sm">Select</button>

        45678B
        Option B

          <button type="button" class="btn btn-success btn-sm">Select</button>

        9988C
        Option C

          <button type="button" class="btn btn-success btn-sm">Select</button>

        4455D
        Option D

          <button type="button" class="btn btn-success btn-sm">Select</button>

<input type="hidden" id="hdOptionId"  value="" />

    <button type="submit" name="buttonType" value="saveSelected" class="btn btn-success">Submit</button>

</form>


text:
Q: how do you do a remember me or a stay signed in function with AngualarFire? or using normal email and password method so that everytime i open the app i dont have to sign in. just go through..

.controller('signupCtrl', function(taskref, $scope, $firebaseArray, $state, $firebaseAuth) {

      var fbref = $firebaseAuth(taskref);

      $scope.createUser = function() {
        taskref.$createUser({
            email: $scope.email,
            password: $scope.password
          })
          .then(function(authData) {
              $state.go('settings');

            };

          })

with this sign in function with either googleAuth or email&password methods

.controller('googleSignUpCtrl', function(taskref, $scope, $firebaseObject, $firebaseAuth, $state) {
  $scope.googleSignIn = function() {
    var authData = taskref.getAuth();

    taskref.authWithOAuthPopup("google", function(error, authData) {

      if (error) {
        console.log("Login Failed!", error);
      } else {
        taskref.child("users").child(authData.uid).once("value",           function(snapshot) {
          var ifExists = snapshot.exists();

          if (ifExists) {

            $state.go('tabsController.pendingTasks');
            console.log("user already exists");
          } else {
            $state.go('settings');
            $scope.authData = authData;
          }
        });
      }
    }, {
      remember: "sessionOnly",
      scope: "email"
    });
  }
})


text:
Q: Android VKAPI вернуть полученные данные Здравствуйте.
Возник вопрос о том, как можно вернуть данные полученные от VK API Android SDK?
у меня есть функция, которая должна вернуть полученные данные которые вернул VKResponse однако когда я делаю return data, то функция возвращает пустое значение...
код функции
public static ArrayList<String> getUsers(String city, int ofset)
{
    final ArrayList<String> rez = new ArrayList<>();

    VKRequest search_users = new VKRequest("users.search", VKParameters.from("count", 1, "hometown", city, "sex", 1, "status", 6, "offset", ofset, VKApiConst.FIELDS, "photo_max_orig, contacts, last_seen, photo_id"));

    search_users.executeWithListener(new VKRequest.VKRequestListener() {
        @SuppressLint("LongLogTag")
        @Override
        public void onComplete(VKResponse response) {
            super.onComplete(response);

            try
            {
                jUsers = new JSONObject(response.responseString);
                userObject = jUsers.getJSONObject("response");
                usersArray = userObject.getJSONArray("items");

                Log.e("VK_FOUND_USERS_ARRAY", String.valueOf(usersArray));

                for (int i = 0; i < usersArray.length(); i++)
                {
                    object = usersArray.getJSONObject(i);

                    Log.e("VK_CONCRETE_USER_OBJECT", String.valueOf(object));

                    rez.add( object.getString("first_name") );
                    rez.add( object.getString("last_name") );
                    rez.add( object.getString("photo_max_orig") );

                    if ( object.has("home_phone") )
                        rez.add( object.getString("home_phone") );
                    if ( object.has("mobile_phone") )
                        rez.add( object.getString("mobile_phone") );
                }
            }
            catch (JSONException je)
            {
                je.printStackTrace();
            }

        }
    });

    Log.e("VK_FUNCTION_REZULT", String.valueOf(rez));
    return rez; //возвращает ""
}

З.Ы в Java и Android я пока что ещё новичок, так что не судите строго за код и такой вопрос=)
UPDATE 1
вот код функции как предложил @rjhdby
public static ArrayList<String> getUsers(String city, int ofset)
{
    final ArrayList<String> rez = new ArrayList<>();

    VKRequest search_users = new VKRequest("users.search", VKParameters.from("count", 1, "hometown", city, "sex", 1, "status", 6, "offset", ofset, VKApiConst.FIELDS, "photo_max_orig, contacts, last_seen, photo_id"));

    search_users.executeWithListener(new VKRequest.VKRequestListener() {
        @SuppressLint("LongLogTag")
        @Override
        public void onComplete(VKResponse response) {
            super.onComplete(response);

            try
            {
                jUsers = new JSONObject(response.responseString);
                userObject = jUsers.getJSONObject("response");
                usersArray = userObject.getJSONArray("items");

                Log.e("VK_FOUND_USERS_ARRAY", String.valueOf(usersArray));

                for (int i = 0; i < usersArray.length(); i++)
                {
                    object = usersArray.getJSONObject(i);

                    Log.e("VK_CONCRETE_USER_OBJECT", String.valueOf(object));

                    rez.add( object.getString("first_name") );
                    rez.add( object.getString("last_name") );
                    rez.add( object.getString("photo_max_orig") );

                    if ( object.has("home_phone") )
                        rez.add( object.getString("home_phone") );
                    if ( object.has("mobile_phone") )
                        rez.add( object.getString("mobile_phone") );
                }
            }
            catch (JSONException je)
            {
                je.printStackTrace();
            }

            Log.e("VK_FUNCTION_REZULT", String.valueOf(rez));
            return rez; //Error:(403, 24) error: incompatible types: unexpected return value
        }
    });
}

A: search_users.executeWithListener(new VKRequest.VKRequestListener() {

Запускается асинхронно и вызывает VKRequest.VKRequestListener() тогда, когда получен ответ.
Соответственно тут у вас rez еще пустой, так как листенер еще не отработал.
Log.e("VK_FUNCTION_REZULT", String.valueOf(rez));
return rez; //возвращает ""

UPD
На самом деле это очень плохая идея синхронно ожидать ответ от метода, результат которого зависит от вложенного асинхронного кода.
Есть два пути, один плохой, другой хороший.
1) Плохой. Очень плохой. Даже и не думайте о его использовании, привожу только для понимания того, как это все работает.
        catch (JSONException je){
            je.printStackTrace();
        }
    }
});
while(rez.size() == 0){
    //курим
}
return rez;

2) Обычно делается по другому.
Меняем сигнатуру вашего метода следующим образом.
public static void getUsers(String city, int ofset)

Добавляем еще один метод, который принимает результат и делает то, что вам нужно
public static void doSomethingWhenUsersReceived(ArrayList<String> rez){
    //обрабатываем результат
}

В теле листенера, когда результат получен, вызываем этот метод
            MyClass.doSomethingWhenUsersReceived(rez);
        }
        catch (JSONException je)
        {


text:
Q: Android Animation with onDraw or ImageView? I want to create an android game. Everytime someone touches the display the player should go up, and if he releases the player should fall.
With the help of many tutorials I made it work but now I want to animate it and I'm stuck. That means the image of the player should be changed every half a second. Additionally an animated rotation should be created when the player goes up.
However (after hours of googling) I couldnt find any helpful answer to my problem. The Android Developers site talks about creating an ImageView and a XML file. But thats where I'm stuck: I dont have an ImageView, my player (for which I used a PNG file) is simply created by the onDraw() method:
public void onDraw(Canvas canvas) {
       for (Sprite s : sprites) {
            canvas.drawBitmap(s.getGraphic(), s.getLocation().x,
                    s.getLocation().y, null);

        }
}

Now I wanted to ask how I should do the animation and the animated rotation. Should I start off with an ImageView or can I somehow "convert" the onDraw method to an ImageView? Or is there another way to do the animation and animated rotation without an ImageView?
Secondly, if I had to create the ImageView I don't understand how I can make the player "dynamic", i.e.: changing the position when someone touches the display.
Thanks in advance :)
EDIT:
Ok, I created my animation.xml file in the drawable folder:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false" android:id="@+id/splashAnimation">
<item android:drawable="@drawable/ship" android:duration="200" />
<item android:drawable="@drawable/ship_2" android:duration="200" />
</animation-list>

and in my main file I added:
ImageView img = (ImageView) findViewById(R.id.splashAnimation);
    img.setBackgroundResource(R.drawable.animation);
    ship_anim= (AnimationDrawable) img.getBackground();
ship_anim.start();

However, now I get the error message: NullPointerException
Where is the Problem?

A: if you have drawables that describe animation, you can always create xml in your drawable folder like this than add this as imageView to the layout
    <?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/img1" android:duration="100" />
<item android:drawable="@drawable/img2" android:duration="100" />
<item android:drawable="@drawable/img3" android:duration="100" />
<item android:drawable="@drawable/mimg4" android:duration="100" />
<item android:drawable="@drawable/img5" android:duration="100" />
</animation-list>

The code for it would look like this:
myAnimation = (AnimationDrawable) findViewById(R.id.animation);

Add just event handler than
if (!isPlaying)
{
playDrawableAnimation();
    isPlaying = true;
} else
{
    faceAnimation.stop();
    isPlaying = false;

}


text:
Q: Should I call release on these cocoa objective-c variables? In the code below I'm making a new NSString with alloc and initializing it with the contents of some file.  Because I'm calling alloc I know it's my responsibility to call release on the string when I'm done.  But what about the variables "lines" and "line"?  Since the method "componentsSeparatedByString" does not start with the word "new" or "create" can I assume "lines" will be autoreleased?  Same question for "line" since "objectAtIndex" also does not start with "new" or "create".

  NSString* buffer = [[NSString alloc] initWithData:[fileManager contentsAtPath:@"/foo"]
                               encoding:NSUTF8StringEncoding];

  NSArray* lines = [buffer componentsSeparatedByString:@"\n"];
  NSString* line = [lines objectAtIndex:5];

  // do something with line

  [buffer release];

So is the code above okay?  Or should I be calling "release" on lines and line too?  Thanks.

A: Yes lines and line will be autoreleased. Remember: you only have to (auto)release if you have explicitly done either of: alloc, retain, copy, new. (Takes some time to start trusting the conventions.)

A: You should not release lines or line. Unless you are planning to use them beyond your function scope. In that case, you should retain them, and then, release them somewhere else.


text:
Q: Trying to make a div appear in the centre of a scrollable page - bug in my code? Just as a preface to make sure I am clear, I don't want the div to appear dead centre in the middle of the page, I want it in the middle of the viewable window. So if you imagine a long page and the user has scrolled down to near the bottom and clicks the button the div will appear in the centre of the screen near the bottom of the page.
here is my code, which doesn't work in chrome:
                function centerdiv() {
var scrolledX, scrolledY;

scrolledX = document.body.scrollLeft;
scrolledY = document.body.scrolltop;

var centerX, centerY;
centerX = document.body.clientWidth;
centerY = document.body.clientHeight;

var leftoffset = scrolledX + (centerX - 100) / 2;
var topoffset = scrolledY + (centerY - 100) / 2;

 $('.current div[name="popup"]').css({'top' : topoffset + 'px', 'left':
 leftoffset + 'px'});}

            $(function() {
        $("html").ajaxStart(function() {
           centerdiv();
            $(".current div[name=popup]").show();
        });
        $("html").ajaxComplete(function() {
            $(".current div[name=popup]").hide();
        });
    });

Note, this is for an iphone mobile website and the ajaxstart function attaching to the html is crucial as it doesn't work on the iphone any other way on my website.

A: You forget to set position to absolute, or fixed
$('.current div[name="popup"]').css({'top' : topoffset + 'px', 'left':
 leftoffset + 'px', 'position':'absolute' });}

A: Here is my solution that works fine:
    var winH = $(window).height();
    var winW = $(window).width();
    $(this).css('top', winH/2 - $(this).height()/2);
    $(this).css('left', winW/2 - $(this).width()/2);
    $(this).show();

$(this) must refer to the DIV element you want to show in the center.

A: wh = $(window).height();
dh = $("#div").height();
$("#div").css("top",(wh - dh)/ 2 + $(window).scrollTop() + 'px');

Edit:
Not the same for width, it's actually:
ww = $(width).width();
dw = $("#div").width();
$("#div").css("left",(ww - dw)/ 2 + 'px');

But it really depends if you have a fixed viewport or not, there are many ways to center it...
Good Luck!

A: If you don't have horizontal scrolling you can do it partially with straight CSS
div{
  left: 50%;
  margin-left: -[box_width / 2]px;
}


text:
Q: Make a post to a login form of a webpage using C# in Xamarin and Android I just started learning C#, and I have also never experienced in developing mobile environments. I have experience in Java and I could adopt some knowledge from there.
I have VisualStudio 2017RC, and started a Xamarin.Android project. Furthermore there is a ASP.NET site for registration and login, and token generation (SQLite user storage). My goal is to make a view in xamarin where the user can type his/her name and password then can login to the website where he/she get an access token.
I have already made a LoginView, it was a piece of cake...
Now I have to post the filled data to the website and log in to the page using c# in Xamarin.Android. Lets see how far I have got to.
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    SetContentView(Resource.Layout.LoginWebview);

    //code for getting the login details(emial, password) from the user
    //code for getting the access token
    //apiBaseUri is fixed value

    MainAsync(email, password, apiBaseUri, loginToken).Wait();
}

public static async Task MainAsync(string email, string password, string apiBaseUri, string loginToken)
{
    var token = await GetApiTokenAsync(email, password, apiBaseUri, loginToken);
}

public static async Task<string> GetApiTokenAsync(string email, string password, string apiBaseUri, string tokenValue)
{
    var token = string.Empty;

    var handler = new HttpClientHandler()
    {
        AllowAutoRedirect = false
    };

    using (var client = new HttpClient(handler))
    {
        client.BaseAddress = new Uri(apiBaseUri);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.Timeout = TimeSpan.FromSeconds(60);

        //set cookie
        client.DefaultRequestHeaders.Add("Set-Cookie", CookieManager.Instance.GetCookie(apiBaseUri));

        //setup login data
        var formContent = new FormUrlEncodedContent(new[]
        {
 //new KeyValuePair<string, string>("grant_type", "password"),
 new KeyValuePair<string, string>("Email", username),
 new KeyValuePair<string, string>("Password", password),
 new KeyValuePair<string,string>("__RequestVerificationToken",tokenValue),
 new KeyValuePair<string,string>("RememberMe","false")
          });

        //send request
        HttpResponseMessage responseMessage = await client.PostAsync("/Login?returnurl=%2FGame%2Fkz%2FToken", formContent);
        var responseJson = await responseMessage.Content.ReadAsStringAsync();
        var jObject = JObject.Parse(responseJson);
        token = jObject.GetValue("access_token").ToString();

        return token;
    }

}
}

Well at line
HttpResponseMessage responseMessage = await client.PostAsync("/Login?returnurl=%2FGame%2Fkz%2FToken", formContent);

The program hangs and I got no access token back.
Let's see the issue from the website point of view: in the webbrowser the login form can be opened with the following link: (I will use some dummy value ("game") in the url in order to keep it private)
http://www.game.nl/PlayGame/kz/Account/Login?ReturnUrl=%2FGame%2Fkz%2Ftoken
With opening this website I can type the email and the password. Then If I click on the log in button I got an access token (which will be used for later purposes). I would like to get to this point, but of course in c# with android phone
I am going to list some additional info about the website  because I think they are also relevant to the solution.
The details are the following, if I log in with the website. (I check the details with Google Chrome developer tool, at network tab)
General:

*

*Request
URL:http://www.game.nl/PlayGame/kz/Account/Login?returnurl=%2FGame%2Fkz%2Ftoken

*Request Method:POST

*Status Code:302 Found

*Remote Address:(private)

FormData:

*

*Email:example@company.nl

*Password:chocolate09#

*__RequestVerificationToken:CfDJ8L1aKkmfKmBLlQIwHTacxWKOtRekEcOfxKQGBrXUEkE2XpWyxYmMKOTlgZ7gCZq3FEx8ILF_VgQcsjBztZhCwUUYSV966s1BgjFs5I8IefGSoei5hfzK-WQQr8Ztjpn3oGq40neXx4_iBUUMRjFpKz_DdBqzQ

*RememberMe:false

The source of the form data:

Email=example%40company.nl&Password=chocolate09%23&__RequestVerificationToken=CfDJ8L1aKkmfKmBLlQIwHTacxWKOtRekEcOfxKQGBrXUEkE2XpWyxYmMKOTlgZ7gCZq3FEx8ILF_VgQcsjBztZhCwUUYSV966s1BgjFs5I8IefGSoei5hfzK-WQQr8Ztjpn3oGq40neXx4_iBUUMRjFpKz_DdBqzQ&RememberMe=false

So I am stuck at this point, and I do not know why it hangs at
await client.PostAsync("/Login?returnurl=%2FGame%2Fkz%2FToken", formContent);

The last lines of the VS console output:
02-11 00:07:01.404 D/Mono    ( 2853): [0x982bf930] hill climbing, change max number of threads 2
02-11 00:07:07.829 D/Mono    ( 2853): [0x9847f930] worker finishing
Thread finished: <Thread Pool> #4
The thread 'Unknown' (0x4) has exited with code 0 (0x0).

A: Your problem I believe is this line in OnCreate:
MainAsync(email, password, apiBaseUri, loginToken).Wait();
Specifically the .Wait() statement. OnCreate is always called on the UI thread. Whenever you use async/await and wait for the result using .Wait() or .Result bad things happen and your app will hang as the continuation cannot jump back to the UI thread - and you will see this in the call to PostAsync as this is the first call that will actually use a different thread to run on.
I guess the reason you are calling .Wait() is because OnCreate is not an async method - well the good news is it can be. I would mark it as async and await the login (you can mark void methods as async, there are pitfalls with doing so, so be sure to catch all exceptions inside the method!)
// Mark the method as async
protected override async void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    SetContentView(Resource.Layout.LoginWebview);

    // remove the .Wait() and await the method call
    await MainAsync(email, password, apiBaseUri, loginToken);
}


text:
Q: How can I access value in nested dictionary using a single key? Assuming that I have a nested dictionary, that is extracted from pickle file, that contains various levels, I would like to get the value by giving only the last key. Keys are unique considering own 'branch'.
The main problem is that I have multiple keys and levels:
 dict = {

    'A': {

        'X': {
            1: [...],
            2: [...]
        },

        'Y': {
            3: [...],
            4: [...]
        }
    }

    'B': {

        'G': {

            'H': {

                'Z': [...]
            }
        }
    }

    'C': [...]

 }

How can I do that?

A: a simple solution would be a recusrive function that even works for nested, nested dictionarys
outer_dict = {'outer': {'inner': 10, 'even_inner': {'innerst': 25}}}

and the function:
def get_val(search_dict, key):
    """ recursive searching the dict """
    for elem in search_dict:
        if elem == key:
            return search_dict[elem]
        if isinstance(search_dict[elem], dict):
            retval = get_val(search_dict[elem], key)
            if retval is not None:
                return retval

value = get_val(outer_dict, 'innerst')
print(value)
>> 25

Problems:
if the key is not unique you will get only the first match. You will need a list to fill a values into if the key can be there more than once.
Please provide a example next time!


text:
Q: rails - how to map routes to multiple models I have a model called publication.rb and a model called user.rb.  A user can choose to subscribe to various publications and set preferences to how often and which particular sections to receive email from each different publication.
So, a User can choose to receive weekly emails from Pub A and monthly on Pub B.
My question is, how do I go about setting up the routes for this since this is CRUD for a User AND a Publication?
Thanks.

A: It's a case for nested routing.
resources :publications
resources :users do
    resources :publications do
      // methods for subcription
    end
end

Now you can access URLs like for subscription:
/users/ID/publications/A/subscribe
/users/ID/publications/B/subscribe

But URL's like this to manage:
/publications/new
/publications/A/edit
etc...


text:
Q: My .htaccess rewrite rule is NOT affecting subfolders and I wish it were I want to restrict direct access to images in directories while still letting those images appear on my pages.  (For example, I want my index.php to be able to use /images/example.jpg in its layout, but restrict directly typing http://foo.com/images/example.jpg into the browser.
I have this .htaccess code that does what I want, but only IF appears in each and every directory.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?foo.com [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?foo.com.*$ [NC]
RewriteRule .*\.(gif|jpg)$ - [F]

BUT, when this .htaccess is placed in the parent directory, it fails to affect the subdirectories.  I have looked through many many posts, and almost all are trying to turn off .htaccess in subdirectories. This is the opposite problem.
I will eventually have thousands of subdirectories under the parent, and I don't want to have to place an .htaccess it in each.
It seems a crazy question, but how do I make this .htaccess rewrite rule work in all subdirectories too?
Thanks in advance!


text:
Q: Create high-resolution charts with Flot on Retina displays I want to show some simple chart in my web application, but using Flot on an Apple device with Retina display looks blurry.
I use the 'normal' viewport settings:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />

and this container for Flot to draw in:

This is what I get:

So obivously Flot doesn't use window.devicePixelRatio by default, so I wanted to help out with some custom code:
var newWidth = $(chart.getCanvas()).attr("width") * window.devicePixelRatio;
var newHeight = $(chart.getCanvas()).attr("height") * window.devicePixelRatio;
$(chart.getCanvas()).attr("width", newWidth);
$(chart.getCanvas()).attr("height", newHeight);
chart.setupGrid();
chart.draw();

This in fact changes the canvas' dimensions and they keep that way even after the drawing. On the iPhone 4S it tells me the canvas dimensions are now 600 * 800 (after the drawing), but it still doesn't look crisp.


text:
Q: Sharing Global variables in python I have 2 files a.py and b.py as follows:
a.py
import b.py
Test="abc"
def main(args):
  global Test
  if args.target=="this":
     Test="klm"
  b.fun()
  #rest of the body which I intend to execute only once
  #hence I cannot call main() again
if __name__ == "__main__":
  #some arguments are parsed
  args = parser.parse_args()
  main(args)

b.py
import a
print a.Test

EDIT: Output:
python a.py
abc

So basically my question is why is the Test variable not getting updated in b.py and how can I make this work? Thanks.

A: import a
a.main()
print a.Test
a.Test = "new Value"
print a.Text

You never invoke the main function.  When you import a module, __name__ is not "__main__", so your main() never runs.  When you run a.py directly it will run main()

A: Added due to question edit:
You need to consider the ordering of the imports execution. Consider these working files.
a.py
print("Entering a")
import argparse

import b
Test="abc"
print("Id of Test: ", id(Test))

def main(args):
  global Test
  if args.target=="this":
     Test="klm"
  b.fun()
  #rest of the body which I intend to execute only once
  #hence I cannot call main() again
if __name__ == "__main__":
  #some arguments are parsed
  print('Entering main')
  parser = argparse.ArgumentParser()
  parser.add_argument('--target', dest='target', type=str)
  args = parser.parse_args()
  main(args)

b.py
print("Entering b")
import a
print a.Test

def fun():
    pass

The console produces the following:
$ python a.py
Entering a
Entering b
Entering a
('Id of Test: ', 40012016L)
abc
('Id of Test: ', 40012016L)
Entering main

The problem is, when you import a python module/file, you will immediately execute all the statements in that module. As such, you have a problem with your dependencies (aka imports), because b is importing a before the value of Test is 'corrected' and then immediately acting on this.
Consider two changes. First, introduce a third file config.py that contains this configuration information and that b does not import a. Second, move all your statements that require this config in b into functions that are called/bootstrapped by a, as obviously intended.
Previous answer:
I have a solution demonstrating the issue, by only modifying b.py
def fun():  # Added because your main calls this. An error?
    pass

from a import Test, main
import a
print Test    # prints 'abc'
print a.Test  # prints 'abc'
main()
print Test    # prints 'abc'
print a.Test  # prints 'klm'

Within the python interpretor, I can produce the following:
>>> import b
abc
abc
abc
klm

In your code, you create a new variable called Test with the command from a import Test that points to the original string object. You actually want to access the Test variable owned by the module a.

A: In a.py you run main in the if statement:
if __name__ == "__main__":
     main()

Only executes main() if that is the main script. When you import the module all the code in the if block is not run because it is not the main script. To have the main method be called remove the if statement or just call main in b.py.


text:
Q: 403 Forbidden when using organizations api on github I have some problem adding a user to the organization using github api.
I've used a GET request to get membership status with the organization that I'm an owner. But I get the response
GET http://api.github.com/orgs/romanc-org/memberships/gromanc
Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 -- response --
403 Forbidden
Server:  GitHub.com
Date:  Tue, 15 Aug 2017 10:34:33 GMT
Content-Type:  application/json; charset=utf-8
Transfer-Encoding:  chunked
Status:  403 Forbidden
X-RateLimit-Limit:  5000
X-RateLimit-Remaining:  4995
X-RateLimit-Reset:  1502793489
X-OAuth-Scopes:  admin:org, repo, user
X-Accepted-OAuth-Scopes:  admin:org, read:org, repo, user, write:org
X-OAuth-Client-Id:  212a8581bdca54d1f503
X-GitHub-Media-Type:  github.v3; format=json
access-control-expose-headers:  ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:  *
content-security-policy:  default-src 'none'
Strict-Transport-Security:  max-age=31536000; includeSubdomains; preload
X-Content-Type-Options:  nosniff
X-Frame-Options:  deny
X-XSS-Protection:  1; mode=block
X-Runtime-rack:  0.027377
Content-Encoding:  gzip
X-GitHub-Request-Id:  2F55:2B87:2E85F4A:6FC7673:5992CE39

{
  "message": "You must be a member of romanc-org to see membership information for gromanc.",
  "documentation_url": "https://developer.github.com/v3/orgs/members/#get-organization-membership"
}

I tried to fetch other users status but faile with the same error.
I also tried to PUT a user to the organization but get
PUT http://api.github.com/orgs/romanc-org/memberships/bt080527
Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Content-Type: application/json
{
  "login": "bt080527",
  "id": 30951532,
  "avatar_url": "https://avatars2.githubusercontent.com/u/30951532?v=4",
  "gravatar_id": "",
  "url": "https://api.github.com/users/bt080527",
  "html_url": "https://github.com/bt080527",
  "followers_url": "https://api.github.com/users/bt080527/followers",
  "following_url": "https://api.github.com/users/bt080527/following{/other_user}",
  "gists_url": "https://api.github.com/users/bt080527/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/bt080527/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/bt080527/subscriptions",
  "organizations_url": "https://api.github.com/users/bt080527/orgs",
  "repos_url": "https://api.github.com/users/bt080527/repos",
  "events_url": "https://api.github.com/users/bt080527/events{/privacy}",
  "received_events_url": "https://api.github.com/users/bt080527/received_events",
  "type": "User",
  "site_admin": false,
  "name": null,
  "company": null,
  "blog": "",
  "location": null,
  "email": null,
  "hireable": null,
  "bio": null,
  "public_repos": 0,
  "public_gists": 0,
  "followers": 0,
  "following": 0,
  "created_at": "2017-08-12T09:57:40Z",
  "updated_at": "2017-08-12T09:57:40Z"
}

 -- response --
403 Forbidden
Server:  GitHub.com
Date:  Tue, 15 Aug 2017 10:47:51 GMT
Content-Type:  application/json; charset=utf-8
Transfer-Encoding:  chunked
Status:  403 Forbidden
X-RateLimit-Limit:  5000
X-RateLimit-Remaining:  4997
X-RateLimit-Reset:  1502797454
X-OAuth-Scopes:  admin:org, repo, user
X-Accepted-OAuth-Scopes:  admin:org, repo
X-OAuth-Client-Id:  212a8581bdca54d1f503
X-GitHub-Media-Type:  github.v3; format=json
access-control-expose-headers:  ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:  *
content-security-policy:  default-src 'none'
Strict-Transport-Security:  max-age=31536000; includeSubdomains; preload
X-Content-Type-Options:  nosniff
X-Frame-Options:  deny
X-XSS-Protection:  1; mode=block
X-Runtime-rack:  0.200124
Content-Encoding:  gzip
X-GitHub-Request-Id:  2FED:2B88:139A091:2BBE319:5992D157

{
  "message": "You must be an admin to add or update an organization membership.",
  "documentation_url": "https://developer.github.com/v3/orgs/members/#add-or-update-organization-membership"
}

What I'm doing wrong?

A: The reason why that's happening is that you're using a token for an OAuth application to perform an action on an organization. That organization has this feature enabled:
https://help.github.com/articles/about-oauth-app-access-restrictions/
but the application in question hasn't been whitelisted. So, the feature kicks in and makes the API behave as you are not a member of the organization.
You'll either need to whitelist the application in question for the organization, or disable that feature.


text:
Q: How to install pytesseract? I have a problem with installing pytesseract. I tried:
pip install pytesseract

I got an error:
Collecting pytesseract
  Using cached https://files.pythonhosted.org/packages/47/e5/892d78db0d26372aa376fc1b127e9cd4cc158727a76e0802069115fcbd6e/pytesseract-0.3.0.tar.gz
Requirement already satisfied: Pillow in /usr/lib/python3/dist-packages (from pytesseract) (5.1.0)
Installing collected packages: pytesseract
  Running setup.py install for pytesseract ... error
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-cu7_ki6k/pytesseract/setup.py'"'"'; __file__='"'"'/tmp/pip-install-cu7_ki6k/pytesseract/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-07yttrn0/install-record.txt --single-version-externally-managed --compile
         cwd: /tmp/pip-install-cu7_ki6k/pytesseract/
    Complete output (20 lines):
    running install
    running build
    running build_py
    creating build
    creating build/lib
    creating build/lib/pytesseract
    copying src/pytesseract.py -> build/lib/pytesseract
    copying src/__init__.py -> build/lib/pytesseract
    running egg_info
    writing pytesseract.egg-info/PKG-INFO
    writing dependency_links to pytesseract.egg-info/dependency_links.txt
    writing entry points to pytesseract.egg-info/entry_points.txt
    writing requirements to pytesseract.egg-info/requires.txt
    writing top-level names to pytesseract.egg-info/top_level.txt
    reading manifest file 'pytesseract.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    writing manifest file 'pytesseract.egg-info/SOURCES.txt'
    running install_lib
    creating /usr/local/lib/python3.6/dist-packages/pytesseract
    error: could not create '/usr/local/lib/python3.6/dist-packages/pytesseract': Permission denied
    ----------------------------------------
ERROR: Command errored out with exit status 1: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-cu7_ki6k/pytesseract/setup.py'"'"'; __file__='"'"'/tmp/pip-install-cu7_ki6k/pytesseract/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-07yttrn0/install-record.txt --single-version-externally-managed --compile Check the logs for full command output.

Pillow I have already installed.
pip install pillow
Requirement already satisfied: pillow in /usr/lib/python3/dist-packages (5.1.0)

I would like to run a code for converting image to .txt.
EDIT
After your advise I tried this:
I have this .py file that should convert images to strings.
img2str.py:
from PIL import Image
from pytesseract import image_to_string

image = Image.open('image.png', mode='r')
print(image_to_string(image))

python3 img2str.py
Traceback (most recent call last):
  File "/home/linux/.local/lib/python3.6/site-packages/pytesseract/pytesseract.py", line 223, in run_tesseract
    proc = subprocess.Popen(cmd_args, **subprocess_args())
  File "/usr/lib/python3.6/subprocess.py", line 729, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.6/subprocess.py", line 1364, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'tesseract': 'tesseract'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "img2str.py", line 4, in <module>
    results = tes.image_to_string(Image.open('image.png'))
  File "/home/linux/.local/lib/python3.6/site-packages/pytesseract/pytesseract.py", line 345, in image_to_string
    }[output_type]()
  File "/home/linux/.local/lib/python3.6/site-packages/pytesseract/pytesseract.py", line 344, in <lambda>
    Output.STRING: lambda: run_and_get_output(*args),
  File "/home/linux/.local/lib/python3.6/site-packages/pytesseract/pytesseract.py", line 253, in run_and_get_output
    run_tesseract(**kwargs)
  File "/home/linux/.local/lib/python3.6/site-packages/pytesseract/pytesseract.py", line 225, in run_tesseract
    raise TesseractNotFoundError()
pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your path

sudo pip install pytesseract --user
[sudo] heslo pro linux:
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

According to your advise I used the commad for the second time and it seems to be installed.
pip install pytesseract --user
Requirement already satisfied: pytesseract in ./.local/lib/python3.6/site-packages (0.3.0)
Requirement already satisfied: Pillow in /usr/lib/python3/dist-packages (from pytesseract) (5.1.0)

A: This error is called because you don't have permission to create a temp file that is required for the installation of pytesseract.
If you run pip install pytesseract --user that should fix your problem.
If that doesn't fix it, then run sudo pip install pytesseract --user, as that uses the highest level of access the system can give you.


text:
Q: Why is the md5 hash of the tar-part of a tar.gz via TeeReader wrong? I was just experimenting with archive/tar and compress/gzip, for automated processing of some backups I have.
My problem hereby is: I have various .tar files and .tar.gz files floating around, and thus I want to extract the hash (md5) of the .tar.gz file, and the hash (md5) of the .tar file as well, ideally in one run.
The example code I have so far, works perfectly fine for the hashes of the files in the .tar.gz as well for the .gz, but the hash for the .tar is wrong and I can't find out what the problem is.
I looked at the tar/reader.go file and I saw that there is some skipping in there, yet I thought everything should run over the io.Reader interface and thus the TeeReader should still catch all the bytes.
package main

import (
    "archive/tar"
    "compress/gzip"
    "crypto/md5"
    "fmt"
    "io"
    "os"
)

func main() {
    tgz, _ := os.Open("tb.tar.gz")
    gzMd5 := md5.New()
    gz, _ := gzip.NewReader(io.TeeReader(tgz, gzMd5))
    tarMd5 := md5.New()
    tr := tar.NewReader(io.TeeReader(gz, tarMd5))
    for {
        fileMd5 := md5.New()
        hdr, err := tr.Next()
        if err == io.EOF {
            break
        }
        io.Copy(fileMd5, tr)
        fmt.Printf("%x  %s\n", fileMd5.Sum(nil), hdr.Name)
    }
    fmt.Printf("%x  tb.tar\n", tarMd5.Sum(nil))
    fmt.Printf("%x  tb.tar.gz\n", gzMd5.Sum(nil))
}

Now for the following example:
$ echo "a" > a.txt
$ echo "b" > b.txt
$ tar cf tb.tar a.txt b.txt
$ gzip -c tb.tar > tb.tar.gz
$ md5sum a.txt b.txt tb.tar tb.tar.gz

60b725f10c9c85c70d97880dfe8191b3  a.txt
3b5d5c3712955042212316173ccf37be  b.txt
501352dcd8fbd0b8e3e887f7dafd9392  tb.tar
90d6ba204493d8e54d3b3b155bb7f370  tb.tar.gz

On Linux Mint 14 (based on Ubuntu 12.04) with go 1.02 from the Ubuntu repositories the result for my go program is:
$ go run tarmd5.go
60b725f10c9c85c70d97880dfe8191b3  a.txt
3b5d5c3712955042212316173ccf37be  b.txt
a26ddab1c324780ccb5199ef4dc38691  tb.tar
90d6ba204493d8e54d3b3b155bb7f370  tb.tar.gz

So all hashes except for tb.tar are as expected.
(Of course if you retry that example your .tar and .tar.gz will be different from this, because of different timestamps)
Any hint about how to get it work would be greatly appreciated, I really would prefer to have it in 1 run though (with the TeeReaders).

A: The issue occurs because tar doesn't read every byte from your reader. After hashing each file, you need to empty the reader to ensure every byte is read and hashed. The way I normally do this is use io.Copy() to read until EOF.
package main

import (
    "archive/tar"
    "compress/gzip"
    "crypto/md5"
    "fmt"
    "io"
    "io/ioutil"
    "os"
)

func main() {
    tgz, _ := os.Open("tb.tar.gz")
    gzMd5 := md5.New()
    gz, _ := gzip.NewReader(io.TeeReader(tgz, gzMd5))
    tarMd5 := md5.New()
    tee := io.TeeReader(gz, tarMd5) // need the reader later
    tr := tar.NewReader(tee)
    for {
        fileMd5 := md5.New()
        hdr, err := tr.Next()
        if err == io.EOF {
            break
        }
        io.Copy(fileMd5, tr)
        fmt.Printf("%x  %s\n", fileMd5.Sum(nil), hdr.Name)
    }
    io.Copy(ioutil.Discard, tee) // read unused portions of the tar file
    fmt.Printf("%x  tb.tar\n", tarMd5.Sum(nil))
    fmt.Printf("%x  tb.tar.gz\n", gzMd5.Sum(nil))
}

Another option is to just add io.Copy(tarMd5, gz) before your tarMd5.Sum() call. I think the first way is clearer even if I needed to add/modify four lines instead of one.


text:
Q: Storing UIImage for later use I am making what can be described as an image manipulation app. My idea is that the user imports UIImages through the pod YPImagePicker and they are stored in two arrays, one for thumbnails and one for the fullsized images. A UICollectionView is then populated with the thumbnails and when the user taps the thumbnail the fullsized image is displayed in a UIImageView.
I am having memory issues with this solution. The RAM hits 300 MB on an iPhone X when I have roughly 10-12 images imported, which I have understood is too much. I guess it is because I store all the fullsized images in an array? Should I store the fullsized images on the users hard drive and not in RAM-memory? Or is there any way I can access the images from the users photo library and fetch the image when the user taps the thumbnail?


text:
Q: How to have yarn fail on yarn install when package.json and yarn.lock are out of sync? On a project I have replaced npm with yarn to get the benefits of it, and also enforce our dependencies are locked in via the yarn.lock.
Now, a developer added a library with npm@4, which only changed the package.json, and not of course the yarn.lock.
I would have expected the yarn install command to crash on the build server, yet yarn has the--to me unexpected behavior--of adding those libraries in their most current version and then updating the yarn.lock on the remote:
$ yarn install
[1/4] Resolving packages...
[2/4] Fetching packages...
warning fsevents@1.1.2: The platform "linux" is incompatible with this module.
info "fsevents@1.1.2" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
Done in 5.07s.

This contradicts yarn's purpose, as the build job does not push the yarn.lock back to the repository nor should it.
I want each developer to be responsible of the version they are checking in.
Hence, is there a way to have yarn install exit with an error code if the package.json and yarn.lock are out of sync?

A: You want the --frozen-lockfile parameter:
$ yarn install --frozen-lockfile
yarn install v0.27.5
warning ../package.json: No license field
[1/4] Resolving packages...
error Your lockfile needs to be updated, but yarn was run with `--frozen-lockfile`.

This was also recently made clear in the docs for yarn install:

yarn install
Install all the dependencies listed within package.json
  in the local node_modules folder.
The yarn.lock file is utilized as follows:

*

*If yarn.lock is present and is enough to satisfy all the dependencies
  listed in package.json, the exact versions recorded in yarn.lock are
  installed, and yarn.lock will be unchanged. Yarn will not check for
  newer versions.

*If yarn.lock is absent, or is not enough to satisfy
  all the dependencies listed in package.json (for example, if you
  manually add a dependency to package.json), Yarn looks for the newest
  versions available that satisfy the constraints in package.json. The
  results are written to yarn.lock.

  If you want to ensure yarn.lock is not updated, use --frozen-lockfile.


text:
Q: How to check (many possible) multiple condtions I have some files for some different (mainly re-branding) setups, we can add more in the future (these versions are not very much related and can include some of the files). Now, these files can also be grouped by equipment category, more to be added in the future, of course. I can make a setup for just an equipment or for all. So, for a file, I can have a combination of any setup types and an equipment (or all of them).
Hence, I can imagine a line like this:
<copy file="${dir.binaries}/A.dll" todir="${dir.install.ProgramFiles}" <IF (NOT (conf.1 or conf.2)) AND (equipment.1 or ALL) />

Now, I can make a condition for all these cases and use if:set, but these conditions can soon be flooding my ant file, didn't they ? A worst case scenario: 4 setups and 5 equipments (or all) => (4+6+4+1)*(5+1) = 90 conditions, isn't it :) ? I can imagine a macrodef, something like IsFileIncluded(equipment, excluded setups, actual setup, actual equipment) - can this work? Another solution?
I want pure ant since this has to also work on the server or a very good reason to convince them to include something else.


text:
Q: Visual studio profiler takes a long time to load not existing symbols I use Visual Studio profiler to find slow places in my page, and every time after profiling it analyzes report. Via output window and Fiddler I see that it tries to find symbols for ntdll.dll, kernel32.dll, iiscore.dll and so on. In Fiddler I see about ~100 attempts to load urls like this:
http://srv.symbolsource.org/pdb/Public/iisutil.pdb/FD34931572094C6E9FD7444A2C3600E92/iisutil.pdb
http://srv.symbolsource.org/pdb/Public/iisutil.pdb/FD34931572094C6E9FD7444A2C3600E92/iisutil.pd_
Result - 404. Every time.
So, 1 minute I profile my application, then 5 minutes I wait for this. How to fix it to load correct pdbs, or skip load 3rd party pdbs?


text:
Q: Why CSS Media Query doesn't work on mobile device but yes on Google Chrome device emulator? As from the title, I don't understand why the media query works on emulator device on Google Chrome and it doesn't work on a real mobile device.
Html meta tag
<meta name="viewport" content="width=max-width, initial-scale=1, maximum-scale=1, user-scalable=no">

Css:
@media screen and (min-device-width:640px) and (max-device-width:767px){...}

Actually I've set up the min and max resolutions from 640/768/850/1024 for mobile devices screen resolution, but it seems be an error, cause .... I don't understand yet

A: You should apply device width in meta viewport
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

A: The CSS should be like the following and check:
@media screen and (min-width:640px) and (max-width:767px){...}


text:
Q: biblatex-chicago doesn't print bibliography using TeXworks I'm doing a large document on Overleaf but I need to upgrade to compile this document (1st figure) so I've tried to compile using TeXworks but It doesn't print the bibliography (2nd figure).
what I need to do on TeXworks

What I got

My configuration
\documentclass[a4paper,12pt,oneside]{article}
\usepackage{ifxetex}

\ifxetex
  \usepackage{fontspec}
\else
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
  \usepackage{lmodern}
\fi
\usepackage[english]{babel} %
\usepackage{csquotes}
\usepackage{lipsum}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{float}
\usepackage{eurosym}
\usepackage{ulem}
\usepackage{multirow}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{color}
\usepackage{setspace}
\usepackage{lscape}
\usepackage{sectsty}
\usepackage{comment}
\usepackage{footmisc}
\usepackage{longtable}
\usepackage{pdflscape}
\usepackage{subcaption}
\usepackage{array}
\usepackage{hyperref}
\usepackage{colortbl}
\usepackage{verbatim}
\usepackage{threeparttable}
\usepackage[top=2.5cm,bottom=2.5cm,left=2.5cm,right=2.5cm]{geometry}
\usepackage{fancyhdr}
\usepackage{rotating}
\usepackage{mathrsfs}
\usepackage{pstricks}
\usepackage{egameps}
\pagenumbering{arabic}
\usepackage{copyrightbox}
\usepackage{makecell, booktabs}
\usepackage{tabularx}

\usepackage{amsthm}
\newtheorem{definition}{Definition}

\usepackage{ragged2e}
\usepackage{mathptmx}

\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}

% subsubsubsection
\setcounter{secnumdepth}{5}
\setcounter{tocdepth}{5}
\makeatletter
\newcommand\subsubsubsection{\@startsection{paragraph}{4}{\z@}{-2.5ex\@plus -1ex \@minus -.25ex}{1.25ex \@plus .25ex}{\normalfont\normalsize\bfseries}}
\newcommand\subsubsubsubsection{\@startsection{subparagraph}{5}{\z@}{-2.5ex\@plus -1ex \@minus -.25ex}{1.25ex \@plus .25ex}{\normalfont\normalsize\bfseries}}
\makeatother

\usepackage{mathptmx}

\hypersetup{%
   colorlinks = {true},
   urlcolor = {black},
   linkcolor = {black},
   citecolor = {black},
}

\newenvironment{conditions*}
  {\par\vspace{\abovedisplayskip}\noindent
   \tabularx{\columnwidth}{>{$}l<{$} @{${}={}$} >{\raggedright\arraybackslash}X}}
  {\endtabularx\par\vspace{\belowdisplayskip}}

%\numberwithin{equation}{section}
%\numberwithin{figure}{section}
%\numberwithin{table}{section}

%%%%%
%BIB
%%%%%

\usepackage[authordate, numbermonth=false,
            backend=biber, noibid, bibencoding=utf8]{biblatex-chicago}

\DeclareFieldFormat{titleaddon}{%
   \mkbibbrackets{\ifcapital{\MakeCapital{#1\isdot}}{#1\isdot}}}

\begin{filecontents}{bib_test.bib}
@article{Owusu2016,
author = {Owusu, Phebe Asantewaa and Asumadu-Sarkodie, Samuel},
doi = {10.1080/23311916.2016.1167990},
issn = {23311916},
journal = {Cogent Engineering},
number = {1},
publisher = {Cogent},
title = {{A review of renewable energy sources, sustainability issues and climate change mitigation}},
volume = {3},
pages = {1--14},
year = {2016}
}
@article{Fell2017,
author = {Fell, Michael James},
doi = {10.1016/j.erss.2017.02.010},
issn = {22146296},
journal = {Energy Research and Social Science},
month = {may},
pages = {129--140},
publisher = {Elsevier},
title = {{Energy services: A conceptual review}},
volume = {27},
year = {2017}
}
\end{filecontents}

\addbibresource{bib_test.bib}
%%%%%
%
%%%%%

\newcommand\fnote[1]{\captionsetup{font=footnotesize}\caption*{#1}}

\lhead{}
\cfoot{}                                    % left header: document author
\rfoot{\large\thepage}                      % center footer: page number
\clubpenalty=10000 \widowpenalty=10000 \setlength{\parindent}{2em}
\def\qed{{\quad \vrule height 5pt width 5pt depth 0pt}}

\pagestyle{fancy}

\fancyhead{}
\fancyfoot{}

\fancyfoot[R]{\thepage}

\usepackage{chngcntr}
\counterwithin{table}{section}
\counterwithin{figure}{section}

\begin{document}

\DeclareNameWrapperFormat{labelname:poss}{#1's}
\newrobustcmd*{\posscitealias}{%
  \AtNextCite{%
    \DeclareNameWrapperAlias{labelname}{labelname:poss}}}

\newrobustcmd*{\posscite}{%
  \posscitealias
  \textcite}

\newrobustcmd*{\Posscite}{\bibsentence\posscite}

\newrobustcmd*{\posscites}{%
  \posscitealias
  \textcites}

\renewcommand{\thepage}{\roman{page}}

\autocite[11]{Owusu2016}. According to \textcite[137]{Fell2017} and  \cite{Fell2017}. Hence, energy services are a powerful engine of economic and social development.

\addcontentsline{toc}{section}{References}
\begin{singlespace}
\printbibliography
\end{singlespace}

\end{document}

note: I had to change the biblatex.def
%\newcommand*{\bibsetup}{%
%  \interlinepenalty=5000\relax
%  \widowpenalty=10000\relax
%  \clubpenalty=10000\relax
%  \raggedbottom
%  \frenchspacing
%  \biburlsetup}

%%% by

\appto{\bibsetup}{\sloppy}


text:
Q: Extracting specific multiple line of records that is pipe delimited in perl I have a file that looks like
NAME|JOHN|TOKYO|JPN
AGE|32|M
INFO|SINGLE|PROFESSIONAL|IT
NAME|MARK|MANILA|PH
AGE|37|M
INFO|MARRIED|PROFESSIONAL|BPO
NAME|SAMANTHA|SYDNEY|AUS
AGE|37|F
INFO|MARRIED|PROFESSIONAL|OFFSHORE
NAME|LUKE|TOKYO|JPN
AGE|27|M
INFO|SINGLE|PROFESSIONAL|IT
I want to separate the records by country. I have stored each line into array variable @fields
my @fields = split(/\|/, $_ );

making $fields[3] as my basis for sorting it. I wanted it to separate into 2 output text files
OUTPUT TEXT FILE 1:
NAME|JOHN|TOKYO|JPN
AGE|32|M
INFO|SINGLE|PROFESSIONAL|IT
NAME|LUKE|TOKYO|JPN
AGE|27|M
INFO|SINGLE|PROFESSIONAL|IT

OUTPUT TEXT FILE 2
NAME|MARK|MANILA|PH
AGE|37|M
INFO|MARRIED|PROFESSIONAL|BPO
NAME|SAMANTHA|SYDNEY|AUS
AGE|37|F
INFO|MARRIED|PROFESSIONAL|OFFSHORE

Putting all that is from JPN to output text 1 & non-JPN country to output text file 2
here's the code that what trying to work out
use strict;
use warnings;
use Data::Dumper;
use Carp qw(croak);

my @fields;
my $tmp_var;
my $count;
;
my ($line, $i);

my $filename = 'data.txt';
open(my $input_fh, '<', $filename ) or croak "Can't open $filename: $!";

open(OUTPUTA, ">", 'JPN.txt') or die "wsl_reformat.pl: could not open $ARGV[0]";
open(OUTPUTB, ">", 'Non-JPN.txt') or die "wsl_reformat.pl: could not open $ARGV[0]";

my $fh;
while (<$input_fh>) {

    chomp;
   my @fields = split /\|/;

   if ($fields[0] eq 'NAME') {
    for ($i=1; $i < @fields; $i++) {
        if ($fields[3] eq 'JPN') {
           $fh = $_;
            print OUTPUTA $fh;
        }
        else {
           $fh = $_;
            print OUTPUTB $fh;
        }
    }

}
}

close(OUTPUTA);
close(OUTPUTB)

Still has no luck on it :(

A: You didn't say what you needed help with, so I'm assuming it's coming up with an algorithm. Here's a good one:

*

*Open the file to read.

*Open the file for the JPN entries.

*Open the file for the non-JPN entries.

*While not eof,

*

*Read a line.

*Parse the line.

*If it's the first line of a record,

*

*If the person's country is JPN,

*

*Set current file handle to the file handle for JPN entries.

*Else,

*

*Set current file handle to the file handle for non-JPN entries.

*Print the line to the current file handle.

my $jpn_qfn   = '...';
my $other_qfn = '...';

open(my $jpn_fh,   '>', $jpn_qfn)
   or die("Can't create $jpn_qfn: $!\n");
open(my $other_fh, '>', $other_qfn)
   or die("Can't create $other_qfn: $!\n");

my $fh;
while (<>) {
   chomp;
   my @fields = split /\|/;
   if ($fields[0] eq 'NAME') {
      $fh = $fields[3] eq 'JPN' ? $jpn_fh : $other_fh;
   }

   say $fh $_;
}

A: Here is the way I think ikegami was saying, but I've never tried this before (although it gave the correct results).
#!/usr/bin/perl
use strict;
use warnings;

open my $jpn_fh, ">", 'o33.txt' or die $!;
open my $other_fh, ">", 'o44.txt' or die $!;

my $fh;
while (<DATA>) {
    if (/^NAME/) {
        if (/JPN$/) {
            $fh = $jpn_fh;
        }
        else {
            $fh = $other_fh;
        }
    }
    print $fh $_;
}

close $jpn_fh or die $!;
close $other_fh or die $!;

__DATA__
NAME|JOHN|TOKYO|JPN
AGE|32|M
INFO|SINGLE|PROFESSIONAL|IT
NAME|MARK|MANILA|PH
AGE|37|M
INFO|MARRIED|PROFESSIONAL|BPO
NAME|SAMANTHA|SYDNEY|AUS
AGE|37|F
INFO|MARRIED|PROFESSIONAL|OFFSHORE
NAME|LUKE|TOKYO|JPN
AGE|27|M
INFO|SINGLE|PROFESSIONAL|IT

A: #!/usr/bin/env perl

use 5.012;
use autodie;
use strict;
use warnings;

# store per country output filehandles
my %output;

# since this is just an example, read from __DATA__ section

while (my $line = <DATA>) {
    # split the fields
    my @cells = split /[|]/, $line;

    # if first field is NAME, this is a new record
    if ($cells[0] eq 'NAME') {
        # get the country code, strip trailing whitespace
        (my $country = $cells[3]) =~ s/\s+\z//;

        # if we haven't created and output file for this
        # country, yet, do so
        unless (defined $output{$country}) {
            open my $fh, '>', "$country.out";
            $output{$country} = $fh;
        }
        my $out = $output{$country};

        # output this and the next two lines to
        # country specific output file
        print $out $line, scalar <DATA>, scalar <DATA>;
    }
}

close $_ for values %output;

__DATA__
NAME|JOHN|TOKYO|JPN
AGE|32|M
INFO|SINGLE|PROFESSIONAL|IT
NAME|MARK|MANILA|PH
AGE|37|M
INFO|MARRIED|PROFESSIONAL|BPO
NAME|SAMANTHA|SYDNEY|AUS
AGE|37|F
INFO|MARRIED|PROFESSIONAL|OFFSHORE
NAME|LUKE|TOKYO|JPN
AGE|27|M
INFO|SINGLE|PROFESSIONAL|IT

A: Thanks for your Help heaps
I was able to solved this problem in perl,
many thanks
#!/usr/local/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Carp qw(croak);

my @fields;
my $tmp_var;
my ($rec_type, $country);

my $filename = 'data.txt';

open (my $input_fh, '<', $filename ) or croak "Can't open $filename: $!";

open  my $OUTPUTA, ">", 'o33.txt' or die $!;
open  my $OUTPUTB, ">", 'o44.txt' or die $!;

my $Combline;
while (<$input_fh>) {

    $_ = _trim($_);
    @fields = split (/\|/, $_);
    $rec_type = $fields[0];
    $country = $fields[3];

        if ($rec_type eq 'NAME') {
            if ($country eq 'JPN') {
                *Combline = $OUTPUTA;
            }
            else {
                *Combline = $OUTPUTB;
            }
        }
   print  Combline;
}

close $OUTPUTA or die $!;
close $OUTPUTB or die $!;

sub _trim {
    my $word = shift;
    if ( $word ) {
        $word =~ s/\s*\|/\|/g;      #remove trailing spaces
        $word =~ s/"//g;        #remove double quotes
    }
    return $word;
}


text:
Q: Проблема с переводом в Django 2.1 Я создал форму которая наследуется от AuthenticationForm. Мне нужно было сделать для поля ввода placeholder. Я написал вот так вот:
class LoginForm(AuthenticationForm):
    username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True, 'class': 'form-control', 'placeholder': _('Username')})

Вопрос такой: почему _('Username') не переводится как "Имя пользователя". Что вместо _('Username') нужно подставить?
К примеру _('Password') почему-то переводится.
Функция _() это from django.utils.translation import gettext, gettext_lazy as _
Надеюсь вы поняли вопрос.

A: Нужно использовать
_('username')

вместо
_('Username')


text:
Q: Java guess game. How do I use data validation to check if a number is within a certain range? I need help coding a set of statements of data validation that checks if a user entry is within a range of 0 and 100, and anything the user types that ISNT a non-decimal integer between 1 and 100 should display an error message. Also I need a way to code how I can get a "goodbye" output to only display if the user enters "n" not "n" and "y." N meaning no and y meaning yes.
Heres my code.
import java.util.Scanner;

public class GuessingGameCalc {

    private static void displayWelcomeMessage(int max) {

        System.out.println("Welome to the Java Guessing Game!");
        System.out.println(" ");
        System.out.println("I'm thinking of a number between 1 and" + " " + max + " " + "let's see if you guess what it is!");
        System.out.println(" ");

    }

    public static int calculateRandomValue(int max) {

      double value = (int) (Math.random() * max + 1);
      int number = (int) value;
      number++;
      return number;
    }

    public static void validateTheData(int count) {
        if( count < 3) {
            System.out.println("Good job!");
        } else if (count < 7) {
            System.out.println("Need more practice.");
        } else{
            System.out.println("Need way more practice.");
        }
    }

    public static void main(String[] args) {
        final int max = 100;
        String prompt = "y";
        displayWelcomeMessage(max);
        int unit = calculateRandomValue(max);
        Scanner sc = new Scanner(System.in);
        int counter = 1;

        while (prompt.equalsIgnoreCase("y")) {
            while (true) {
                System.out.println("Please enter a number.");

                int userEntry = sc.nextInt();

                if (userEntry < 1 || userEntry > max) {
                    System.out.println("Invalid guess! Guess again!");
                    continue;
                }

                if (userEntry < unit) {
                    if ( (unit - userEntry) > 10 ) {
                        System.out.println("Way Too low! Guess higher!");
                    } else {
                        System.out.println("Too low! Guess higher!");
                    }
                } else if (userEntry > unit) {
                    if( (userEntry - unit) > 10 ){
                        System.out.println("Way Too high! Guess lower!");
                    } else {
                        System.out.println("Too high! Guess lower!");
                    }
                } else {
                    System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
                    validateTheData(counter);
                    break;
                }
                counter++;
            }
            System.out.println("Would you like to try again? Yes or No?");
            prompt = sc.next();
            System.out.println("Goodbye!");
        }
    }
}

A: Instead of using .nextInt() rather use .nextLine(), which returns a String and then parse it to an int and catch the NumberFormatException
So basically you'll have this structure:
try {
    int userEntry = Integer.parseInt(sc.nextLine());
    ...
} catch (NumberFormatException nfe) {
    System.out.println("Please enter a valid number.");
}

Oh, just a comment on the rest of your code. You don't really need two while loops, one will be more than sufficient.