text:
Q: Little Main Computer program to display quotient followed by remainder This is what I have so far but I can't get it to work. I need to have it input a dividend and a divisor and output the result along with the remainder. Example: if the input is 33 followed by 6 the output will be 5 followed by 3 since 33/6 is 5 remainder 3.
00          INP                      //ask the user
01          BRZ     QUIT            // halt the execution if input zero
02          STA     DIVIDEND        // store in dividend variable
03          INP                     // input dividor
04          BRZ     QUIT            // halt the execution if input zero
05          STA     DIVISOR         // store in divider variable
06          LDA  DIVIDEND          // load into acc
07  LOOP    STA  RESULT            // store the temp result
08          LDA  RESULT             // load the result
09          SUB  DIVISOR            // subtract the dividor to acc BRP
10          BRP  LOOP                //loop if acc is positive or zero
11          LDA  RESULT             // load the result into acc
12          OUT                     // display the result
13  QUIT    HLT                     // halt if zero
14          HLT                     // halt the execution
15  DIVIDEND    DAT                 //declare variable
16  DIVISOR     DAT
17  RESULT      DAT

A: Currently you correctly get the input, calculate the remainder and output it. You just miss the part where you calculate the quotient and output it. The quotient is really the number of times you jump back to the start of the loop. So, increment a counter in each iteration of the loop. Then when you exit the loop you'll have counted one too many, so for the quotient you would output one less than that value.
Other remarks:

*

*It is not necessary to perform LDA RESULT if it immediately follows STA RESULT, since that value is still in the accumulator -- no need to reload it.

*There is no need to have HLT followed by HLT. That second one will never be executed.

*It is not useful to say in comments what an LMC instruction does... For instance, "ask the user" is not a useful comment next to INP. Comments should explain something more -- something that is specific to this program. Most of your comments are just saying what someone could look up in a LMC language specification. That is not the purpose of comments.
So here is your code with the extra counter for getting the quotient, and with the above remarks taken into account. You can run it here.

#input: 19 9
          INP // Input the dividend
          BRZ QUIT // Zero is not considered a valid input
          STA DIVIDEND
          INP // Input divisor
          BRZ QUIT // Division by zero is not allowed
          STA DIVISOR
          LDA ZERO // Initialise quotient
          STA QUOTIENT
          LDA DIVIDEND // Let dividend be the initial value of the remainder
// Repeat as long as remainder would be non-negative:
LOOP      STA REMAINDER
          LDA QUOTIENT // Increment quotient
          ADD ONE
          STA QUOTIENT
          LDA REMAINDER // Reduce remainder
          SUB DIVISOR
          BRP LOOP
// Output the results
          LDA QUOTIENT // quotient is one too great now
          SUB ONE
          OUT
          LDA REMAINDER
          OUT
QUIT      HLT

// constants:
ZERO      DAT 0
ONE       DAT 1

// variables:
DIVIDEND  DAT
DIVISOR   DAT
QUOTIENT  DAT
REMAINDER DAT

<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.813/lmc.js"></script>


text:
Q: How do I focus the AG Grid after it loses focus? I have a function that causes the grid to jump multiple rows. I use the endless row model of the grid, so jumping over 30ish rows at once will prompt the grid to rerender the next few rows after the jump and lose focus on the grid as a whole. Any other key events on the page at the time will instead be processed as part of the surround page element rather than as part of the grid.
How do I put the grid back into focus after this jumping of rows? I assume it is an HTML issue, as none of the grid api functions (if attached to the function) will work due to the grid's html being out of focus, and I cannot add a global event listener to the function's key presses because then it would mess up other properties on the page. How would I go about refocusing it? Thank you!

A: In order to scroll to a certain row and select the first cell you need to get the focues cell and remember its row index:
// remember previous index
var lastRowIndex = gridApi.getFocusedCell().rowIndex;

// perform your actions...

// scroll to index
gridApi.ensureIndexVisible(lastRowIndex);

// select first cell/column
gridApi.setFocusedCell(lastRowIndex, columnApi.getAllDisplayedColumns()[0]);

If you need to scroll to the grid itself, you can use:
const element = document.getElementById("gridId");
element.scrollIntoView();

https://www.w3schools.com/jsref/met_element_scrollintoview.asp

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why was Ginny not allowed to play Quidditch with her brothers? When Ginny joined the Gryffindor Quidditch team and was showing talent,
it came as a complete surprise for her brothers. George said:

"Actually, I dunno how she got so good, seeing how we never let
  her play with us. . . ." "She's been breaking into your broom shed in
  the garden since the age of six and taking each of your brooms out in
  turn when you weren't looking," said Hermione from behind her
  tottering pile of Ancient Rune books. "Oh," said George, looking
  mildly impressed. "Well — that'd explain it." ~Harry Potter and the Order of the Phoenix, Chapter 26: Seen and Unforeseen

Could be that her family was protective of Ginny, considering her their little baby girl, but I don't recall even Mrs. Weasley forbidding Ginny to participate in any sports activity. She mainly opposed Ginny being told Order secrets related to the return of Voldemort, which was understandable. And even in that case, Ginny's  brothers had no problem with Ginny getting information Mrs. Weasley considered too dangerous and thus unsuitable for her age, for example, Sirius' and Lupin's update on the Voldemort situation at the beginning of Harry's fifth year:

"Asleep, yeah, right," said Fred in an undertone, after Hermione bade
  them good night and they were climbing to the next floor. "If Ginny's
  not lying awake waiting for Hermione to tell her everything they said
  downstairs, then I'm a flobberworm. . . ." ~Harry Potter and the Order of the Phoenix, Chapter 6: The Noble and Most Ancient House of Black

So if they were fine with Ginny being told Order secrets, why not let her join their Quidditch games? After all, they let Ron join and from what I could tell they were also fine with girls (Angelina Johnson, Alicia Spinnet and Katie Bell) playing Quidditch on the Gryffindor team, so why not play with their little sis?
Is there something in the Weasley family dynamics I am missing?

A: The Weasleys are poor and even used brooms are expensive and therefore closely guarded.
I think the brothers were very carefully to their brooms and guarding them jealously. If you don't have been raised up with several siblings: The youngest child is always the one who is guilty of breaking things deliberately (even if they aren't, I speak from experience, I was the youngest).
And as the others said, she is a girl. Little boys may have some qualities, but being obnoxious and disdainful to little girls seems to be an culturally independent trait.

A: As Valorum said, it's basically because she's a girl, but it's more involved than that. Ginny is the only girl and the youngest, so it's probably a bit of them being protective and a lot them not wanting her to hang around them because they think she's annoying.
Ginny is the youngest
Not wanting the youngest kids around is a common dynamic in mixed-age groups even if it's all boys or all girls. Goodness knows my older siblings and cousins spent enough time trying to get rid of me when I was trying to hang out with them instead of the siblings and cousins younger than me. Now that she's older (and more openly assertive!), they do pay more attention to her, even if they don't play Quidditch with her.
Ginny is the only girl
The fact that they happily play with the girls on their team doesn't mean a whole lot. Insofar as protectiveness is involved, lots of boys are more protective of their own sisters than they are of girls in general. But it's more likely that they assumed she wouldn't be good enough at Quidditch for it to be fun to play with her, or just generally didn't want to hang out with girls and their cooties. Now they're older and they've grown out of this.
When George says "Actually, I dunno how she got so good, seeing how we never let her play with us," he's talking mostly about the past. It is grammatically ambiguous, but Hermione's response ("since the age of six") supports the interpretation that he means they never let her play with them when they were children. They still don't seem to (at least not in #4), but it's clear that this precedent was established when they were quite young.
The Hermione factor
Another big part of why the Weasley boys start treating Ginny more as an equal is because Hermione does, which brings her at least partway into the Harry-Ron-Hermione group.
Quidditch vs. Order secrets
It's not too surprising that they don't object to Hermione telling her everything now, because (a) they've all grown up, (b) she needs to know about Voldemort in a way that she didn't need to play Quidditch.

