text:
Q: Application only runs every 4th time? (python) I made a program, and for no good reason, an error similar to this unexplained error is raised ever time except for the 4th:
Traceback (most recent call last):
  File "C:\Users\caleb.sim\3D Objects\Sim Inc\Applications\Games\Chicken Clicker\class1.py", line 54, in <module>
    openbutton = Button(root, image=photo, width = 500, height=500, command = moar_eggz)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2165, in __init__
    Widget.__init__(self, master, 'button', cnf, kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2095, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
TclError: unknown color name ".45051576"

I cannot make sense of the error. If it helps, as it usually does, here is the code:
from tkinter import *
from PIL import Image, ImageTk
import time, threading

root = Tk()
root.title("Chicken Clicker")
eggz = 0
eggvalue = 0.2
eggzps = 0
chookz = 0
def moar_eggz():
    global eggz, eggvalue, eggzps, chookz
    chookz = chookz + 1
    eggzps = chookz / 100
    printchookz = round(chookz)
def update_labels():
    try:
        while True:
            eggzLabel = "Eggs: " + str(eggz)
            eggzpsLabel = eggzps
            eggvalueLabel = "Egg Value: " + str(eggvalue)
            chookzLabel = " Chickens: " + str(chookz)
            label1.config (text=eggzLabel)
            label2.config (text=eggzpsLabel)
            label3.config (text=eggvalueLabel)
            label4.config (text=chookzLabel)
            time.sleep(0.2)
    except: pass
def main_loop():
    global eggz, printeggzps
    try:
        while True:
            global eggz, printeggzps
            eggz += printeggzps
            time.sleep(1)
    except: pass
eggzLabel = "Eggs: " + str(eggz)
eggzpsLabel = eggzps
eggvalueLabel = "Egg Value: " + str(eggvalue)
chookzLabel = " Chickens: " + str(chookz)
label4 = Label(root, text=eggzLabel)
label3 = Label(root, text=eggzLabel)
label2 = Label(root, text=eggzLabel)
label1 = Label(root, text=eggzLabel)
label4.pack()
label3.pack()
label2.pack()
label1.pack()
imagecnv = Image.open("img\\1.png")
photo = ImageTk.PhotoImage(imagecnv)
threading.Thread (target = main_loop).start()
threading.Thread (target = update_labels).start()

openbutton = Button(root, image=photo, width = 500, height=500, command = moar_eggz)
openbutton.pack()

root.mainloop()

I have no idea what may have caused it.
Any help given will be highly appreciated!
Thanks in advance!

A: You don't need threads to run it - you can use root.after(time, function) (instead of thread, while and sleep) to run function every time milliseconds.
You could run update_labels() in moar_eggz() - you don't have to run it in loop. But I kept it to show how to use two root.after().
import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---

def moar_eggz():
    global eggzps, chookz

    chookz += 1
    eggzps = chookz / 100

def update_labels():
    try:
        label1.config(text="Eggs: " + str(eggz))
        label2.config(text=eggzps)
        label3.config(text="Egg Value: " + str(eggvalue))
        label4.config(text=" Chickens: " + str(chookz))
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 100ms
    root.after(100, update_labels)

def main_loop():
    global eggz

    try:
        eggz += printeggzps # ??? printeggzps didn't exist in original code
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 100ms
    root.after(100, main_loop)

# --- main ---

root = tk.Tk()
root.title("Chicken Clicker")

eggz = 0
eggvalue = 0.2
eggzps = 0
chookz = 0
# ??? printeggzps didn't exist in original code
printeggzps = 1

# empty labels - `update_labels()` will add text
label4 = tk.Label(root)
label3 = tk.Label(root)
label2 = tk.Label(root)
label1 = tk.Label(root)
label4.pack()
label3.pack()
label2.pack()
label1.pack()

imagecnv = Image.open("img\\1.png")
photo = ImageTk.PhotoImage(imagecnv)

openbutton = tk.Button(root, image=photo, width=500, height=500, command=moar_eggz)
openbutton.pack()

# run it first time at once
main_loop()
update_labels()
# or run it first time after 100ms
#root.after(100, main_loop)
#root.after(100, update_labels)

root.mainloop()

BTW: you can also use update_labels() inside main_loop() and then you will need only one root.after()


text:
Q: Synchronous ASIHTTPRequest updating label It seems very simple but not easy for me.. I am calling a few Synchronous ASIHTTPRequests and when each request is finished, I want to update a Label like following..
self.status.text = @"Google";

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];

self.status.text = @"Yahoo";

NSURL *url = [NSURL URLWithString:@"http://www.yahoo.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];

self.status.text = @"Apple";

NSURL *url = [NSURL URLWithString:@"http://www.Apple.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];

However, it only show nothing but "Apple" once all calls are done.. What is the simple and best way to achieve this?

A: UIKit has no chance to redraw the label because you're blocking the main thread for the whole url request.
You should use asynchronous requests instead, so the UI will be responsive all the time. Also update the UI in a completion block:
self.status.text = @"Google";

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
  self.status.text = @"Yahoo";
  // start another request etc.
}];
[request startAsynchronous];

redpajama_set_name: RedPajamaStackExchange


text:
Q: UWP app Google Authentication works on Desktop but not on Xbox One I have implemented google auth using WebAuthenticationBroker like below. It works perfectly fine on Desktop or Surface using same google account but when I try it on Xbox, it doesnt work.
     string authString = "https://accounts.google.com/o/oauth2/auth?client_id=" + Uri.EscapeDataString(ClientID);
                authString += "&scope=openid%20email%20profile";
                authString += $"&redirect_uri={Uri.EscapeDataString(RedirectURI)}";
                authString += $"&code_challenge={code_challenge}";
                authString += $"&code_challenge_method={code_challenge_method}";
                authString += "&response_type=code";
                authString += "&include_granted_scopes=true";

     string endURL = "https://accounts.google.com/o/oauth2/approval";
   Uri startURI = new Uri(authString);
      Uri endURI = new Uri(endURL);
   var receivedData = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startURI, endURI);

On UWP i receive an Approval_Code and full profile information but on Xbox, response is something like below
{https://accounts.google.com/o/oauth2/approval?as=xxxxxxxx=none&xsrfsign=xxxxxx}

Anyone knows what is special about Xbox one? how to fix this?

A: I finally found a solution. Problem is to use WebAuthenticationOptions.None when using this option, it works fine on desktop and surface Windows 10 machiens but this option doesnt work correctly for Xbox One. it returns no authorization code.
But browser title bar has always this code and in order to obtain this code, WebAuthenticationOptions.UseTitle needs to be used. Once used response has an element called "code" and you can just parse it as below
      var queryStringParams = System.Web.HttpUtility.ParseQueryString(receivedData.ResponseData.Substring(receivedData.ResponseData);

string code= queryStringParams["code"];

When using WebAuthenticationOptions.None response doesnt have queryStringcalled "code" but as "approvalCode". there is also this difference. I dont know why. But anyhow WebAuthenticationOptions.UseTitle can be used for all UWP devices. I have tested on all and works like a charm


text:
Q: Is there way to mock pojo other then setting values manually in mockito? consider a method returns class A in my service,
public List<A> method(){
A a=B.method_b();
List<A> list=new ArrayList<>();
for(A aa:a){
A classA=new A();
classA.setVal1(aa.getVal1());
list.add(classA);
}
        return list;
    }

My pojo class
class A{
private int val1;
private int val2;
.
.
.
.
private int val10;
//setter and getter
}

so in test case ,i wrote as
@Mock
B b;
@Test
public void check(){
 Mockito.when(b.method_b())
        .thenReturn(return_A());
}
private A return_A(){
A a=new A();
a.setVal1(1);
.
.
.
a.setVal10(10);
}

Here everything is working fine .Code coverage is also fine.But my question is ,is there any possible way to avoid above private method that returns class A by using mockito ?

A: in a unittest you define the behavior of your class depending on input.
This means you have to specify this input. There is no way around it.
There are different ways to do that.
one way it to configure the DTO the way you did.
Another way is to generate the input data. But this has some downsites:
 - you still need a method (or class) to do that,
 - it makes your test harder to read and understand,
 - it introduces failure possibilities in your test making it less reliable,
One more way  is to set only those values needed for the current test in the //arrange section of your test method:
@Mock
B b;
@Test
public void check(){
  // arrange
  Mockito.when(b.method_b())
        .thenReturn(return_A());
  A a=new A();
  // values to be used by cut in this test
  a.setVal1(1);
  a.setVal3(3);

  // act
  // assert
}

A: I came across this https://devskiller.github.io/jfairy/. This may useful for providing setter values if don't want to set values manually (hardcoded values).

A: A solution with PODAM
Add the gradle dependency
testImplementation 'uk.co.jemos.podam:podam:7.2.5.RELEASE'

How to use it ?
PodamFactory podamFactory = new PodamFactoryImpl();
Student student = podamFactory.manufacturePojo(Student.class);

A: I am very happy to use AutoFixture for .NET.
You can check JFixture for Java.
I think it is what you want.


text:
Q: Tool for height and width measurement of image in pixel Can anyone suggest me a tool to measure the dimension of an image in pixel.
I need it so that I can use a part of the image by specifying background-position-x and background-position-y as well as for height and width after assessing the position of the starting point in the image in terms of pixel.

A: in Chrome u can get a free add-on called page ruler:
https://chrome.google.com/webstore/detail/page-ruler/jlpkojjdgbllmedoapgfodplfhcbnbpn
Even Inspect element of Google chrome will give you height and width in pixels


text:
Q: JS: Calling function on Submit Hello everyone I'm still new to JS, so I want to ask about calling a function when form is submitted.

[update] Form

    <form id="report" class="form-horizontal" method="post" action="<?= site_url('api/load_report') ?>">
        <fieldset>

                Sales Name

                    <input type="text" name="sales_name" class="form-control input-xlarge txt-up" value="<?php echo set_value('cust_name'); ?>" placeholder="Enter Customer Name" style="height: 30px;"/>

                    <input id="get_report" type="submit" class="btn btn-success btn-inline " value="Get Report" style="width:110px; margin-left: -155px;"/>

                    Customer Name	Activity
                    Detail	Start Time
                    Finish Time	Note
                    Action

        </fieldset>
    </form>

Controller

public function load_report() {
    $this->db->where('user_id', $this->input->post('sales_name'));

    $query = $this->db->get('activity');
    $result = $query->result_array();
    $this->output->set_output(json_encode($result));  }

JS

var load_report = function() {
    $.get('api/load_report', function(o){

        var output = '';
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }
        $("#xreport").html(output);
    }, 'json');
};

If I call the function on form load it works fine, but I want to call it on form submit, how to do that?

Here is what I tried

var load_report = function () {
    $("#report").submit(function(){
     $.get('api/load_report', function(o){
        var output = '';
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }
        $("#xreport").html(output);
    }, 'json');
});
};

