text:
Q: Firebase database not recognizing children So my database is structured like this:
Categories
   Category1
      item1
         userData
            uid: someData
      item2
         userData
            uid: someData
      item3
         userData
            uid: someData
   Category2
      item1
         userData
            uid: someData
      item2
         userData
            uid: someData
      item3
         userData
            uid: someData

In my app I have two collectionViewControllers. The first one shows cells labeled category 1, category 2 etc. while the second collectionViewController should show cells with the items in each category.
The problem is that my app will not retreive the different items under the category nodes no matter how I try.
ref = Database.database().reference().child("Category1")
    ref.observeSingleEvent(of: .value) { (snapshot) in
        print(snapshot.childrenCount)
        for item in snapshot.children.allObjects as! [DataSnapshot] {
            print(item.value)
        }
    }

In the example above, printing snapshot.children prints zero (twice, for some reason), and printing item in snapshot.children.allobjects prints nothing.
In the first collectionViewController, which references the Categories node, I'm able to retrieve the category1 and category2 data like this:
ref = Database.database().reference().child("Categories")
    ref.observe(.value) { (snapshot) in
        for category in snapshot.children {
            let categorySnap = category as! DataSnapshot
            let categoryArray = categorySnap.key
            self.categoryArray.append(categoryArray)
            self.collectionView?.reloadData()
        }
    }

I've tried this exact method in my seccond collectionViewController referencing the Category1 node, without printing anything, just adding it to the category array in the viewcontroller and reloading the collectionView. The cells still show up blank.

A: You need to pass through every node to be able to retrieve data. In the first code snippet, you have the following:
ref = Database.database().reference().child("Category1")

This won't retrieve anything because before Category1, you have node Categories which you didn't traverse through, therefore change it to the following:
ref = Database.database().reference("Categories").child("Category1")


text:
Q: Repeat list to max number of elements What is the most efficient method to repeat a list up to a max element length?
To take this:
lst = ['one', 'two', 'three']
max_length = 7

And produce this:
final_list = ['one', 'two', 'three', 'one', 'two', 'three', 'one']

See also How to replicate array to specific length array for Numpy-specific methods.
See also Circular list iterator in Python for lazy iteration over such data.

A: I'd probably use iterools.cycle and itertools.islice:
>>> from itertools import cycle, islice
>>> lst = [1, 2, 3]
>>> list(islice(cycle(lst), 7))
[1, 2, 3, 1, 2, 3, 1]

A: Multiply appropriately?
>>> lst = ['one', 'two', 'three']
>>> max_length = 7
>>>
>>> q, r = divmod(max_length, len(lst))
>>> q * lst + lst[:r]
['one', 'two', 'three', 'one', 'two', 'three', 'one']

Benchmarked mine and mgilson's solution, mine looks more efficient, for example for the below test mine takes about 0.7 seconds while mgilson's takes about 2.8 seconds.
from timeit import timeit
data = "lst = ['one', 'two', 'three'] * 1000; max_length = 12345678"

print(timeit('q, r = divmod(max_length, len(lst)); q * lst + lst[:r]',
             data,
             number=10))

print(timeit('list(islice(cycle(lst), max_length))',
             data + '; from itertools import cycle, islice',
             number=10))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to immediately save any streaming video (without having to download it) once it's fully buffered? I do notice that it seems to save the entire video buffer for YouTube videos to my hard drive (I used resource manager to find out where): in the cache folder on Chrome
But what about videos other than YouTube ones? E.g. http://www.pbs.org/wnet/nature/episodes/bears-of-the-last-frontier/full-episode-hour-one-city-of-bears/6540/

A: I think there are two options from what I understand you require.
Internet Download Manager(IDM) downloads directly even you have seen the whole video (a video that is completely buffered), it does not start from first.
A second more appropriate option is Flash video accelerator that comes with Installing Download Accelerator Plus(DAP).
But The only reason I prefer IDM over DAP is the reason that there are no Ads in IDM, However DAP outpeforms due to the video accelerator and also downloads it. It even works for non Flash Videos for download!

A: I prefer and currently using videocacheview. You can reteive the buffered files for any website like metacafe, vimeo, youtube etc.
Internet download manager (IDM) and other youtube downloaders suffer from one common flaw that once you have seen the whole video and decide to download it. The downloading starts from the top. Which i find irritating especially when the video is big.
Moreover in videocacheview the video quality is exactly the same as you watched.
Get it here


text:
Q: What is the limit of $n(nI + A)^{-1}$ for $A$ p.s.d. matrix? Let $A$ be $K \times K$ positive definite symmetric matrix with known inverse $A^{-1}$ and set $I$ the identity matrix of dimension $K$.
Can one show that (generally or under some conditions)
$$\lim_{n \rightarrow \infty} n \left(nI + A\right)^{-1} = I$$

A: This limit holds for any matrix. Any $k \times k$ matrix $A$ cannot have eigenvalues of arbitrary magnitude, so $(n I + A)^{-1}$ is defined for all $n$ in some neighborhood of infinity (and minus infinity). In this neighborhood we can state that
$$n\left(nI + A\right)^{-1}=n\left(n(I + \frac{1}{n}A)\right)^{-1} = \left(I + \frac{1}{n}A\right)^{-1}.$$
So if we define $f(h) = \left(I + hA\right)^{-1}$, we are interested in the limit $$\lim_{h\to 0} f(h).$$ We have seen that $f$ is indeed defined in a neighborhood around $0$ and since taking inverses is continuous we find that $f$ is continuous and thus
$$\lim_{n \to \infty} n\left(nI + A\right)^{-1} = \lim_{h \to 0} f(h)= f(0) = (I+ 0 \cdot A)^{-1} = I.$$

I think of this argument as a sort of generalization of how I would prove that $$\lim_{n \to \infty} \frac{n}{n + a} = 1$$ for any real (or indeed complex) number $a$.

A: Another solution using Neumann series.
$n\left(nI + A\right)^{-1}== \left(I - \left(- \frac{1}{n}A \right)\right)^{-1}.$
$\sum_{k=0}^\infty \left(- \frac{1}{n}A \right)^k$ is converging in operator norm for any matrix $A$ for $n$ big enough, since for such n, $\frac{|||A|||}n \leq 1$ . Then, for $n$ big enough :
$$\left(I - \left(- \frac{1}{n}A \right)\right)^{-1}=\sum_{k=0}^\infty \left(- \frac{1}{n}A \right)^k=I+\sum_{k=1}^\infty \left(- \frac{1}{n}A \right)^k=I+S_n.$$
Finally, $S_n$ tends to $0$ in operator norm as $n \to \infty$. Indeed :
$$|||S_n|||\leq \sum_{k=1}^\infty \left(\frac{1}n\right)^k |||A|||^k=\sum_{k=1}^\infty \left(\frac{|||A|||}n\right)^k.$$
But, for n big enough $\frac{|||A|||}n \leq 1$, then :
$$|||S_n|||\leq \sum_{k=1}^\infty \left(\frac{|||A|||}n\right)^k = \frac{|||A|||}n \frac 1 {1-\frac{|||A|||}n}\to 0$$

A:
See $A$ as a linear bounded operator on $\mathbb{C}^K$, then for any continous function $f$ on the spectrum $\sigma(A)$ of $A$, $$\lVert f\rVert=\lVert f(A)\rVert_{op}.$$

Define continuous function  $f_n=n(n+t)^{-1}, f=1$ on $\sigma(A)$,then $f_n$ converges to $f$ uniformly, so $\lVert f_n(A)-f(A)\rVert_{op}=\lVert f_n-f\rVert\to 0$.


text:
Q: How to use memento pattern with undo functionality I have a problem using the memento and the command pattern simultaneously. I fully understand the memento pattern is used to save the state of my object on execute before executing the change on the object so that I can return back to the initial object in on unexecute, but the memento pattern is always saving the same reference of the object when I set the state of it in the memento, do I need to clone the object before creating a memento and setting it too it?
Here's what I have:
public class Memento
{
    MyObject myObject;

    public MyObject getState()
    {
        return myObject;
    }

    public void setState(MyObject myObject)
    {
        this.myObject = myObject;
    }
}

Command:
public class ZoomCommand extends Command
{
    Image image;
    Memento memento

    public InsertCharacterCommand(Image image)
    {
        //instantiate
        this.image = image;
    }

    @Override public void execute()
    {
        //create Memento before executing
        memento = new Memento();
        // set the initial zoom level of the image before executing
        memento.setState(image);
        //set new state
        image.zoomIn(image.getZoom() + 1);
    }

    @Override public void unExecute()
    {
        // redo go back to initial state of image before zoom, but image has the same zoom level
        this.image = memento.getState();
    }
}

Image has the same same zoom level in unExecute too, how can I fix this?

A: Yes, you need to clone the object.
As usual, the examples found on the internet are rather anemic, but Refactoring Guru has a workable example.  Their code for loading and saving the object looks like this:
public String backup() {
    try {
        ByteArrayOutputStream b= new ByteArrayOutputStream();
        ObjectOutputStream o= new ObjectOutputStream(b);
        o.writeObject(this.allShapes);
        o.close();
        return Base64.getEncoder().encodeToString(b.toByteArray());
    } catch (IOException e) {
        return "";
    }
}

public void restore(String state) {
    try {
        byte[] data = Base64.getDecoder().decode(state);
        ObjectInputStream o = new ObjectInputStream(new ByteArrayInputStream(data));
        this.allShapes = (CompoundShape) o.readObject();
        o.close();
    } catch (ClassNotFoundException e) {
        System.out.print("ClassNotFoundException occurred.");
    } catch (IOException e) {
        System.out.print("IOException occurred.");
    }
}

Notice that it doesn't deal in references.  Rather, it provides a scheme for saving out and restoring the entire object's state.  Essentially it is a deep copy of the Java object.


text:
Q: What does a inner-product between a vector and matrix mean? I'm reading through Axler Sheldons Linear Algebra Done Right, and stumbled uppon the following question:

Suppose $V$ is an inner-product space and $v,w \in \mathcal{L} (V)$. Define
  $T  \in \mathcal{L} (V)$ by $Tu = \langle u,v \rangle w$. Find a formula for $trace (T)$.

The thing I can't wrap my head around is that $v$ is transformation (or matrix), and we're trying to take the inner product between a matrix and a vector.
If I assume that the $\mathcal{L}$ is nothing but a typo, then the whole statement makes sense, but I'm just wondering:
Is the inner product between a vector and transform a valid operation?


text:
Q: including images into JS object and sending through Ajax I have a JS object that collects form values and store them into arrays.
var myJSObject = {

    names = [],
    images = [],
    ....
}