A: George doesn't say that their parents didn't let Ginny play, he says that he and his brothers didn't let her play.
It's not unusual for children to exclude their younger siblings from games on the grounds that they are too young to play the game properly. It is also common for brothers to exclude their sisters from games on the grounds that girls can't play the game properly.
This behaviour is not kind and (especially in the second case) not logical, but kids can be like that. They pick up prejudices from their parents and other adults and act on them more openly than the adults might (at least in these supposedly "enlightened" times).

A: All these answers are good, but I think that they are trivializing the most important motivator: Molly Weasley.
Molly was a very domineering person, and she desperately wanted a girl child, and was increasingly frustrated until Ginny was finally born.
Ron's self esteem is a running sub-plot throughout all the books, culminating in the revelation given by the Gaunt horcrux specifically taunting Ron for not being the girl that Ron's mother wanted.
Ron is constantly brushed aside, while Ginny is always under Molly's wing. Ron gets used and damaged hand-me-downs, Ginny gets new stuff. Ron or Fred or George get in trouble at school? A howler. Ginny gets in trouble? Molly visits.
Molly kills Bellatrix for daring to aim a curse at Ginny.

Now, children learn from their parents. Fred and George can go out and bludger each other all they want. But should Molly discover that Fred and George did anything to put Ginny in harm's way, imagined or not, they would have their mother's wrath to pay. Better to exclude her than risk it.
Psychologically, this need not be understood or necessarily even recognized by the family. They pick up on their mother's attitude toward Ginny and develop an aversion to involving her in their get into trouble ways. (I suspect they have plenty of lesser experiences getting yelled at by Molly because of something they did together while including Ginny when younger.) And, as the other answers say, because Fred and George were thick as thieves and didn't want their sister involved with cool guy stuff, like Quidditch.
So here's an upvote for @T.E.D's comment too.

A: I think it's just because the family is protective of her. After all, Ginny was the youngest and Ginny's siblings would not have wanted her to get hurt, even Fred & George.
Of course, it could also be her brothers not wanting her to play since she's a GIRL. They probably thought sports like Quidditch weren't fit for her.
Ginny was the girl Molly had wanted for so long, so naturally Molly was protective of her. If one of the boys did something to her (like get her hurt or let her get hurt etc.), the punishment would be much bigger than if it was one of the boys themselves.


text:
Q: How to include an MVC View into Master.master page There was a business requirement, where we have inherit/include "Master.Master" file into Mvc View[cshtml] .
I tried but doesn't find any solution.
Is there any way to achieve the above task.
Thanks in Advance
Abdul Aleem S


text:
Q: Pandas: list of lists to expanded rows I have an extension to this question. I have lists of lists in my columns and I need to expand the rows one step further. If I just repeat the steps it splits my strings into letters. Could you suggest a smart way around? Thanks!
d1 = pd.DataFrame({'column1': [['ana','bob',[1,2,3]],['dona','elf',[4,5,6]],['gear','hope',[7,8,9]]],
                   'column2':[10,20,30],
                  'column3':[44,55,66]})

d2 = pd.DataFrame.from_records(d1.column1.tolist()).stack().reset_index(level=1, drop=True).rename('column1')

d1_d2 = d1.drop('column1', axis=1).join(d2).reset_index(drop=True)[['column1','column2', 'column3']]

d1_d2

A: It seems you need flatten nested lists:
from collections import Iterable

def flatten(coll):
    for i in coll:
            if isinstance(i, Iterable) and not isinstance(i, str):
                for subc in flatten(i):
                    yield subc
            else:
                yield i

d1['column1'] = d1['column1'].apply(lambda x: list(flatten(x)))
print (d1)
                 column1  column2  column3
0    [ana, bob, 1, 2, 3]       10       44
1   [dona, elf, 4, 5, 6]       20       55
2  [gear, hope, 7, 8, 9]       30       66

And then use your solution:
d2 = (pd.DataFrame(d1.column1.tolist())
        .stack()
        .reset_index(level=1, drop=True)
        .rename('column1'))

d1_d2 = (d1.drop('column1', axis=1)
          .join(d2)
          .reset_index(drop=True)[['column1','column2', 'column3']])

print (d1_d2)
   column1  column2  column3
0      ana       10       44
1      bob       10       44
2        1       10       44
3        2       10       44
4        3       10       44
5     dona       20       55
6      elf       20       55
7        4       20       55
8        5       20       55
9        6       20       55
10    gear       30       66
11    hope       30       66
12       7       30       66
13       8       30       66
14       9       30       66

A: Assuming the expected result is same as jezrael.
pandas >= 0.25.0
d1 = d1.explode('column1').explode('column1').reset_index(drop=True)

d1:
   column1  column2  column3
0      ana       10       44
1      bob       10       44
2        1       10       44
3        2       10       44
4        3       10       44
5     dona       20       55
6      elf       20       55
7        4       20       55
8        5       20       55
9        6       20       55
10    gear       30       66
11    hope       30       66
12       7       30       66
13       8       30       66
14       9       30       66


text:
Q: Ionic framework, pass var to view from construct? I call in my app in construct() a external json, in console log I see correct result of:
var url = 'https://my_path.co/apiv1/products';

this.http.get(url).map(res => res.json()).subscribe(items => console.log(items));

I tried like:
this.http.get(url).map(res => res.json()).subscribe(items => items);

and

this.http.get(url).map(res => res.json()).subscribe(items => {items => items});

With *ngFor I don't get any resulsts, also if I create in construct a string I cannot get it in view like {{my_string}}
How can I pass my json result to view to list all elements?

A: In order to show the results in the view, you need to declare a property in the component, and assign what you want to show in the view, to  that property:
@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

  public items: any; // This creates a public property (accessible from the view), called items, whose type is any (could assign anything to it).
  public myString: string;

  // It's better to avoid making http calls in the constructor, we should use ionViewWillLoad / ionViewWillEnter or any other life cycle hood
  constructor() {}

  ionViewWillLoad() {
    let url = 'https://my_path.co/apiv1/products';

    this.myString = 'Demo app!';

    this.http.get(url)
      .map(res => res.json())
      .subscribe(itemsFromServer => {

        // Here you can assign the result (itemsFromServer) to the property from the component (would be this.items)
        this.items = itemsFromServer;
        console.log(this.items)

      });
    }

}

Now you can use the items and the myString properties in your view, like this:
<ion-header>
    <ion-navbar color="primary">
        <ion-title>{{ myString }}</ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <ion-item *ngFor="let item of items">
      {{ item | json }}
    </ion-item>
</ion-content>


text: Q: PDFBox Vector Rendering PDFBox sometimes renders vectors as image, sometimes keep them as they are.. How does PDFBox decide to render or not? Is there any way to force PDFBox to not render vector into images?


text:
Q: How to remove redundant file open operation in ruby I made a ruby program to copy content of one CSV file to a new CSV file.
This is my code -
require 'csv'
class CopyFile
  def self.create_duplicate_file(file_name)

    CSV.open(file_name, "wb") do |output_row|
      output_row << CSV.open('input.csv', 'r') { |csv| csv.first }
      CSV.foreach('input.csv', headers: true) do |row|
      output_row << row
      end
    end
  end
end

puts "Insert duplicate file name"
file_name = gets.chomp
file_name = file_name+".csv"
CopyFile.create_duplicate_file(file_name)

puts "\nDuplicate File Created."

I am opening the input.csv file twice, one to copy headers and then to copy content.
I want to optimise my code. So is there a way to optimise it further?

A: Just use the cp method:
FileUtils.cp(src, destination, options), no need to reinvent the wheel, like this:
class CopyFile
  def self.create_duplicate_file(file_name)
    FileUtils.cp('input.csv',file_name)
  end
end

or better yet:
file_name = gets.chomp
file_name = file_name+".csv"
FileUtils.cp('input.csv', file_name)


text:
Q: Ubuntu on my computer I just want you to say me if Ubuntu would run smoothly (I meam, not without too much lags and freezing) on my computer.
Here are the specs:
Intel Pentium 4 CPU 2.40 GHz, 512 MB RAM, Intel 82845G/GL/GE/PE/GV Grpahics Controller
Now, I´m runnig Windows XP , but it´s not smooth enough
Can you help me ? Tank you very much :)