Instead of assigning the array into my #div, it shows the array data in the new blank tab like this:
my current result so far
any help would be appreciated, thanks.

Update: New calling function

  var load_report = function () {
    $("#report").submit(function (evt) {
        evt.preventDefault();
        var url = $(this).attr('action');
        var postData = $(this).serialize();

        $.post(url, postData, function (o) {
            if (o.result == 1) {
                var output = '';
                Result.success('Clocked-in');
                for (var i = 0; i < o.length; i++) {
                    output += Template.dodo(o[i]); //this data[0] taken from array in api/load_report
                    console.log(output);
                    $("#xreport").html(output);
                }
            } else {
                Result.error(o.error);
                console.log(o.error);
            }
        }, 'json');
    });
};

with this new calling function I'm able to retrieve data from api/load_report without getting stuck on e.preventDefault or even open a new tab, I console.log and the result show correctly in the console, but it doesn't show on the div somehow.

my template.js (if needed)

this.dodo = function(obj){
    var output ='';
    output +='<table border=1, width=100%, style="margin-left: 0%"';
    output += '
';
    output += '' + obj.user_id + '	';
    output += '' + obj.cust_name + '	';
    output += '' + obj.act_type + '	';
    output += '' + obj.act_detail + '	';
    output += '' + obj.date_added + '	';
    output += '' + obj.date_modified + '	';
    output += '' + obj.act_notes + '	';
    output += '
';
    output +='
';
    output += '
';
    return output;
};

Result (note, user_id = form.sales_name)
  result preview

A: You could alway do the following:

function myFunction() {
    alert("Hello! I am an alert box! in a function");
}
<form>

<input type="text" />
<input type="submit" value="submit" onclick="return myFunction();"/>

</form>

P.S. This question might be answered in this question already, add onclick function to a submit button

A: Try to prevent form to get submit by using preventDefault()
$("#report").submit(function(e){ //add param "e"
     e.preventDefault(); //to prevent form to submit
     //further code....
});

A: Ok just try
function mysubmit(){
     $.get('api/load_report', function(o){
        var output = '';
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }
        $("#xreport").html(output);
    }, 'json');
}

as your script and
<form id="report" class="form-horizontal" onsubmit="event.preventDefault(); mysubmit();" method="post" action="<?= site_url('api/load_report') ?>">

as your form

A: First off, I would advise against using onclick or onsubmit directly on the dom like so.
<form onsubmit="myFunction();"></form>

The biggest reason for me is that it negatively impacts readability and sometimes even future maintenance of the project . It is nice to keep html and javascript separate unless you are using a framework that provides templating features/functionality such as angularjs.
Another big one is that you can only have one in-line event present and it is easy to accidentally overwrite, which can lead to confusing bugs.
The reason it is going to a new tab is because of the .submit(). This will call your function, but then proceed with internal jQuery event handling which includes refreshing the page. There are two solutions I see most viable here.
1st Solution:
Add a event.preventDefault(); at the start of your function to stop jQuery from refreshing your page.
$("#report").submit(function(e) {
      e.preventDefault();
 });