The problem I have is that my form contains images and I tried to store them in the JS object and send the whole thing through Ajax. But my images` array is always empty.
Update:
Sorry for the delay as I was busy with other projects. Here is my JS Classes:
HTML:

     <input class="upl-img" type="file" />

     <input class="upl-img" type="file" />

JS:
var formElement = function(options){

    var defaults = {
            elemID : 0,
            elemText : " ",
            elemnOrder : 0,
            mandatory : false,
            elemType : 0,
            elemImage : null,
            formFields : []
        }

        //Some methodes

        this.construct(options);

        }

         var formSection = function(options){

        var defaults = {
            sectionID : null,
            sectionTitle : " ",
            sectionOrder : 0,
            formElements : []
        }

        //Some methodes

        this.construct(options);

        }

So my formSection contains an array of formElement. Each formElement could contain an image that the end user may upload.
When the end user hits submit button a function will create a new formSection object and inject in all the formElements objects. The final formSection object needs to be posted through Ajax. I tried to used a FormData object to collect files without success.
Thank you

A: HTMLElement objects are complex objects, and image elements are actually files on your computer, so if it was possible it would mean UPLOADING a file to the server, which means the servers need to be specificaly involved with itsa script. im prety sure you cant send them with a simple post or get http request.
JSON is ment for passing primitive types in an object notetion style.
what you can do is use a plugin such as Uplodify, which contains a PhP script that enables uploading files to the server from you computer, by giving a URI.
but that means the php script needs to tun on the server.


text:
Q: Question about ,(?=(?:[^']*'[^']*')*[^']*$) C# Regex Split - commas outside quotes
var result = Regex.Split(samplestring, ",(?=(?:[^\"]*\"[^\"]*')*[^\"]*$)");

I have problems to understand how it works.
Specifically, I don't know what the * matches here?
",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)")
                     ^

Does it mean
there are 0 or more of (?=(?:[^\"]*\"[^\"]*')
update for a sample input
2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,"Corvallis, OR",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34

Use the following code to test:
string samplestring = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

A: It means that the group (?:[^']*'[^']*') is matched zero or more times.
,       // match one comma
(?=     // Start a positive lookAHEAD assertion
(?:     // Start a non-capturing group
[^']*   // Match everything but a single-quote zero or more times
'       // Match one single-quote
[^']*   // Match everything but a single-quote zero or more times
'       // Match one single-quote
)*      // End group and match it zero or more times
[^']*   // Match everything but a single-quote zero or more times
$)      // end lookAHEAD

A: You could check your regex and make your test on this website :
http://www.annuaire-info.com/outil-referencement/expression-reguliere/
;) have fun


text:
Q: Hiding HTML form elements not using id's

Question 1

  <input type="radio" name="name_radio1" value="value_radio1" onclick=$().hide(); />Audio Question
  <input type="radio" name="name_radio1" value="value_radio2" onclick=$().hide(); />Image Question
  <input type="radio" name="name_radio1" value="value_radio3" onclick=$().hide(); />Standard Question

  <input name="question" size="35" class="standardQuestion" type="text" value="" />

  <input name="audioFile" class="audioFile" type="file" />

  <textarea name="message" rows="10" cols="20">
  </textarea>

  <input name="imageFile" class="imageFile" type="file" />

Question 2

    <input type="radio" name="name_radio1" value="value_radio1" onclick=$().hide(); />Audio Question
    <input type="radio" name="name_radio1" value="value_radio2" onclick=$().hide(); />Image Question
    <input type="radio" name="name_radio1" value="value_radio3" onclick=$().hide(); />Standard Question

    <input name="question" size="35" class="standardQuestion" type="text" value="" />

    <input name="audioFile" class="audioFile" type="file" />

    <textarea name="message" rows="10" cols="20">
    </textarea>

    <input name="imageFile" class="imageFile" type="file" />

`I am trying to add to an HTML Quiz editor started by someone else that allows me to add from 1 to n questions.  Quiz questions can be based upon an audio recording, an image, or just plain text.  If the question is an audio/image/text based question, I would need to only show the HTML form elements related to an audio/image/text based question.  The questions on the quiz can be changed/updated/deleted by the user of the editor so an audio question could be changed to an image or text based question.  If the question type is changed via a radio button, the appropriate controls for that question type need to be displayed.
For example...

Question 1
Radio ImageQuestion     Radio AudioQuestion     Radio TextQuestion

textbox 1  (Only show if Radio Button ImageQuestion is checked)

File       (Only show if Radio Button AudioQuestion is checked)

textbox 2  (Only show if Radio Button TextQuestion is checked)

Question 2 (same elements as above)
....

Question N (same elements as above)
While each question will have the same HTML form elements, the data in each question should be independent so when I hide some control for question 1 since the user clicked on a specific radio button there, it should not impact what is diplayed for questions 2 to N.
The key constraint I would like to work with is not use id's since the code that I am working on is over halfway done and has been implemented without id's.  And I could not hardcode the id's since I don't know how many of them will actually be needed.  It would be a significant change to add id's but if that is the only reasonable way or clearly the best way that this can be accomplished, please let me know.  Any advice on the best approach to take would be appreciated.  Right now the code is using jquery/javascript and I would like to stick with that and basic html/css.  I am speculating based upon my research that I may need to use code like .parent().find("a specific class") and the onclick event but I'm not sure if this is the right approach to take and is even feasible.    Thanks.

A: Are you trying to do this without javascript?


text:
Q: Get a reason for change in stock when using the woocommerce_product_set_stock hook I am using woocommerce and have created a custom table in order to monitor stock movements on products. I am using the woocommerce_product_set_stock hook in order to achieve this and it is working successfully. This shows the amount by which stock level is increased or decreased and by which user, date etc. Here is the function:
 add_action( 'woocommerce_product_set_stock', array( $this, 'save_stock' ) );

 public function save_stock( $product ) {
    //get the previous stock level from the custom table
    global $wpdb;
    $old_qty = $wpdb->get_var("SELECT qty FROM wp_stock_log WHERE product_id = '".$product->get_id()."' ORDER BY id DESC LIMIT 1 ");

    //get current stock level and calculate the change.
    $qty = $product->get_stock_quantity();
    $change_in_stock = $qty-$old_qty;

    //get user full name
    $current_user = wp_get_current_user();
    $first_name = $current_user->user_firstname;
    $last_name = $current_user->user_lastname;
    $full_name = $first_name . ' ' . $last_name;

    $data = array();
    //insert new row into the custom table
    $data['date_created'] = date( 'Y-m-d H:i:s', time() );
    $data['qty'] = $product->get_stock_quantity();
    $data['qty_change'] = $change_in_stock;
    $data['product_id'] = $product->get_id();
    $data['user'] = $full_name;
    $data['reason'] = SOME REASON ;
    $wpdb->insert( $wpdb->prefix.'stock_log', $data );
}

The wp_stock_log table is as follows:
|--------|--------------|------------|-----|----------|-----------|-------------|
|   ID   | date_created | product_id | qty |qty_change|   user    | reason      |
|--------|--------------|------------|-----|----------|-----------|-------------|
|   1    | 14-08-2020   | 123        | 12  |  -2      | Customer1 | Sale        |
|--------|--------------|------------|-----|----------|-----------|-------------|
|   2    | 15-08-2020   | 123        | 10  |  -1      | Customer2 | Sale        |
|--------|--------------|------------|-----|----------|-----------|-------------|
|   3    | 15-08-2020   | 123        |  9  |   4      | Manager   | Stock Added |
|--------|--------------|------------|-----|----------|-----------|-------------|
|   4    | 17-08-2020   | 123        |  13 |  -1      | Customer2 | Sale        |
|--------|--------------|------------|-----|----------|-----------|-------------|

I would like to show the reason for the change in stock, for example "Sale" if a customer has placed an order, or "Stock Added" if a shop manager has added new stock to inventory. How could I achieve this. Is there an existing property that I will be able to use to tell me if it is related to an order?


text:
Q: flowplayer video on ipad/ipod touch not working in drupal7 using ipad plugin - byte range headers problem I've successfully integrated Flowplayer into my Drupal installation using the video and flowplayer. I upgraded flowplayer files to the latest release 3.2.7 and all works ok, but not on iPad - iPod Touch.
I loaded the js for the iPad plugin in the Flowplayer module like this:
drupal_add_js(drupal_get_path('module', 'flowplayer') . '/flowplayer/example/flowplayer.ipad-3.2.2.js');

and I see that it is loaded fine.
then in Flowplayer js I had this line
$(selector + ':not(.flowplayer-processed)').addClass('flowplayer-processed').flowplayer(settings.basePath + settings.flowplayerSwf, config);

I changed this in this way:
//I added the first line because in  the example it worked that way
$(selector + ':not(.flowplayer-processed)').attr('url', config.clip.url);
$(selector + ':not(.flowplayer-processed)').addClass('flowplayer-processed').flowplayer(settings.basePath + settings.flowplayerSwf, config);
//then i add ipad support (the selctor is hardcoded to maike things work)
$f('flowplayer-video').ipad();

In this way, on my iPod touch (I think it's the same on iPad) I see the player but the video doesn't start (there is some kind of blocked overlay).
You can look at the site here
EDIT - now i got it working thanks to teddy suggestion. now i'll try to find out how to setup my script so that it returns byte-range headers.
If anyone knows how to do this, please post here.

A: The server that serves the actual MP4 video to the iPad must support the HTTP header called byte-range.
I would try using an alternate video source from another server, as a proof-of-concept to see if this is the cause of the problem.
Here is an MP4 video served with the byte-range header: http://mediaelementjs.com/media/echo-hereweare.mp4


text:
Q: Jest configuration for react component testing I am trying to set up react component testing with jest in my project, which seems to be a little complicated configuration-wise. Currently I'm getting thrown the following error when trying to run the tests from the test file with the arrow

Jest encountered an unexpected token

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

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

This is where it fails
When I run it from the terminal, however, this part seems to pass. But it throws on something else:
Here
Which is annoying, because I'm not able to debug it this way, and from the arrow in the test it fails to run at all so I cannot debug it either.
Here is my package.json relevant dependencies and jest configurations:
"dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.3.0",
    "babel-jest": "^28.1.3",
    "lodash-es": "^4.17.21",
    "react": "^18.0.0",
    "react-calendly": "^2.2.2",
    "react-i18next": "^11.8.8",
    "styled-components": "^5.3.1"
  },
  "devDependencies": {
    "@babel/preset-env": "^7.18.10",
    "@babel/preset-react": "^7.18.6",
    "@lexense/dv-deps": "^4.2.180",
    "@lexense/dv-lint": "^4.2.186",
    "@lexense/dv-prettier": "^4.2.180",
    "@lexense/dv-test": "^4.2.186",
    "babel-jest": "^28.1.3",
    "jest": "^28.1.3",
    "react-test-renderer": "^18.2.0"
  },
  "engines": {
    "node": "16.x",
    "yarn": ">=1.22.0"
  },
  "jest": {
    "testEnvironment": "jest-environment-jsdom",
    "transform": {
      "^.+\\.js$": "babel-jest"
    }
  }
}

My babel.config.js file:
module.exports = {
  presets: [
    '@babel/preset-env',
    ['@babel/preset-react', { runtime: 'automatic' }],
  ],
};

The test itself Link.spec.js:
// Importing the jest testing library
import '@testing-library/jest-dom';