A: it might be that Ubuntu would be running slowly on your system. I think Ubuntu (with Unity) is too much too handle for your computer to run smoothly.
I recommend to check out Xubuntu or Lubuntu. It is basically Ubuntu with a more lightweight window manager. Those distros should run perfectly on your computer.
Xubuntu: http://xubuntu.org/
Lubuntu: http://lubuntu.net/


text:
Q: Send a variable to other function I am trying to make a simple web page in with im using fetch to display some users (i display them as list of cards). Also, every user has a button which navigate to another page in which I want to display  the user's posts (another fetch about posts).
The prblem is that i should know the id of the user in which i pressed the button in order to display his posts. But how can i get this id?
Here is the fetch code which displays the the list of user cards:
function getUsers() {
  fetch('https://jsonplaceholder.typicode.com/users')
    .then((res) => res.json())
    .then((data) => {
      let output = '
Users
';
      data.forEach(function(user) {
        output += `

Name: ${user.name}

Email: ${user.email}

              <input type="button" id="${user.id}"  value="Show posts" onClick="showpost(this.id)">

        `;
      });
      document.getElementById('output').innerHTML = output;
    })
}

A: Modify the line below
<input type="button" id="${user.id}"  value="Show posts" onClick="showpost(this.id)">

to
<input type="button" id="${user.id}"  value="Show posts" onClick="showpost(${user.id})">

Now your function showpost should look something like
function showpost(userId){
    alert(userId); // Here you get the ID of the user you want to display the posts
}

Do the display of posts by extending the function.


text:
Q: Function pointer as template argument? Is it possible to pass a function pointer as a template argument without using a typedef?
template<class PF>
class STC {
    PF old;
    PF& ptr;
public:
    STC(PF pf, PF& p)
        : old(*p), ptr(p)
    {
        p = pf;
    }
    ~STC() {
        ptr = old;
    }
};

void foo() {}
void foo2() {}

int main() {
    void (*fp)() = foo;
    typedef void (*vfpv)();
    STC<vfpv> s(foo2, fp); // possible to write this line without using the typedef?
}

A: It is totally possible,
I'd also recommend looking up boost::function & boost::bind as an alternative solution.

A: Yes:
STC<void (*)()> s(foo2, fp); // like this
It's the same as taking the typedef declaration and removing the typedef keyword and the name.

A: I you cannot use boost as Maciek suggested (e.g. you cannot use external libraries in your project) you might try to use a functor.


text:
Q: AVAudioPlayer - must you create a property for it to work? (Xcode) This is the code I'm using now, and it's not working (nothing happens when I press the button that calls this method). Previously, I had a property for audioPlayer and it worked (all the audioPlayers below were self.audioPlayer obviously). The problem was that when I tried to play the sound twice, it would end the first sound playing.
This is no good because I'm making a soundboard and want sounds to be able to overlap. I thought I could just make audioPlayer a local variable instead of a property and all would be ok but now the sound doesn't work at all and I can't figure out why. In all tutorials I've found for AVAudioPlayer, a property is made but no one explains why. If this can't work, what alternatives do I have to make sounds that can overlap?
- (void)loadSound:(NSString *)sound ofType:(NSString *)type withDelegate:(BOOL)delegate {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                     pathForResource:sound
                                     ofType:type]];

AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
if (delegate) audioPlayer.delegate = self;
[audioPlayer prepareToPlay];

[audioPlayer play];
}

A: The reason you need a property or ivar is for the strong reference it provides. When using ARC any object without a strong pointer to it is fair game for deallocation, and in fact that is what you are seeing.
You are also correct that an AVAudioPlayer strong pointer will only allow one audio player to be referenced at a time.
The solution, if you choose to continue to use AVAudioPlayer is to use some sort of collection object to hold strong reference to all the player instances. You could use an NSMutableArray as shown here:
Edit I tweaked the code slightly so method that plays the sound takes an NSString soundName parameter.
@synthesize audioPlayers = _audioPlayers;
-(NSMutableArray *)audioPlayers{
    if (!_audioPlayers){
        _audioPlayers = [[NSMutableArray alloc] init];
    }
    return _audioPlayers;
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [self.audioPlayers removeObject:player];
}
-(void)playSoundNamed:(NSString *)soundName{
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                         pathForResource:soundName
                                         ofType:@"wav"]];
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    if (audioPlayer){
        [audioPlayer setDelegate:self];
        [audioPlayer prepareToPlay];
        [audioPlayer play];
        [self.audioPlayers addObject:audioPlayer];
    }
}

Generally an AVAudioPlayer is overkill for an sound-effect/soundboard application. For quick sound "drops" you will likely find the audio toolbox framework, as outlined in my answer to this question.

From looking at the System Sound class reference, it seems like you
  can only play one sound at a time.

It can only play one SystemSoundID at a time. So for example if you have soundOne and soundTwo. You can play soundOne while soundTwo is playing, but you cannot play more than one instance of either sound at a time.

What's the best way to be able to play sounds that can overlap while
  still being efficient with the amount of code and memory?

Best is opinion.
If you need two instances of the same sound to play at the same time, then I would say the code posted in this answer would be the code to use. Due to the fact that each overlapping instance of the same sound requires creating a new resource, code like this with its audioPlayerDidFinishPlaying: is much more manageable(the memory can easily be reclaimed).
If overlapping instances of the same sound are not a deal-breaker then I think just using AudioServicesCreateSystemSoundID() to create one instance of each sound is more efficient.
I definitely would not try to manage the creation of and disposal of SystemSoundIDs with each press of a button. That would go wrong in a hurry. In that instance AVAudioPlayer is the clear winner on just maintainability alone.

A: I am assuming you are using ARC. The reason that the audio player doesn't work is because the AVAudioPlayer object is being released and then subsequently destroyed once the loadSound: method terminates. This is happening due to ARC's object management. Before ARC, the code:
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
if (delegate) audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer play];

would play the sound as expected. However, the AVAudioPlayer object would still exist long after the loadSound: method terminates. That means every time you play a sound, you would be leaking memory.
A little something about properties
Properties were introduced to reduce the amount of code the developer had to write and maintain. Before properties, a developer would have to hand write the setters and getters for each of their instance variables. That's a lot of redundant code. A fortunate side-effect of properties was that they took care of a lot of the memory management code needed to write setters/getters for object-based instance variables. This meant that a lot of developers started using properties exclusively, even for variables that didn't need to be public.
Since ARC handles all the memory management details for you, properties should only be used for their original purpose, cutting down on the amount of redundant code. Traditional iVars will be strongly referenced by default, which means a simple assignment such as:
title = [NSString stringWithFormat:@"hello"];
is essentially the same as the code:
self.title = [NSString stringWithFormat:@"hello"];.
OK, back to your question.
If you are going to be creating AVAudioPlayer instances in the loadSound: method, you'll need to keep a strong reference to each AVAudioPlayer instance or else ARC will destroy it. I suggest adding the newly created AVAudioPlayer objects into a NSMutableArray array. If you adopt the AVAudioPlayerDelegate protocol, you can implement the audioPlayerDidFinishPlaying:successfully: method. In which you can remove the AVAudioPlayer object from the array, letting ARC know that it's OK to destroy the object.


text:
Q: How to activate new adminhtml theme in Magento? I developed a new module under Magento, it works well. I designed a new adminhtml theme, however I don't find from where to activate it. I browsed all the backend and found only [design change] which change the store theme..
Is there a way to tell Magento to use my theme?

A: Within config.xml under etc folder of your module, add the following
    <stores>
        <admin>
            <design>
                <package>
                    <name>NameSpace</name>
                </package>
                <theme>
                    <default>theme</default>
                </theme>
            </design>
        </admin>
    </stores>

Assuming you created your theme under app/design/adminhtml/NameSpace/theme