2nd Solution (Likely better):
You are making an ajax call with $.get(...). You could add an event listener on a button (probably on the button used to submit the form) that fires your ajax call.  Here is an example that assumes the submit button has the id of loadData.
$("#loadData").click(function(){
   $.get('api/load_report', function(o){
      var output = '';
      for (var i = 0; i < o.length; i++){
          output += Template.dodo(o[i]);
      }
      $("#xreport").html(output);
  }, 'json');
}


text:
Q: Fetching an array of objects with binary files from Node I'm reading an array with text and image objects from my Node/MongoDB backend to my React frontend with the Fetch API.
Here's the structure of the array that needs to be read.
{
   _id: 616f9059791382150cf0f62a,
   title: 'stuff ',
   body: 'things!',
   ref: '537ac166131f94a4065e34508afmomf0.PNG',
   _createdBy: 61685a8e575fe41d48bb0fa2,
   created: 2021-10-20T03:43:21.605Z,
   __v: 0
 }
 {
   _id: 6170c39aba8eea4a982d6c1c,
   title: 'test',
   type: 'image',
   ref: '533dc166131f94a4065e34508afdadf1.PNG',
   _createdBy: 61685a8e575fe41d48bb0fa2,
   created: 2021-10-21T01:34:18.830Z,
   __v: 0
 }

Each ref is a reference to an image stored in GridFS that needs to be linked to the corresponding object.
What's the best way to do this? Should I .map through each object, and stream each object with its corresponding image one at a time to the frontend?
Should I upload the array first, then the stream a second array of images, then assign images to objects on the frontend?
Or maybe combine them in the backend, then stream it all as one giant array?
I'm new to binary data. Any guidance or suggested reading is appreciated!


text:
Q: Select all likes from tweet liked by users So, as you can see in the title, I am looking for how to find all the likes of tweet and then add a users who like to this query without losing the total result of likes.
This is my likes table.
SELECT COUNT(*)
from likes INNER JOIN tweets ON likes.id_tweet = tweets.id
GROUP BY likes.id_tweet;

+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| id       | int(11) | NO   | PRI | NULL    | auto_increment |
| id_user  | int(11) | NO   | MUL | NULL    |                |
| id_tweet | int(11) | NO   | MUL | NULL    |                |
+----------+---------+------+-----+---------+----------------+

When I run this query, I can get all the likes :
SELECT COUNT(*)
from likes INNER JOIN tweets ON likes.id_tweet = tweets.id
GROUP BY likes.id_tweet;

Like this:
+----------+
| COUNT(*) |
+----------+
|        1 |
|        4 |
|        1 |
|        1 |
|        2 |
|        1 |
|        1 |
|        1 |
|        1 |
|        2 |
|        1 |
|        1 |
|        3 |
|        1 |
|        1 |
|        1 |
|        1 |
|        1 |
|        1 |
|        1 |
|        3 |
|        2 |
|        1 |
|        1 |
|        2 |
|        1 |
|        3 |
|        1 |
|        1 |
|        1 |
|        3 |
|        3 |
|        2 |
+----------+

and I get all my likes but when i add  where likes.id_users = ...
I lost my all likes for just likes of one users likes, concretely i want to recover all the likes of tweets that a users like.

Like this

+-----------+----+----------+-----------+------------+----------------------------------------------------------------------------------------------------------------------------------------------+--------+---------------------+
| all likes | id | id_reply | id_poster | id_retweet | text                                                                                | id_img | tweet_date          |
+-----------+----+----------+-----------+------------+----------------------------------------------------------------------------------------------------------------------------------------------+--------+---------------------+
|         50 |  2 |     NULL |      1714 |       NULL | Mon premier tweet                                                                                |   NULL | 2019-01-23 14:25:24 |
|         43 | 35 |     NULL |      1752 |       NULL | Phasellus id sapien in sapien iaculis congue. Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl. Aenean lectus. P |   NULL | 2018-04-29 00:00:00 |
|         22 | 50 |     NULL |      1908 |       NULL | In congue. Etiam justo. Etiam pretium iaculis justo. In hac habitasse platea dictumst. Etiam faucibus cursus urna. Ut tellus.                |   NULL | 2018-05-23 00:00:00 |
+-----------+----+----------+-----------+------------+----------------------------------------------------------------------------------------------------------------------------------------------+--------+---------------------+

Thanks

A: Try this:
SELECT COUNT(*), GROUP_CONCAT(likes.[id_user])
from likes INNER JOIN tweets ON likes.id_tweet = tweets.id
GROUP BY likes.id_tweet;


text:
Q: Why does the stability of a nucleus depend on the binding energy $\textit{per nucleon}$ instead of the total binding energy? The larger the total binding energy of a nucleus, the greater the minimum energy that must be added to infinitely separate the constituent nucleons. Shouldn't the total binding energy, then, be used to determine the stability of a nucleus? I don't understand why the binding energy per nucleon is used instead.

A: Jon Custer is right, here is why.
The total binding energy is the sum of the energy in the attractive part due to the residual nuclear force between quarks in neighboring nucleons and the repulsive part due to the proton-proton electrostatic repulsion.
The attractive part is strictly local, acting to stick protons and neutrons together that are close enough to touch- it is a very short-ranged force. On the other hand, a single proton in the nucleus feels the repulsion of all the other protons in the nucleus, not just its nearest neighbors. Once the net attractive contribution becomes equal to the repulsive contribution, the binding energy per nucleon approaches zero and there's almost nothing left to make it energetically favorable for the nucleus to remain in one piece: give it just the right bump, and it flies apart.
This is why the binding energy per nucleon is so strong in helium and relatively much weaker in uranium.


text:
Q: I accidentally disabled a Windows 10 service, now I can't start processes as administrator I can't start sc, cmd as administrator, can't access services.msc.
Also some non-administrator applications are not starting.


text:
Q: UPDATE with INNER JOIN or MIN? I am trying to transfer some data between tables.  The 'NEW' table can have multiple entries of the data that was originally not meant to have multiple entries in the 'OLD' table.  I would like to take the data from the 'OLD' table and copy it over to the new table where the NEW.ID is the lowest where new.OtherID=old.OtherID, basically a MIN(ID) per group of OtherID's equal to each other.
'NEW' table
ID | OtherID | Data
1       1      NULL
2       1      NULL
3       2      NULL
4       3      NULL
5       3      NULL

'OLD'
OtherID | Data

1            data1
2            data2
3            data3
4            data4
5            data5

Desired Outcome on updated 'NEW' table:
ID | OtherID | Data

1       1       data1
2       1       NULL
3       2       data2
4       3       data3
5       3       NULL

etc
Thanks!

A: This is how you could use INNER JOIN with UPDATE in MySQL:
UPDATE NEW n
  INNER JOIN (
    SELECT
      OtherID,
      MIN(ID) AS ID
    FROM NEW
    GROUP BY OtherID
  ) m ON n.ID = m.ID
  INNER JOIN OLD o ON n.OtherID = o.OtherID
SET n.Data = o.Data

A: You can try:
UPDATE new
   SET Data = ( SELECT DATA FROM old WHERE otherID = new.otherID )
 WHERE NOT EXIST
       ( SELECT NULL FROM new AS new2
          WHERE new2.id < new.id
            AND new2.otherID = new.otherID )

Note that this is standard SQL92 and should work with any RDBMS.

A: This worked for me in PostgreSQL, though I may have gotten the quoting wrong for MySQL.
UPDATE newtable SET
 `Data` = oldtable.`Data`
FROM
 oldtable
WHERE
 newtable.`ID` IN (
  SELECT MIN(sub_newtable.`ID`)
  FROM newtable sub_newtable
  GROUP BY
   sub_newtable.`OtherID`
 )
 AND newtable.`OtherID` = oldtable.`OtherID`

A: You can use:
UPDATE `NEW`
LEFT JOIN `OLD`
    ON `NEW`.`OtherID` = `OLD`.`ID`
SET `NEW`.`Data` = `OLD`.`Data`

EDIT: I'm sorry, this will update all records that correspond to columns in OLD.


text:
Q: Does Oracle update columns when the data values are the same? If I have a column called NAME and it has a value of "CLARK" and I run an update statement
update table1 set name = 'CLARK';

Does Oracle actually update the column or does it ignore the update command since the values are the same?
I found this question (Oracle, how update statement works) and the first answer implies that an update occurs even if the values are equal.  I also tried it in SQL Developer and it ran but I don't know if an update truly occurred.
Thanks in advance.

A: Yes, Oracle does update the column even if it the same.
In a really simple example, this makes no difference.  But consider the following:-

*

*When a record is updated, a lock is obtained on that record for the updating session,

*When a record is updated, triggers on the table would fire

This aspects of the update show that the column is actually updated.
Of course, perhaps there are some optimisations when the value is the same, but these are not visible to you as a user of Oracle.

A: Yes, all row are updated and all triggers fired, even if the actual values doesn't change.


text:
Q: Updating Rails models through AJAX? Let's assume that I have a Rails app in which users can write blog posts. After the user starts typing, an AJAX function is called which commits a POST request and saves the blog post. What I'd like to do is be able to check if a blog post is already in the database, and then continuously save it through AJAX as the user types.
I'm using HTML5 contenteditable attribute for the title and content blog post input areas:

Here's the JavaScript to do what I want:
$(function(){
        if ($("#title-create-partial").length > 0) {
            setTimeout(autoSavePost, 6000);
        }
    });

    function autoSavePost(){
        $.ajax({
            type: "POST",
            url: "/submissions",
            dataType: "json",
            data: {title: $("#title-create-partial").text().serialize(), content: $("#content-create-partial").text().serialize()},
            success: function(){
                $("#success-indicate").fadeIn().delay(4000).fadeOut();
            }
        });
        setTimeout(autoSavePost, 6000);
    }

However, in my JS console I'm getting an error stating that the data I've given to .ajax doesn't have a serialize method. I'm not sure how to pass it correctly to AJAX.
Also, once I do send it through AJAX, I'm not sure how to update the :content on the database side. Here's the create controller that the AJAX url routes to:
    def create
    @submission = Submission.where(title: params[:title]).first_or_create(
        title: params[:title],
        content: params[:content],
        user_id: params[:user_id]
        )
    @submission.user = current_user
    if @submission.save
        redirect_to :action => :show, :id => @submission.id
    else
        redirect_to :action => :index
    end

end

How do I send the text from contenteditable divs, and then in the controller how do I update the content? I've heard about update_attributes, but I'm not sure how to use that.

A: This code here:
$("#title-create-partial").text()

returns a string.  Then you call a method named serialize() on a string.  There is no javascript method named serialize().  jQuery has a method named serialize(), but it must be called on a jQuery object.  A string is not a jQuery object.  And as far as I can tell, serialize() doesn't even work on non-form elements.  Here is how you would use serialize:
var str = $( "form" ).serialize();

Or,
var str = $( "#my_text_input, #my_select").serialize()

which will produce a string like this:
"text_input_name=hello&select_name=goodbye"

However, according to the jQuery docs, jQuery automatically serializes the key/value pairs you specify for data inside .ajax()--so you don't want to serialize them again.

How do I send the text from contenteditable divs, and then in the
  controller how do I update the content?

You need to pick an event to trigger your ajax call.  Probably the best bet would be to set a timeout to go off every 5 minutes, which calls your ajax function.
As far as updating the content in the database, you can query your database and see if the user has a post with the same title.  If the query comes back with 0 results, then create a new post with the content.  Otherwise, set the post's content to the new content.  Something like this:
id = params[:session][:id]
ajax_title = params[:title]
ajax_content = params[:content]

user = User.find id
posts = user.posts.where(title: ajax_title)

if posts.empty?
  post = user.posts.create(title: ajax_title, content: ajax_content)
else
  post[0].content = ajax_content
  post[0].save
end

That assumes you've done:
class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

A: This is rather a comment than an answer. I write it here because it is a bit long.
I have difficulty to understand your logic. It seems the server will create tons of posts on every hit.
Let's say you are going to write a post titled "Updating Rails models through AJAX".
When you type "U" in title input, the Ajax is triggered, the server received a title "U". There is no such post titled "U" in db, so controller create one.
Then you type "p". Again there is no such post, so new post "Up" created.
Now you have two posts, "U" and "Up". And more will be created once typing.
See the problem? Correct me if wrong.
Add: About Solution
I have not done such case before so can't provide practice but some ideas only.
Subjectively I don't think creating post by direct typing is a good idea, the reason as above. I would suggest:

*

*Basic: Create post on submit, either Ajax of normal request.

*Advanced: Add option to save as draft. And also add feature to see or load from draft(edit form). The post is same as normal post with extra column "draft" as true

*Even advanced: After typing lots of code, saying 100 characters in body, autosave it as a draft. This is similar to your code with the main difference at server-side draft setting.
You may also noticed, in Stackoverflow, if you write an answer but don't submit it, next time when you go back, the draft of answer is still in in the form. This is easier than your case, because an answer is always associated with a question and you are only allowed to post answers one by one, so the draft can be easily identified.
But blog post is different, it's the main model, no association, and you can create multiple drafts at same time. So you need to pay attention to draft loading.
Just some cents.

A: please only using text() when geting value title and content. And when using serialize() is more effective on getting data from form input. So change your code into below.
$(function(){
        if ($("#title-create-partial").length > 0) {
            setTimeout(autoSavePost, 6000);
        }
    });

function autoSavePost(){
    $.ajax({
        type: "POST",
        url: "/submissions",
        dataType: "json",
        data: {title: $("#title-create-partial").text();, content: $("#content-create-partial").text();},
        success: function(){
            $("#success-indicate").fadeIn().delay(4000).fadeOut();
        }
    });
    setTimeout(autoSavePost, 6000);
}


text:
Q: Link to Anchor under Fixed Header from Another Page I'm trying to link to an anchor on one page (Page 1) from another one (Page 2). Both pages have a fixed header. As such, I'm using the follow script on both pages:
$(document).ready(function(){
    $('.testlink').bind('click', function(e) {
        e.preventDefault();
        var sHref = this.href.split("#");
        var topDistance = $("#"+sHref[1]).position().top;
        var tds = topDistance - 146 ;
        $("html, body").animate({ scrollTop: tds }, 'slow');
        return false;
    });
});

Example link:
How the deductible works

Example anchor link:

This links to the anchor, then offsets it, so that the anchor isn't under the header.
When I link to an anchor from Page 1 to an anchor on Page 1, everything works fine. When I link to one on another page, the script doesn't work and anchor is underneath the header.
I tried recoding it like this:
$(document).ready(function(){
    $('.testlink').bind('click', function(e) {
        e.preventDefault();
        $(location).attr( 'href', $(this).attr('href') );
        var sHref = this.href.split("#");
        var topDistance = $("#"+sHref[1]).position().top;
        var tds = topDistance - 146 ;
        $("html, body").animate({ scrollTop: tds }, 'slow');
        return false;
    });
});

...but that didn't work. Perhaps I wrote what I wanted to do incorrectly. If so, I would appreciate some help.
BTW, as mentioned above, when click to an anchor from the link on the same page, the page doesn't refresh - it just goes to the anchor. I'd like for that to stay, if possible (meaning no refresh). If the link is coming from another page, yes, refresh/load the page.

A: try this
    function scrollToAnchor(anchor) {
            $("html, body").animate({ scrollTop: $(anchor).position().top - 146 }, 'slow');
    }

    $(document).ready(function() {
        $('.testlink').bind('click', function(e) {
            e.preventDefault();
            var sHref = this.href.split("#");
            scrollToAnchor("#"+sHref[1]);
            return false;
        });

        //now scroll to the anchor when loading page - this was missing
        scrollToAnchor(document.location.hash);
    });


text:
Q: GET Minuscules and capitals PhP I have an array with some words that if they match the word they receive from the GET they print a message, but sometimes it doesn't work because it doesn't match the capitals, is there any way to ignore the capitals and minicules? :( and sorry I'm very new to php, this php is for a command in twitch :)
<?php
> $so = $_GET["option"];
$default = 'Go check out $(touser) at twitch.tv/$(touser) and go show them some love ';
if(isset($so) && $so != ""){
   $prefix = "Go check out my great friend who is part of our crew and go show them some love in twitch.tv/";
  > $channel = array(
      "gusbars(example)" => $prefix."gusbars/",
      "vicent" => $prefix."viventtv/",
      "smoxx" => $prefix."smoxxao/",
      "tecno" => $prefix."tecnoteam/"
   );

   if(array_key_exists($so, $channel)){
    echo $channel[$so];
   }else if($so == "list"){
    foreach ($channel as $a_so => $value){
        echo $a_so." | ";
      }
   }else{
    echo $default;
   }
}else{
   echo $idefault;
}
?>

A: You could use PHP's strtolower() function to be sure the variable you are trying to match/compare is always a consistent case. E.g.

$so = strtolower($_GET["option"]);


text:
Q: Nodejs memory cache thread safety I have a Node service. The node service has a memory cache, it's an in-memory key-value store. The node service also running a periodic task runs every day which is rebuild cache (CPU intensive and cost a lot of time).  When rebuild cache task is running, Will it block other /get request? Is there any race condition here?
/get: get the cache data by key

setInterval(()=>{ rebuildCache() ; }, 3600)

async rebuildCache(filepath: string, key: string): Promise<void> {
  const obj = constructFromFile(filepath)
  //load json from filepath. do some cpu intensitive work. (build schema, reference, etc)

  cache[key] = obj
}

A:
Will it block other /get request?

It depends upon what rebuildCache() does and how it works.  If it's a synchronous operation (entirely CPU), then that will block the event loop and will block all request processing.

Is there any race condition here?

It depends upon how the code that uses the cache is written and what rebuildCache() does.  If any operations that uses the cache are asynchronous and they depend upon cache consistency from before it runs an asynchronous operation to after it finishes an asynchronous operation, then a rebuildCache() can occur in that window of time and you could indeed have a race condition.

The devil is in the details of your actual implementation for both code using the cache and the function that rebuilds the cache so we can only offer hypothetical answers without seeing the actual code.

FYI, this code in your question:
setInterval(rebuildCache())

only calls rebuildCache() once.  To actually call it on any interval, you would need something like this:
setInterval(rebuildCache, t);

Note, you pass a function reference (without the parens) and you pass a time for the timer interval.


text:
Q: Exposing TFS buildnumber via an endpoint of .NET Core WebAPI In a solution I have a .NET Core 2.2 WebAPI project (among other projects).
The solution has a corresponding build pipeline set up in TFS. Every TFS build has a build number, for example "20190615.15". What I would like to do is to expose this build number via an Web-API endpoint in order to fulfill maintaining and tracing purposes.
As a pre-solution I have managed to set the AssemblyInformationalVersion attribute from the build pipeline, and with the following controller I can easily retrieve the desired build-number:
[Route("api/[controller]")]
[ApiController]
public class VersionController : ControllerBase
{
    [HttpPut(Name = "version")]
    public Task<ApplicationVersion> Version()
    {
        return Task.FromResult(new ApplicationVersion
        {
            Version = ReadVersionFromAssemblyInfo()
        });
    }

    private string ReadVersionFromAssemblyInfo()
    {
        return Assembly.GetEntryAssembly()
            .GetCustomAttribute<AssemblyInformationalVersionAttribute>()
            .InformationalVersion;
    }

    public class ApplicationVersion
    {
        public string Version { get; set; }
    }
}

What I have done is pretty easy:
First I introduced a new ARG called "VERSION_NUMBER" in the Dockerfile of the Web-API and set the InformationalVersion at the last publish step:
FROM microsoft/dotnet:2.2-sdk AS build
ARG VERSION_NUMBER
WORKDIR /src
COPY SomeAPI/SomeAPI.csproj SomeAPI/
RUN dotnet restore SomeAPI/SomeAPI.csproj
COPY . .
WORKDIR /src/SomeAPI
RUN dotnet publish SomeAPI.csproj -c Release -o /app -p:InformationalVersion=$VERSION_NUMBER

Then in the docker-compose.yml file I set the same arg:
services:
  someapi:
    image: someApi:${TAG:-latest}
    build:
      context: .
      dockerfile: SomeAPI/Dockerfile
      args:
        VERSION_NUMBER: ${VERSION_NUMBER}

And finally in the Docker-Compose task of TFS build I set the above-mentioned argument:

It works like charm, and if I access my endpoint https://somedomain.com/api/version then I get a json back with the desired build-number.
The issue is that in my solution I reuse/leverage the AssemblyInformationalVersion attribute, but I would like to have this attribute set with the proper version number (f.e.: 1.0.1). So eventually the https://somdomain.com/api/version endpoint would return the a .json like:
{
    "Version": "1.0.1",
    "BuildNumber": "20190615.15"
}

What is the best way to expose the build-number (coming from TFS build) via a Web-API endpoint? Is it possible to set a custom property (xml tag) in the .csproj file, therefore I can use the AssemblyInformationalVersion for the intended purpose? Thanks for help!

A: I have successfully figured how to solve my issue. There are two good approaches to do it:
First approach: Introduce a custom .csproj property which can be accessed in run-time. First create a property class:
namespace MyNamespace
{
    /// <summary>
    /// A run-time-accessible property specified in .csproj file in order to store the build-number of the CI build-pipeline.
    /// </summary>
    [AttributeUsage(AttributeTargets.Assembly)]
    public sealed class BuildNumberAttribute : Attribute
    {
        public BuildNumberAttribute(string buildNumber)
        {
            BuildNumber = buildNumber;
        }

        public string BuildNumber { get; }
    }
}

Add the following item-group to .csproj file in order to make the property accessible:
  <ItemGroup>
    <AssemblyAttribute Include="MyNamespace.BuildNumberAttribute">
      <_Parameter1>"$(BuildNumber)"</_Parameter1>
    </AssemblyAttribute>
  </ItemGroup>

Finally in the dockerfile, pass the build argument
RUN dotnet publish SomeAPI.csproj -c Release -o /app -p:BuildNumber=$VERSION_NUMBER

Note that VERSION_NUMBER is set to $(Build.BuildNumber) in docker-compose task of TFS build pipeline.
To access this newly added property, do the following:
private string ReadBuildNumber()
{
    return Assembly.GetEntryAssembly()
        .GetCustomAttribute<BuildNumberAttribute>()
        .BuildNumber.Trim('"');
}

The second approach:
Using "Replaced tokens" task in TFS build pipeline. With this you can set a template in appsettings.json, and the template can be replaced by task. For detailed info, check this stackoverflow question


text:
Q: Set Initial Value for Required attribute Using Data Annotations to specify validation rules for a model, I want to set the initial value for the Required attribute so that it fails if it's equal to that value. This was an option in webforms using the validation controls, but I don't see similar using Data Annotations.
If there's no built in way to do it, I'll probably just build a new Required Attribute that inherits from it.
UPDATE: Based on comments/answers, I definitely know this is not an ideal situation and I should be using the placeholder attribute of HTML5. However, I need to do this for an existing form that already had shadow text being added in a non-ideal way.

A: I wouldn't handle that in MVC, I'd work on getting the shadow text to not post with the form.  HTML 5 has "placeholder".  I'd use that or implement something like it: http://davidwalsh.name/html5-placeholder
Check this out for a simple quick placeholder approach that degrades properly in non-html5 browsers:
JQuery placeholder HTML5 simulator
Just add the placeholder attribute to your textboxes and use that javascript to make it work regardless of HTML version.

A: I dont know there is any built in annotations available or not for notequalto, but you can create your own NotEqualAttribute, inheritValidationAttribute (for validation on server) and implement IClientValidatable (to produce data-something tags, to do validation on client).
Also you have to write code in jquery for client validation.
refer this
How does DataAnnotations really work in MVC?

A: I ended up creating a new attribute that inherits from the RequiredAttribute:
public class RequiredWithInitialValueAttribute : RequiredAttribute
{
    public string InitialValue { get; set; }

    public RequiredWithInitialValueAttribute(string initialValue)
    {
        InitialValue = initialValue;
    }

    public override bool IsValid(object value)
    {
        if (value.ToString().SafeEquals(InitialValue)) return false;
        return base.IsValid(value);
    }
}

Still curious if there's a better way since this seems like something that should be built in, but for now I'm using this.

A: Don't do this.
Placeholder text is not a value. It should not be posted. It should not be validated.
This contradicts common sense, is a crime against humanity and introduces several problems.

*

*What if you need an optional number field with a placeholder text?
(Validation will fail because placeholder is a string.)

*What happens when your application is localized?
(Validation will fail until someone finds this attribute value is being compared with.)

*Validation will have to be server-only and there will be no way to "grey out" placeholder text.
(Unless you specify the placeholder once more in the script file and monitor change events.)

*You will have to specify this "placeholder" at least twice, and in different places.
(If I got you right, it's once in the attribute and once in the constructor.)

*There will be no way for placeholder to actually be the value.
(This can happen, if not for this field, then for any other that uses the attribute.)

*This will freak the hell out of the future maintainers.
(Do you even doubt that?)
Instead,
Use placeholder attribute and degrading solutions as suggested by Milimetric.
As an alternative for restless DYI-ers, place the label in a div and position it over the input field with your own JavaScript. This is known as "overlabel" technique and there are plenty examples on the web. (But you'll have to test your solution thoroughly on the browsers you want to support.) You may even roll out your own custom HTML helper:
@Html.PlaceholderFor(m => m.SomeField)

(I completely made it up, it's up to you to implement it.)


text:
Q: Determining whether a subspace of the plane (with Euclidean topology) is locally compact There is a theorem that states that a Hausdorff space is locally compact if and only if every point has a compact neighborhood. Checking whether every point has such a neighborhood can be tedious and time-consuming for more complex spaces, so is it possible to determine whether a subspace of a plane is locally compact by a simpler means; e. g. are there any sufficient conditions for local compactness in such spaces that might be simpler to prove than using the above theorem, using only general topology? I appreciate your help.

A: Your question is bit vague. In general there is no way to avoid checking whether every point has a compact neighborhood, even it the space is a subset of a (Euclidean) plane. There are some general theorems that might help you, for example the following:
A subspace $X$ of a locally compact Hausdorff space $L$ is locally compact if and only if it can be written as $X = A \cap U$, where $A$ is closed and $U$ is open in $L$. This applies to subsets $X$ of any finite-dimensional Euclidean space.
Moreover, your space $X$ must be defined somehow, and in some cases it is fairly obvious from the definition that it is locally compact. For example, if you have a continuous map $f : L \to Y$ defined on a locally compact Hausdorff space $L$, then all preimages of subsets $M \subset Y$ having the form $M = B \cap V$,  where $B$ is closed and $V$ is open in $Y$, are locally compact.

A: Maybe this is not quite what you were expecting, but here's an interesting way to get a large class of locally compact subspaces of $\mathbb{R}^2$.
The Heine-Borel theorem states that in $\mathbb{R}^n$ any subset $A \subseteq \mathbb{R}^n$ is compact if and only if it is closed and bounded.
Now take any closed and bounded subset $C$ of $\mathbb{R}^n$ , by the Heine-Borel theorem $C$ is compact and since any compact topological space is locally compact it follows that $C$ is locally compact.
So any closed and bounded subset of $\mathbb{R}^n$ is locally compact.
In the case when $n=2$, we can easily generate a large number of examples of locally compact spaces from our above deductions.
Examples:

*

*The circle $\mathbb{S}^1$ is compact, and thus locally compact.

*Any finite set of points is locally compact.

*Any finite union of closed balls are closed, and thus locally compact.

*$[a,b] \times [c,d]$ is closed and bounded and thus locally compact for any $a,b,c,d \in \mathbb{R}$


text:
Q: Can I inject external script files with executeScript() in MV3? Is the code below fine in MV3? I was wondering if it could be published on Chrome Web Store.
  chrome.scripting.executeScript({
    target: { tabId: tabId },
    func: () => {
      const tag = document.createElement('script')
      tag.src = 'https://my-server/script.js'
      document.head.appendChild(tag)
    },
    args: [],
    world: 'MAIN'
  })

The code was able to be uploaded as unpackaged extension MV3 and executed.
I referred to the information.

extension developers can use the scripting.executeScript() method to either inject a static file or a function. https://developer.chrome.com/docs/extensions/mv3/mv3-migration/#executing-arbitrary-strings


text:
Q: Python & MySQL - Numeric type limited? I'm trying to use MySQL to save some time-series boolean data, and then make a decision according to the saved data.
I am required to save the last 144 samples, and then check if more than X% are non-zero.
I try to use a Numeric field with a scale of 44. At some point the data is truncated to 9999999999.
That's how I created the column:
op.add_column('object', sa.Column('data_history',        sa.Numeric(scale=44), nullable=False, default=0))

Here's my code that handles the calculation:
happens_now = data < DATA_THRESHOLD
mask = 0
for i in xrange(144):
    mask <<= 1
    mask |= 1
safe_logging.info('History: {} LongHistory: {}'.format(my_object.data_history, long(my_object.data_history)))
my_object.data_history *= 2
safe_logging.info('History: {} LongHistory: {}'.format(my_object.data_history, long(my_object.data_history)))
my_object.data_history += happens_now
safe_logging.info('History: {} LongHistory: {}'.format(my_object.data_history, long(my_object.data_history)))
history_to_consider = long(my_object.data_history) & mask
safe_logging.info('Mask: {} Data: {} Happens now: {} History: {}'.format(mask, data, happens_now, history_to_consider))
pop_count = self._PopCount(history_to_consider)
if (not my_object.is_total) and pop_count/144 > PERCENTAGE_THERSHOLD:
    my_object.is_total = True

Here's my log output for two consecutive data insertions:
INFO:  History: 8589934591 LongHistory: 8589934591
INFO:  History: 17179869182 LongHistory: 17179869182
INFO:  History: 17179869183 LongHistory: 17179869183
INFO:  Mask: 22300745198530623141535718272648361505980415 Data: 10 Happens now: True History: 17179869183

INFO:  History: 9999999999 LongHistory: 9999999999
INFO:  History: 19999999998 LongHistory: 19999999998
INFO:  History: 19999999999 LongHistory: 19999999999
INFO:  Mask: 22300745198530623141535718272648361505980415 Data: 10 Happens now: True History: 19999999999

I tried to find a limitation in MySQL docs and couldn't. Python seems to handle well long numbers (see mask).
Is it a SQLAlchemy limitation? Some MySQL limitation I missed?

A: So, as @Shadow pointed out, I mixed up scale and precision.
Scale is the number of digits after the decimal point, precision is total number of digits.
In addition, max precision is 30, so I'll have to concat two BigInts or so, to have a bigger number.


text:
Q: java.io.File exists() sometimes returns incorrect result I came across one issue in java file.exists() gives incorrect result sometimes. I observed same behavior in our application when file actually exists till it returns false. I observed this behavior in GFS2 mounting directory.
Please suggest, if anyone knows alternative for this or to solve this issue advise me as earliest. I am using java 1.7.

A: In the case where you find file.exists() returns false
try using file.getAbsoluteFile().exists(), this will return true.

The getAbsolutePath returns the absolute form of this abstract pathname.This is Equivalent to new File(this.getAbsolutePath()).

This question has answers here but no accepted answer.
This appears to be a bug

An ugly work-around is using getAbsoluteFile() on all File objects that came
  from "unknown" sources


text:
Q: How can I change the state of App.js from a form treatment? My App.js contains my Router and my routes. I have a route to my Home component and a route to my LoginForm component.
In my LoginForm I use axios (call to an API) for the authentication. I store the user in the localstorage and redirect to my Home component.
In my App.js I have a boolean isLoggedIn in my state. In the componentDidount I check if there is something in the localstorage to update my state. I cannot find a way to change the state without refreshing the page.
What should I do to make the update of the state in App.js from my LoginForm component ?
App.js
class App extends Component {
    componentDidMount() {
        let state = localStorage["appState"];
        if (state) {
            let AppState = JSON.parse(state);
            this.setState({ isLoggedIn: AppState.isLoggedIn,user: AppState.user });
        }
    }
    render() {
        return (
            <Router>
                <div className="App">
                    <Route path="/" exact component={BatteryUp} />
                    <Route path="/login" exact component={LoginForm} />
                </div>
            </Router>
        );
    }
}

LoginForm -> axios then & render
.then(response => {
    let appState = { isLoggedIn: true, user: userData };
    localStorage.setItem("appState",JSON.stringify(appState));
    this.setState({ redirect: true });
}

render() {
    if (this.state.redirect) {
        return <Redirect to="/" />;
    }
    return (
        <form className="container" onSubmit={this.handleFormSubmit}>
        </form>
    );
}

A: This usually what redux is used for.  You would update the state in redux, and then the update to the reducer would be propagated to the App.  Another solution would be to have all of this logic contained within the APP component.  Which is not going to make things very modular.


text:
Q: google smart home limit on number of devices returned from sync When Google issues a Sync to discover our SmartHome devices, we can some times return a high number (could be a 1000). It appears that if we return 60 devices or more they are not discovered. If return 50, they are discovered. Is there a known limit on the number of devices we can return?
-Rich


text:
Q: How can I fix this "syntax error, unexpected '=' " problem? I was working on my homework to design the air conditioner by Verilog coding on modelsim, and it keeps failing to compile with a syntax error.
I'm using ModelSim PE Student Edition 10.4a.
module air (rst, power, cooling, dehumidification, ventilation, cl_switch, cl_button, clk, cooler, outdoor_fan, dehumidifier, ventilator, cooling_level);

input rst, power, cooling, dehumidification, ventilation, cl_switch, cl_button, clk;
output reg cooler, outdoor_fan, dehumidifier, ventilator;
output reg [2:0] cooling_level;

parameter OFF = 1'd0;
          ON = 1'd1;

And here's the error message.

** Error: (vlog-13069) C:/Modeltech_pe_edu_10.4a/examples/air.v(8): near "=": syntax error, unexpected '='.
** Error: C:/Modeltech_pe_edu_10.4a/examples/air.v(8): (vlog-13205) Syntax error found in the scope following 'ON'. Is there a missing
  '::'?

air.v(8) is this
ON = 1'd1;

part.  I couldn't figure out what's wrong with my code.

A: If you define more then one parameter value, you should separate them with commas:
parameter OFF = 1'd0,
          ON = 1'd1;


text:
Q: What does getint (int *) mean? getint (int *);

I am not really sure what does getint (int *) mean? Can someone explain this?

A: This is a function prototype declaring the function getint(). The function takes as pointer to an int as a parameter.
When prototyping a function it is not necessary to specify the parameters' names.
The prototype is missing a return type, which for C then defaults to int. Omiting a return type however is violating the recent C standard, so code doing so could be considered invalid.
An equivalent to
getint(int *);

though would be
int getint(int * pi);

A: TL;DR getint (int *); is a forward declaration for a function, in a very bad programming style. Without any explicit return type, it will default to int.
The recommended way to write is is to specify the return type explicitly, like

*

*if int, like
int getint(int *);  //yes, omitting the identifier name is correct, see note below

or,
int getint(int * outVar);    //we can have the name, if we want.

*if void, like
void getint(int *);

or,
void getint(int * outVar);

or any return type you want.

NOTE:
Just for further reference, from C11, chapter §6.7.6.3, Function declarators, (emphasis mine)

If, in the declaration 'T D1', D1 has the form
D( parameter-type-list )

...
A parameter type list specifies the types of, and may declare identifiers for, the parameters of the function.

So, the identifier name is optional.

A: The code is not valid C. If it compiles, consider upgrading to a compiler which is not older than 15 years.
History lesson:
In older, obsolete versions of the C standard you were allowed to omit the return type when writing a function declaration, in which case getint(int *); would mean the same thing as int getint(int *);, because if you specified no return type it would default to int. It was however bad practice to do so even back in 1990.


text:
Q: Difficulty in getting Tensorflow to work When I enter the following code in the Python interpreter;
import tensorflow as tf

I get the following error:
C:\Users\Rahul\AppData\Local\Programs\Python\Python35\python.exe
"D:/Programs/Python programs/tensorflow_hw/tf_hw.py"

Traceback (most recent call last):

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-
packages\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in
swig_import_helper
return importlib.import_module(mname)

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)

File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 906, in create_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in <module>
_pywrap_tensorflow_internal = swig_import_helper()

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 16, in swig_import_helper
return importlib.import_module('_pywrap_tensorflow_internal')

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)

ImportError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "D:/Programs/Python programs/tensorflow_hw/tf_hw.py", line 1, in <module>
import tensorflow as tf

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
raise ImportError(msg)

ImportError: Traceback (most recent call last):

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in swig_import_helper
return importlib.import_module(mname)

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)

File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 906, in create_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed

ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in <module>
_pywrap_tensorflow_internal = swig_import_helper()

 File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 16, in swig_import_helper
return importlib.import_module('_pywrap_tensorflow_internal')

File "C:\Users\Rahul\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)

ImportError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems
for some common reasons and solutions.

Include the entire stack trace
above this error message when asking for help.

Process finished with exit code 1

I've tried Python 3.6.2(both 32-bit and 64-bit) and now i'm running Python 3.5.2(64-bit). I also have the required "dll" file install from the Microsoft Visual C++ 2015 redistributable software.
My specs:

*

*Windows 7 Ultimate(64-bit) ; Service Pack 1

*Intel Pentium 2020M processor

*Intel HD Graphics

*Python 3.5.2(64-bit)

*4GB RAM

I'm unable to solve the problem. Any form of help is appreciated.


text:
Q: (F#, mono for OS X) Errors is happened in visual studio code but send file to fsi successfully (fsi:send file) I have got errors with the following codes in visual studio code. However, I am able to send the file with command (fsi:send file) and it is executed successfully. It seems I didn't setup the VSC with Ionide properly.
Please feel free to comment.
#load "packages/MathNet.Numerics.FSharp.3.14.0-beta01/MathNet.Numerics.fsx"

open MathNet.Numerics

SpecialFunctions.Gamma(0.5) // Unexpected identifier in implementation file

open MathNet.Numerics.LinearAlgebra
let m : Matrix<float> = DenseMatrix.randomStandard 50 50
(m * m.Transpose()).Determinant()

Syntax check for mistakes and errors in vscode, but the code can be executed in fsi

*

*This directive may only be used in F# script files (extensions .fsx or .fsscript). Either remove the directive, move this code to a script file or delimit the directive with '#if INTERACTIVE'/'#endif'

*The namespace or module 'MathNet' is not defined.

*Unexpected identifier in implementation file

A: The first error, "This directive may only be used in F# script files (extensions .fsx or .fsscript)", is telling you how to solve it. You haven't told us the filename of your F# file that you're getting errors in, but I bet it ends with .fs, right? The .fs extension is intended for files that are part of a larger project. A good rule of thumb is that if you have any .fs files, you need a project file (currently that's going to be in .fsproj format, which is an ugly XML file, but VS Code can help you create it).
If you want to use the #load directive, it must be in an F# script file, which means a file with an .fsx extension. (The .fsscript extension is also allowed, but I never see anyone using it in practice. The .fsx extension is the de facto standard).
Simply rename your .fs file to .fsx and that should solve error #1. Then errors #2 and #3 should go away on their own -- they are happening because the F# compiler isn't loading the MathNet namespace, which is because it's ignoring the #load directive in a .fs file. Once the #load directive is processed, then the MathNet.Numerics.fsx file should be loaded, and that file in turn loads all the namespaces needed.
So this was simply because you saved the file as a .fs file when you needed .fsx.


text:
Q: Changing size for inline math and for math environments separately I am writing my thesis in the memoir class, and had to change the general font size for the document to 12pt. Because I use a lot of align environments with long formulas, I changed the size of these via
\DeclareMathSizes{12}{10}{8}{7}

to 10pt with even smaller (script)script sizes.
The problem is, that this not only changes the setup in explicit math environments, but also for expressions like $a$ that are used inline in the text.
My question is therefore: Is it possible to access the sizes in math environments and for inline math separately? Since I practically only use the align environment, I thought about changing things there specifically, but I would prefer a solution that either
a) Changes explicitly only the settings in (all) math environments, but not inline, or
b) Changes the inline math size back, after it is set to 10pt with the command shown above.
Since the document is quite large, manually setting the size for every inline math command is sadly not practical.
Thank you in advance, audiophiel
EDIT: I adopted some techniques shown in Altering fontsize in equations globally, however I would still be thankful for a "cleaner" approach.


text:
Q: Ubuntu can't login after set LD_LIBRARY_PATH for CUDA I'm having a problem with my configuration of LD_LIBRARY_PATH environment variable for UBUNTU.
My system configuration is the following: UBUNTU 17.10 CUDA 8.0 (required by Tensorflow) NVIDIA DRIVER 387.26
My current LD_LIBRARY_PATH is set as follow in the .profile file: export LD_LIBRARY_PATH="/usr/lib/nvidia-387:/usr/local/cuda/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
I had to include also /usr/lib/nvidia-387 because of this
I also had to set my primary graphic controller to "INTEL" because I wanted my GPU free from any other graphic process (basically I run sudo prime-select intel)
However when /usr/lib/nvidia-387 is set I can't login to my profile anymore: after password input I just get a black screen for several seconds, and I eventually return to the login screen.
I also attach my current XORG conf (copied and pasted from other similar topic).
Section "ServerLayout"
  Identifier "layout"
  Screen 0 "nvidia"
  Inactive "intel"
EndSection

Section "Device"
  Identifier "intel"
  Driver "modesetting"
  BusID "PCI:0@0:2:0"
  Option "AccelMethod" "None"
EndSection

Section "Screen"
   Identifier "intel"
   Device "intel"
EndSection

Section "Device"
   Identifier "nvidia"
   Driver "nvidia"
   BusID "PCI:1@0:0:0"
   Option "ConstrainCursor" "off"
EndSection

Section "Screen"
   Identifier "nvidia"
   Device "nvidia"
   Option "AllowEmptyInitialConfiguration" "on"
   Option "IgnoreDisplayDevices" "CRT"
EndSection

Any idea how to solve? It's important that I keep the LD_LIBRARY_PATH as is.
Thank you for your help.

A: I didn't solve the problem. But I have a workaround for you.
1. edit /etc/default/grub
Modify GRUB_CMDLINE_LINUX_DEFAULT to
GRUB_CMDLINE_LINUX_DEFAULT='pcie_port_pm=off acpi_backlight=none acpi_osi=Linux acpi_osi=! acpi_osi="Windows 2009"'

This step is to prevent blank screen after logging in.
2. move nvidia library directories to /etc/ld.so.conf.d/nvidia.conf
The content of nvidia.conf is
/usr/lib/nvidia-390
/usr/lib32/nvidia-390

These directories depends on driver version on your computer.
3. create /etc/init.d/nvidia
To disable and enable nvidia runtime libraries.
#!/bin/sh
### BEGIN INIT INFO
# Provides:          nvidia
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     5
# Default-Stop:      0 6
# Short-Description: load/unload nvidia library
# Description:       load/unload nvidia library
### END INIT INFO

PRIME=$(prime-select query)
if [ "$PRIME" = "nvidia" ]; then
    exit 0
fi

case "$1" in
  start)
    sleep 10
    cd /etc/ld.so.conf.d
    mv nvidia.conf.bak nvidia.conf
    ldconfig
    nvidia-smi
    ;;
  stop)
    cd /etc/ld.so.conf.d
    mv nvidia.conf nvidia.conf.bak
    ldconfig
esac

4. execute update-rc.d nvidia defaults
You should find SXXnvidia in /etc/rc5.d/ and KXXnvidia in /etc/rc6.d/, /etc/rc0.d/.
Try to execute /etc/init.d/nvidia stop and nvidia-smi, you should see error messages of libraries not found.
Try to execute /etc/init.d/nvidia start, then nvidia-smi is fine again.
If everything is OK, you can reboot now. You are expected to login to desktop.
5. If anything goes wrong
The most possible problem is nvidia script not executed. If it happens, you can press Ctrl+Alt+F1 to tty mode, execute /etc/init.d/nvidia stop; reboot. Then you can go back to unity desktop to debug.
6. known side-effect
When use intel as prime GPU, unity-control-center(system settings) will be failed to start.
GLib-CRITICAL **: g_strsplit: assertion `string != NULL' failed.

Note: my system spec
# uname -r
4.13.0-32-generic
# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.3 LTS
Release:    16.04
Codename:   xenial
# dpkg -l | grep cuda
ii  cuda-9-0                                    9.0.176-1                                    amd64        CUDA 9.0 meta-package
ii  cuda-command-line-tools-9-0                 9.0.176-1                                    amd64        CUDA command-line tools
ii  cuda-core-9-0                               9.0.176-1                                    amd64        CUDA core tools
ii  cuda-cublas-9-0                             9.0.176.1-1                                  amd64        CUBLAS native runtime libraries
ii  cuda-cublas-dev-9-0                         9.0.176.1-1                                  amd64        CUBLAS native dev links, headers
ii  cuda-cudart-9-0                             9.0.176-1                                    amd64        CUDA Runtime native Libraries
ii  cuda-cudart-dev-9-0                         9.0.176-1                                    amd64        CUDA Runtime native dev links, headers
ii  cuda-cufft-9-0                              9.0.176-1                                    amd64        CUFFT native runtime libraries
ii  cuda-cufft-dev-9-0                          9.0.176-1                                    amd64        CUFFT native dev links, headers
ii  cuda-curand-9-0                             9.0.176-1                                    amd64        CURAND native runtime libraries
ii  cuda-curand-dev-9-0                         9.0.176-1                                    amd64        CURAND native dev links, headers
ii  cuda-cusolver-9-0                           9.0.176-1                                    amd64        CUDA solver native runtime libraries
ii  cuda-cusolver-dev-9-0                       9.0.176-1                                    amd64        CUDA solver native dev links, headers
ii  cuda-cusparse-9-0                           9.0.176-1                                    amd64        CUSPARSE native runtime libraries
ii  cuda-cusparse-dev-9-0                       9.0.176-1                                    amd64        CUSPARSE native dev links, headers
ii  cuda-demo-suite-9-0                         9.0.176-1                                    amd64        Demo suite for CUDA
ii  cuda-documentation-9-0                      9.0.176-1                                    amd64        CUDA documentation
ii  cuda-driver-dev-9-0                         9.0.176-1                                    amd64        CUDA Driver native dev stub library
ii  cuda-drivers                                390.12-1                                     amd64        CUDA Driver meta-package
ii  cuda-libraries-9-0                          9.0.176-1                                    amd64        CUDA Libraries 9.0 meta-package
ii  cuda-libraries-dev-9-0                      9.0.176-1                                    amd64        CUDA Libraries 9.0 development meta-package
ii  cuda-license-9-0                            9.0.176-1                                    amd64        CUDA licenses
ii  cuda-misc-headers-9-0                       9.0.176-1                                    amd64        CUDA miscellaneous headers
ii  cuda-npp-9-0                                9.0.176-1                                    amd64        NPP native runtime libraries
ii  cuda-npp-dev-9-0                            9.0.176-1                                    amd64        NPP native dev links, headers
ii  cuda-nvgraph-9-0                            9.0.176-1                                    amd64        NVGRAPH native runtime libraries
ii  cuda-nvgraph-dev-9-0                        9.0.176-1                                    amd64        NVGRAPH native dev links, headers
ii  cuda-nvml-dev-9-0                           9.0.176-1                                    amd64        NVML native dev links, headers
ii  cuda-nvrtc-9-0                              9.0.176-1                                    amd64        NVRTC native runtime libraries
ii  cuda-nvrtc-dev-9-0                          9.0.176-1                                    amd64        NVRTC native dev links, headers
ii  cuda-repo-ubuntu1604                        9.1.85-1                                     amd64        cuda repository configuration files
ii  cuda-runtime-9-0                            9.0.176-1                                    amd64        CUDA Runtime 9.0 meta-package
ii  cuda-samples-9-0                            9.0.176-1                                    amd64        CUDA example applications
ii  cuda-toolkit-9-0                            9.0.176-1                                    amd64        CUDA Toolkit 9.0 meta-package
ii  cuda-visual-tools-9-0                       9.0.176-1                                    amd64        CUDA visual tools
ii  libcuda1-390                                390.12-0ubuntu1                              amd64        NVIDIA CUDA runtime library
ii  libcudnn7                                   7.0.5.15-1+cuda9.0                           amd64        cuDNN runtime libraries
ii  libcudnn7-dev                               7.0.5.15-1+cuda9.0                           amd64        cuDNN development libraries and headers
# dpkg -l | grep nvidia
ii  nvidia-390                                  390.12-0ubuntu1                              amd64        NVIDIA binary driver - version 390.12
ii  nvidia-390-dev                              390.12-0ubuntu1                              amd64        NVIDIA binary Xorg driver development files
ii  nvidia-modprobe                             390.12-0ubuntu1                              amd64        Load the NVIDIA kernel driver and create device files
ii  nvidia-opencl-icd-390                       390.12-0ubuntu1                              amd64        NVIDIA OpenCL ICD
ii  nvidia-prime                                0.8.2                                        amd64        Tools to enable NVIDIA's Prime
ii  nvidia-settings                             390.12-0ubuntu1                              amd64        Tool for configuring the NVIDIA graphics driver


text:
Q: Error starting Guile with `readline` support I'm trying to configure Guile to use readline.
Here's my ~/.guile:
(use-modules (ice-9 readline))

(there was more, this one line is sufficient to have this failure)
Here's a log of my interaction:
agam@ssdnodes-61de65ea00d0b:~$ guile
guile: warning: failed to install locale
Backtrace:
In ice-9/boot-9.scm:
  1752:10 12 (with-exception-handler _ _ #:unwind? _ # _)
In unknown file:
          11 (apply-smob/0 #<thunk 7fb7984660c0>)
In ice-9/boot-9.scm:
    724:2 10 (call-with-prompt ("prompt") #<procedure 7fb796fc2e80 ?> ?)
In ice-9/eval.scm:
    619:8  9 (_ #(#(#<directory (guile-user) 7fb79846cc80>)))
In unknown file:
           8 (primitive-load "/home/agam/.guile")
In ice-9/eval.scm:
   721:20  7 (primitive-eval (use-modules (ice-9 readline)))
In ice-9/psyntax.scm:
  1230:36  6 (expand-top-sequence ((use-modules (ice-9 readline))) _ ?)
  1222:19  5 (parse _ (("placeholder" placeholder)) ((top) #(# # ?)) ?)
   259:10  4 (parse _ (("placeholder" placeholder)) (()) _ c&e (eval) ?)
In ice-9/boot-9.scm:
  3927:20  3 (process-use-modules _)
   222:17  2 (map1 (((ice-9 readline))))
  3928:31  1 (_ ((ice-9 readline)))
   3329:6  0 (resolve-interface (ice-9 readline) #:select _ #:hide _ ?)

ice-9/boot-9.scm:3329:6: In procedure resolve-interface:
no code for module (ice-9 readline)

If it helps, I'm doing this within Guile installed via guix install guile. I have installed glibc-locales, and GUIX_LOCPATH is set to "$HOME/.guix-profile/lib/locale"

A: Turns out the locale ... warning was a red herring, I was missing the readline package.
I needed to

*

*guix install guile-readline, followed by

*. "$GUIX_PROFILE/etc/profile"
After that, guile starts up fine.


text:
Q: Can't get my head around implementing an Undo/Redo functionality, should I use a Stack? I'm getting kind of confused right now, having one of those days I guess.
I need to implement an Undo and Redo functionality for a form. For simplicities sake, let's say that I only save the control which was modified and the value it had when it left Focus.
How do I save this information in a way that lets me go back or forth in the 'timeline'.
I thought about using a Stack, but while I was testing my little demo, I had a mild aneurysm and here I am.
Code needed, not really but would help. I'm more interested in the algorithm I'd need to implement. Any suggestions?

A: A stack is perfect if you push a "change" onto it, and when undo pop a "change" from it.  You then push that popped change into another stack representing redo.  At some point in the future, hopefully on save, you clear both stacks.
It's not actually as simple as that, as you need to record the type of change, understand the old and new values etc.  So when you pop from the undo stack, the thing you pop must describe what the prior value was and what control it was set to.
Inverse for the redo stack, it needs to understand what the new value was and where it went.  But yes, the idea of two stacks is a good start for a homebrew undo-redo.
A good example of a business object based undo is CSLA.NET, which has UndoableBase:
http://www.lhotka.net/cslanet/
http://www.koders.com/csharp/fidCF6AB2CF035B830FF6E40AA22C8AE7B135BE1FC0.aspx?s=serializationinfo
However this records a snapshot of an object's state, so it would be more advanced that your form-based concept.  However, CSLA.NET offers full data binding support so a data bound object inheriting from UndoableBase would naturally support undo (not redo) in the UI.

A: Yes, you would use a stack.  There are a couple ways to do it; read these references:
http://en.wikipedia.org/wiki/Command_pattern
http://en.wikipedia.org/wiki/Memento_pattern
Each has its pros/cons.

A: I would use an IUndoableAction interface. The implementations could store whatever data they needed to be done and undone. Then yes, I would use a Stack to hold them.
interface IUndoableAction
{
    void Do();
    void Undo();
}
Stack<IUndoableAction> Actions;

Each kind of action would implement the Do and Undo methods.
Then, somewhere there would be these two methods:
    void PerformAction(IUndoableActionaction)
    {
        Actions.Push(action);
        action.Do();
    }

    void Undo()
    {
        var action = Actions.Pop();
        action.Undo();
    }

As for what to store in the action classes, some actions could just store the old value.  However, once I had an action to swap two rows in a spreadsheet.  I didn't store the values of every cell in both rows -- I just stored the row indices so they could be swapped back.  It could be easy to fill up tons of memory if you stored all of that state for every action.
Then you want a Redo stack as well, and when you undo an action it is pushed onto the redo stack.  The redo stack will need to be cleared when a new action is performed, so things don't get out of order.

A: Probably the most straightforward is to have the undo/redo stack combination.
An alternative is to have an array or list of actions, and just increment/decrement a pointer to an index in the array.  When an action is undone, the index is moved back by one, and when the action is redone, the index is moved forward by one.
The advantage here is that you don't require a pop-and-then-push sequence for each action.
Things to consider:

*

*If you undo several times, and then perform an action, all of the
redo actions must be eliminated.

*Make sure you check the boundaries and ensure that there is an action available to undo/redo before trying to perform the undo/redo.


text:
Q: Почему не работает bottom_bar?
Всем здраствуйте! Помогите пожалуйста с проблемой!
При нажатии на кнопки bottom_bar контент не меняется.
<ons-page>
  <ons-toolbar>

Tab 1

  </ons-toolbar>
    <ons-tabbar swipeable position="auto">
      <ons-tab page="tab1.html" label="Tab 1" active>
      </ons-tab>
      <ons-tab page="tab2.html" label="Tab 2" active-icon="md-face">
      </ons-tab>
      <ons-tab page="tab3.html" label="Tab 3" active-icon="md-face">
    </ons-tab>
    </ons-tabbar>
  </ons-page>

  <template id="tab1.html">
    <ons-page id="Tab1">

        Tab 1

    </ons-page>
  </template>

  <template id="tab2.html">
    <ons-page id="Tab2">

        Tab 2

    </ons-page>
  </template>

  <template id="tab3.html">
    <ons-page id="Tab3">

       Tab 3

    </ons-page>
  </template>

    <ons-bottom-toolbar>
      <ons-tabbar position="auto">
        <ons-tab page="tab4.html" label="Tab 4" class="tables">
        </ons-tab>
        <ons-tab page="tab5.html" label="Tab 5" class="orders">
        </ons-tab>
        <ons-tab page="tab6.html" label="Tab 6" class="orders">
        </ons-tab>
      </ons-tabbar>
    </ons-bottom-toolbar>

    <template id="tab4.html">
      <ons-page id="Tab4">

          Tab 4

      </ons-page>
    </template>

    <template id="tab5.html">
      <ons-page id="Tab5">

          Tab 5

      </ons-page>
    </template>

    <template id="tab6.html">
      <ons-page id="Tab6">

          Tab 6

      </ons-page>
    </template>


text:
Q: Is there any way to view user-defined functions in Chrome DevTools? Firebug's DOM panel has the ability to display user-defined object methods by checking the Show User-defined Functions option.
I've been searching but can't seem to find a similar option within the Chrome DevTools. Is there a way to toggle the visibility of user-defined functions within the Chrome DevTools?

A: The Chrome DevTools do not differenciate between the different types of variables and properties. They actually do not have an explicit panel for that.
DOM properties are generally shown unfiltered, while within the Properties side panel they are grouped by their prototype chain.


text:
Q: 2 products next to each other on Woocommerce product category page I use the Wordpress Avada-theme and Woocommerce for a webshop. Now I have put some code in my css to display 2 products next to each other in my shop in Avada in responsive view.
I used this code:
@media only screen and (max-width: 800px) {
/* lists on mobile */
div.woocommerce.columns-4 > ul {
display: flex;
justify-content: space-between;
align-items: flex-start;
flex-wrap: wrap;
}
/*li elements on mobile*/
div.woocommerce.columns-4 > ul > li {
width: 50%;
box-sizing: border-box;
}
}

Now on the homepage (Aalvink.nl`) I get 2 products next to each other (big improvement), but on the product-category pages the I still see 1 product per column (eg https://www.aalvink.nl/product-categorie/bbq-american-style/).
Does anybody know how to fix this? Or can anyone see what I've done wrong that these category-pages are being excluded from this styling?

A: Try to use this css:
@media only screen and (max-width: 800px) {
  /* lists on mobile */
    .products.products-4 {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      flex-wrap: wrap;
    }
  /*li elements on mobile*/
    .products.products-4 > li {
      width: 50%;
      box-sizing: border-box;
    }
  }

You dont have div with 'woocommerce columns-4' classes on page https://www.aalvink.nl/product-categorie/bbq-american-style/

A: In home page, there is a width of 49% while it is different in product page. I have added the CSS in my answer with media query as it is needed only in mobile view. Hope this helps.

@media (max-width:767px){
  #main ul.products > li.product{
      width:49%;
      float:left !important;
  }
}