import { cleanup, render, screen } from '@testing-library/react';
import React from 'react';

import Link from '../src/Link';

// afterEach function runs after each test suite is executed
afterEach(() => {
  cleanup(); // Resets the DOM after each test suite
});

describe('Link Component', () => {
  // Test 1
  test('Link Rendering', () => {
    render(<Link href={'www.facebook.com'} text={'Facebook'} />);
    const link = screen.getByTestId('link');
    expect(link).toBeInTheDocument();
  });
});

I would like some help, if anyone knows about the topic. Thanks in advance.


text:
Q: Track onclick events My goal is to store the total amount of clicks on links in a certain page into a variable and recall that variable when the user exits the page. Would this be a correct way of doing it?
window.onunload = function(){
    alert("Total Links Clicked:" + clicks(););
}

var clicks = function(){
    var clickArray = [];
    var getLinks = document.getElementsByTagName(A);

    var clickValue = getLinks.onclick = function() {
    clickArray.push("1");
    }

    var totalClicks = clickArray.length;

    return totalClicks;
}

A: Your code won't work for several reasons:

*

*You bind the click handler in clicks() function and don't call clicks() until the page is unloaded, at which point it is too late to handle any clicks. You need to bind the click handler when the page loads.

*You can't set .onclick on a list of elements, which is what your getLinks variable is given it was set to the result of getElementsByTagName() (get elements not get element).

*You pass an undeclared variable A to getElementsByTagName(); you should pass the string "a".

*You have a semicolon inside the alert()'s closing ), which is a syntax error.

You could try something like this:
window.onload = function() {
    var clicks = 0;

    window.onunload = function(){
        alert("Total Links Clicked:" + clicks);
    }

    function clicked() {
         clicks++;
    }

    var getLinks = document.getElementsByTagName("a");
    for (var i = 0; i < getLinks.length; i++)
        getLinks[i].onclick = clicked;
};

Note that the browser may block an alert() during an unload event, but if you use console.log() instead you can see that clicks had the right value.
Note also that of course a click on a link to another page will cause an unload, so the click count will only be more than 1 if you have links within the current page.
Demo: http://jsfiddle.net/A3bkT/1/

A: You can use sessionStorage or localStorage for that.
if(typeof(Storage)!=="undefined")
{
   // store the clicks here
   sessionStorage.numClicks = value;
}

and read more on these two here : http://www.w3schools.com/html/html5_webstorage.asp

A: Bind a global event listener and just store the count with sessionStorage:
var clicks = 0;

document.addEventListener('click', function(event) {
    if (event.target.nodeName == 'A') {
        window.sessionStorage.setItem('clicks', ++clicks);
    }
}, false);


text:
Q: Python Tkinter grid set up My first coding project, and I am trying to create an app to use as a dashboard on an old laptop.
Weather app concept
Can I use tkinters grid to create boxes like in the picture?
I have stumbled for two days and I cannot come up with a good result at all nor have I managed to create a good box yet.
Here is my code:
import requests
from tkinter import *
from PIL import ImageTk, Image

def weather():
    city=city_listbox.get()
    url="https://api.openweathermap.org/data/2.5/weather?q={}&appid=*myappid*&units=metric".format(city)
    res=requests.get(url)
    output=res.json()

weather_status=output['weather'][0]['description']
temperature=output['main']['temp']
feelslike=output['main']['feels_like']
humidity=output['main']['humidity']
wind_speed=output['wind']['speed']

weather_status_label.configure(text="Weather status : "+ weather_status)

if weather_status=="few clouds":
    partial_cloud_label=Label(image=partial_cloud)
    partial_cloud_label.grid(row=3, column=4)

temperature_label.configure(text="Temperature : "+ str(temperature) +"°C")

feelslike_label.configure(text="Feels like : "+ str(feelslike) +"°C")

humidity_label.configure(text="Humidity : "+ str(humidity) +"%")

wind_speed_label.configure(text="Wind speed  : "+ str(wind_speed) +"m/s")

window=Tk()
window.geometry("1920x1080")
window.iconbitmap('localfile')
window.title('Show dis weather')

partial_cloud=ImageTk.PhotoImage(Image.open("local file"))
day_clear=ImageTk.PhotoImage(Image.open("localfile"))
cloudy=ImageTk.PhotoImage(Image.open("localfile"))

city_name_list=["City1", "City2"]

city_listbox=StringVar(window)
city_listbox.set("select the city")
option=OptionMenu(window,city_listbox,*city_name_list)
option.grid(row=2,column=6,padx=150,pady=10)

b1=Button(window,text="Select",width=15,command=weather)
b1.grid(row=5,column=6,padx=150)

weather_status_label=Label(window, font=("didot",15,"bold"))
weather_status_label.grid(row=10,column=6)

temperature_label=Label(window,font=("didot",15,"bold"))
temperature_label.grid(row=16,column=6)

feelslike_label=Label(window,font=("didot",15,"bold"))
feelslike_label.grid(row=22,column=6)

humidity_label=Label(window,font=("didot",15,"bold"))
humidity_label.grid(row=28,column=6)

wind_speed_label=Label(window,font=("didot",15,"bold"))
wind_speed_label.grid(row=34,column=6)

window.mainloop()

Seeking advice towards Tkinter gui.
I was thinking that you could possibly create boxes and set all the "widgets" or data inside them.
For e.x, creating a box and put it to the left and have the weather status and information inside there. A box NW for the buttons to choose city. Box N to show big text for which city it is showing information for.
Is this possible in Tkinter?
If I have left insufficient information or if this is a too loose thread to being helped through, please write and tell me about it, I am very new in this, so I appreciate all help.
With Regards!

A: I would use Frames in order to organize the view.
And instead of using random bigger numbers to try spacing things out(empty rows and columns stay at size zero until filled with content), you should take a look into the weight option of grid.row(or column)configure as well as the row(or column)span option of grid itself.
in order to achieve your view you might wanna start with something like this:
import tkinter as tk