text:
Q: How to get values from object and assign them to consts So I'm pulling some data from my DB and it comes out in the form of an object. I'd like to take this object and turn it into separate constants. This is the object
(sorry for link, I dont have enough rep to post images)
https://i.imgur.com/ay7cI29.png
How can I take values out from the object and assign them to constants.  I want to get the value of the field 'address' which is the apartment's address and assign it to a const called rent.

A: You can use destructuring for this very easily:
const { rent: address, ownerEmail, otherProperty1, otherProperty2 } = yourObject;
console.log(rent); //The address

A: You can use destructuring. So, let's say you only want the id from the object. You could do something like the following:
const { id } = await fetchMyData();

A: you can access the object properties like,
1.
const {ac, address} = yourObject;

2.
const ac = yourObject.ac;
const address = yourObject.address;

Hope this can help!


text:
Q: align values in table I have aligned values in my table the way I want them. However, for some reason this messes up my first row completely. I simply want the labels to be centered above the values. How can I solve this?
Thanks a lot in advance!
\begin{table}[H]
       \centering
       \renewcommand{\arraystretch}{1.7}
       %\begin{tabular}[width=\textwidth]{l l l l l l}
       \begin{tabularx}{\textwidth}{XSSSSS}
       \hline
       \hline
        \multicolumn{6}{c}{Price} \\
       \hline
          & Cheese & Butter & Milk & Yoghurt & Cream  \\
          \hline
          \hline
          Cheese &  -0.847*** &  0.002 &  -0.068*** & -0.066*** &  -0.031** \\

          Butter & 0.017 & -0.996*** &  0.007    &    0.008   &    -0.028\\

          Milk  &   -0.224***  &   0.002   &    -0.846***  &   0.029    &    0.016 \\

          Yoghurt  &   -0.208*** &    0.018   &     0.052   &    -0.748***  &  -0.033  \\

          Cream  &  -0.289*** &   -0.072   &     0.039   &    -0.091***  &  -0.631***  \\
          \hline
          \hline
           \multicolumn{6}{c}{\footnotesize  * p$<$0.1, ** p$<$0.05, *** p$<$0.01}
       \end{tabularx}
       \caption{Second stage estimation of own- and cross-price elasticities}
       \label{cross_price_2d}
\end{table}

A: Is it what you want? I had to load geometry to prevent the table to overflow into the margin.
    \documentclass{article}
    \usepackage{geometry}
    \usepackage{float}
    \usepackage{siunitx}
    \usepackage{tabularx}

    \begin{document}

    \begin{table}[H]
           \centering
           \renewcommand{\arraystretch}{1.7}
           \begin{tabularx}{\textwidth}{XSSSSS}
           \hline
           \hline
            &\multicolumn{5}{c}{Price} \\
           \hline
              & {Cheese} & {Butter} & {Milk} & {Yoghurt} & {Cream} \\
              \hline
              \hline
              Cheese & -0.847*** & 0.002 & -0.068*** & -0.066*** & -0.031** \\

              Butter & 0.017 & -0.996*** & 0.007 & 0.008 & -0.028\\

              Milk & -0.224*** & 0.002 & -0.846*** & 0.029 & 0.016 \\

              Yoghurt & -0.208*** & 0.018 & 0.052 & -0.748*** & -0.033 \\

              Cream & -0.289*** & -0.072 & 0.039 & -0.091*** & -0.631*** \\
              \hline
              \hline
               \multicolumn{6}{c}{\footnotesize * p$<$0.1, ** p$<$0.05, *** p$<$0.01}
           \end{tabularx}
           \caption{Second stage estimation of own- and cross-price elasticities}
           \label{cross_price_2d}
    \end{table}

    \end{document}

A: First off, you need to encase the header words "cheese", "butter", etc in curly braces to inform the machinery of the siunitx package that they are words, not numbers. (The letter "e", in particular, tends to confuse the S column type.)
Second, to conserve horizontal space, you should switch from the unadorned S column type, which centers the entire column contents on the decimal markers, to something such as S[table-format=-1.6]. I would also issue the instruction \sisetup{table-align-text-post = false}, so as to avoid any gaps between the numbers and the trailing asterisks.
Third, I'd replace the \hline directives with the line-drawing macros of the booktabs package: \toprule, \cmidrule, \midrule, \bottomrule, and \addlinespace. See the code below for an implemenation of this idea. I would also not execute \renewcommand{\arraystretch}{1.7}.

\documentclass{article} % or some other suitable document class
\usepackage{siunitx,tabularx,booktabs}
\begin{document}

\begin{table}[ht]
\sisetup{table-align-text-post = false}
\begin{tabularx}{\textwidth}{@{} X *{5}{S[table-format=-1.6]} @{}}
    \toprule
    & \multicolumn{5}{c}{Price} \\
    \cmidrule(l){2-6}
    & {Cheese} & {Butter} & {Milk} & {Yoghurt} & {Cream}  \\
    \toprule
    Cheese & -0.847*** &  0.002    & -0.068*** & -0.066*** & -0.031** \\

    Butter &  0.017    & -0.996*** &  0.007    &  0.008    & -0.028 \\

    Milk   & -0.224*** &  0.002    & -0.846*** &  0.029    &  0.016 \\

    Yoghurt& -0.208*** &  0.018    &  0.052    & -0.748*** & -0.033  \\

    Cream  & -0.289*** & -0.072    &  0.039    & -0.091*** & -0.631***  \\
    \bottomrule\addlinespace
    \multicolumn{6}{c}{\footnotesize $*\ p<0.1$, ${**}\ p<0.05$, ${*{**}}\ p<0.01$}
\end{tabularx}
\caption{Second stage estimation of own- and cross-price elasticities}
\label{cross_price_2d}
\end{table}

\end{document}

A: With tabularray package, in standard article document:
\documentclass{article}
%---------------- Show page layout. Don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%
\usepackage{tabularray}
\UseTblrLibrary{booktabs, siunitx}

\begin{document}
    \begin{table}[ht]
\begin{talltblr}[
caption = {Second stage estimation of own- and cross-price elasticities},
  label = {cross_price_2d},
 note{} = {*:    $p<0.10$,\quad
           **:   $p<0.05$,\quad
           ***:  $p<0.01$.}
                ]{colsep = 3pt,
                 colspec = {@{} l *{5}{X[c,si={table-format=-1.3{**}}]} @{}},
                 }
    \toprule
        &   \SetCell[c=5]{c}   {{{Price}}}
                    &           &           &           &                       \\
    \cmidrule{2-6}
        & {{{Cheese}}}
                    & {{{Butter}}}
                                & {{{Milk}}}
                                            & {{{Yoghurt}}}
                                                        & {{{Cream}}}           \\
    \midrule
Cheese  & -0.847\TblrNote{***}
                    &  0.002    & -0.068\TblrNote{***}
                                            & -0.066\TblrNote{***}
                                                        & -0.031\TblrNote{**}   \\
Butter  &  0.017    & -0.996\TblrNote{***}
                                &  0.007    &  0.008    & -0.028                \\
Milk    & -0.224\TblrNote{***}
                    &  0.002    & -0.846\TblrNote{***}
                                            &  0.029    &  0.016                \\
Yoghurt & -0.208\TblrNote{***}
                    &  0.018    &  0.052    & -0.748\TblrNote{***}
                                                        & -0.033                \\
Cream   & -0.289\TblrNote{***}
                    & -0.072    &  0.039    & -0.091\TblrNote{***}
                                                        & -0.631\TblrNote{***}  \\
    \bottomrule
\end{talltblr}
    \end{table}
\end{document}

(red lines indicate page layout)

A: You want to specify table-format and to use tabular*, not tabularx.
I also suggest to use booktabs features and to not setting the \arraystretch to such a large value as 1.7. Also, avoid [H] and let the table float, unless you want to spoil the typographic aspect of your document.
\documentclass{article}
\usepackage{siunitx,booktabs}

\begin{document}

\begin{table}[htp]
\centering

\setlength{\tabcolsep}{0pt}% leave the computations to TeX