A: Looking at the source code of the page, you have forgotten to wrap your UL element with your div.woocommerce.columns-4
If you wrap your UL element in the product page, you should get the same result.


text:
Q: Indian spelling: -ize or -ise? In Indian spelling, what is the correct suffix, -ize or -ise?
E.g. authorized or authorised?

A: Being a country which was ruled by the British, I think the suffix - ise was the one which was naturally used. More recent   contacts with AmE may have influenced usage.

*

*word-forming element used to make verbs, Middle English -isen, from Old French -iser, from Late Latin -izare, from Greek -izein, a verb-forming element denoting the doing of the noun or adjective to which it is attached.

*English picked up the French form, but partially reverted to the correct Greek -z- spelling from late 16c. In Britain, despite the opposition to it (at least formerly) of OED, Encyclopaedia Britannica, the "Times of London," and Fowler, -ise remains dominant. Fowler thinks this is to avoid the difficulty of remembering the short list of common words not from Greek which must be spelled with an -s- (such as advertise, devise, surprise). (Etymonline)

According to the Oxford Dictionary (language matters):

*

*Many verbs that end in -ize can also end in -ise: both endings are correct in British English, though you should stick to one or the other within a piece of writing. For example: finalize/finalise; organize/organise; realize/realise. This website spells these words with the -ize ending, but the main dictionary entries for the verbs show that the -ise spelling is also correct.