class Application(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        #Window config
        tk.Tk.wm_title(self, "WeatherApp")
        self.geometry("1920x1080")

        #Main Layout
        self.mainframe = tk.Frame(self)
        self.mainframe.pack(fill="both", expand = True)
        self.mainframe.grid_rowconfigure(0, weight=1)
        self.mainframe.grid_rowconfigure(1, weight=1)
        self.mainframe.grid_columnconfigure(0, weight=1)
        self.mainframe.grid_columnconfigure(1, weight=1)
        self.mainframe.grid_columnconfigure(2, weight=1)
        self.mainframe.grid_columnconfigure(3, weight=1)

        #Top Container
        self.top = tk.Frame(self.mainframe)
        #placing in the main frame
        self.top.grid(row = 0, column = 0, columnspan = 4)

        #configure layout for top view
        self.top.grid_rowconfigure(0, weight=1)
        self.top.grid_columnconfigure(0, weight=1)

        #content of top view
        self.toplabel = tk.Label(self.top, text = "City: ")
        self.toplabel.grid(row = 0, column = 0)

        #day1
        self.day1 = tk.Frame(self.mainframe)
        #placing in the main frame
        self.day1.grid(row = 1, column = 0)

        #configure layout for top view
        self.day1.grid_rowconfigure(0, weight=1)
        self.day1.grid_columnconfigure(0, weight=1)

        #content of day1 frame
        self.label1 = tk.Label(self.day1, text="saturday")
        self.label1.grid(row = 0, column = 0)

        #day2
        self.day2 = tk.Frame(self.mainframe)
        #placing in the main frame
        self.day2.grid(row = 1, column = 1)

        #you don't have to configure if all cells should have equal size

        #content of day1 frame
        self.label2 = tk.Label(self.day2, text="sunday")
        self.label2.grid(row = 0, column = 0)

        #day3
        self.day3 = tk.Frame(self.mainframe)
        #placing in the main frame
        self.day3.grid(row = 1, column = 2)

        #content of day1 frame
        self.label3 = tk.Label(self.day3, text="monday")
        self.label3.grid(row = 0, column = 0)

        #day4
        self.day4 = tk.Frame(self.mainframe)
        #placing in the main frame
        self.day4.grid(row = 1, column = 3)

        #content of day1 frame
        self.label4 = tk.Label(self.day4, text="tuesday")
        self.label4.grid(row = 0, column = 0)

app = Application()
app.mainloop()

EDIT:
The __init__ function is always getting called when a class is being used, see. You can use other functions from within each other, but you can't just toss it in there and expect it to run without beeing called, you might wanna take a look at inner Functions.
But that isn't what I would do in your case.
I would create 2 new other classes (1 for top frame, 1 for bottom frame) and inhereting from the tk.Frame class for 2 reasons:

*

*readability since everything is where it belongs and nicely grouped togehter

*reuseability because the content of all your bottom frames is the same(widget wise) so you can just pass the values to change:

import tkinter as tk

class Application(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        #Window config
        tk.Tk.wm_title(self, "WeatherApp")
        self.geometry("1920x1080")

        #Main Layout
        self.mainframe = tk.Frame(self)
        self.mainframe.pack(fill="both", expand = True)
        self.mainframe.grid_rowconfigure(0, weight=1)
        self.mainframe.grid_rowconfigure(1, weight=1)
        self.mainframe.grid_columnconfigure(0, weight=1)
        self.mainframe.grid_columnconfigure(1, weight=1)
        self.mainframe.grid_columnconfigure(2, weight=1)
        self.mainframe.grid_columnconfigure(3, weight=1)

        #Top Container
        #note the changed declaration, since we're now calling
        #our own Frame class
        self.top = TopFrame(self.mainframe)
        #placing in the main frame
        self.top.grid(row = 0, column = 0, columnspan = 4)

        #day1
        # note the passthrough of the day argument
        self.day1 = DayFrame(self.mainframe, "saturday")
        #placing in the main frame
        self.day1.grid(row = 1, column = 0)

        #day2
        self.day2 = DayFrame(self.mainframe, "sunday")
        #placing in the main frame
        self.day2.grid(row = 1, column = 1)

        #day3
        self.day3 = DayFrame(self.mainframe, "monday")
        #placing in the main frame
        self.day3.grid(row = 1, column = 2)

        #day4
        self.day4 = DayFrame(self.mainframe, "tuesday")
        #placing in the main frame
        self.day4.grid(row = 1, column = 3)

class TopFrame(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        #add code for your widgets in top frame here
        label = tk.Label(self, text="Top Frame")
        label.grid(row = 0, column = 0)

class DayFrame(tk.Frame):

    def __init__(self, parent, day):
        tk.Frame.__init__(self, parent)

        # add code for bottom frame widgets here
        # pass nessecary variables through to reuse the code
        self.day = day
        self.daylabel = tk.Label(self, text = day)
        self.daylabel.grid(row = 0, column = 0)

app = Application()
app.mainloop()

Also please note what thelizzard said about my sloppiness when it comes to using .grid(row=0, column=0) in the same row, because you will run into errors with this as soon as you want to change anything about the variable!

A: Thank you Newb, and you others, for different answers.
I have used Newb's code and made some changes, like making it a 12 grid big and changing the order of where the frames should be.
I have also tried to implement the "weather" code from the original code, and there is where I got stuck.
Can you put a function inside another function?
I still cannot understand what init is for, but that I can learn on the side.
Here is the updated code:
import tkinter as tk
#from tkinter import *
from PIL import ImageTk, Image

class Application(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        #Window config
        tk.Tk.wm_title(self, "WeatherApp")
        self.geometry("1920x1080")
        self.iconbitmap('localfile')
        #This part I have added
        self.partial_cloud=ImageTk.PhotoImage(Image.open("localfile"))
        self.day_clear=ImageTk.PhotoImage(Image.open("localfile"))
        self.cloudy=ImageTk.PhotoImage(Image.open("localfile"))

        #This part I have added
        def weather():
            self.city=city_listbox.get()
            self.url="https://api.openweathermap.org/data/2.5/weather?q={}&appid=*myappid*&units=metric".format(city)
            self.res=requests.get(url)
            self.output=res.json()

            self.weather_status=output['weather'][0]['description']
            self.temperature=output['main']['temp']
            self.feelslike=output['main']['feels_like']
            self.humidity=output['main']['humidity']
            self.wind_speed=output['wind']['speed']

            self.weather_status_label.configure(text="Weather status : "+ weather_status)

                if weather_status=="few clouds":
                    partial_cloud_label=Label(image=partial_cloud)
                    partial_cloud_label.grid(row=3, column=4)

            temperature_label.configure(text="Temperature : "+ str(temperature) +"°C")

            feelslike_label.configure(text="Feels like : "+ str(feelslike) +"°C")

            humidity_label.configure(text="Humidity : "+ str(humidity) +"%")

            wind_speed_label.configure(text="Wind speed  : "+ str(wind_speed) +"m/s")

        #Main Layout
        self.mainframe = tk.Frame(self)
        self.mainframe.pack(fill="both", expand = True)
        self.mainframe.grid_rowconfigure(0, weight=1)
        self.mainframe.grid_rowconfigure(1, weight=1)
        self.mainframe.grid_rowconfigure(2, weight=1)
        self.mainframe.grid_columnconfigure(0, weight=1)
        self.mainframe.grid_columnconfigure(1, weight=1)
        self.mainframe.grid_columnconfigure(2, weight=1)
        self.mainframe.grid_columnconfigure(3, weight=1)

        #Top Left Container
        self.tl = tk.Frame(self.mainframe)
        #placing in the main frame
        self.tl.grid(row = 0, column = 0)

        #configure layout for top view
        self.tl.grid_rowconfigure(0, weight=1)
        self.tl.grid_columnconfigure(0, weight=1)

        #This part I have added

        #content of top view
        self.city_name_list=["city1", "city2"]

        self.city_listbox=StringVar(self.tl)
        self.city_listbox.set("select the city")
        self.option=OptionMenu(self.tl,city_listbox,*city_name_list)
        self.option.grid(row=0,column=0,padx=150,pady=10)

        self.b1=Button(self.tl, text="Select",width=15,command=weather)
        self.b1.grid(row=0,column=0,padx=150)
        #self.tllabel = tk.Label(self.tl, text = "Button ", font=("Sentinel", 20, "bold"))
        #self.tllabel.grid(row = 0, column = 0)

        #Top Middle Container (tm)
        self.tm = tk.Frame(self.mainframe)
        #placing in the main frame
        self.tm.grid(row = 0, column = 1) #Leaving comment for my self columnspan = 4

        #configure layout for top view
        self.tm.grid_rowconfigure(0, weight=1)
        self.tm.grid_columnconfigure(0, weight=1)

        #content of top view
        self.tmlabel = tk.Label(self.tm, text = "City: ", font=("Sentinel", 36, "bold"))
        self.tmlabel.grid(row = 0, column = 0)

        #Left Container
        self.left = tk.Frame(self.mainframe)
        #placing in the main frame
        self.left.grid(row = 1, column = 0)

        #configure layout for top view
        self.left.grid_rowconfigure(0, weight=1)
        self.left.grid_columnconfigure(0, weight=1)

        #content of top view
        self.leftlabel = tk.Label(self.left, text = "Weather ", font=("Sentinel", 20, "bold"))
        self.leftlabel.grid(row = 0, column = 0)

        #day1
        self.day1 = tk.Frame(self.mainframe) # Tried to make a border, leaving comment for my self width=3, height=100, highlightbackground="black", highlightthickness=1) #bd=100)#relief=tk.RIDGE)
        #placing in the main frame
        self.day1.grid(row = 2, column = 0)

        #configure layout for top view
        self.day1.grid_rowconfigure(0, weight=1)
        self.day1.grid_columnconfigure(0, weight=1)

        #content of day1 frame
        self.label1 = tk.Label(self.day1, text="Saturday", font=("Sentinel", 26, "bold")).grid(row = 0, column = 0)

        #day2
        self.day2 = tk.Frame(self.mainframe)
        #placing in the main frame
        self.day2.grid(row = 2, column = 1)

        #you don't have to configure if all cells should have equal size

        #content of day1 frame
        self.label2 = tk.Label(self.day2, text="Sunday", font=("Sentinel", 26, "bold")).grid(row = 0, column = 0)

        #day3
        self.day3 = tk.Frame(self.mainframe)
        #placing in the main frame
        self.day3.grid(row = 2, column = 2)

        #content of day1 frame
        self.label3 = tk.Label(self.day3, text="Monday", font=("Sentinel", 26, "bold")).grid(row = 0, column = 0)

        #day4
        self.day4 = tk.Frame(self.mainframe)
        #placing in the main frame
        self.day4.grid(row = 2, column = 3)

        #content of day1 frame
        self.label4 = tk.Label(self.day4, text="Tuesday", font=("Sentinel", 26, "bold")).grid(row = 0, column = 0)

app = Application()
app.mainloop()

You have already helped me a lot, but if you feel to help me how to implement this, feel free to do it.
Thanks and have a great day!
EDIT:
Hi there!
Sorry for bumping an old thread, I am still working to make this application working!
When I am  trying to run the following code, I get the NameError: "name 'city_listbox' is not defined code" at line 172
Anyone has any energy and clue what I can do to implement the Weather code inside the grid code supplied from Newb?
import requests
import tkinter as tk
#from tkinter import *
from PIL import ImageTk, Image

class Application(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        def weather():
           def __init__(self, TopLFrame):
               city=city_listbox.get()
               url="https://api.openweathermap.org/data/2.5/weather?q={}&appid=ID&units=metric".format(city)
               res=requests.get(url)
               output=res.json()

               weather_status=output['weather'][0]['description']
               temperature=output['main']['temp']
               feelslike=output['main']['feels_like']
               humidity=output['main']['humidity']
               wind_speed=output['wind']['speed']

               weather_status_label.configure(text="Weather status : "+ weather_status)

               if weather_status=="few clouds":
                   partial_cloud_label=tk.Label(image=partial_cloud)
                   partial_cloud_label.grid(row=3, column=4)

               temperature_label.configure(text="Temperature : "+ str(temperature) +"°C")

               feelslike_label.configure(text="Feels like : "+ str(feelslike) +"°C")

               humidity_label.configure(text="Humidity : "+ str(humidity) +"%")

               wind_speed_label.configure(text="Wind speed  : "+ str(wind_speed) +"m/s")

        #Window config
        tk.Tk.wm_title(self, "WeatherApp")
        self.geometry("1920x1080")
        #self.iconbitmap('linktopicture')

        #self.partial_cloud=ImageTk.PhotoImage(Image.open("linktopicture"))
        #self.day_clear=ImageTk.PhotoImage(Image.open("linktopicture"))
        #self.cloudy=ImageTk.PhotoImage(Image.open("linktopicture"))

        #Main Layout
        self.mainframe = tk.Frame(self)
        self.mainframe.pack(fill="both", expand = True)
        self.mainframe.grid_rowconfigure(0, weight=1)
        self.mainframe.grid_rowconfigure(1, weight=1)
        self.mainframe.grid_rowconfigure(2, weight=1)
        self.mainframe.grid_columnconfigure(0, weight=1)
        self.mainframe.grid_columnconfigure(1, weight=1)
        self.mainframe.grid_columnconfigure(2, weight=1)
        self.mainframe.grid_columnconfigure(3, weight=1)

        #Top Left Container
        self.tl = TopLFrame(self.mainframe, weather)
        self.tl.grid(row = 0, column = 0)

        #self.tl.grid_rowconfigure(0, weight=1)
        #self.tl.grid_columnconfigure(0, weight=1)

        #Top Middle Container (tm)
        self.tm = TopMFrame(self.mainframe)
        self.tm.grid(row = 0, column = 1)

        #self.tm.grid_rowconfigure(0, weight=1)
        #self.tm.grid_columnconfigure(0, weight=1)

        #Left Container
        self.left = MidFrame(self.mainframe)
        self.left.grid(row = 1, column = 0)

        #self.left.grid_rowconfigure(0, weight=1)
        #self.left.grid_columnconfigure(0, weight=1)

        #day1
        self.day1 = BottomFrame(self.mainframe, "Monday")
        self.day1.grid(row = 2, column = 0)

        #self.day1.grid_rowconfigure(0, weight=1)
        #self.day1.grid_columnconfigure(0, weight=1)

        #day2
        self.day2 = BottomFrame(self.mainframe, "saturday")
        #placing in the main frame
        self.day2.grid(row = 2, column = 1)

        #day3
        self.day3 = BottomFrame(self.mainframe, "test")
        self.day3.grid(row = 2, column = 2)

        #day4
        self.day4 = BottomFrame(self.mainframe, "test2")
        self.day4.grid(row = 2, column = 3)

class TopMFrame(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        #add code for your widgets in top frame here
        self.label = tk.Label(self, text="Top Mid Frame")
        self.label.grid(row = 0, column = 0)

class TopLFrame(tk.Frame):

    def __init__(self, parent, Application):
        tk.Frame.__init__(self, parent)

        self.city_name_list=["City1", "City2"]

        self.city_listbox=tk.StringVar(self)
        self.city_listbox.set("select the city")

        self.option=tk.OptionMenu(self, city_listbox, *city_name_list)
        self.option.grid(row=0,column=0,padx=150,pady=10)

        self.b1=tk.Button(self, text="Select",width=15,command=weather)
        self.b1.grid(row=0,column=0,padx=150)

class MidLFrame(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.label = tk.Label(self, text="Left Frame")
        self.label.grid(row = 0, column = 0)

        self.weather_status_label=tk.Label(self, font=("didot",15,"bold"))
        self.weather_status_label.grid(row=10,column=6)

        self.temperature_label=tk.Label(self,font=("didot",15,"bold"))
        self.temperature_label.grid(row=16,column=6)

        self.feelslike_label=tk.Label(self,font=("didot",15,"bold"))
        self.feelslike_label.grid(row=22,column=6)

        self.humidity_label=tk.Label(self,font=("didot",15,"bold"))
        self.humidity_label.grid(row=28,column=6)

        self.wind_speed_label=tk.Label(self,font=("didot",15,"bold"))
        self.wind_speed_label.grid(row=34,column=6)

class BottomFrame(tk.Frame):

    def __init__(self, parent, day):
        tk.Frame.__init__(self, parent)

        # add code for bottom frame widgets here
        # pass nessecary variables through to reuse the code
        self.day = day

        self.label1 = tk.Label(self, text = day, font=("Sentinel", 26, "bold"))
        self.label1.grid(row = 0, column = 0)

app = Application()
app.mainloop()

With Regards,
Joggster!


text:
Q: Scheduling Auctions I am working on an auctions site and I want to schedule auction so users can set the date and time they want their auction to start and end. I added Published_at, end_time and draft which is default to true in my db migration and I can create an auction and select a published_at time and end_time which stores in db but I am having difficulty making the auction to now show on the date and time selected and end on the date and time selected.
Model/auction.rb
class Auction < ApplicationRecord
  mount_uploader :image, ImageUploader
  belongs_to :user
  has_many :bids, dependent: :destroy

  scope :draft, -> {
    where(:draft => true)
  }

  # scope :draft, where(:draft => true)
  scope :published, proc {
    where(:draft => false).where('published_at <= ?', Time.zone.now)
  }

  before_save :ensure_published_at, :unless => :draft?
  protected
  def ensure_published_at
    # Set it to current time if none has been specified.
    self.published_at ||= Time.zone.now
  end

  def publish!
    self.draft = false
    self.save!
  end
end

auctions_controller.rb
def index
  @auctions = Auction.published
end

so I guess what I am trying to do in the model is for the draft to change from true to false so I can show in Index controller, but seems I'm getting many things wrong.
I would appericiate any help please.


text:
Q: Google Place API Autocomplete Service in Android Application How can I  do as in this example ?

A: Try to add this async task in your activity.
public class Async extends AsyncTask<String, String, String> {
    String resp = "";
    Double lat;
    Double lng;

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        try {
            resp = downloadUrl(PLACES_API_BASE + TYPE_DETAILS + OUT_JSON
                    + "?key=" + API_KEY + "&reference=" + arg0[0]
                    + "&sensor=false");

            JSONObject jsonObj = new JSONObject(resp.toString());
            JSONObject jObj = jsonObj.getJSONObject("result");
            JSONObject jObj2 = jObj.getJSONObject("geometry");
            JSONObject jObj3 = jObj2.getJSONObject("location");
            lat = jObj3.getDouble("lat");
            lng = jObj3.getDouble("lng");

            Log.e("lat", "" + lat);
            Log.e("lng", "" + lng);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.e("response---->", resp);
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Location loc = new Location("");
        loc.setLatitude(lat);
        loc.setLongitude(lng);
        updateCurrentMarker(loc);
        changeCamera(getLastCameraUpdate(loc));
        marker.setDraggable(true);
        // btn_save.setVisibility(View.GONE);
    }
}

private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

private ArrayList<LocationAutoCompleteModel> autocomplete(String input) {
    ArrayList<LocationAutoCompleteModel> resultList = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE
                + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?sensor=false&key=" + API_KEY);
        // sb.append("&components=country:uk");
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList<LocationAutoCompleteModel>(
                predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            LocationAutoCompleteModel lm = new LocationAutoCompleteModel();
            lm.setDesc(predsJsonArray.getJSONObject(i).getString(
                    "description"));
            lm.setRef(predsJsonArray.getJSONObject(i)
                    .getString("reference"));
            resultList.add(lm);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}

public class PlacesAutoCompleteAdapter extends ArrayAdapter<String>
        implements Filterable {

    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    @Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return resultList.get(index).getDesc();
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());
                    Log.e("ExampleApplication getFilter",
                            "" + constraint.toString());

                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }
}

And call like this
AutoCompleteTextView autoCompView = (AutoCompleteTextView) rootView.findViewById(R.id.searchLocation);
        autoCompView.setThreshold(3);
        autoCompView.setAdapter(new PlacesAutoCompleteAdapter(getActivity(),
                android.R.layout.simple_list_item_1));
        autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

                String PARAMETERS = resultList.get(arg2).getRef();
                Log.e("ref string", PARAMETERS);
                new Async().execute("" + PARAMETERS);
            }
        });


text:
Q: Sequentially Execute Php sripts in batch file only after execution of one is completed I have a requirement where I have multiple php scripts to be executed and one php script depends on the result of previous script. Note that all of these scripts update MySQL database.
Can anyone tell me tools or commands for this purpose?
Thank you!
This is the code in my jobs.bat file
path to php directory\php.exe  path to php scritps\script 1.php
 path to php directory\php.exe  path to php scritps\script 2.php

I just want to know whether command 2 will wait for the "script 1" until is completely executed and updated the database OR both the commands will execute sequentially in parallel?

A: You could be a little more specific about what kind of data needs to be passed from one php script to another.
A bash script would work just fine to execute the php scripts sequentially:
php /path/to/script1.php
php /path/to/script2.php
php /path/to/script3.php

As for the passing of data from one php script to another, you have several options.  One of them is packing all the variables you need to pass into an array, serializing it, then outputting it to a file.  When the next script starts, the first thing you would do is access the file, unserialize the array, then use the data it contains in your script.
First php script:
// code that does stuff
...

// this comes at the end of your script
// example of variables that you might want to send to the next script
$some_var = 4;
$some_string = 'It works for strings too.';
$some_array = array('red' => '#ff0000', 'green' => '#00ff00', 'blue' => '#0000ff');

// bundle the variables into an array
$bundled_data = array([0] => $var, [1] => $some_string, [2] => $some_array);

// serialize the array into a string
$serialized_array = serialize($bundled_data);

// then write to the file
$file = fopen('temp.txt', 'w');
$file.write($serialized_array);
$file.close();

Second php script:
// this comes at the beginning of your script
// retrieve the saved data
$file_text = file_get_contents('/path/to/temp.txt');
$bundled_data = unserialize($file_text);

// access the data and use it in your script
$var = $bundled_data[0];
$some_string = $bundled_data[1];
$some_array = $bundled_data[2];

Hopefully this answer is relevant to your situation.  In the future, please post code examples, and explain what you have tried.


text:
Q: canon advanced printing technology printer status window I need uninstall or disable canon advanced printing technology printer status window (CNAB5SWD.exe). Does anyone know how?

A: You should have a Canon  program group that comes with an uninstall shortcut.
To simply disable it, in Windows 7 it would be:
Start (round button) ➯ Devices and Printers
Right-click on the Canon & pick PRINTER properties (not just Properties)
Go to the Advanced tab (approx. middle tab) and you'll see Enable Advanced Printing Features.  Uncheck that box.  OK etc.

Note that from what I've read, removing CAPT may also take away the ability to Print Preview in some programs.


text:
Q: How to read and modify Object passed to a function in React In my main function App(), in useEffect(), I get data (variable named document) using some API with success. My data is the Object with some fields ie title and text.
I pass this data through my functions and I want different functions to use different parts of the document. Later, I render title with success:
import React from 'react'
import "./Title.css"

function Title({document}) {
    return (

            {document.title}

    )
}

export default Title;

I want to render 'text' field too, BUT I'd like to split it on newlines
import {useState, useEffect} from 'react'
import React from 'react'

function SourceText({ document }) {
    return (

            {document.text.split()}

    )
}

export default SourceText

Which does not work and returns error

TypeError: document.text is undefined

which is weird because when I return just document.text in divs, this object exists.
I tried to add something like this
const [text, setText] = React.useState(null);
React.useEffect(() => {
    setText(document.text)
    console.log(document.text);
}, []);

But it does not look like it sets document.text value to text variable. What I can't get too is that console in the browser prints the entire object after adding these lines of code.
I am new to React and JavaScript and I really don't get how to modify and use the value passed to a function.
Thanks
EDIT:
I pass the document from App to TabGroup, then to Source and then to SourceText. The last one is here:
import './Source.css';
import SourceText from './SourceText';
import Title from './Title';

function Source({document}) {
  return (

        <Title title={document.title}/>
        <SourceText document={document} />

  );
}

export default Source;

As I mentioned Title always renders, and using just {document.text} in SourceText does work too

A: document.text.split() will return an array. str.split() without any parameters returns an array.
You cannot render arrays directly unless you loop through each item. Also, always add checks for null | undefined when trying to render values.
{document?.text && document.text.split().map...}

A: After @Tom Bombadil post I was able to find the solution
import {useState, useEffect} from 'react'
import React from 'react'

function SourceText({ document }) {

    return (

            {document.text && document.text.split('at').map((line) => (line))}

    )
}

export default SourceText

EDIT: didn't take too long to realize my earlier notes were wrong. Seems like it was indeed some async issue - hard to understand for me because the error and result depend on the duration of data fetching.


text:
Q: Python Can this setup have memory leak? I have a few simple scripts that run continuously (24/7 forever).
However, a few of these scripts are slowly eating up all my memory.  I was confused why/how.  The general format is:
import time
SLEEPTIME = 10 # some number so it's not always running
def main():
    # example stuff, obviously much more complex in actual
    for i in xrange(0, 10000):
        i

def run():
    while True:
        start = time.time()
        main()
        time.sleep(SLEEPTIME - (time.time() - start))
        print('Finish loop')
if __name__ == '__main__':
    run()

I run it by navigating to folder:  nohup python script.py &
(ubuntu 12.04 server, python 2.7.3)
Is it possible for things to not get garbage collected in the format I have created?  Is there a sure proof way to make sure that the server releases all the memory?  Running garbage collection is bad (and didnt work.)
Thanks!

A: If you're running on a *nix based system, I'd recommend you run a cron job instead.
Cron jobs work by scheduling your script every x minutes, hours or days. Your script will simply run, do some work, and instead of going to sleep just exit. Your script simplified will look as follows:
def main():
    # example stuff, obviously much more complex in actual
    for i in xrange(0, 10000):
        pass

def run():
    main()

if __name__ == '__main__':
    run()

The advantage of this is that your script starts from "fresh" everytime, and you don't have to worry about memory leaks.
Here's a one line specifying your cron job to start every minute:
*/60 * * * * *     root python /path/to/your/script.py


text:
Q: Jquery cookie not created Hi there i included the jquery.cookie-plugin in my head-tag, now i am using this snippet to test cookie:
$(document).ready(function() {
    $userSettings = array(
        "personal_information" = array(
            "name" => "name",
            "last_name" => "lastname"
        ),
        "extra_information" = array(
            "twitter" => "anyName",
            "facebook" => "anyName",
            "website" => "http://domain.com/",
            "programming_languages" => array("JavaScript", "PHP", "Java")
        )
   );
});
// Creating the JSON object
$jsonObject = json_encode($userSettings);

(function($){
        $(document).on('ready', function(){
            //A cookie by the name 'userSettings' now exists with a serialized copy of $userSettings
            $.cookies.set( 'userSettings', <?php echo $jsonObject; ?> );

            //A variable named 'userSettings' now holds the unserialized object, it should be identical to the PHP variable 'userSettings'
            var userSettings = $.cookies.get( 'userSettings' );

            // Do something with the values read from cookie
            console.log(userSettings);
        });
})(jQuery);

But there is no log in my console, anybody could tell me what i am doing wrong, cause i get this referenceE in my console:
ReferenceError: invalid assignment left-hand side

$userSettings = array("personal_information" = array(

Greetings!!

A: Try this
 <?php
$userSettings = array(
    "personal_information" = array(
        "name" => "name",
        "last_name" => "lastname"
    ),
    "extra_information" = array(
        "twitter" => "anyName",
        "facebook" => "anyName",
        "website" => "http://domain.com/",
        "programming_languages" => array("JavaScript", "PHP", "Java")
    )
 );

  // Creating the JSON object

$jsonObject = json_encode($userSettings);
  ?>

<script type="text/javascript">
   (function($){
    $(document).on('ready', function(){
        //A cookie by the name 'userSettings' now exists with a serialized copy of $userSettings
        $.cookie.set( 'userSettings', <?php echo $jsonObject; ?> );

        //A variable named 'userSettings' now holds the unserialized object, it should be identical to the PHP variable 'userSettings'
        var userSettings = $.cookie.get( 'userSettings' );

        // Do something with the values read from cookie
        console.log(userSettings);
    });
 })(jQuery);

   </script>

A: You have to use $.cookie() instead:
(function($){
    $(document).on('ready', function(){

        $.cookie( 'userSettings', '<?php echo $jsonObject; ?>' ); // change here

        var userSettings = $.cookie( 'userSettings' ); // here

        console.log(userSettings);
    });
})(jQuery);

A: Why not make it into a JSON object straight away:
var userSettings = [{
    "personal_information" : {
        "name" :"name",
        "last_name" : "lastname"
    }},
    {"extra_information" : {
        "twitter" : "anyName",
        "facebook" : "anyName",
        "website" : "http://domain.com/",
        "programming_languages" : ["JavaScript", "PHP", "Java"]
    }
}]

And @Jai is right: you should use $.cookie() instead of get() and set()
$.cookie( 'userSettings', JSON.stringify(userSettings));


text:
Q: how to save a parquet with pandas using same header than hadoop spark parquet? I have a couple of files (csv,..) and am using pandas and pyarrow.table (0.17)
to save it as parquet on disk (parquet version 1.4)
colums
id : string
val : string

table = pa.Table.from_pandas(df)
pq.write_table(table, "df.parquet", version='1.0', flavor='spark', write_statistics=True, )

However, Hive and Spark does not recognize the parquet version:
org.apache.parquet.VersionParser$VersionParseException: Could not parse created_by: parquet-cpp version 1.5.1-SNAPSHOT using format: (.+) version ((.*) )?\(build ?(.*)\)
        at org.apache.parquet.VersionParser.parse(VersionParser.java:112)
        at org.apache.parquet.CorruptStatistics.shouldIgnoreStatistics(CorruptStatistics.java:60)
        at org.apache.parquet.format.converter.ParquetMetadataConverter.fromParquetStatistics(ParquetMetadataConverter.java:263)

Just wondering, how to save as "spark parquet" in snappy format,
without using launching spark (ie a bit of overkill).
Metadata seems missing.
EDIT based on Pace Comments:
Issue on older version of parquer, now fixed
https://issues.apache.org/jira/browse/PARQUET-349
Older version of Hive, Spark still have the issue.
https://issues.apache.org/jira/browse/HIVE-19464
Python Arrow does not provide the parquet version:
https://github.com/apache/arrow/blob/4591d76fce2846a29dac33bf01e9ba0337b118e9/python/pyarrow/_parquet.pxd#L360

A: Besides Pace excellent comments/inights.
A workaround of this issue ist to use fastparquet,
as follow:
import fastparquet as fp
df = df.to_pandas()
fp.write('yourdir', df, fixed_text=None,
         compression='SNAPPY', file_scheme='hive')


text:
Q: ReactJS Error input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML` I have a super simple React page connecting to NodeJS endpoints. I'm getting this error "Uncaught Error: input is a void element tag and must neither have children nor use dangerouslySetInnerHTML."
I have tried multiple solutions posted in SOF(put a label outside the input tag, use self close input tags, etc.) and all around but nothing helped.
EmailFaxDetails.js
import React, { useState } from 'react'
import FetchOrderDetails from './FetchOrderDetails';
import '../App.css';

const EmailFaxDetails = () => {

    const [message, setMessage] = useState('');
    const [isShown, setIsShown] = useState(false);

  const handleChange = event => {
    setMessage(event.target.value);
    console.log(event.target.value);
  };

  const handleClick = event => {
    event.preventDefault();
    setIsShown(true);
    console.log(message);

  }

    return(

            Order Number: <input placeholder="Order Number" type="text" id="message" name="message" onChange={handleChange} value={message} autoComplete="off" />

            <button onClick={handleClick}>Search</button>

            {isShown && <FetchOrderDetails ord_no={message}/>}

    )
}

export default EmailFaxDetails;

FetchOrderDetails.js
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import '../App.css';

const FetchOrderDetails = ({ord_no}) => {
    const [data, setData] = useState([]);

    const url = `http://localhost:5000/api/customerOrder/${ord_no}`
      useEffect(() => {
        axios.get(url)
        .then(response => {
          console.log(response.data)
          setData(response.data)
        })
        .catch((err) => console.log(err));
      }, [url]);

    if(data) {
        return(

                {data.map((order) => (

                      Sales Ack Email: <input placeholder="Sales Ack Email" id="salesAck">{order.cmt[0]}</input>

                      Invoice Email: <input placeholder="Invoice Email" id="salesInv">{order.cmt[1]}</input>

                        <button>Update</button>

                ))}

        )
    }
    return (

Something went wrong, please contact IT!

    )
}

export default FetchOrderDetails;

App.js
import React from 'react';
import EmailFaxDetails from './components/EmailFaxDetails';
import './App.css';

function App() {

  return (
    <>
    <EmailFaxDetails />
    </>
  );
}

export default App;

A: In the FetchOrderDetails.js
Sales Ack Email: <input placeholder="Sales Ack Email" id="salesAck">{order.cmt[0]}</input>

Invoice Email: <input placeholder="Invoice Email" id="salesInv">{order.cmt[1]}</input>

input element is a self-closing tag and can't contain children elements or text.
If you want to add a default value for the input you can add defaultValue property.
Sales Ack Email: <input defaultValue={order.cmt[0]} placeholder="Sales Ack Email" id="salesAck" />

Invoice Email: <input defaultValue={order.cmt[1]} placeholder="Invoice Email" id="salesInv" />

Or add a value property and onChange event to update the value.


text:
Q: React responsive image without srcset? I want to confirm whether or not React is able to serve responsive images without needing srcset tag in html.
Using state with the window width, I can set conditional renderings of images. Using chrome and checking the network flow, it seems the desired images are being served without having to serve all images.
import React from "react"
import images from "../assets/images"

class App extends React.Component{
    state = {
        width: 0
    }
    componentDidMount(){
        window.addEventListener("resize", this.handleResize)
        this.setState({
            width: window.innerWidth
        })
        console.log(this.state.width)
    }
    handleResize = () =>{
        this.setState({
            width: window.innerWidth
        })
        console.log(this.state.width)
    }
    render(){
        const image = this.state.width > 1000 && this.state.width !== 0 ? images.HD : images.LD
        return(

        )
    }
}

export default App

Is this a valid way to serve specific images with different resolutions?


text:
Q: How to directly call conversion operator? struct Bob
{
    template<class T>
    void operator () () const
    {
        T t;
    }

    template<class T>
    operator T () const
    {
        T t;
        return t;
    }
};

I can directly call Bob's operator() like this
Bob b;
b.operator()<int>();

How to directly call the conversion operator with a specific template parameter like this?
Bob b;
std::string s = b.???<std::string>();

It's not possible to use static_cast
Bob b;
std::string s = static_cast<std::string>(b);

http://ideone.com/FoBKp7
error: call of overloaded 'basic_string(Bob&)' is ambiguous
Question
How to call directly with template parameter OR it's not possible. I know there are workarounds using a wrapping function.

A: Use a helper function:
template< typename T >
T explicit_cast( T t ) { return t; }

int main()
{
    Bob b;
    std::string s = explicit_cast<std::string>(b);
}

A: You can call it directly (explicitly) like this:
Bob b;
std::string s = b.operator std::string();

but it's not "with a specific template parameter" (but there's no need for).
See also WhozCraig's comment


text: Q: PermitRootLogin in Debian 10 or 11 OOB, Debian does not allow root to log in over SSH. I read man ssh and found a reference to PermitRootLogin config key but no mention of its option values. Here I learned that it can be set to yes and did so. Still not able to log in as root: Permission denied. Looking for a surefire way to enable root to log in through SSH. Since I am working with throwaway test VMs there are no security considerations that could constrain me from that.


text:
Q: How do I listen to mouse clicks from RelatedItemLineMarkerInfo? I need to run a custom action when my marker is clicked.
I tried, according to tutorial,
NavigationGutterIconBuilder<PsiElement> builder =
        NavigationGutterIconBuilder.create(LessonScriptIcons.PUZZLE).
                setTarget(this).
                setTooltipText("Navigate to component");

RelatedItemLineMarkerInfo<PsiElement> m = builder.createLineMarkerInfo(this);

But I can't figure out how to get to the marker's navigation handler, or otherwise listen to this marker's events. (The cursor moving to the beginning of "this" element is a slightly undesired, but unimportant side effect that would be nice to suppress).
Then I tried this:
RelatedItemLineMarkerInfo marker =  new RelatedItemLineMarkerInfo(this, getTextRange(), MyIcons.VOLUME, 0, tooltipProvider, handler, GutterIconRenderer.Alignment.CENTER, new ArrayList<GotoRelatedItem>());

This approach allows me to listen to the marker's mouse clicks. However, now I am experiencing a peculiar problem: whenever the marked line of code is edited, this results in duplicate, triplicate, etc. markers in the gutter.
What's the correct way to do it?

A: Turns out I needed to specify a pass.
int pass = Pass.UPDATE_OVERRIDEN_MARKERS;

RelatedItemLineMarkerInfo marker =  new RelatedItemLineMarkerInfo(this, getTextRange(), MyIcons.VOLUME, pass, tooltipProvider, handler, GutterIconRenderer.Alignment.CENTER, new ArrayList<GotoRelatedItem>());

I had to use Pass.UPDATE_OVERRIDEN_MARKERS even though IntelliJ marked it as deprecated and said it will be removed shortly (see the link below). However, the constant recommended by IntelliJ, Pass.LINE_MARKERS, results in duplicate markers.
https://github.com/JetBrains/intellij-community/blob/master/platform/analysis-impl/src/com/intellij/codeHighlighting/Pass.java


text:
Q: Encrypting absolutely everything, even within the LAN Has anybody tried that approach already? I'm really considering it: Instead of relying on network based IDS etc., every packet must use encryption which was initiated by a certificate issued by my own CA.

*

*Every client gets a unique client certificate

*Every server gets a unique server certificate

*Every service additionally requires to login.

Both SSL and SSH would be ok. Access to the internet would be done via an SSL tunnel to the gateway.
Is it feasible? Does it create practical problems? How could it be done and enforced? What do you think?
More details
My goal is to simplify the LAN's security concept - I'm not yet sure, if that's a crazy idea! But I feel, that securing a HTTPS or SSH server from internet threats (if using mutual authentication) is sometimes easier than monitoring everything that can happen in the wild world of a LAN.
On a non-encrypted LAN, I feel it's really hard to be a good step ahead of a potential attacker, because of threats like:

*

*Low level attacks like ARP spoofing, Port stealing, ...

*WLAN access (e.g. every developer will be allowed to access the SVN server from the (W)LAN - I don't think it will be through a VPN...)

=> For simplicity, isn't it easier to make the assumption, that there is always an attacker in the LAN?
=> Could I end up simplifying a (small company's) LAN security concept by treating it like a WAN? Or would I rather complicate it?
IPSec and alternatives
IPSec sounds very promising, but I'd be interested in alternatives to IPSec, too - Using SSL/SSH individually per service and creating an Stunnel to the Gateway? Using Kerberos maybe? ... What are the advantages of IPSec or the others?
If you can help me with getting a better grasp on IPSec, please see my follow-up question specifically on IPSec.

A: IPSec is the standard for this.  It comes in different forms and there is a lot of vocabulary to it.
I recommend this guide to IPSec to get you started.

A: I use IPsec here for everything.  The reasoning is that most attacks are made by insiders anyway - the bad side/good side thinking is flawed.  (If anyone makes off with the servers they can have fun trying to break the full-disk encryption, so no problem there, either.)
It's also fun to use telnet, NIS, NFS and FTP without any worries - feels like the good old days!  :-)

A: Do you have a threat model where unfettered access to your LAN infrastructure is expected? If so, yes, deploying IPSEC to all end-points is probably what you want.
However, in most threat models there's enough perimeter security that you can essentially ignore the LAN infrastructure as a cheap access method.
The picture changes if you have WiFi installed, you'd need something between the WiFi network(s) and the wired network(s) to ensure that you don't have any information leakage via that route.

A: On the windows side what you are looking for is Domain and Server isolation.  You can play with it using this labcast
My default windows implementation plan for a new install has this included.  In windows it's not hard to set up and offers lots of extra security (and there's really no "extra" administration you might need a few more security groups).
NAP doesn't require IPsec (or even the PKI - that's only if you want to run native mode).  SCCM is an additional product- nothing extra is required for domain and server isolation.  NAP is primarily designed for send "health" information about a client and if that client doesn't pass your "health" check then it is deferred to only communicate with a remediation server(s). Health is defined as patch requirements AV settings, security settings etc.  You certainly can use SCCM to set up IPSEC, but it's not a requirement.
With Domain and server isolation I don't have the ability to check those "health"- nor is it the point.  When it's set up I am encrypting the traffic and ensuring that and additionally guaranteeing that the servers and clients are only allowed to communicate with the servers and clients required for that business function (eg HR workstations are the only workstations allowed to communicate with the HR server).

A: The security term is "protection of data in transit."  Yes, there are groups that do this, and yes, in some ways it does simplify LAN security. IPSEC and IPv6 can be used to support this.
The complementary concept is "protection of data at rest," which means encrypting your disks.

A: Don't know what systems and infrastructure you're using but Microsoft's System Centre Config Manager (SCCM) has a Network Access Protection (NAP) component that does exactly what you're after.
It PKI encrypts all client-server traffic and puts non-authenticated machines into what is effectively a DMZ where they're unable to to talk to any server/machine/system that hasn't been specifically setup to sit in that DMZ also. It can also allow pre-check machines patch level, anti-virus, security, etc settings before allowing them onto the main LAN (obviously in this case you'd have an updates server or two sitting in the DMZ.
Step by step guides to settings this up for demo/testing are here.


text:
Q: Create a manual property binder in c# I have a task I am trying to complete, and trying to do it the best way possible.
Let say I have a jObject
var jobj = {val1: 1, val2: "s"} // on server

and I need to user the properties in that object as the params for a Method.Invoke call.
someMethod.Invoke(class, params);

I need some way to take the properties from the JObject and convert them into an array of objects to pass to the invoke method.
I can easily get the param details
var param = Method.GetParameter("ParameterName");

this will give me the value, type be it a string or a complex object.
While a believe I could write the code to do this I think it would be better to use built in .Net functionality if it exists.
.Net does very similar conversions for all WEB_API and MVC Controller calls, and I would like to tap into those existing functions to do the work as they are probably very well vetted, but I am having trouble finding out how it is done.
I have found the IActionValueBinder and the DefaultModelBinder but I cannot figure out how to use these outside the context of a standard controller.


text:
Q: protobuf text format parsing maps This answer clearly shows some examples of proto text parsing, but does not have an example for maps.
If a proto has:
map<int32, string> aToB

I would guess something like:
aToB {
    123: "foo"
}

but it does not work. Does anyone know the exact syntax?

A: I initially tried extrapolating from an earlier answer, which led me astray, because I incorrectly thought multiple k/v pairs would look like this:
aToB {         # (this example has a bug)
    key: 123
    value: "foo"
    key: 876        # WRONG!
    value: "bar"    # NOPE!
}

That led to the following error:
 libprotobuf ERROR: Non-repeated field "key" is specified multiple times.

Proper syntax for multiple key-value pairs:
(Note: I am using the "proto3" version of the protocol buffers language)
aToB {
    key: 123
    value: "foo"
}
aToB {
    key: 876
    value: "bar"
}

The pattern of repeating the name of the map variable makes more sense after re-reading this relevant portion of the proto3 Map documentation, which explains that maps are equivalent to defining your own "pair" message type and then marking it as "repeated".

A more complete example:
proto definition:
syntax = "proto3";
package myproject.testing;

message UserRecord {
  string handle = 10;
  bool paid_membership = 20;
}

message UserCollection {
  string description = 20;
  // HERE IS THE PROTOBUF MAP-TYPE FIELD:
  map<string, UserRecord> users = 10;
}

message TestData {
  UserCollection user_collection = 10;
}

text format ("pbtxt") in a config file:
user_collection {
  description = "my default users"
  users {
    key: "user_1234"
    value {
      handle: "winniepoo"
      paid_membership: true
    }
  }
  users {
    key: "user_9b27"
    value {
      handle: "smokeybear"
    }
  }
}

C++ that would generate the message content programmatically
myproject::testing::UserRecord user_1;
user_1.set_handle("winniepoo");
user_1.set_paid_membership(true);
myproject::testing::UserRecord user_2;
user_2.set_handle("smokeybear");
user_2.set_paid_membership(false);

using pair_type =
    google::protobuf::MapPair<std::string, myproject::testing::UserRecord>;

myproject::testing::TestData data;
data.mutable_user_collection()->mutable_users()->insert(
    pair_type(std::string("user_1234"), user_1));
data.mutable_user_collection()->mutable_users()->insert(
    pair_type(std::string("user_9b27"), user_2));

A: The text format is:
aToB {
    key: 123
    value: "foo"
}


text:
Q: ContentDistributionTrigger after insert ContentDownloadUrl null I have a ContentDistributionTrigger trigger after insert & update which when fired has a null value for ContentDownloadUrl.
The ContentDistribution is created in a  ContentDocumentLinkTrigger as such:
ContentDistribution cd = new ContentDistribution();
cd.Name = (String)link.LinkedEntityId + ' logo' ;
cd.ContentVersionId = // my id
cd.RelatedRecordId = link.LinkedEntityId;
cd.PreferencesAllowOriginalDownload = true;
cd.PreferencesPasswordRequired = false;
insert cd;

Then in my ContentDistributionTrigger:
trigger ContentDistributionTrigger on ContentDistribution ( after insert, after update ) {

    for (ContentDistribution cd : Trigger.new) {
        System.debug(cd.ContentDownloadUrl);
    }
}

debugs as "null"
Is the ContentDownloadUrl generated after the after insert trigger fires? If so, why don't I catch it in the "after update" run of this trigger?
Thank you,

A: You need to requery the object based on the trigger context with the fields you want in order to get their values.
List<ContentDistribution> contextList = [ select id, DistributionPublicUrl, ContentDownloadUrl, ContentDocumentId from ContentDistribution where id in :Trigger.new ];

And now you can work with contextList instead of Trigger.new.


text:
Q: In laravel, I am getting the view of current user as a follower of itself instead of followers In database i have following structure

id | following_id | followed_id
1  |     3        |    1
2  |     2        |    1

I have user model and it looks like this

public function userFollows()
    {
        return $this->belongsToMany('Diskourse\Models\User','followers','following_id','followed_id');

}

public function userIsFollowed()
{
    return $this->belongsToMany('Diskourse\Models\User','followers','followed_id','following_id');
}

public function followers()
{
   return $this->userIsFollowed->merge($this->userFollows);
}

And at last view looks like this

Followers

            @if(!$user->followers()->count())

No followers

            @endif
                @foreach($user->followers() as $follower)

                    @include('user/partials/userblock')

                @endforeach

If its working it should display user 3 and 2 as a follower of 1. Instead current user profile block is displaying twice. Please Help !!!!

A: Is the userblock partial looking for the variable $user? because that is still set to the current user.  I would use this:
@each('user.partials.userblock', $user->userFollows, 'user')

That will repeat the userblock view for each follower, passing the follower in as $user


text: Q: All letters appear as Capital letters in Word 2007 even if CapsLock is off In my Word 2007 all letters typing from or copying from some where else appears as capital letters. Things were fine till yesterday. I checked whether Caps Lock is on, but it is not. Is there any option in Word to capitalize all letters. How can I avoid this issue ?


text:
Q: Internet explorer with tinymce creates box when clicked I would like to make tinymce work in my CMS with IE but i stumbled over the following problem:
When i click into the editor i get a very ugly box which makes users unhappy.
It is not possible to select more than one paragraph.
I am sure there is a workaround or init setting for this.

Can anyone help me?

A: I found out the reason for this problem. It was a css setting:
p {
  min-height : 18px;
}

After removal everything worked fine.
Edit: The following css setting had the same unwanted effect:
p {
  width : 250px;
}

Helpfull link concerning the problem: http://www.satzansatz.de/cssd/onhavinglayout.html


text:
Q: argument "male" is missing, with no default I'm trying to create a function that performs calculations based off of a patient's information. However, I keep getting the same error message that says "Error in SMARTRISK(PATIENT1): argument "male" is missing, with no default".
Here is the function:
SMARTRISK=function(age,male,smoker,systolic,diabetic,CAD,CVD,AAA,PAD,yrs,HDL,
                   TCHOL,eGFR,loghsCRP)
{
  SMARTRISK=(-0.0850*age)+(0.00105*(age^2))+(0.156*male)+(0.262*smoker)+
    (0.00429*systolic)+(0.223*diabetic)+(0.140*CAD)+(0.406*CVD)+(0.558*AAA)+
    (0.283*PAD)+(0.0229*yrs)-(0.426*HDL)+(0.0959*TCHOL)-(0.0532*eGFR)+
    (0.000306*(eGFR^2))+(0.139*loghsCRP)
  return(SMARTRISK) #return the SMARTRISK linear predictor as an output of the function
}

Then I initiated the following data frame:
age=65
male=0
smoker=1
systolic=160
diabetic=1
CAD=0
CVD=0
AAA=0
PAD=1
yrs=12
HDL=2
TCHOL=4
eGFR=100
loghsCRP=1
PATIENT1=data.frame(age,male,smoker,systolic,diabetic,CAD,CVD,AAA,PAD,yrs,HDL,
                    TCHOL,eGFR,loghsCRP)

And here is the final calculation I'm trying to perform:
(1-(0.81066^(exp(SMARTRISK(PATIENT1))+2.099)))*100

I am not understanding why things are getting caught up at "male". I have also tried print(male) and print(male)==1 within the function, but keep getting the same results. Why would it not understand the argument "male" but understand the "age" argument?

A: I am working on the same thing. I had set up mine a bit differently
Data= data.frame('age',.....)
then
SMARTRISK= function(Data)
and the long formula that goes under it
then for the patient data, I did
PATIENT1= data.frame(65,....)
and got my answer that way


text:
Q: Assigning value to variable from a select count So I've been programming a lot in sql recently but I'm still a newby and don't know a lot of the rules for the language and when the compiler doesn't help much I really don't know what to do.
In this case I got three errors:
Error(5,12): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: (...)
Error(5,125): PLS-00103: Encountered the symbol ")" when expecting one of the following:     * (...)
Error(22,20): PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:     end not pragma final instantiable order overriding static    member constructor map

Here's the code, a trigger that inserts into a MENSALIDADE table if the date difference on CONTRATO.DATA_CONTRATO and today's DATE (more specifficaly the month difference) is lesser than 8 and if they have any registers in FATURA where ESTADO is 'Nao pago' (sorry for portuguese but it's 'Not paid'):
create or replace TRIGGER ANULAR_CONTRATO BEFORE DELETE ON CONTRATO
FOR EACH ROW
DECLARE
valor NUMBER;
juro NUMBER;
BEGIN
juro := (SELECT COUNT(N_FATURA) FROM FATURA WHERE (EXTRACT(month FROM FATURA.DATA_FATURA) = (EXTRACT(month FROM SYSDATE))));
valor := (50 + juro);
IF DELETING THEN
IF ((MONTHS_BETWEEN(:OLD.DATA_CONTRATO, SYSDATE)) <= 8) THEN
  IF EXISTS (SELECT (FATURA.CODIGO_CLIENTE) FROM FATURA, CONTRATO WHERE (FATURA.CODIGO_CLIENTE = CONTRATO.CODIGO_CLIENTE)) THEN
    IF EXISTS (SELECT (FATURA.CODIGO_CLIENTE) FROM FATURA, CONTRATO WHERE ((FATURA.CODIGO_CLIENTE = CONTRATO.CODIGO_CLIENTE) AND (FATURA_ESTADO = 'Nao Pago'))) THEN
      INSERT INTO MENSALIDADE (N_MENSALIDADE, CODIGO_CLIENTE, N_CONTRATO, VALOR, DATA_FIM) VALUES (SEQ_MENSALIDADE.NEXTVAL, CONTRATO.CODIGO_CLIENTE, CONTRATO.N_CONTRATO, valor ,CONTRATO.DATA_FIM_CONTRATO);
    END IF;
  END IF;
ELSE
  IF EXISTS (SELECT (FATURA.CODIGO_CLIENTE) FROM FATURA, CONTRATO WHERE (FATURA.CODIGO_CLIENTE = CONTRATO.CODIGO_CLIENTE)) THEN
    IF EXISTS (SELECT (FATURA.ESTADO) FROM FATURA, CONTRATO WHERE (FATURA.CODIGO_CLIENTE = CONTRATO.CODIGO_CLIENTE) AND (FATURA_ESTADO = 'Nao Pago')) THEN
      INSERT INTO MENSALIDADE (N_MENSALIDADE, CODIGO_CLIENTE, N_CONTRATO, VALOR, DATA_FIM) VALUES (SEQ_MENSALIDADE.NEXTVAL, CONTRATO.CODIGO_CLIENTE, CONTRATO.N_CONTRATO, valor ,CONTRATO.DATA_FIM_CONTRATO);
    END IF;
  END IF;
END IF;
END IF;
END ANULAR_CONTRATO;

The first to errors probably I can't do what I'm doing the I'm doing but some help on how to do it properly would be really appreciated.
The third one I have no idea why is happening. Thank you!

A: This will help:

 SELECT COUNT(N_FATURA) into juro
 FROM FATURA
 WHERE (EXTRACT(month FROM FATURA.DATA_FATURA) = (EXTRACT(month FROM SYSDATE)));

A: You need to use SELECT INTO in PL/SQL to set values returning from SELECT queries. Can you change it as follows and see what error you get after that?
Also IF EXISTS is not valid in Oracle, see here.
I guess, you cannot get the values of the deleted row with CONTRATO.DATA_FIM_CONTRATO, instead, you need to write :old.DATA_FIM_CONTRATO. This time, here.
create or replace TRIGGER ANULAR_CONTRATO BEFORE DELETE ON CONTRATO
FOR EACH ROW
DECLARE
valor NUMBER;
juro NUMBER;
cond1 NUMBER;
cond2 NUMBER;
BEGIN
SELECT COUNT(N_FATURA) INTO juro FROM FATURA WHERE EXTRACT(month FROM FATURA.DATA_FATURA) = EXTRACT(month FROM SYSDATE);
valor := 50 + juro;
IF DELETING THEN
    IF (MONTHS_BETWEEN(:OLD.DATA_CONTRATO, SYSDATE)) <= 8 THEN
        SELECT COUNT(FATURA.CODIGO_CLIENTE) INTO cond1 FROM FATURA, CONTRATO WHERE (FATURA.CODIGO_CLIENTE = CONTRATO.CODIGO_CLIENTE) AND (FATURA_ESTADO = 'Nao Pago');
        IF cond1 > 0 THEN
            INSERT INTO MENSALIDADE (N_MENSALIDADE, CODIGO_CLIENTE, N_CONTRATO, VALOR, DATA_FIM) VALUES (SEQ_MENSALIDADE.NEXTVAL, :old.CODIGO_CLIENTE, :old.N_CONTRATO, valor ,:old.DATA_FIM_CONTRATO);
        END IF;
    ELSE
        SELECT COUNT(FATURA.ESTADO) INTO cond2 FROM FATURA, CONTRATO WHERE (FATURA.CODIGO_CLIENTE = CONTRATO.CODIGO_CLIENTE) AND (FATURA_ESTADO = 'Nao Pago');
        IF cond2 > 0 THEN
            INSERT INTO MENSALIDADE (N_MENSALIDADE, CODIGO_CLIENTE, N_CONTRATO, VALOR, DATA_FIM) VALUES (SEQ_MENSALIDADE.NEXTVAL, :old.CODIGO_CLIENTE, :old.N_CONTRATO, valor ,:old.DATA_FIM_CONTRATO);
        END IF;
    END IF;
END IF;
END ANULAR_CONTRATO;


text:
Q: Issues with executable: file not found after using chmod to fix permissions I have downloaded and extracted the Linux binary for the blackbox PDDL planner, and I'm trying to get the blackbox file to execute. I changed to the directory with the file and tried ./blackbox, which gave me a permissions error. No big deal, just run chmod 755 blackbox to give it executable permissions. But then, when I try ./blackbox again, I get the following error:
bash: ./blackbox: No such file or directory

It does the same when I give the command arguments. When I run ls -l though, I see the blackbox file and it has -rwxr-xr-x permissions, so I'm not sure why it's "losing" the file.
I'm running Ubuntu 14.04 as a dual boot with Windows 7, if that matters.
EDIT: I found a helpful question over on Superuser, which has gotten me partially there. I ran readelf -l ./blackbox | grep ld-linux to find what I needed, then did a package content search to find out I needed the libc6-i386 package. Now I can do the following:
user@ubuntu:~/path$ ./blackbox
./blackbox: error while loading shared libraries: libstdc++.so.6: cannot open shared object file: No such file or directory
user@ubuntu:~/path$ ldd blackbox
    linux-gate.so.1 =>  (0xf77af000)
    libstdc++.so.6 => not found
    libm.so.6 => /lib32/libm.so.6 (0xf774f000)
    libgcc_s.so.1 => not found
    libc.so.6 => /lib32/libc.so.6 (0xf75a4000)
    /lib/ld-linux.so.2 (0xf77b0000)

A: Turns out the blackbox executable was a 32-bit program, and I am running a 64-bit OS. Here's the (somewhat hacky) steps I took to resolve this issue (partially chronicled in this question on Superuser):

*

*uname -m told me I have a 64-bit OS, but file blackbox told me that this exe was 32-bit.

*ldd blackbox (strangely) told me that the file was not a dynamic executable, even though I also saw this from file. Trying readelf -l ./blackbox | grep ld-linux told me [Requesting program interpreter: /lib/ld-linux.so.2], which was a shared library that I didn't have at that location.

*sudo apt-get install libc6-i386 to get that library file (found that with a package search on packages.ubuntu.com).

*Now ldd gave me output, and I was missing libstdc++.so.6 and libgcc_s.so.1 (see my edit), so I needed to get these files.

*After a bit more pacakage searching, I found that the gcc-snapshot package had the two files I was missing. This is probably a massive hammer for my tiny nail, and there are likely better solutions, but sudo apt-get install gcc-snapshot got me the files I needed.

*After running ldd again, this resolved the issue with libgcc_s.so.1, but libstdc++.so.6 was still not found. I ended up going to the place where ldd found libgcc_s.so.1 and running sudo ln -s /usr/lib/gcc-snapshot/lib32/libstdc++.so.6 libstdc++.so.6 to get a symlink to the recently installed file.


text:
Q: Shell: send foreground process to background without suspending it? I have a command I'm running in the background,
fnordctl &

Occasionally I pull it up into the foreground,
fg

Now, I'd like to send it back to the background to continue running. Typing Ctrl-z will suspend the process, and it won't continue running until I run bg.
Is there a way I could background the process without suspending it?
If that's not possible, maybe there's a way I could bind the suspend operation and subsequent bg to a shortcut key (e.g. Meta-z)? I'm using Bash, so maybe this is something I could create a custom Readline binding for?