\begin{tabular*}{\textwidth}{
  @{\extracolsep{\fill}}
  l
  *{5}{S[table-format=-1.3***]}
  @{}
}
\toprule
&\multicolumn{5}{c}{Price} \\
\cmidrule{2-6}
& {Cheese} & {Butter} & {Milk} & {Yoghurt} & {Cream}  \\
\midrule
Cheese &  -0.847*** &  0.002 &  -0.068*** & -0.066*** &  -0.031** \\
Butter & 0.017 & -0.996*** &  0.007    &    0.008   &    -0.028\\
Milk  &   -0.224***  &   0.002   &    -0.846***  &   0.029    &    0.016 \\
Yoghurt  &   -0.208*** &    0.018   &     0.052   &    -0.748***  &  -0.033  \\
Cream  &  -0.289*** &   -0.072   &     0.039   &    -0.091***  &  -0.631***  \\
\midrule[\heavyrulewidth]
\multicolumn{6}{l}{\footnotesize  * p$<$0.1, ** p$<$0.05, *** p$<$0.01}
\end{tabular*}

\caption{Second stage estimation of own- and cross-price elasticities}
\label{cross_price_2d}

\end{table}

\end{document}


text:
Q: When is this complex-valued function analytic? $$f(z) = e^{z}(z-\overline{z})^2\\=-4e^z(\Im(z))^2$$
I'm not sure if I could just determine where it's analytic here by considering this expression, so I let $z = x+iy$ for $x,y\in \mathbb{R}$.
$$f(z) = -4e^{x}e^{iy}y^2$$
so the jacobian matrix with the partial derivatives are
$$J = \begin{pmatrix}-4y^2 e^{x}\cos y & -4e^{x}(2y \cos y - y^2 \sin y) \\ -4y^2 e^x \sin y & -4e^x (2y\sin y + y^2 \cos y)\end{pmatrix}$$
and the Cauchy Riemann equations only satisfy if
$y = \frac{\pi}{2} + k\frac{\pi}{2}$ for all $k \in \mathbb{Z}$.
This means that $f$ is analytic for only complex numbers with imaginary component multiples of $\frac{\pi}{2}$.
However, I doubt this answer because if I let (for example) $z = x + 1i$, then
$$f(z) = -4e^x e^{i}$$
which seems to be differentiable (since $e^x$ is differentiable) and the rest are just constants. So it seems to me that any possible complex number can allow $f$ to be analytic (since any $y$ value would give a differentiable function $e^x$ in the end result (but obviously not satisfying the CR equations))
Do I have some sort of misconception about differentiability?

A: Actually, for $f$ be $\mathbf{C}$-differentiable at $x+iy$ the following conditions must be satisfied:
$$-4y^2e^x \cos y = -4e^x(2y \sin y+y^2\cos y),$$
$$ 4e^x(2y \cos y-y^2\sin y)=-4y^2 e^x \sin y,$$
which can be simplified to
$$ y\sin y = 0,$$
$$ y \cos y = 0.$$
So only points with $y=0$ satisfy the CR equations, so $f$ can be $\mathbf{C}$-differentiable only at points on the line $y=0.$
When you evaluate $f$ at $x+i$ you get the result $f(z)=-4e^xe^i,$ but you can't know if $f$ is $\mathbf{C}$-differentiable at some point by evaluating $f$ at the point, that's just the value that $f$ takes at that point.
Now note that $f$ can't be analytic at any point, since if $f$ is analitic at some point, then it is $\mathbf{C}$-differentiable in some neighborhood of the point. But $f$ can be $\mathbf{C}$-differentiable only at points on the line $y=0,$ so any neighborhood of a point at which $f$ is $\mathbf{C}$-differentiable must contain points at which $f$ is not.


text:
Q: JavaFX: New SpinnerValueFactory results in StackOverflow I have a foreach loop creating about 180 panes and initalizing them. One part of the panes is a spinner. For each spinner a new SpinnerValueFactory is made:
SpinnerValueFactory factory = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, products.get(i).getStock());
//getStock() returns an integer between 0 and 300

Every 6th time the foreach loop is gone through, I get the following error:
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.StackOverflowError (the following lines repeat)
    at javafx.scene.control.SpinnerValueFactory$IntegerSpinnerValueFactory.lambda$new$215(SpinnerValueFactory.java:475)
    at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.ObjectPropertyBase.fireValueChangedEvent(ObjectPropertyBase.java:105)
    at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
    at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
    at javafx.scene.control.SpinnerValueFactory.setValue(SpinnerValueFactory.java:150)
at javafx.scene.control.SpinnerValueFactory$IntegerSpinnerValueFactory.lambda$new$215(SpinnerValueFactory.java:478)(...)

It looks like Java stops creating new SpinnerValueFactories due to a StackOverflow. Then Java tries to set the factory to the spinners, but as no factory exists, more errors are printed.
If I remove the method call, no error occurs:
SpinnerValueFactory factory = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 5);

The project is nested in a database, a FXML file, its controller and a launching class. I tried to make a minimal example, but removing everything except the shortened method resulted in no error. Interestingly a friend of mine using the same project and the same SDK experiences no error. For me it also seems strange that it takes exactly 6 times to go through the foreach loop until the StackOverflow occurs whereas the second version creates all 180 panes without any problem. Why does the StackOverflow only occur when having the getStock() call?

A: I used the Debugger of my IDE (actually the first time) and found the option to set 'Java Exception Breakpoints'. It added some information to my exception:
http://i.stack.imgur.com/jGc7J.png
Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate java.lang.Integer.toString()
value=-2

Obviously I set the factory's min value to 0 and tried to set the max value to -2 which doesn't work. I changed the value in the database and now it works fine. What an embarrassing fault. Thanks for your help!


text:
Q: Read the data from a text file and reshape the data in python using pandas I need to convert the following text file into csv format using Python pandas.
I have a dataset in the following format. It is a text file and doesn't have header.

And I need it in a format like this:
SourceFile  RowNo ColNo Value
InputFile.txt   1   1   H1000
InputFile.txt   1   2   Sample_ID
InputFile.txt   1   3   MGA_E
InputFile.txt   1   4   MGA_N
InputFile.txt   2   1   H1001
InputFile.txt   2   2   Method
InputFile.txt   2   6   AR101
InputFile.txt   3   1   H1002
InputFile.txt   3   2   Units
InputFile.txt   3   3   metres
InputFile.txt   3   4   metres
InputFile.txt   4   1   H1003
InputFile.txt   4   2   LLD
InputFile.txt   4   6   0.01
InputFile.txt   4   7   5
InputFile.txt   5   1   D
InputFile.txt   5   2   DAL011
InputFile.txt   5   3   446500
InputFile.txt   5   4   6644000
InputFile.txt   5   5   L
InputFile.txt   5   6   9.13
InputFile.txt   6   1   D
InputFile.txt   6   2   DAL020
InputFile.txt   6   3   462800
InputFile.txt   6   4   6653400
InputFile.txt   6   5   L
InputFile.txt   6   6   8.6
InputFile.txt   7   1   EOF

Here is what I have tried:
if 'txt' in str(path_txt):
        all_dfs = pd.read_csv(str(path_txt), dtype=str, sep='\t', header=None)  # Reading file

else:
        print ('Unknow file', str(path_txt))
for (i, c) in enumerate(all_dfs.columns):
        ds = ds.append(pd.DataFrame({
            'SourceFile': path_txt.name,
            'RowNo': range(1, len(all_dfs) + 1),
            'ColNo': i + 1,
            'Value': all_dfs[[str(c)]].values[:, 0],
            }))
 ds['Value'].replace('', np.nan, inplace=True)
 ds.dropna(subset=['Value'], inplace=True)
 ds.to_csv('Data.csv', index=False)

*

*SourceFile(name of the  txt file)

*RowNumber(which row, Value field is coming)

*ColumnNumber(which column, value field is coming)

*Value(actual data)
Error: KeyError: "None of [Index(['0'], dtype='object')] are in the [columns]"

A: This code will do exactly what you want, in a simpler (and faster) way:
with open('your_file.txt') as f:
    text = f.read().strip()