A:
Authorize is the standard spelling in American and Canadian English. Authorise is standard in all main varieties of English outside North America.

I am from India and I suggest you to use -ise. The spellings in Indian English are greatly influenced by British English (thanks to their 4 century rule over India). So when in doubt, you can always go with the UK spelling.
However, I also would like to point out that due to increased Americanization, US spellings are also becoming commonplace and acceptable.

A: For 'ize' and 'ise', the 'z' version is AmE.
To answer this question, it depends what do you practice. Indians practice both -BrE and AmE. But most of the Indian schools follow BrE and thus, if you pick any school text-book and check, you find 'ise'.
It's worth noting that British ruled the country for over 400 years. And, I think English was introduced by them. So, since then, Indians generally follow or practice BrE.
You can also check most of the newspapers including Times of India (one of the oldest newspapers in the nation). Example is this where you read the BrE version 'authorised'.


text:
Q: Firefox not playing Vimeo videos I am using Ubuntu 20.04.1 LTS. I have installed the latest version of Firefox. However, Firefox does not play Vimeo videos. The video's title frame downloads and the loading button displays but the video never starts. Interestingly, the video plays very well in Chrome.
I have already done what is recommended in the following webpages:

*

*How to Install and Use FFmpeg on Ubuntu 18.04

*Vimeo Troubleshoot player error messages

*Mozilla Support: Firefox is not playing videos on websites
But none of these solutions have worked. Could someone help me on this? I prefer using Firefox to Chrome.

A: This here did the trick for me:
sudo apt-get install ffmpeg

Found at Mozilla Support Forums

A: Workaround (crap "answer"):
If I have an audio problem, firefox videos won't play...
Being too lazy too look into the actual problem, I often have to pulseaudio -k or pkill pulseaudio and videos start immediately after pulseaudio respawns (if they were already in the process of attempting to play).
(My 20.04 VM experiences regular audio problems with the audio randomly cutting out)

A: I also prefer Firefox to Chrome, but Chromium/Chrome is better than Firefox on multiple video sites, not just Vimeo. I stick with Chromium for playing videos because it's both faster loading for many video websites and less glitchy when playing videos than Firefox.


text:
Q: Perl, Sort nested hash I have a data structure which looks like this (hash of hashes):
$VAR1 = {
          'masterkeyB' => {
                'D' => ['b', 'c', 'a'],
                'A' => ['b', 'a', 'c'],
                'C' => ['a', 'c', 'b'],
                'B' => ['a', 'c', 'b'],
              },
          'masterkeyA' => {
                'B' => ['a', 'c', 'b'],
                'C' => ['a', 'c', 'b'],
                'A' => ['b', 'a', 'c'],
                'D' => ['b', 'c', 'a'],
                }
        };