lines = [[('InputFile.txt', line_no + 1, col_no + 1, cell) for col_no, cell in enumerate(re.split('\t', l.strip())) if cell != ''] for line_no, l in enumerate(re.split(r'[\r\n]+', text))]
l = []
for line in lines:
    l.extend(line)
df = pd.DataFrame(l, columns=['SourceFile', 'RowNo', 'ColNo', 'Value'])

Output:
>>> df
       SourceFile  RowNo  ColNo      Value
0   InputFile.txt      1      1      H1000
1   InputFile.txt      1      2  Sample_Id
2   InputFile.txt      1      3      MGA_E
3   InputFile.txt      1      4      MGA_N
4   InputFile.txt      2      1      H1001
5   InputFile.txt      2      2     Method
6   InputFile.txt      2      6      AR101
7   InputFile.txt      3      1      H1002
8   InputFile.txt      3      2      Units
9   InputFile.txt      3      3     metres
10  InputFile.txt      3      4     metres
11  InputFile.txt      4      1      H1003
12  InputFile.txt      4      2        LLD
13  InputFile.txt      4      6       0.01
14  InputFile.txt      4      7          5
15  InputFile.txt      5      1          D
16  InputFile.txt      5      2     DAL011
17  InputFile.txt      5      3     446500
18  InputFile.txt      5      4    6644000
19  InputFile.txt      5      5          L
20  InputFile.txt      5      6       9.13
21  InputFile.txt      6      1          D
22  InputFile.txt      6      2     DAL020
23  InputFile.txt      6      3     462800
24  InputFile.txt      6      4    6653400
25  InputFile.txt      6      5          L
26  InputFile.txt      6      6        8.6
27  InputFile.txt      7      1        EOF

I verified that it produces your expected output dataframe perfectly.


text:
Q: How to use ValueResolver in another ValueResolver or chain ValueResolver with Symfony I'm using Symfony 6.2 with php 8.1.
Since the update of SF 6.2 i had to remove SensioFrameworkExtraBundle and migrate my code from ParamConverter to new custom ValueResolver.
However, i'm facing a lack a feature from this migration or i miss something :(
With a custom ParamConverter, i could resolve a parameter and rewrite the new content in the Request. This allow me to chain any ParamConverter.
The new way with custom ValueResolver does not rewrite the content in the Request.
Of course i can force to rewrite the content or create a new attribute in the Request but i feel it's wrong or not proper way.
My use case :
The resolver for TranslationKey need the resolver result of TranslationDomain and TranslationLanguage.
basically i would like to chain these resolver or group them like we can do in form Constraint.
services.yaml
App\Service\\ranslation\Request\ValueResolver\TranslationLanguageValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 103 }

App\Service\Translation\Request\ValueResolver\\TranslationDomainValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 102 }

App\Service\Translation\Request\ValueResolver\TranslationKeyValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 101 }

My controller :
public function edit (Request             $request,
   TranslationLanguage $translationLanguage,
   TranslationDomain   $translationDomain,
   TranslationKey      $translationKey,
   TranslationHelper   $translationHelper,
   Translation         $translation): Response
{
    [some code]
}

TranslationKeyValueResolver :
public function resolve (Request $request, ArgumentMetadata $argument): iterable
{
    $argumentType = $argument->getType();
 if (!$argumentType || !($argumentType === TranslationKey::class)) {
        return [];
   }

   $translationLanguage = $request->get('translationLanguage'); //=> does not return the object since it's not chained
    [some code]

    return [new TranslationKey($translationKey)];
}

Before :
    public function apply(Request $request, ParamConverter $configuration)
    {
        [some code]

        $request->attributes->set($configuration->getName(), new TranslationLanguage($languages));

        return true;
    }

After :
public function resolve (Request $request, ArgumentMetadata $argument): iterable
{
    $argumentType = $argument->getType();
 if (!$argumentType || !($argumentType === TranslationLanguage::class)) {
        return [];
   }

    [some code]

 return [new TranslationLanguage($languages)];
}

So, i tried to create a new attribute in Request with the new value, but it feel terribly wrong since it suppose all resolver has been executed before and in order. But it's working.
I though to revolve again TranslationLangage and TranslationDomain in TranslationKeyValueResolver but i don't know how, neither what tag i should set in that case ? Custom tag ?
App\Service\Translation\Request\ValueResolver\TranslationKeyValueResolver:
  tags:
    - { name: controller.argument_value_resolver, priority: 101 }
    - { name: another_tag_to_resolve_argument_from_resolver, priority: 101 } ??

Any idea please ?
Radyium
Thanks


text:
Q: How to print a double value that is just less than another double value? Actually I am working on range expression in c++. So what I want is if I have any expression like
x<1

Then my
double getMax(...);

should return a double value that is just before 1.000 (double precision) on a number line.
I tried doing this
double getMax(double& a)
{
    return (a-numeric_limits<double>::min());
}

But I am still getting same value as a in return statement.
I think C++ is converting it to nearest double in cout statement.
int main()
{
    double a = 32;
    cout<<scientific<<getMax(a)<<endl;
    return 0;
}

output:
3.200000e+001