I would like to sort this structure in alphabetical order :
$VAR1 = {
          'masterkeyA' => {
                'A' => ['a', 'b', 'c'],
                'B' => ['a', 'b', 'c'],
                'C' => ['a', 'c', 'b'],
                'D' => ['a', 'b', 'c'],
              },
          'masterkeyB' => {
                'A' => ['a', 'b', 'c'],
                'B' => ['a', 'b', 'c'],
                'C' => ['a', 'c', 'b'],
                'D' => ['a', 'b', 'c'],
                }
        };

Note that all the arrays are sorted except for 'C'.

A: Just iterate over the keys in nested loops, sort the values as you encounter them. Edit: see http://p3rl.org/dsc#HASHES-OF-HASHES
use feature qw(postderef);
use Tie::Hash::Indexed qw();

my $unsorted = {
    'masterkeyB' => {
        'D' => ['b', 'c', 'a'],
        'A' => ['b', 'a', 'c'],
        'C' => ['a', 'c', 'b'],
        'B' => ['a', 'c', 'b'],
    },
    'masterkeyA' => {
        'B' => ['a', 'c', 'b'],
        'C' => ['a', 'c', 'b'],
        'A' => ['b', 'a', 'c'],
        'D' => ['b', 'c', 'a'],
    }
};