A: First of all, you need to ensure that you actually print sufficiently many digits to ensure all representable values of double are displayed. You can do this as follows (make sure you #include <iomanip> for this):
    std::cout << std::scientific << std::setprecision(std::numeric_limits<double>::max_digits10) << getMax(a) << std::endl;

Secondly, numeric_limits<>::min is not appropriate for this. If your starting value is 1.0, you can use numeric_limits<double>::epsilon, which is the smallest difference from 1.0 that is representable.
However, in your code example, the starting value is 32. Epsilon does not necessarily work for that. Calculating the right epsilon in this case is difficult.
However, if you can use C++11(*), there is a function in the cmath header that does what you need std::nextafter:
#include <iostream>
#include <limits>
#include <iomanip>
#include <cmath>

double getMax(double a)
{
  return std::nextafter(a,std::numeric_limits<double>::lowest());
}

int main()
{
    double a = 32;
    std::cout << std::scientific
              << std::setprecision(std::numeric_limits<double>::max_digits10)
              << getMax(a)
              << std::endl;
    return 0;
}

I've also put it on liveworkspace.
To explain:
double nextafter(double from, double to);

returns the next representable value of from in the direction of to. So I specified std::numeric_limits<double>::lowest() in my call to ensure you get the next representable value less than the argument.
(*)See Tony D's comment below. You may have access to nextafter() without C++11.

A: I think you've got the right idea.
Check out Setting the precision of a double without using stream (ios_base::precision) not so much for the question, but for the examples they give of using precision.  You might want to try something like printing with a precision of 53.
The way I usually see "close to but not quite" involves setting a difference threshold (typically called epsilon).  In that case, you wouldn't use a getMax function, but have an epsilon used in your usage of less than.  (You could do a class with the epsilon value and operator overloading.  I tend to avoid operator overloading like a plague.)
Basically, you'd need:
bool lessThanEpsilon(double number, double lessThan, double epsilon)
{
    return (lessThan - number >= epsilon);
}

There are other varieties, of course.  Equals would check if Math.abs(number - equals) < epsilon


text:
Q: How to recover ownership of private repo whose old owner was removed from the organization Following is the problem I have:
User A joined our organization and created a private repository. This user A was then removed from our organization but the repository he created wasn't transferred to anyone. Now we want to add more collaborators to this repo but we can't since the old owner is gone. Is there a way we can do that? Also can we change the ownership of the repository?


text:
Q: Scraping news articles using Selenium Python I am Learning to scrape news articles from the website https://tribune.com.pk/pakistan/archives. The first thing is to scrape the link of every news article. Now the problem is that <a tag contains two href in it but I want to get the first href tag which I am unable to do
I am attaching the html of that particular part
The code I have written returns me 2 href tags but I only want the first one
def Url_Extraction():
    category_name = driver.find_element(By.XPATH, '//*[@id="main-section"]/h1')
    cat = category_name.text  # Save category name in variable
    print(f"{cat}")
    news_articles = driver.find_elements(By.XPATH,"//div[contains(@class,'flex-wrap')]//a")

    for element in news_articles:
        URL = element.get_attribute('href')
        print(URL)
        Url.append(URL)
        Category.append(cat)
        current_time = time.time() - start_time
        print(f'{len(Url)} urls extracted')
        print(f'{len(Category)} categories extracted')
        print(f'Current Time: {current_time / 3600:.2f} hr, {current_time / 60:.2f} min, {current_time:.2f} sec',
              flush=True)

Moreover I am able to paginate but I can't get the full article by clicking the individual links given on the main page.

A: You have to modify the below XPath:
Instead of this -
news_articles = driver.find_elements(By.XPATH,"//div[contains(@class,'flex-wrap')]//a")
Use this -
news_articles = driver.find_elements(By.XPATH,"//div[contains(@class,'flex-wrap')]/a")


text:
Q: Gibbon After member deleted, I can not add him again I don't know if this is gem/api related question or implementation, but after deleting a member from a list, I can't add him again.
I'm obtaining that
is already a list member. Use PUT to insert or update list members.

I am using the following methods to add members from a list:
class SubscribeToNewsletterService
 def initialize(user)
  @user = user
  @gibbon = Gibbon::Request.new(api_key: ENV['MAILCHIMP_API_KEY'])
  @list_id = ENV['MAILCHIMP_LIST_ID']
end

def call
@gibbon.lists(@list_id).members.create(
  body: {
    email_address: @user.email,
    status: "subscribed",
    merge_fields: {
      FNAME: @user.first_name,
      LNAME: @user.last_name,
     }
   }
 )
 end
end


text:
Q: How to insert multiple values into the function argument and use it in a PHP query I have a PHP function with a query to the database.
function display_content($dish_type){
    $con = mysqli_connect("localhost", "root", "", "cookbook");

    $sort = isset($_POST["sort"]) ? $sort = $_POST["sort"] : "alphabet";
    $sql = "SELECT * FROM recipes WHERE type = $dish_type ORDER BY name";

    $order_query = "SELECT * FROM recipes WHERE concat(name, description, tags) LIKE '%$data[0]%'".$sqlloop." ".$tag_filter." AND type = $dish_type ORDER BY";

    switch ($sort) {
        case "alphabet":
            $sql = $order_query." name";
        break;

        case "alphabet_rev":
            $sql = $order_query." name DESC";
        break;

        // More...
    }

    $res = mysqli_query($con,$sql);

    while($row = mysqli_fetch_assoc($res)) {
        // Code...
    }

    mysqli_close($con);
}

I want to display the results based on the $dish_type (it's a select in HTML). Selecting a type works fine, the content is displayed on the page as it should. The problem is when I'm trying to display all of the dish types at once. Here is the php for calling the function:
// Display all results <-- the problematic part
function recipe_list_all(){
    ob_start();
    // ???
    $content = ob_get_contents();
    ob_end_clean();

    if(!empty($content)){
        // ???
    }
}

// Display results for "dishes"
function recipe_list_dishes(){
    ob_start();
    display_content(array("snacks", "dishes", "desserts", "other"));
    $content = ob_get_contents();
    ob_end_clean();

    if(!empty($content)){
        display_content("dishes");
    }
}

// Display results for "desserts"
function recipe_list_desserts(){
    ob_start();
    display_content("'desserts'");
    $content = ob_get_contents();
    ob_end_clean();

    if(!empty($content)){
        display_content("'desserts'");
    }
}

// Display results for "snacks"
function recipe_list_snacks(){
    ob_start();
    display_content("'snacks'");
    $content = ob_get_contents();
    ob_end_clean();

    if(!empty($content)){
        display_content("'snacks'");
    }
}

// Display results for "other"
function recipe_list_other(){
    ob_start();
    display_content("'other'");
    $content = ob_get_contents();
    ob_end_clean();

    if(!empty($content)){
        display_content("'other'");
    }
}

$food_type = isset($_POST["food_type"]) ? $food_type = $_POST["food_type"] : "all_types";

switch ($food_type){
    case "all_types":
        recipe_list_all();
    break;

    case "dishes":
        recipe_list_dishes();
    break;

    case "desserts":
        recipe_list_desserts();
    break;

    case "snacks":
        recipe_list_snacks();
    break;

    case "other":
        recipe_list_other();
    break;
}

I can't do something like this:
function recipe_list_all(){
    ob_start();
    recipe_list_dishes();
    recipe_list_desserts();
    recipe_list_snacks();
    recipe_list_other();
    $content = ob_get_contents();
    ob_end_clean();

    if(!empty($content)){
        recipe_list_dishes();
        recipe_list_desserts();
        recipe_list_snacks();
        recipe_list_other();
    }
}

because it will display the results separated. I have a sorting system, so the results will be sorted (for example) alphabetically a-z for dishes, then a-z for desserts, etc. I want to mix the results. How can I do that?


text:
Q: Wpf UserControl hosted in Winforms MDI application. Launch Dialogbox I have written wpf Usercontrol which will be hosted in Winforms MDI window. UseControl has a code to launch Wpf Modal dialog box but the positions of the Dialog box is random. I am not sure how to hook the owner property for dialog so that i can center the dialog window to the parent MDI child window.
Ex.
Window w = new Window() //wpf Window
w.Owner = //Don't know how to put Winforms Window here
w.ShowDiaog();

Any ideas please
Thanks


text:
Q: Proving this set is compact I am going through Carothers Real Analysis to study for quals, and came across this question.
Show that the set $A = \{x \in \ell_2 : \lvert x_n \rvert \leq \frac{1}{n}, n \in \mathbb{N}\}$ is compact in $\ell_2$. Hint: first show that $A$ is closed. Next, use the fact that $\sum_{n=1}^{\infty} \frac{1}{n^2} < \infty$ to show that $A$ is "within $\epsilon$" of the set $A \cap \{x \in \ell_2 : \lvert x_n \rvert = 0, n \geq N\}$ for some $N \in \mathbb{N}$.
Now I can prove what the hint says to prove. What I do not understand is how on earth this shows that $A$ is compact. This question comes at the beginning of the compactness chapter and all I have at my disposal is that a set is compact iff it is totally bounded and complete iff every sequence has a convergent subsequence, and that if $A \subset M$ and $A$ is compact, then $A$ is closed in $M$, and that if $M$ is compact and $A$ is closed, then $A$ is compact.


text:
Q: Passing a variable from my JS file to my HTML file? I have this code :
var uri = 'https://api.twitter.com/oauth/authenticate'
+ '?' + qs.stringify({oauth_token: oauthToken})

Trying to use that 'uri' variable (< a href=uri essentially) in one of my angular-src component HTML files.
Is it possible..? Using NodeJS
EDIT: The full code :
var oauthToken = "";
var oauthTokenSecret = "";
app.get('/', function (req, res) {
//Step-1 Obtaining a request token
request.post({url : requestTokenUrl, oauth : oauth}, function (e, r, body){

//Parsing the Query String containing the oauth_token and oauth_secret.
var reqData = qs.parse(body);
oauthToken = reqData.oauth_token;
oauthTokenSecret = reqData.oauth_token_secret;

//Step-2 Redirecting the user by creating a link
//and allowing the user to click the link
var uri = 'https://api.twitter.com/oauth/authenticate'
+ '?' + qs.stringify({oauth_token: oauthToken})
 res.render('home', {url : uri});

I am not using a view engine so I am trying to just forget about the res.render and simply pass the dynamic variable to my HTML file.

A: I am assuming that you are using EJS files in Express.
In your EJS file home.ejs add something like this:
<script>
var authUrl = "<%= url %>";
<script>

Then, in the browser you can just use the value of the variable authUrl.
What this is doing is taking the EJS variable url, that you defined in your res.render function call, and placing it, as a string, into the HTML that will be sent to the browser. Then the browser takes that value and loads it into the variable authUrl.


text:
Q: What is the difference between []int and int[] When I want to implement a function in C++ , if it matters to receive the int array in the following cases?
void fn1(int []a) {
  a[0] = 1;
}

void fn2(int a[]) {
  a[0] = 1;
}

A: Well, the question is not clear.. Whether to receive the int array or not, it depends on the logics of your method. In Java it is better to write a[], but you can write either way.
Also, look over here - pass array to method Java

A: In Java,the declaration is same...
but in C++,the fn1() declaration need to be different

A: In Java, there is no semantic difference.
In C++, the first syntax is invalid.


text:
Q: $k \subseteq K$ be a field extension with $[K:k] = p$ prime, $f(X) \in k[x]$ with $\deg{f(X)} = p + 1$. $f$ has a root in $K$ iff has a root in $k$. I just want to see if my proof is correct.
It goes this way:
Suppose $\alpha \in K$ is a root of $f$, with minimal polynomial $p_\alpha \in k[X]$. Then $k \subseteq k(\alpha) \subseteq K$ is a composition of field extensions, with $[K: k] = [K: k(\alpha)][k(\alpha): k] = p$. This implies that either $[K:k(\alpha)] = p$ and $[k(\alpha): k] = 1$ or $[K: k(\alpha)] = 1$ and $[k(\alpha): k] = p$. As the first already establishes the desired result, we suppose that $[K: k(\alpha)] = 1$ and $[k(\alpha): k] = p$. Then, $p_\alpha | f$, i.e., $f = gp_\alpha$ for some $g \in k[X]$. Because $\deg{f} = p+1$ and $\deg{p_\alpha} = [k(\alpha) : k] = p$, we can conclude that $\deg{g} = 1$. Polynomials of degree 1 always have roots in their field of coefficients, which implies that $g$, and hence $f$, has a root in $k$.
Is this correct? Can you answer more elegantly?


text:
Q: get file name from blob key in Appengine In app-engine, given a BlobKey, and nothing but the blob key, how do you get the name of the file that the blob key is pointing to? For instance if the file is image1.png. How do I retrieve the name of the blob file?

A: You can use BlobInfo to retreive instance properties like the filename
blob_info = blobstore.BlobInfo.get(your_blobkey)
file_name = blob_info.filename.

Docs: https://cloud.google.com/appengine/docs/python/blobstore/blobinfoclass#BlobInfo_get
But if you save or upload your blobs in GCS, you do not have a BlobInfo object. More info here: https://cloud.google.com/appengine/docs/python/blobstore/fileinfoclass


text:
Q: Clases Inmutables en python necesito modificar la siguiente clase para convertirla en una clase inmutable, sin heredar de tuple, namedtuple o dataclass. Lo he intentado de la siguiente forma, pero no es válida dado que pese a que devuelve el resultado esperado, se puede modificar el valor de los atributos, así como añadir nuevos atributos con el método dict, pese al uso del método slots
class Operacion:
      """Una clase que debe ser modificada para ser inmutable sin """
    __slots__ = ()

    def __init__(self, operandoA, operandoB):
        super().__setattr__("operandoA", operandoA)
        super().__setattr__("operandoB", operandoB)

    def producto(self):

        return self.operandoA * self.operandoB

if __name__ == "__main__":

    # Ejemplos
    r = Operacion(25, 78)
    print(r.operandoA) # Prints 25
    print(r.operandoB)  # Prints 78
    print(r.producto()) # Prints 1950

A: te ha faltado hacer una cosa. Usando __slots__ limitas la creacion de nuevos atributos (que por cierto has olvidado enumerar en tu codigo!), pero tienes que hacer un override del metodo __setattr__ para que no te deje modificar los valores.
Seria algo asi:
class Operacion:
    """Una clase que debe ser modificada para ser inmutable sin """
    __slots__ = ('operandoA', 'operandoB')

    def __init__(self, operandoA, operandoB):
        super(Operacion, self).__setattr__("operandoA", operandoA)
        super(Operacion, self).__setattr__("operandoB", operandoB)

    def producto(self):
        return self.operandoA * self.operandoB

    def __setattr__(self, name, value):
            """
            Hacemos un override del setter de atributos
            """
            if name in self.__slots__:
                msg = "'%s' no tiene permiso para sobreescribir %s" % (self.__class__,name)
                raise AttributeError(msg)

            else:
                msg = "'%s' no tiene atributo %s" % (self.__class__,name)
                raise AttributeError(msg)

Fijate que lo he hecho con una condicion if para que distinga si estas modificando un atributo ya existente o bien intentando crear uno nuevo.
Ejemplo 1:
r = Operacion(25, 78)
r.operandoA = 1

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-133-b903f542a2a0> in <module>
----> 1 r.operandoA = 1

<ipython-input-132-d3502f09ce61> in __setattr__(self, name, value)
     18                 msg = "'%s' no tiene permiso para sobreescribir %s" % (self.__class__,
     19                                                     name)
---> 20                 raise AttributeError(msg)
     21
     22             else:

AttributeError: '<class '__main__.Operacion'>' no tiene permiso para sobreescribir operandoA

Ejemplo 2:
r.operandoC = 1

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-135-68869d3bd2f8> in <module>
----> 1 r.operandoC = 1

<ipython-input-132-d3502f09ce61> in __setattr__(self, name, value)
     24                 msg = "'%s' no tiene atributo %s" % (self.__class__,
     25                                                     name)
---> 26                 raise AttributeError(msg)
     27
     28

AttributeError: '<class '__main__.Operacion'>' no tiene atributo operandoC


text:
Q: Mapping JSON response to an abstract type in JAVA rest Service I am working with an ecommerce company and I am integrating with 3 different payment gateways. All of them require a callbackurl to post back the transaction status.
I have defined a resource to store the status of the transaction
http://www.api.com/api/users/{userid}/order/{orderId}/payments/{paymentModeId}/paymentStatus

I have defined an interface called IPaymentStatusResponse and have created 3 implementations. Based on the paymentModeId in the uri path, appropriate implementation will be picked up to persist the transaction status.
eg: callback url for three different gatewyas will look like this
payment mode 1 - paytm, payment mode 2 - payu ,payment mode 3- cc avenue.
http://www.api.com/api/users/300/order/501/payments/1/paymentStatus
http://www.api.com/api/users/300/order/501/payments/2/paymentStatus
http://www.api.com/api/users/300/order/501/payments/3/paymentStatus

Method signature
public void createPaymentStatus(
            @PathParam("paymentModeId") int paymentModeId,
            IPaymentStatusResponse response) throws MyAppException {
        paymentServiceImpl.createPaymentResponse(response, paymentModeId);
}

Is this the correct way to approach this?
When I did a HTTP post I get the following error:
Can not construct instance of com.myapp.dto.payments.IPaymentStatusResponse, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
 at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@1ee3ab21; line: 1, column: 1]

Other option , I ll have to define different end points for all the different gateways and map the response object.
UPDATE:
A good explanation can be found here
http://programmerbruce.blogspot.in/2011/05/deserialize-json-with-jackson-into.html
It needs a type element in the response json to pick the concrete class.
Sample json with type mentioned and configuration of my interface. This works. But not sure how to handle this because the response json is not under my control and it comes from the payment gateway providers
{
  "MID":"abc",
  "TXNID":"T123",
  "ORDERID":"100",
  "BANKTXNID":"B123",
  "TXNAMOUNT":"1",
  "CURRENCY":"INR",
  "STATUS":"TXN_SUCCESS",
  "RESPCODE":"01",
  "RESPMSG":"Txn Success",
  "TXNDATE":"2015-12-14 02:10:29.742447",
  "GATEWAYNAME":"ICICI",
  "BANKNAME":"ICICI",
  "PAYMENTMODE":"CC",
  "type":"PayTMPaymentResponse",
  "CHECKSUMHASH":"ggg"
}

Interface
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @Type(value = PayTMPaymentResponse.class, name = "PayTMPaymentResponse") })
public interface IPaymentStatusResponse {

}

Can this be implemented with some query or path parameter ?

A: Spring/Jackson is not able to deserialize automatically.
You'll have to provide custom deserializer for a given type.
I think it should be easier to do one POJO for shared information and 3 strategies.
it should help in case if you're using jackson. I think other libs have something similar to that.
http://wiki.fasterxml.com/JacksonPolymorphicDeserialization