tie my %sorted, 'Tie::Hash::Indexed';
for my $k1 (sort keys $unsorted->%*) {
    for my $k2 (sort keys $unsorted->{$k1}->%*) {
        my $v = $unsorted->{$k1}{$k2};
        $v = [sort $v->@*] unless 'C' eq $k2;
        $sorted{$k1}{$k2} = $v;
    }
}
__END__
$HASH1 = {
    masterkeyA => {
        A => ['a', 'b', 'c'],
        B => ['a', 'b', 'c'],
        C => ['a', 'c', 'b'],
        D => ['a', 'b', 'c']
    },
    masterkeyB => {
        A => ['a', 'b', 'c'],
        B => ['a', 'b', 'c'],
        C => ['a', 'c', 'b'],
        D => ['a', 'b', 'c']
    }
};

A: Unlike arrays, hashes in perl don't stay in sorted order, so the common paradigm is to sort the hash keys while you're traversing the data structure. The basic code snippets you need are
for my $k ( sort keys %hash ) {
  for my $sk ( sort keys %{$hash->{$k}} ) {
    # do something
  }
}

to access hash keys in sorted order, and
if ( $k ne 'KEY' ) {
  # sort this array
  $hash->{$k} = sort @{$hash->{$k}}
}

to selectively sort arrays.
For example, say you're printing out the hash:
use strict;
use warnings;
use feature ':5.16';

my $data = {
      'masterkeyB' => {
            'D' => ['b', 'c', 'a'],
            'A' => ['b', 'a', 'c'],
            'C' => ['a', 'c', 'b'],
            'B' => ['a', 'c', 'b'],
          },
      'masterkeyA' => {
            'B' => ['a', 'c', 'b'],
            'C' => ['a', 'c', 'b'],
            'A' => ['b', 'a', 'c'],
            'D' => ['b', 'c', 'a'],
            }
    };

for my $mk ( sort keys %$data ) {
  say $mk;
  for my $letter ( sort keys %{$data->{$mk}} ) {
    say '  ' . $letter;
    if ( $letter eq 'C') {
      say '    [ ' . join(", ", @{$data->{$mk}{$letter}}) . ' ]';
    }
    else {
      say '    [ ' . join(", ", sort @{$data->{$mk}{$letter}}) . ' ]';
    }
  }
}

result:
masterkeyA
  A
    [ a, b, c ]
  B
    [ a, b, c ]
  C
    [ a, c, b ]
  D
    [ a, b, c ]
masterkeyB
  A
    [ a, b, c ]
  B
    [ a, b, c ]
  C
    [ a, c, b ]
  D
    [ a, b, c ]

Obviously you can change the say lines to do whatever you are planning to do with this data.

A: I think this does what you need. Not easy to ready but works.
my %sorted;
map {my $key = $_; map {$sorted{$key}->{$_} = ($_ eq 'C' ? $hash{$key}->{$_} : [sort @{$hash{$key}->{$_}}])} keys %{$hash{$key}}} keys %hash;

or sort original hash
map {my $key = $_; map {$hash{$key}->{$_} = ($_ eq 'C' ? $hash{$key}->{$_} : [sort @{$hash{$key}->{$_}}])} keys %{$hash{$key}}} keys %hash;

or shorter version
map {my $key = $_; map {$hash{$key}->{$_} = [sort @{$hash{$key}->{$_}}] if($_ ne 'C')} keys %{$hash{$key}}} keys %hash;


text:
Q: GCP AppEngine Permissions I need to grant a GCP project user permissions so he is able to run cron tasks from the app engine console. I've been looking around and could not find suitable permissions for that.
Any tip??

A: I believe that the permission required to do this is cloudscheduler.jobs.run, which is provided by the Owner, Editor, roles/cloudscheduler.jobRunner, or roles/cloudscheduler.admin roles.
See the IAM permissions reference

A: According to the official documentation, your account requires one of the following IAM roles: Owner or Editor.


text:
Q: How to split a tar file into smaller parts at file boundaries? I have a tar file that I want to split into multiple smaller tar files. This would be easy with split, but I want the splitted files to be fully usable tar files themselves, which split can't do as it will split at arbitrary points, not at file boundaries.
So how to split a tar file into smaller parts at file boundaries, so that no file ends up being half in one tar and half in the other tar?
Solutions that don't use tar and accomplish the task by other means would be welcome as well.
PS: Yes, there will be cases where this isn't possible (tar with files larger then the split size).

A: If recreating the archive is an option this Bash script should do the trick (it's just a possible manner):

#!/bin/bash

if [ $# != 3 ] ; then
    echo -e "$0 in out max\n"
    echo -e "\tin:  input directory"
    echo -e "\tout: output directory"
    echo -e "\tmax: split size threshold in bytes"
    exit
fi

IN=$1 OUT=$2 MAX=$3 SEQ=0 TOT=0
find $IN -type f |
while read i ; do du -bs "$i" ; done |
sort -n |
while read SIZE NAME ; do
    if [ $TOT != 0 ] && [ $((TOT+SIZE)) -gt $MAX ] ; then
        SEQ=$((SEQ+1)) TOT=0
    fi
    TOT=$((TOT+SIZE))
    TAR=$OUT/$(printf '%08d' $SEQ).tar
    tar rf $TAR "$NAME"
done

It sorts (ascending order) all the files by size and starts creating the archives; it switches to another when the size exceeds the threshold.
NOTE: Make you sure that the output directory is empty.
USE AT YOUR OWN RISK

A: I don't believe there are any existing tools to do this, but it would be reasonably easy to implement yourself. The tar format is pretty simple, so you'd just have to have a split that took it into consideration. The basic theory is to read a header, look at the stated length of the incoming file, and determine whether to split now or write out the current file. Read the next header, and repeat.

A: There is a tool, tarsplitter which safely splits tar archives. You specify the number of parts you want to split the archive into, and it will figure out where the file boundaries are.
https://github.com/AQUAOSOTech/tarsplitter
The output smaller archives won't be exactly the same size, but pretty close - assuming the files in the original archive don't have a lot of variation.
Example - split the archive "files.tar" into 4 smaller archives:
tarsplitter -p 4 -i files.tar -o /tmp/parts
Creating:
/tmp/parts0.tar
/tmp/parts1.tar
/tmp/parts2.tar
/tmp/parts3.tar

A: The tarsplitter command offered by @ruffrey looks like an awesome option.
I downloaded it, then did:
brew install golang

to be able to compile it.  (Hmm...is it already in Homebrew?  Nope.)  The command successfully compiled on my Mac on 10.14.  I'm currently making a copy of my gigantic archive to run tarsplitter against it.  Two thumbs up for the recommendation.
I'm a relative noob when it comes to compiling other people's code, so it would have been helpful if the author made it clear it was written in GO instead of C/C++ and needed a new compiler installed.  Also, make install doesn't work as there's no install in the Makefile, so I just did:
cp build/tarsplitter_mac /usr/local/bin/tarsplitter

Neat that the GO compiler built for Mac, Linux, and Windows.


text:
Q: Magnitude of each column in a matrix I have an input matrix that has 3 rows and 1000 columns. Each column represents and x, y, z variable. I want to find the magnitude of each column and store that in an output matrix that has 1 row and 1000 columns.
This is my current attempt but it doesn't seem to be working:
output(1,:) = norm(input(3,:));

my input matrix looks like:
x1, x2,...,x1000
y1, y2,...,y1000
z1, z2,...,z1000

I want my output matrix to look like:
[magnitude(x1,y1,z1), magnitude(x2,y2,z2),...,magnitude(x1000,y1000,z1000)]

Any help would be greatly appreciated.

A: norm(input(3,:)) will give you the norm of the 1000 elements of the third row.
Easy solution is to just run a for loop.
output = zeros(1,1000); %Preallocate space
for i = 1:length(output)
  output(i) = norm(input(:, i));
end

A: MATLAB's norm function only works for single vectors. Let A be the name of the matrix which columns you want to find the norm to. Then this command does the job:
norm_A = sqrt(sum(A.*A));

Here is an example:
>> A = [1:5; 1:5; 1:5]

A =

     1     2     3     4     5
     1     2     3     4     5
     1     2     3     4     5

>> norm_A = sqrt(sum(A.*A))

norm_A =

    1.7321    3.4641    5.1962    6.9282    8.6603


text:
Q: No Console messages in Android Studio with Emulator I'm using the emulator that comes with android studio to test my app. Usually if I use my phone to test it I can get all kinds of console messages and logcat. However, with the emulator I get no further messages after the ones seen in the screenshot.

How can I change it so that I see all the console messages that the app is producing?
I use the following method to output personal console messages. This doesn't work when I use the emulator.
Log.d("MapString", "TextFile: " + textContents);
I'm going to take a guess and say it has something to do with dubugging but I can't say for sure... please help!