text:
Q: Objective-c floating button, same procedure different behaviour I have a created a floating button on a UITableViewController. It works like expected.
Now I wanted to use the button as well on a UIViewController where I added a UITableView.
The code for creating the floating button is identically, but the behaviour is different.
At the UITableViewController the button stay where it shall.
At the UIViewController the button moves up (when I scroll down) and down (when I scroll up)
How do I get the button stay where it shall on the UIViewController. Like on the UITableViewController?
TableViewController.h
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "SingletonClass.h"

@interface MagTableViewController : UITableViewController <UIGestureRecognizerDelegate>

@property (strong, nonatomic) IBOutlet UITableView *magTableView;
@property (strong, nonatomic) UIButton *oButton;
@property (nonatomic) float originalOrigin;

@end

TableViewController.m  - floating button, works like expected
- (void)viewDidLoad
{
    [super viewDidLoad];
    SingletonClass *sharedSingleton = [SingletonClass sharedInstance];
    self.originalOrigin = sharedSingleton.photoButtonY; // 430.0

    [self addOverlayButton];
}

#pragma mark Camera Button
- (void)addOverlayButton {
    self.oButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.oButton.frame = CGRectMake(132.0, self.originalOrigin, 56.0, 56.0);
    [self.oButton setImage:[UIImage imageNamed:@"CameraButton56x56.png"] forState:UIControlStateNormal];
    [self.oButton addTarget:self action:@selector(toCameraView:) forControlEvents:UIControlEventTouchUpInside];

    [self.view insertSubview:self.oButton aboveSubview:self.view];
}

// to make the button float over the tableView including tableHeader
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGRect tableBounds = self.tableView.bounds; // should be _magTableView, but works with _tableView as well. But I do not know where this _tableView comes from...
    //CGRect tableBounds = self.magTableView.bounds;

    // floating Button;
    CGRect floatingButtonFrame = self.oButton.frame;
    floatingButtonFrame.origin.y = self.originalOrigin + tableBounds.origin.y;
    self.oButton.frame = floatingButtonFrame;

    [self.view bringSubviewToFront:self.oButton]; // float over the tableHeader
}

ViewController.h
#import <UIKit/UIKit.h>
#import "SingletonClass.h"

@interface DetailViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIButton *oButton;
@property (nonatomic) float originalOrigin;

@end

ViewController.m - Jumping Button, not wanted behaviour (Update: works no, no jumping anymore)
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.originalOrigin = [[SingletonClass sharedInstance] photoButtonY];  // 430.0
    [self addOverlayButton];

    [self initTableView]; // initiate the tableview and works properly
}

#pragma mark Camera Button
- (void)addOverlayButton {
    self.oButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.oButton.frame = CGRectMake(132.0, self.originalOrigin, 56.0, 56.0);
    [self.oButton setImage:[UIImage imageNamed:@"CameraButton56x56.png"] forState:UIControlStateNormal];
    [self.oButton addTarget:self action:@selector(toCameraView:) forControlEvents:UIControlEventTouchUpInside];

    [self.view insertSubview:self.oButton aboveSubview:self.view];
}

/** Remove this function and the button stayed where I expected it
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGRect tableBounds = self.tableView.bounds;

    // floating Button;
    CGRect floatingButtonFrame = self.oButton.frame;
    floatingButtonFrame.origin.y = self.originalOrigin + tableBounds.origin.y;
    self.oButton.frame = floatingButtonFrame;

    [self.view bringSubviewToFront:self.oButton]; // float over the tableHeader
}
*/


text:
Q: Having some doubts about C pointers and memory address I'm really newbie in C and I have this piece of code about LinkedList in C:
struct ListNode* addnode(struct ListNode *head,int val)
{
    struct ListNode* newnode = malloc(sizeof(struct ListNode));
    newnode->val = val;
    newnode->next = NULL;
    if (!head) head = newnode;
    else {
        struct ListNode *this = head;
        while(this->next)
            this = this->next;
        this->next = newnode;
    }
    return head;
}

int main(void)
{
    struct ListNode *head = NULL;

    head = addnode(head,4);
    addnode(head,9);
    addnode(head,1);

    return 0;
}

My question is: in the main why if I write
    addnode(head,4);
    addnode(head,9);
    addnode(head,1);

Instead of
head = addnode(head,4);
    addnode(head,9);
    addnode(head,1);

Doesn't work ? The first one is creating the following linkedlist : 4->9->1, and the second one is creating 3 different Linkedlist heads. But wouldn't it be the same as we are always using the memory address of head ? So the head is always saving his previous node.
Thank you in advance I will appreciate your answers

A: Initially the pointer head is initialized as a null pointer
struct ListNode *head = NULL;

This pointer is passed by value to the function addnode
addnode(head,4);

The function deals with a copy of the value of the pointer head declared in main that is used as an argument expression of the function. Changing the copy does not influence on the original pointer head.
So after the call the pointer head will still be a null pointer.
The function returns the modified value of the copy of the pointer
struct ListNode* addnode(struct ListNode *head,int val)
{
    //...
    if (!head) head = newnode;
    //...
    return head;
}

To change the original pointer head you need to assign the returned value to the pointer head like
head = addnode(head,4);

Now the pointer head points to the first node of the list.
All other calls of the function
addnode(head,9);
addnode(head,1);

append new nodes to the tail of the list. That is these calls do not influence on the value of the pointer that points to the first node of the list. So there is no need to assign the returned value of the function to the pointer head though nevertheless you could write
head = addnode(head,9);
head = addnode(head,1);

To make it more clear consider a very simple example
#include <stdio.h>

int f( int x )
{
    x += 1;

    return x;
}

int main( void )
{
    x = 0;

    f( x );

    printf( "x = %d\n", x );
}

If you will not substitute this statement
    f( x );

for
    x = f( x );

then the variable x will not be changed in main after calling the function f because the function f changes a copy of the value of the variable x   used as the function argument.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Activate toggling on a single button by using bootstrap I would like to activate toggling on a single button by using http://twitter.github.com/bootstrap/javascript.html#buttons
What I would like to do is… to hide/show a view when I click on the button and toggle the state of the button changing his text.
Here is my code (1). It hides/show the view but it does not change the text on the button.
How should I do it using bootstrap?
createToggleButton = function (parentElement) {
    var buttonElement = $(document.createElement('button'));

    buttonElement.text('Customize');
    buttonElement.prop('class', 'btn');
    buttonElement.attr('type', 'button');
    buttonElement.attr('data-toggle', 'button');
    parentElement.prepend(buttonElement);

    buttonElement.on('click', function (event) {
        event.preventDefault();
        $(event.currentTarget).parent('div').find('.control-group').toggle(function () {
            buttonElement.text('new message'); // it changes just the first time,
                               // then I would like to set the original message;
        });
    });
};

A: for your toggle option why don't you do:
$(event.currentTarget).parent('div').find('.control-group').toggle(function(){
    $(this).hide();
    $('.btn').attr('value','First text you want');
},function(){
    $(this).show();
    $('.btn').attr('value','Second text you want');
});


text:
Q: is it possible to lock Sim Card Using Gammu Please help, i need information how to lock my SIM card.
For security purpose i want to lock using new PIN Code.
I operate sim card using modem and access it with gammuservice. Is It possible lock simcard using gammu. if it is not, any bode can explain the alternative. I need lock it programmaticly
thanks for any advice

A: If you know PUK code, it should be possible using:
gammu entersecuritycode PUK currentpuk newpin

See documentation for more details: https://wammu.eu/docs/manual/gammu/index.html#cmdoption-gammu-arg-entersecuritycode


text:
Q: "CompareToIgnoreCase" no funciona Estoy realizando un programa que me compare atributos y me retornen el valor (-1, 0, 1) cuando mis atributos sean o no iguales.
Este es mi código del método:
public int Comparar(CostosImpl CostosRef, CostosImpl CostosHerr, boolean cotizar) {

    if(CostosRef.getConcepto().equalsIgnoreCase(CostosHerr.getConcepto())) {

        if(CostosRef.getReferencia().equalsIgnoreCase(CostosHerr.getReferencia())) {

            if(CostosRef.getReferencia().equalsIgnoreCase("1000")) {

            int equals = CostosRef.getDescripcion().compareToIgnoreCase(CostosHerr.getDescripcion());
            if(equals == 0) {
                equals = CostosRef.getNumeroParte().compareToIgnoreCase(CostosHerr.getNumeroParte());
                if(equals == 0) {
                    if(!cotizar) {
                        return Double.compare(CostosRef.getMonto(), CostosHerr.getMonto());
                    }
                }
                return equals;
            } else
                return equals;
             }
        }
        else {
            int equals = CostosRef.getReferencia().compareToIgnoreCase(CostosHerr.getReferencia());
            if(equals == 0) {
                if(!cotizar) {
                    return Double.compare(CostosRef.getMonto(), CostosHerr.getMonto());
                }
            }
            return equals;
        }
    }
    return 0;

}

Es simple, al inicio solo valida si "Concepto" y "Referencia" son iguales, , si "Referencias" son iguales, se procede a checar si el valor es 1000 y de ahí más proceso...
Mi problema en sí, es que mi programa DEBE retonarme un valor 0 si losa atributos "Concepto" y "Referencia" son iguales.
Estos son mis atributos:
CostosRef.setConcepto("Refaccion");
        CostosRef.setReferencia("1000");
        CostosRef.setMonto(150);
        CostosRef.setDescripcion("ABISAG.SUP.PUER.TRA.D");
        CostosRef.setNumeroParte("67550T9d3AT00ZZ");

        CostosHerr.setConcepto("Refaccion");
        CostosHerr.setReferencia("1000");
        CostosHerr.setMonto(150);
        CostosHerr.setDescripcion("cABISAG.SUP.PUER.TRA.D");
        CostosHerr.setNumeroParte("67550T9d3AT00ZZ");

Como pueden ver, "Referencia" y "Concepto" coinciden, y espero que me retorne un valor 0 y no lo hace, me regresa un negativo.
¿Qué podría agregar?.
Gracias.

A: Solamente es un problema que vos podes solucionar.. Miremos las 3 primeras lineas de tu codigo:
if(CostosRef.getConcepto().equalsIgnoreCase(CostosHerr.getConcepto())) {
    if(CostosRef.getReferencia().equalsIgnoreCase(CostosHerr.getReferencia())) {
        if(CostosRef.getReferencia().equalsIgnoreCase("1000")) {

En este punto, ya sabes que los conceptos son iguales, que las referencias son iguales, y que la referencia es 1000. Entonces aca deberias devolver el 0. Pero tu codigo, sigue haciendo cosas cuando llega a este punto.
Lo que tenes que hacer es revisar tu codigo y seguirlo paso a paso.


text:
Q: getting numbers with comma's added at appropriate place I am trying to get numbers with commas using JavaScript but it's not working. Please check my code and let me know where I went wrong. Please don't mark this question as a duplicate; I know this question has been asked before, but it's not helping me.
Thanks in advance.
Here is what I have tried-
function numberWithCommas() {
  var x = document.getElementById('abc').value;
    x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

html code-
<input type="text"  onblur="calculate(); numberWithCommas()" name="abc" id="abc" placeholder="abc" />

A: I see in your code that onblur you try to initiliaze two functions: calculate() and numberWithCommas(). In your code above the function calculate() is not defined. Make sure that it is in your final code otherwise you will get a Reference Error and the code will not run as you expect.
I made a test and your code seems to work fine regarding numberWithCommas() function. Only you need to assign to the input form the new value in which you add the commas. Please have a look at the code below:
JS
function numberWithCommas() {
  var x = document.getElementById('abc').value;
  var y = x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  document.getElementById('abc').value = y;
}

HTML:
<input type="text"  onblur="numberWithCommas()" name="abc" id="abc" placeholder="abc" />

You can see that I removed the calculate() function because it is not defined in the code you shown. But of course you can use it in case it exists in your final code snippet.
You have a fiddle here with the working example: https://jsfiddle.net/fxduzemx/


text:
Q: nestableSortable vs Nestable JS library I'm trying to create a navigation menu editor comprised of multiple nested, sortable forms that will ultimately be submitted en masse as one giant nested JSON data blob containing all of the form data.
The two libraries I'm examining are nestableSortable (https://github.com/mjsarfatti/nestedSortable) and Nestable (https://github.com/dbushell/Nestable). These two libraries seem to be the most commonly used projects for this type of work, however neither seems to have built-in functionality for serializing and nesting these forms. Right now I'm under the assumption that either library will require me to somehow build this functionality myself.
Nestable appears to be a bit newer and doesn't depend on JQuery-UI, while nestableSortable appears to be a bit more feature-rich. I'm also wondering if anyone has had a similar issue with nested forms and whether they have any tips on how to get either of these libraries to easily serialize nested forms into a JSON structure, and whether either of these libraries is better suited for such a project.

A: If anyone is interested, after further inspection I found that Nestable requires this format in order to work:

Item 1

I wasn't particularly pleased with the idea that the JS library would be so strict regarding required element attributes, as I felt that the Javascript should handle this somewhat independently of the markup. Because of this, I wound up choosing nestedSortable over the Nestable library.
Further, nestedSortable appears to have useable properties for left/right/parent attributes for nodes in the tree, which may be helpful on the server side when performing tree manipulations.

A: I started with nestedSortable and then switched to nestable. I am now switching back to nestedSortable because it is compatible down to IE7 (a project requirement). Yes, it is easy to appreciate the more minimalistic structure of nestable, however, be sure to test with your target browser(s) before committing to either of these (excellent) utilities.
BTW, both have the ability to serialize their data (nestable has one, nestedSortable has multiple).


text:
Q: Examples of zero-dimensional commutative rings with non-discrete Spec? If I'm not mistaken, if the spectrum $\mathrm{Spec}(R)$ (with the Zariski topology) of a commutative ring $R$ is discrete,
then $R$ has Krull dimension zero.
Would anyone know an example of a commutative ring $R$ of Krull dimension zero whose spectrum is non-discrete? Can such a ring be also local and reduced?
Note: If I'm not mistaken: a commutative, reduced, local, von-Neumann-regular ring is a field [cf. this post and its answer], hence its spectrum is a one-point space, which is discrete. So a comm, reduced, local ring with non-discrete spectrum is necessarily not von-Neumann-regular.
(Edit: As a post has pointed out, a commutative, Krull-dimension-zero, local, reduced ring is just a field.)

A: spec(R) is zero dimensional if and only if it is Hausdorff and totally disconnected. So, take a non-discrete, totally disconnected compact Hausdorff space $X$ and let $R=C(X\to\mathbb{Z}_2)$ the algebra of all continuous functions $X\to\mathbb{Z}_2$ with pointwise operations.


text:
Q: actionmailer "from" setting I am using ActionMailer and in my mailer model, I have a from set like this
default :from => "from@example.org"

In my environment.rb, I have a different username within
ActionMailer::Base.smtp_settings = {}

but I'd like the from address to override this.. so that the user sees only that. Is this possible? Additionally, when I change my settings within environment.rb, I don't see my changes take place... do I need to restart my rails server to refresh these settings?
===
here are some of my settings:
ActionMailer::Base.smtp_settings = {
:tls => true,
:address => "smtp.gmail.com",
:port => "587",
:domain => '==.org',
:authentication => :plain,
:user_name => '===',
:password => '==='

}

A: Gmail doesn't let you send as a different user -- it will always make the "From" address the account you're using to sign on (this is for security/spam prevention I believe, that way you can't spoof someone else's address).
Assuming you own the e-mail address(es) you want to send from, there's a way through your Google account to allow sending from those e-mail address(es). Go into the Gmail options, click the "Accounts" section, and click "Add another e-mail address you own."

A: It appears that now it's possible to send emails with a different sender through gmail's SMTP.
I've listed my way to do it here:
Send an email through gmail but configure a different email address


text:
Q: How to crawl in desired order or Synchronously in Scrapy? The problem
I'm trying to create a spider that crawls and scrapes every product from a  store and outputs the results to a JSON file, that includes going into each category in the main page and scraping every product (just name and price), each product class page includes infinite scrolling.
My problem is that each time I make a request after scraping the first page of a class of item, instead of getting the next batch of items from that same type, I get the items from the next category and the output ends up being a mess.
What I've already tried
I've already tried messing with settings and forcing concurrent requests to one and setting different priorities for each request.
I've found out about asynchronous crawling but I can't figure out how to create the requests in order.
Code
import scrapy
from scrapper_pccom.items import ScrapperPccomItem

class PccomSpider(scrapy.Spider):
    name = 'pccom'
    allowed_domains = ['pccomponentes.com']
    start_urls = ['https://www.pccomponentes.com/componentes']

    #Scrapes links for every category from main page
    def parse(self, response):
        categories = response.xpath('//a[contains(@class,"enlace-secundario")]/@href')
        prio = 20
        for category in categories:
            url = response.urljoin(category.extract())
            yield scrapy.Request(url, self.parse_item_list, priority=prio, cb_kwargs={'prio': prio})
            prio = prio - 1

    #Scrapes products from every page of each category
    def parse_item_list(self, response, prio):

        products = response.xpath('//article[contains(@class,"tarjeta-articulo")]')
        for product in products:
            item = ScrapperPccomItem()
            item['name'] = product.xpath('@data-name').extract()
            item['price'] = product.xpath('@data-price').extract()
            yield item

        #URL of the next page
        next_page = response.xpath('//div[@id="pager"]//li[contains(@class,"c-paginator__next")]//a/@href').extract_first()
        if next_page:
            next_url = response.urljoin(next_page)
            yield scrapy.Request(next_url, self.parse_item_list, priority=prio, cb_kwargs={'prio': prio})

Output vs Expected
What it does: Category 1 page 1 > Cat 2 page 1 > Cat 3 page 1 > ...
What I want it to do: Cat 1 page 1 > Cat 1 page 2 > Cat 1 page 3 > ... > Cat 2 page 1

A: This is easy,
Get list of all categories in all_categories, now don't scrape all links, just scrape 1st category link, and once all pages have been scraped for that category, then send request to another category link.
Here is the code, I did not run code so there maybe some syntax error, but logic is what you need
class PccomSpider(scrapy.Spider):
    name = 'pccom'
    allowed_domains = ['pccomponentes.com']
    start_urls = ['https://www.pccomponentes.com/componentes']

    all_categories = []

    def yield_category(self):
        if self.all_categories:
            url = self.all_categories.pop()
            print("Scraping category %s " % (url))
            return scrapy.Request(url, self.parse_item_list)
        else:
            print("all done")

    #Scrapes links for every category from main page
    def parse(self, response):
        categories = response.xpath('//a[contains(@class,"enlace-secundario")]/@href')

        self.all_categories = list(response.urljoin(category.extract()) for category in categories)
        yield self.yield_category()

    #Scrapes products from every page of each category
    def parse_item_list(self, response, prio):

        products = response.xpath('//article[contains(@class,"tarjeta-articulo")]')
        for product in products:
            item = ScrapperPccomItem()
            item['name'] = product.xpath('@data-name').extract()
            item['price'] = product.xpath('@data-price').extract()
            yield item

        #URL of the next page
        next_page = response.xpath('//div[@id="pager"]//li[contains(@class,"c-paginator__next")]//a/@href').extract_first()
        if next_page:
            next_url = response.urljoin(next_page)
            yield scrapy.Request(next_url, self.parse_item_list)

        else:
            print("All pages of this category scraped, now scraping next category")
            yield self.yield_category()


text:
Q: Why the image size in markdown changes after exporting to PDF by Typora I'm writing documents with Markdown in Typora, but I found something strange.
I found that my image got bigger after exporting to PDF.
The code I use in Typora is like below (the contents have no meaning):
## 1

## 2

$$
\frac{1}{2}
$$
sfsdfsdfasfsadfasfasfsafsd

What I saw in Typora, is like below (that's really what I want):
result in Typora
But after exporting to PDF by Typora, I got something like this:
result in PDF
It seems like the pictures were enlarged, and in the second part the layout is completely different.
Can anybody tells me how to fix this problem? I want the layout in the second part in PDF be the same in Typora : picture in left and text/formula in right, or inverly. And how to avoid magnifying the images after exporting to PDF?
I've found a "solution", like exporting to HTML at first, then printing it to PDF. But in this way, the hyperlink will disappear (for example, the hyperlink of the catalogue). So I need a another way. Thanks in advance.


text:
Q: Code Mirror - Make a given line completely greyed out I'm working with Code Mirror and I'm trying to make a given line completely greyed out (so it looks like a comment usually looks like in code editors). So far I've come up with this:
editorDiv = this;

var editor = CodeMirror(function(elt) {
  editorDiv.parentNode.replaceChild(elt, editorDiv);
}, {
  value:       "function myScript(){\n\treturn 100; \n}\n",
  lineNumbers: true,
  readOnly:    "nocursor",
  theme:       "monokai"
});

console.log(editor);

var line = editor.getLineHandle(1);
console.log(line);

editor.addLineClass(line, "text", "greyed-out");

Let's say I want the return 100; line to be greyed out (which is line 2 in the editor and line 1 as per the API). My idea was to add the greyed-out class to this line and having the class be something like:
.greyed-out { color: grey; }

However, this does not work since there are other classes from Code Mirror which have higher priority and overwrite the greyed-out class.
I'm not sure if there's a specific way to do this through Code Mirror's API, or a general way to remove the unwanted attributes from the higher priority classes.
Could someone give me some help with this?

A: The best way to over-ride a rule from another class is to give your selector a higher specificity, for example:
#container .foo-list li .greyed-out { color: grey; }

Alternatively, you could use !important on the rule, but this is considered bad practice and should be avoided where at all possible.
.greyed-out { color: grey !important; }

A: In such case you can use !important:
.greyed-out { color: grey !important; }

However it shuld be avoided and used only if necessary. You can also increase specificity of your styles by extending selector.


text:
Q: Raspberry Pi - More GPIO pins or/and more leds Like the title said, I need more GPIO pins or just a way to control a lot leds
So I need to control more than 40 leds, or even more, anyway more than raspberry pi has GPIO pins. So I know that there is extension board for Raspberry Pi that extends the GPIO, that's one way to solve it. If anyone ever had one can recommend it to me.
Another idea that I got was to use led matrix but instead use the same idea, I mean for example led row 1 and column 4 or so, but the leds won't be in Grid, instead, they will be separated with wires. But the problem, if we want to do like that:
X O X
O X O
X O X

where X is on and O is off, it's not possible. All leds will be lit up, not like in the pattern. If anyone has the solution to one of the ideas then please share it with me, thank you for your time!

A: You want to control lots of LEDs using as few GPIO pins as possible.
Solution
The way to do this is to use a technique called Charlieplexing. The name comes from the inventor, Charlie Allen of the company Maxim, and the technique takes advantage of the feature of GPIO pins that allows them to be changed from outputs to inputs while a program is running. When a pin is changed to be an input, not enough current will flow through it to light an LED or influence other pins connected to the LED that are set as outputs.
use breadboard

for more information go to this link
http://razzpisampler.oreilly.com/ch04.html


text:
Q: unable to change ownership of files I am working out on an answer as given here
https://superuser.com/a/623998/63915
I copied the windowsios to a usb drive
mount -t o loop win.iso /media/usb

but I see permissions problem all the files are owned by root:root
and when I try to do do
sudo chown -R user:user /media/usb/

there is no change in permissions in files of USB
I see following
 ls -l
total 3250
-rwxrwxrwx 1 root root     110 Oct  9 17:11 autorun.inf
drwxrwxrwx 1 root root       0 Oct  9 17:11 docs
drwxrwxrwx 1 root root   40960 Oct  9 17:35 grub
-rwxrwxrwx 1 root root     313 Oct  9 17:25 grub.cfg
drwxrwxrwx 1 root root 1208320 Oct  9 17:13 i386
-rwxrwxrwx 1 root root   45124 Oct  9 17:14 ntdetect.com
-rwxrwxrwx 1 root root    3204 Oct  9 17:13 readme.htm
-rwxrwxrwx 1 root root  260288 Oct  9 17:14 RUFUSLDR
-rwxrwxrwx 1 root root 1310720 Oct  9 17:13 setup.exe
drwxrwxrwx 1 root root       0 Oct  9 17:13 support
-rwxrwxrwx 1 root root  449797 Oct  9 17:16 txtsetup.sif
drwxrwxrwx 1 root root       0 Oct  9 17:13 valueadd
-rwxrwxrwx 1 root root      10 Oct  9 17:13 win51
-rwxrwxrwx 1 root root      10 Oct  9 17:13 win51ip

what went wrong here?

A: chown fails because the mounted file system is fuseblk. So you are trying to write meta data to a file system which the file system does not support (cannot store). You can only change permissions and ownership on a Unix filesystem like  ext3 or ext4.
If you want that mounted point with ownership applied to a specific user/group, specify at the mount time:
mount -o uid=username,gid=groupname /dev/sdb1 /path/to/mount

See also:

*

*https://superuser.com/questions/57092/cant-change-permission-ownership-group-of-external-hard-drive-on-ubuntu

*https://unix.stackexchange.com/questions/73955/unable-to-change-permissions-of-file-system-root


text:
Q: Adding an arrayList to another arrayList in a separate class? I'm having some difficulty adding an arrayList of user details to another arrayList which contains details of each user i create.
I have 2 classes: addUser and Database.
In the addUser class i have the following code:
        JLabel submitButton = new JLabel("Submit: ");
        contentPane.add(submitButton);
        JButton addUser = new JButton("+ Add User");
        addUser.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            addToArray();
            databaseArray.add(app);
            frame.dispose();}});
        contentPane.add(addUser);

        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

    //arraylist of details for a single applicant
    final ArrayList<String> app = new ArrayList<String>();
    public void addToArray()
    {
        appNumber = appNumberField.getText();
        name = nameField.getText();
        date = dateField.getText();
        fileLoc = fileLocField.getText();
        country = countryRefField.getText();
        app.add(appNumber);
        app.add(name);
        app.add(date);
        app.add(fileLoc);
        app.add(country);
    }

in the database class i have the following code:
public class Database
{
    public ArrayList<ArrayList> applicants;

    /**
     * Constructor for objects of class Database
     */
    public Database()
    {
        applicants = new ArrayList<ArrayList>();
    }

    /**
     * adds a new applicant to the database
     */
    public void addApplicant(ArrayList app)
    {
        applicants.add(app);
    }

    public void list()
    {
       int n = applicants.size();
       for(int i = 0; i < n ; i++)
       System.out.println(applicants.get(i));
    }
}

However when i add a user from the addUser class it does not appear when i use the list method in the Database class.
Any help would be appreciated.
Thanks.

A: import java.util.ArrayList;

public class Store {
int appNumber;// = appNumberField.getText();
String name;// = nameField.getText();
int date;// = dateField.getText();
boolean fileLoc;// = fileLocField.getText();
String country;// = countryRefField.getText();

public Store(int appNumbe, String nam, int dat, boolean fileLo,
        String countr) {
    appNumber = appNumbe;
    name = nam;
    date = dat;
    fileLoc = fileLo;
    country = countr;
}

public static void main(String[] args) {

    ArrayList<Store> app = new ArrayList<Store>();
    app.add(new Store(22, "Name", 2, false, "India"));

}
}

I think you should try something like this to store data . It will be easy to insert and retrive .


text:
Q: memory allocation in Stack and Heap This may seem like a very basic question, but its been in my head so:
When we allocate a local variable, it goes into stack. Similarly dynamic allocation cause the variable to go on heap. Now, my question is, is this variable actually lie on stack or heap or we will just a reference in the stack and Heap.
For example,
Suppose I declare a variable int i. Now this i is allocated on the stack. So, when I print the address of i, this will be one of the location on stack? Same question for heap as well.

A: I'm not entirely sure what you're asking, but I'll try my best to answer.
The following declares a variable i on the stack:
int i;

When I ask for an address using &i I get the actual location on the stack.
When I allocate something dynamically using malloc, there are actually TWO pieces of data being stored. The dynamic memory is allocated on the heap, and the pointer itself is allocated on the stack. So in this code:
int* j = malloc(sizeof(int));

This is allocating space on the heap for an integer. It's also allocating space on the stack for a pointer (j). The variable j's value is set to the address returned by malloc.

A: The pointer variable itself would reside on the stack.  The memory that the pointer points to would reside on the heap.
int *i = malloc(sizeof(int));

i would reside on the stack, the actual memory that i points to *i would be on the heap.

A: I agree with Chris. Just another way to explain that. Consider the following code:
int* j = malloc(sizeof(int));
free(j);

Even after using free(j) which should deallocate the memory from the heap, the pointer still exists and we need to explicitly make it NULL. This definitely suggests that there is also a stack counterpart of the pointer otherwise it should have been inexistent after the free command. This stack variable is the one pointing to the address on the heap where the memory was dynamically allocated using malloc.

A: Mr. Eberle's answer is 100% correct, but since Google shows this as the first answer when searching for malloc heap or stack, I have to add that malloc() allocates data on the heap 'most' of the time. If the allocated data was larger than MMAP_THRESHOLD which is usually 128kb on 32-bit systems, malloc() will not use the heap and instead allocates the data in an Anonymous Memory Segment located usually below the stack, growing in the direction of low memory.
This is the same region that dynamically loaded libraries are located (libc.so, etc.). Here's the relevant passage from man malloc:

Normally, malloc() allocates memory from the heap, and adjusts the
  size of the heap as required, using sbrk(2).  When allocating blocks
  of memory larger than MMAP_THRESHOLD bytes, the
         glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2).  MMAP_THRESHOLD is 128 kB by default,
  but is adjustable using  mallopt(3).   Prior  to
         Linux 4.7 allocations performed using mmap(2) were unaffected by the RLIMIT_DATA resource limit; since Linux 4.7, this limit is also
  enforced for allocations performed using mmap(2).

As a practical example, feel free to check the following post. It basically allocates 300kb with malloc() and then runs pmap <PID> to show the relevant memory segment.

A: Hopefully the following is helpful:
void foo()
{
    // an integer stored on the stack
    int a_stack_integer;

    // a pointer to integer data, the pointer itself is stored on the stack
    int *a_stack_pointer;

    // make a_stack_pointer "point" to integer data that's allocated on the heap
    a_stack_pointer = (int*)malloc(10 * sizeof(int));
}

In the case of stack variables, the variable itself (the actual data) is stored on the stack.
In the case of heap allocated memory, the underlying data is always stored on the heap. A pointer to this memory/data may be stored locally on the stack.
Hope this helps.

A: stack or heap are not separate memory, they are memory segments that a running program is allocated by the system, just different ways of organizing data in memory.
So when you get &i, it is a memory address, simple as that.


text:
Q: Why do these two for loops give different results? int num=1025;
for (int i = num; i<1030; System.out.println("i =" + i), i++); //loop 1

System.out.println(""); // for spacing results

for (int i = num; i<1030; System.out.println("i =" + i)) { //loop 2
    i++;
}

You can run them on your java compiler and you would see what am saying.

A: It's the first time I see println in the increment expression of a for loop.
The difference is due to the fact that in the second loop, i++ is performed before the increment expression, so println prints the new value of i.
In the first loop, i is incremented in the increment expression, but after the println, so the previous value of i is printed.

A: Because:

*

*loop1 prints i before it increments it,

*loop2 prints i after it increments it.
In a for loop
  for (<initial> ; <test> ; <post> ) {
       <body>
  }

The loop <body> is executed before the <post> clause of the for loop.  In your examples, you have the increment of i in different places ...

Aside: both forms of your loop are poor style ... with the print statement at that point.  Don't ever do that in real code.

A: This is how your first for loop works:

*

*Initialize i to 1025

*check the condition i<1030

*print and then increment i and then repeat from step above

Note print statement followed by increment of i value.
This is how your second for loop works:

*

*Initialize i to 1025

*check the condition i<1030

*increment i

*Print value of i (note it will be i + 1)  and then repeat from step 2 above.

A: In each iteration of for loop:-

The Boolean expression is evaluated. If it is true, the body of the loop is executed. After the body of the for loop executes, the flow of control jumps back up to the update statement.

Hence for
for (int i = num; i<1030; System.out.println("i =" + i), i++);

First it will execute System.out.println("i =" + i)(1st statement in increment condition of for loop) then it will do i++(2nd statement in increment condition of for loop)
In case of
for (int i = num; i<1030; System.out.println("i =" + i))

First it will execute i++(the body of for loop) then it will run System.out.println("i =" + i) (which is the increment condition in this case)

A: for loop    working is illustrated as below.

    for ( declaration ; condition ; update action ) {
        //for block
    }

below is the order in which the for loop is executed.
1. declaration
2. condition check
3. for block execution
4. update action.
In your case the println statement in second loop is executed after the i++ operator. Hence the value is incremented to 1026 before it is being printed on the console.

A: The for 2nd for loop will treat System.out.println("i =" + i) as your update statement of the for loop and increment in i is done before this execution.
To explain it better consider the structure of any for loop :
for(initialization; Boolean_expression; update){
   //Statements
}
The initialisation step is executed first and only once. Then the next Boolean_expression is evaluated. If found true the body will be executed, if false then the loop terminates.
After the body executes the control jumps back to the update statement and executed.
so in the above code System.out.println("i =" + i) is treated as the update statement and executed last, thats why the output is
i =1025
i =1026
i =1027
i =1028
i =1029
i =1026
i =1027
i =1028
i =1029
i =1030


text:
Q: Get the least value in JavaScript For example we have this code:
var json = {
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    },
    "user3" : {
        "id" : 1
    }
}

I want to get the least id in JavaScript:
"user3" : {
        "id" : 1
}

How to get the least id in object via JavaScript?
Please Help!
Thanks ;)

A: Could do something like..
var min = null;
var obj = null;
for (var i in json) {
    if (json.hasOwnProperty(i)) {
        if (min === null || json[i].id < min) {
            min = json[i].id;
            obj = json[i];
        }
    }
}


text:
Q: Word 2007 multiple BeforeClose event handling I have office 2007 installed on the windows 7 platform.
In the Word application exists our supplier's add-in that catches BeforeClose document event and asks customer the question before exitting.
Now, I developed MY custom add-in that also catches BeforeClose document event and performs some operation.
The question is: HOW can I control, which of the "catching" will perform FIRST and which SECOND?
I need that MY add-in will work first and the supplier code will work after me, before the documnet will closed.
Thanks a lot in advance,
Milo

A: The only thing I can see would be the loading order of the addins. You might need to "name" your addin file so it loads first (not sure there is another way), then check if it effectively triggers first on all you system configurations.


text:
Q: /wikipedia/en_id not working on MQL query Does anybody know why is this query not working? It was yesterday:
[{  "mid": "/m/02_286",  "key": {
"namespace": "/wikipedia/en_id",    "value": null  }}]

I get this response
{  "result": []}

I want to obtain the ID 38252 so I can obtain a wikipedia link like this:
http://en.wikipedia.org/wiki/index.html?curid=38252
You can see further details here: https://developers.google.com/freebase/v1/mql-cookbook
You can take a look to the query here
EDIT :
I noticed that with Paris there is an "en_id" key https://www.freebase.com/m/02_286?keys= but with New York city there is no "en_id" key https://www.freebase.com/m/02_286?keys=. Its weird because there was an id a couple of days ago...
Thanks!

A: That's not the topic where the /wikipedia/en_id/38252 key lives.  You can find this out by reversing your query like here
{
  "mid": null,
  "name": null,
  "key": {
    "namespace": "/wikipedia/en_id",
    "value": "38252"
  }
}

The topic that you are looking for is https://www.freebase.com/m/09jm8
Your original query is fine.  It's just that that particular topic doesn't have a /wikipedia/en_id key.  It did up until June 17, as you can see by looking at the historical view:
https://www.freebase.com/m/02_286?keys&lang=en&filter=%2Ftype%2Fobject%2Fkey&historical=true
This is probably a data bug, but you can't fix it by changing your query.


text:
Q: ImportError: no module named BeautifulSoup or BeautifulSoup4 - Python On MacOS, I installed homebrew, then installed pip.
Trying to use a Python scraper that uses "BeautifulSoup" package.
Ran: pip install -r requirements.txt
requirements.txt includes:
BeautifulSoup
ipython

BeautifulSoup gives an error, after googling I realized that there is a new version. so I ran:
pip install beautifulsoup4

seems to have installed correctly. Then I ran the scraping script and I got the following error:
Traceback (most recent call last):
  File "scrape.py", line 3, in <module>
    from BeautifulSoup import BeautifulSoup
ImportError: No module named BeautifulSoup

I tried changing BeautifulSoup to BeautifulSoup4 in the script, but it is the same error.
Anything else I can try?
This is the script I am trying to use: https://github.com/jojurajan/wp-content-scraper

A: This is essentially because beautifulsoup4 has a different interface to
its previous versions.
The old version exposes a module named BeautifulSoup.
from BeautifulSoup import BeautifulSoup

The new way to import the module in Python would be.
from bs4 import BeautifulSoup

However, it seems that you are using a scraper written by someone else relying on the old BeautifulSoup. To solve this you have to install the old version.
Maybe you can share the complete requirements.txt and we will see what is the version it's using.

A: The code in question was created by me. The scraper uses Python 2.7 and older version of BeautifulSoup. It was a mistake on my part to not mention the Python version and BeautifulSoup version in requirements.txt. Newbie mistakes while releasing code into the wild. :)
I have updated the README to specify about the supported Python version.


text:
Q: How to execute python from C++ I have a C++ program that needs to make certain calls to a library which is written in Python.  (As opposed to rewriting the entire library in C++...)
What's the simplest way to do this?  I need to pass 2 numbers into the library, and get 2 numbers back.
I need it to be portable and run in both Windows and Linux, so for example using POSIX popen is not possible.
So far the best solution I have is to write a python wrapper, called by a "system" call in the C++ code, that takes command line parameters, calls the function, and writes the result to a file, which is then opened by the C++ program.
If you know anything better please let me know...

A: If boost is an option, you can use boost.python : embedding

A: You can directly embed the python interpreter into your application. See the official documentation for a full explanation.


text:
Q: Efficiently transforming many different models in modern OpenGL Suppose I want to render many different models, each with a different transformation matrix I want to be applied to their vertices. As far as I understand, the naive approach is to specify a matrix uniform in the vertex shader, the value of which is updated for each mesh during rendering.
It's obvious to me that this is a bad idea, due to the expense of many uniform updates and draw calls. So, what is the most efficient way to achieve this in modern OpenGL?
I've genuinely tried to find a straight, clear answer to this question. Most answers I find vaguely mention UBOs, or instance drawing (which afaik won't work unless you are drawing instances of the same mesh many times, which is not my goal).

A: With OpenGL 4.6 or with ARB_shader_draw_parameters, each draw in a multi-draw rendering command (functions of the form glMultiDraw*) is assigned a draw index from 0 to the number of draw calls specified by that function. This index is provided to the Vertex Shader via the gl_DrawID input value. You can then use this index to fetch a matrix from any number of constructs: UBOs, SSBOs, buffer textures, etc.
This works for multi-draw indirect rendering as well. So in theory, you can have a compute shader operation generate a bunch of rendering commands, then render your entire scene with a single draw call (assuming that all of your objects live in the same vertex buffers and can use the same shader and other state). Or at the very least, a large portion of the scene.
Furthermore, this index is considered dynamically uniform, so you can also use it (or values derived from it and other dynamically uniform values) to index into arrays of textures, fetch a texture from an array of bindless textures, or the like.


text:
Q: Is the complement of interval graph an interval graph also? In Graph Theory, IG is an interval graph, then the question is: Is the complement of IG also an interval graph? if so, then  how can we prove it?

A: No, this is not true. The complement of this graph is not an interval graph (It is $C_4$), while the graph itself is an interval graph:


text:
Q: How to split a string for key value pairs and save them to a dictionary? I have the below code which works fine to split a string and save key value pairs into a dictionary. Is there a more elegant and efficient way to do the same? Thank you!
    private void SplitString()
    {
        string testConfig = "application?test1=value1&test2=value2&test3=value3";

        var dict = new Dictionary<string, string>();

        if (!string.IsNullOrEmpty(testConfig) && testConfig.Contains("?"))
        {
            string parameters = testConfig.Substring(testConfig.LastIndexOf("?") + 1);

            string[] parameterArray = parameters.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            if (parameterArray.Length > 0)
            {
                foreach (var item in parameterArray)
                {
                    string[] param = item.Split(new char[] { '=' });

                    if (param.Length == 2)
                    {
                        switch (param[0].ToUpper())
                        {
                            case "TEST1":
                                dict.Add("TEST1", param[1]);
                                break;
                            case "TEST2":
                                dict.Add("TEST2", param[1]);
                                break;
                            case "TEST3":
                                dict.Add("TEST3", param[1]);
                                break;
                        }
                    }
                }
            }
        }
    }

A: It looks like you are trying to split a query string into a dictionary of query parameters. You should be able to use the HttpUtility.ParseQueryString method. Note that this method returns a NameValueCollection. That object will probably work for you, but if you need a Dictionary, you can use a simple for loop to convert the NameValueCollection to a Dictionary.
Also, if you decide for whatever reason to stick with your original code, you can greatly simplify this code:
switch (param[0].ToUpper())
{
    case "TEST1":
        dict.Add("TEST1", param[1]);
        break;
    case "TEST2":
        dict.Add("TEST2", param[1]);
        break;
    case "TEST3":
        dict.Add("TEST3", param[1]);
        break;
}

You don't need a separate case for each possible value. Instead, you can simply write this:
dict.Add(param[0].ToUpper(), param[1]);


text:
Q: css border-bottom out of control echo '

'.$result['title'].'
<object class="video" width="95%" height="55%">
        <param name="movie" value="http://www.youtube.com/v/'.$match[0].'?fs=1&hl=en_US&rel=0">
        </param><param name="allowFullScreen" value="true"></param>
        <param name="allowscriptaccess" value="always"></param>
        <embed src="http://www.youtube.com/v/'.$match[0].'?fs=1&hl=en_US&rel=0"
        type="application/x-shockwave-flash" wmode="opaque" allowscriptaccess="always"
        allowfullscreen="true" width="95%" height="55%"></embed></object>
'.$result['description'].'

';

why does .post {border-bottom:2px black solid;} displays border at the top of the paragraph?
you don't believe me, try it for urself HERE

A: It doesn't, you're just doing it wrong. There's no text in the
 node for it to be under, and you've got a bottom margin defined. See the screenshot I'm about to upload.

A: You shouldn't be nesting p tags.  Be sure your markup is correct.
Nested p tags will render as separate p tags.
Since you have nested p tags, your markup looks like this when rendered to the browser:

hobotnica zajebant

<object>...</object>

...

A: In addition to what these fellas said.  If you don't have content or a height defined of an element, it will appear just like, so it's doing what it's supposed to.
You can add a padding/margin/height to your
 if you want that to appear different.  Or put it on the element containing your movie, rather than the empty


text:
Q: DocuSign API Set Signer Language Not Working for First Signer In my tests so far when creating and sending an envelope using the DocuSign API v2.1 it is not respecting the setting for the supportedLanguage for the first signer, but does for the 2nd signer.
Here's the JSON for Signers array that I'm using:
"signers" :
    [
        {
            "email" : "test@acme.com",
            "emailNotification" :
            {
                "emailBody" : "",
                "emailSubject" : "Please Sign the Agreement",
                "supportedLanguage" : "de"
            },
            "name" : "Elisabeth Kiefer",
            "recipientId" : "1",
            "routingOrder" : "1",
            "tabs" :
            {
                "dateSignedTabs" :
                [
                    {
                        "anchorIgnoreIfNotPresent" : false,
                        "anchorString" : "/DateSigned1/",
                        "anchorUnits" : "pixels",
                        "anchorXOffset" : "0",
                        "anchorYOffset" : "0",
                        "documentId" : "1",
                        "locked" : "false",
                        "name" : "Date Signed",
                        "pageNumber" : "1",
                        "tabLabel" : "Data Signed",
                        "value" : ""
                    }
                ],
                "fullNameTabs" :
                [
                    {
                        "anchorIgnoreIfNotPresent" : false,
                        "anchorString" : "/SigName1/",
                        "anchorUnits" : "pixels",
                        "anchorXOffset" : "0",
                        "anchorYOffset" : "0",
                        "documentId" : "1",
                        "locked" : "false",
                        "name" : "Name",
                        "pageNumber" : "1",
                        "tabLabel" : "Name",
                        "value" : ""
                    }
                ],
                "signHereTabs" :
                [
                    {
                        "anchorIgnoreIfNotPresent" : false,
                        "anchorString" : "/Signature1/",
                        "anchorUnits" : "pixels",
                        "anchorXOffset" : "0",
                        "anchorYOffset" : "0",
                        "documentId" : "1",
                        "locked" : "false",
                        "name" : "Sign Here",
                        "pageNumber" : "1",
                        "tabLabel" : "Signature",
                        "value" : ""
                    }
                ]
            }
        },
        {
            "email" : "test2@random.com",
            "emailNotification" :
            {
                "emailBody" : "",
                "emailSubject" : "Please Sign the Agreement",
                "supportedLanguage" : "es"
            },
            "name" : "Fabio Gallego",
            "recipientId" : "2",
            "routingOrder" : "1",
            "tabs" :
            {
                "dateSignedTabs" :
                [
                    {
                        "anchorIgnoreIfNotPresent" : false,
                        "anchorString" : "/DateSigned2/",
                        "anchorUnits" : "pixels",
                        "anchorXOffset" : "0",
                        "anchorYOffset" : "0",
                        "documentId" : "1",
                        "locked" : "false",
                        "name" : "Date Signed",
                        "pageNumber" : "1",
                        "tabLabel" : "Data Signed",
                        "value" : ""
                    }
                ],
                "fullNameTabs" :
                [
                    {
                        "anchorIgnoreIfNotPresent" : false,
                        "anchorString" : "/SigName2/",
                        "anchorUnits" : "pixels",
                        "anchorXOffset" : "0",
                        "anchorYOffset" : "0",
                        "documentId" : "1",
                        "locked" : "false",
                        "name" : "Name",
                        "pageNumber" : "1",
                        "tabLabel" : "Name",
                        "value" : ""
                    }
                ],
                "signHereTabs" :
                [
                    {
                        "anchorIgnoreIfNotPresent" : false,
                        "anchorString" : "/Signature2/",
                        "anchorUnits" : "pixels",
                        "anchorXOffset" : "0",
                        "anchorYOffset" : "0",
                        "documentId" : "1",
                        "locked" : "false",
                        "name" : "Sign Here",
                        "pageNumber" : "1",
                        "tabLabel" : "Signature",
                        "value" : ""
                    }
                ]
            }
        }
    ]

You can see that the first signer's supportedLanguage is set to "de" and the second signer is set to "es". When I receive the emails for these and view the document only the second signer has the language set for the website and email. The first signer has everything in English and not German as expected.

A: The language setting is superseded by the user's selected lang that comes from the account.
So, you may want to change the email address to both to some random/unused emails that you know for sure are not part of any account user and check again.
There's no way for you to force the languages of the enduser, they can always overwrite your selection.


text:
Q: How do programming languages call code written in another language? Sorry if this is too vague. I was recently reading about python's list.sort() method and read that it was written in C for performance reasons.
I'm assuming that the python code just passes a list to the C code and the C code passes a list back, but how does the python code know where to pass it or that C gave it the correct data type, and how does the C code know what data type it was given?

A: Python can be extended in C/C++ (more info here)
It basically means that you can wrap a C module like this
#include "Python.h"

// Static function returning a PyObject pointer
static PyObject *
keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
// takes self, args and kwargs.
{
    int voltage;
    // No such thing as strings here. Its a tough life.
    char *state = "a stiff";
    char *action = "voom";
    char *type = "Norwegian Blue";
    // Possible keywords
    static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

    // unpack arguments
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
                                     &voltage, &state, &action, &type))
        return NULL;
    // print to stdout
    printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
           action, voltage);
    printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);

    // Reference count some None.
    Py_INCREF(Py_None);
    // return some none.
    return Py_None;
}
// Static PyMethodDef
static PyMethodDef keywdarg_methods[] = {
    /* The cast of the function is necessary since PyCFunction values
     * only take two PyObject* parameters, and keywdarg_parrot() takes
     * three.
     */
    // Declare the parrot function, say what it takes and give it a doc string.
    {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
     "Print a lovely skit to standard output."},
    {NULL, NULL, 0, NULL}   /* sentinel */
};

And using the Python header files it will define and understand entry points and return locations in the C/C++ code.

A: I can't speak to Python/C interaction directly, but I can give some background to how these sorts of things work in general.
On a particular platform or implementation, there is a calling convention that specifies how parameters are passed to subroutines and how values are returned to the caller. Compilers and interpreters that target that platform or implementation generate code to conform to that convention, so that subroutines/modules/whatever written in different languages can communicate with each other.
In my assembly class, we had an assignment where we had to write a program using VAX assembler, C, and Pascal (this was in the mid-Cretaceous1980s).  The driver was in one of C or Pascal (can't remember which anymore), which called the assembly routine, which called the other routine (which was written in whichever language the driver wasn't).  Our assembly code had to pop and push parameters from the stack based on the VMS calling convention.

A: Each computing platform has (or should have) an application binary interface (ABI). This is a specification of how parameters are passed between routines, how values are returned, what state the machine should be in and so on.
The ABI will specify things such as (for example):

*

*The first integer argument (up to some number of bits, say 32) will be passed in a certain register (such as %EAX or R3). The second will be passed in another specific, register, and so on.

*After the list of register is used, additional integer arguments will be passed on the stack, starting at a certain offset from the value of the stack pointer when the call is made.

*Pointer arguments will be treated the same as integer arguments.

*Floating-point arguments will be passed in floating-point registers F1, F2, and so on, until those registers are used up, and then on the stack.

*Compound arguments (such as structures) will be passed as integer arguments if they are very small (e.g., four char objects in one structure) or on the stack if they are large.

Each compiler or other language implementation will generate code that conforms to the ABI, at least where its routines call or are called from other routines that might be outside the language.


text:
Q: how to generate unrepeating random layouts public class Music extends Activity {
    private int [] layouts = {
            R.layout.question_selector,
            R.layout.question_selector2,
            R.layout.question_selector3,
            R.layout.queston_selector4,
            R.layout.question_selector5,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        int i = layouts.length;
        Random r = new Random();

        while (--i > 0) {
            int j = r.nextInt(i + 1);

            //swap values
            int temp = layouts[j];
            layouts[j] = layouts[i];
            layouts[i] = temp;

        }
        setContentView(layouts[i]);
    }
}

Here's what i have done so far: it works just fine, but I have notice that there are times that some layouts are shown over and over again. What I want is that when I press the button and it generates a layout randomly, the next time I'll press the button again it should not repeat the layout that had been shown before. How can I do such thing?

A: You can create an arrayList and then shuffle it instead of an array with Random, this will make it random but only use every item once
EDIT, code example:
     ArrayList<int> mArrayList = new ArrayList<int>;
        //OR ArrayList<int> mArrayList = new ArrayList<int>(Arrays.asList(mOrdinaryArray));
     mArrayList.put(R.blabla.blabla);
     mArrayList.put(R.blabla.blablatwo);
     Collections.shuffle(mArrayList);
     Log.d(TAG, "output after shuffle: " + mArrayList);


text:
Q: trying to locate output file from postgresql \o -o command I am making an automated script from terminal that creates a file with the output of \l
But I do not know where the \o command in postgresql prints out the file that it has made. The documentation doesn't inform where.
I did read this, but no luck:
Sincerely

A: \o points at the named file in current working directory of psql.  As you found out, this has some issues in automated environments.
This means you have basically two options:

*

*use absolute paths with \o

*Alternatively you can use \cd to set your current working directory inside your psql script.

In your particular case, however, you know that psql -l gives you the same info?  That may be easier to manage in an automated environment.


text:
Q: How can I plot the output of a PD compensator in matlab? I have a simple PD compensator in a control loop. I want to see the compensator output step response. My code looks like this:
plant = tf(820,[0.08 1 0])

% PD Compensator
Kp = 2.25;
Ki = 0;
Kd = 0.025;
comp_pd = pid(Kp, Ki, Kd)

% plant with pd compensator
plant_pd = feedback(comp_pd*plant,1);
% pd compensator output
pd_output=feedback(comp_pd,plant);

figure();
step(plant_pd)
step(pd_output)
grid on;
ylim([-12 12]);
xlim([0 0.1]);

When I run the code, I get this error:
Error using DynamicSystem/step (line 95)
Cannot simulate the time response of models with more zeros than poles.

How can I plot the compensator output?

A: That's because, as the error message suggests, the transfer function of an ideal PD compensator is not "proper" and cannot be represented or simulated.
To work around this issue, it is common to practice to have an "approximate derivative" term, so that instead of having:
comp_pd = Kp + Kd*s

You have something like
comp_pd = Kp + Kd*s/(1+Tf*s)

This is the relevant section of the documentation on the topic:

So in your code, simply replace:
comp_pd = pid(Kp, Ki, Kd)

by
comp_pd = pid(Kp, Ki, Kd, Tf)

where Tf is small, say 1e-3 although you may have to experiment until you find the right value depending on the time constant of your system.


text:
Q: Switching between activities using different recycler views from two activities I have two activities which are MainActivity and AnotherActivity and each activity has their own recyclerview. What I want to achieve is that if I'm in MainActivity and I click a recyclerview cell, then I should go to AnotherActivity and vice versa. The problem I have is that I don't know how to tell what activity is currently running so that I can manipulate it in if condition wherein if the activity running is MainActivity then I should redirect to AnotherActivity.
MainActivity.java
public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
String[] list = {"COLLECTIONS", "NOW PLAYING", "ADD PLAYLIST", "LOVE SONGS"};
public int activityNum = 0;

public final static String TAG = MainActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
    RecyclerAdapter adapter=new RecyclerAdapter("main", list, list, MainActivity.this);
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));

    Log.i(TAG, TAG);
  }
}

AnotherActivity.java
public class AnotherActvity extends AppCompatActivity {

RecyclerView recyclerView;
String[] list = {"Iridescent", "Bohemian Rhapsody", "November Rain", "I Love You"};
public int activityNum = 1;

public final static String TAG = MainActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_another);

    recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
    RecyclerAdapter adapter=new RecyclerAdapter("another", list, list, AnotherActvity.this);
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(AnotherActvity.this));

    Log.i(TAG, "AnotherActvity");
  }
}

RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {

LayoutInflater inflater;
String page;
String[] menu_list;
String[] song_title;
int returnVar = 0;

public RecyclerAdapter(String page, String[] menu_list, String[] menu_icons, Context context) {
    inflater= LayoutInflater.from(context);
    this.menu_list = menu_list;
    this.page = page;
}

public RecyclerAdapter(String page, String[] song_title, String[] song_artist, String[] song_duration, Context context) {
    inflater=LayoutInflater.from(context);
    this.song_title = song_title;
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = null;
    RecyclerViewHolder viewHolder = null;

    if(page == "main") {
        view = inflater.inflate(R.layout.main_list, parent, false);
        viewHolder = new RecyclerViewHolder(view);
    }else if(page == "another"){
        view = inflater.inflate(R.layout.another_list, parent, false);
        viewHolder = new RecyclerViewHolder(view);
    }
    return viewHolder;
}

@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
    if(page == "main") {
        holder.item.setText(menu_list[position]);
        holder.imageView.setTag(holder);
    }else if(page == "another") {
        holder.item.setText(menu_list[position]);
        holder.imageView.setTag(holder);
    }
}

public void setLength(int returnVar) {
    this.returnVar = returnVar;
}

public int getLength() {
    return this.returnVar;
}

@Override
public int getItemCount() {
    if(page == "main") {
        setLength(menu_list.length);
    }else if(page == "another") {
        setLength(menu_list.length);
    }
    return getLength();
  }
}

RecyclerViewHolder.java
public class RecyclerViewHolder extends RecyclerView.ViewHolder {

TextView item;
ImageView imageView;
boolean lala = false;

public RecyclerViewHolder(final View itemView) {
    super(itemView);

    item = (TextView) itemView.findViewById(R.id.list_title);
    imageView = (ImageView) itemView.findViewById(R.id.list_avatar);

    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
  }
}

A: As in onCreateViewHolder method inflating layout according to page String, so just add one more parameter to RecyclerViewHolder of String type and pass page:
public RecyclerViewHolder(final View itemView,final String page) {
    super(itemView);
    ...
    @Override
        public void onClick(View v) {
            if(page.equals("main")){
              // start MainActivity Activity here
             }else{
              // start AnotherActvity Activity here
             }

        }
}

And pass page to RecyclerViewHolder constructor when creating object in onCreateViewHolder:
viewHolder = new RecyclerViewHolder(view,page);

NOTE:
Use String.equals or equalsIgnoreCase instead of == for comparing String values currently == is used in RecyclerViewHolder and onBindViewHolder for comparing Strings


text:
Q: Exit code: 3221225477 working with tdbc::mysql testing this script (parameters are not real, of course):
package require tdbc::mysql

tdbc::mysql::connection create test_conn -user test_admin -passwd test_passw -db test -host www.test.com -port 3306
set consulta "SELECT * FROM entes"
set sentencia [test_conn prepare $consulta ]
$sentencia foreach row {
puts $row
}
$sentencia close
test_conn close

I get this

Exit code: 3221225477

However, using this
puts [test_conn evaldirect $consulta ]

i get the right lists.
So, is something wrong with "prepare" or have i made a mistake ?
Thanks,
Alejandro


text:
Q: About threading in .NET Below is a code sample presenting the design of a Windows form I use in a Windows CE application.
We are having some unresolved problems in our application, and I suspect that the problem comes from the thread used here as background worker (since the class BackgroundWorker is not available in Windows CE).
You can see that a lock object is used to prevent multiple instances of MyWorker.
Is it the right way to prevent multiple instances of such "worker"? Would it work as expected? Would a singleton worker be better?
public class MainForm : Form {
    private object myLock = new Object();
    private bool isWorkerStarted = false;

    private Thread worker;

    public MainForm() {
    }

    public void btn_Click() {
        lock(myLock) {
            if(!isWorkerStarted) {
                MyWorker worker = new MyWorker();
                worker.StartEvent  = new EventHandler(ThreadStart);
                worker.EndEvent = new EventHandler(ThreadStop);
                workerThread = new Thread(worker.DoWork);

                workerThread.Start();

                isWorkerStarted = true;
            }
        }
    }

    public void ThreadStart(object sender, EventArgs args) {
        lock(myLock) {
            isWorkerStarted = true;
            // Invoke some delegate to interact with the window
        }
    }

    public void ThreadStop(object sender, EventArgs args) {
       lock(mylock) {
           isWorkerThread = false;
       }

       this.Invoke(new NewFormDelegate(OpenForm));
    }

    private void OpenForm() {
       AnotherWindowForm awf = new AnotherWindowForm();
       awf.Show();
       this.Close();
    }

    //******************
    // Worker class
    //******************
    public class MyWorker() {
        public event EventHandler StartEvent;

        public void OnStart() {
            if(StartEvent != null) {
                    StartEvent(this, new EventArgs());
            }
        }

        // Edit 2011-07-19
        public void OnEnd() {
           if(EndEvent != null) {
                    EndEvent(this, new EventArgs());
           }
        }

        public void DoWork() {
            OnStart();
            // Do some work.
            OnEnd();
        }
    }

}
Edit 2011-07-19
Here are more details about the goal of the project.
We have a Windows form with only one button on a Windows CE device. When the user clicks on the button, a worker thread must be started requesting a WCF service. During the execution of the thread, the little hourglass indicates to the user that the program is busy. When the worker is done (i.e. when he receives a "good" answer), it must stops and open another Windows form on the top of the current one (for that purpose I'm using the method Invoke to delegate the creation of the new form).
The only requirement is that the user should not be able to run two workers (for example by clicking two times on the button). And the facts are that sometimes, we can see that two workers are making requests to the WCF service from the same device.

A: I would not use lock() in this case.  If the background worker is already running, the main GUI thread will sit on that lock until the other thread has finished.
I would recommend instead using a Mutex.  This way you can set it to automatically skip over the section if it's already locked.
So you should do something like:
Mutex mtx = new Mutex();

public void btn_Click() {
   if ( mtx.WaitOne(0) == true )
   {
       //Do your stuff
   }
   else
   {
       //Let user know you can't do this yet?  Or, queue it up?  Or, why
       // can the user click this button if they can't do anything anyway?
   }
}

You'll need to do a mtx.Release() whenever your thread is done doing its stuff.

A: You don't need to use a lock here at all as the btn_Click method will only be called by the UI thread (unless you explicitly call it from another thread which would be bad).
So the code only needs a null check to ensure you only have one worker thread created.
public class MainForm : Form
{
    private Thread workerThread = null;

    public MainForm()
    { }

    public void btn_Click()
    {
        if (workerThread == null)
        {
            var worker = new MyWorker();
            worker.StartEvent += (s, e) =>
            {
                //Invoke some delegate to interact with the window
            };
            workerThread = new Thread(worker.DoWork);
            workerThread.Start();
        }
    }
}

EDIT: In response to a comment from the OP.
public class MainForm : Form
{
    private Thread workerThread = null;

    public MainForm()
    { }

    public void btn_Click()
    {
        if (workerThread == null || workerThread.IsAlive == false)
        {
            var worker = new MyWorker();
            worker.StartEvent += (s, e) =>
            {
                //Invoke some delegate to interact with the window
            };
            worker.EndEvent += (s, e) =>
            {
                //Clean up
            };
            workerThread = new Thread(worker.DoWork);
            workerThread.Start();
        }
    }
}

And MyWorker now looks like this:
public class MyWorker
{
    public event EventHandler StartEvent;
    public event EventHandler EndEvent;

    public void OnStart()
    {
        var se = this.StartEvent;
        if (se != null)
        {
            se(this, new EventArgs());
        }
    }

    public void OnEnd()
    {
        var ee = this.EndEvent;
        if (ee != null)
        {
            ee(this, new EventArgs());
        }
    }

    public void DoWork()
    {
            this.OnStart();
            // do some work
            this.OnEnd();
    }
}


text:
Q: Save method not working in laravel controller with no error message I'm in a situation that i still couldn't figure out how to solve.
I have a function in a Laravel controller that ends in save, everything goes nice and i got no errors but the data don't go to the DB.
I already made a lot of tests and everything is as expected but don't persist the data.
Can someone help me?
I've looked in a lot of places and didn't find anything that could help me, find some things about the id typo but is not my case.
Here's the function in the controller:
public function saveCodeList(Request $request)
{
    try{
        \DB::beginTransaction();
        $input = $request->all();

        foreach ($input as $i){
            $pecaId = $this->TecmanutencaoPecaM
                ->where('peca', $i['peca'])
                ->select('id')
                ->first();

            if($pecaId){
                $codPeca = new TecManutencaoEstoqueCodPeca();
                $codPeca->idPeca = $pecaId->id;
                $codPeca->codigo = $i['codigo'];
                $codPeca->emEstoque = 's';

                if ($codPeca->save()) {
                    return response()->json('salvo', 200);
                } else {
                    return response()->json('Erro ao salvar');
                }
            }  elseif ($i['codigo'] !== null || $i !== '') {
                return response()->json('Sem códigos a adicionar', 200);
            }
        }

        \DB::commit();
    } catch (\Exception $e){
        \DB::rollback();
        return response()->json($e.'erro');
    }
}

I'm using Vue in the frontend.
Any help will be most appreciated.
Thanks in advance.

A: You are committing the database after you have a returned a response, as a result you are never actually committing the transaction to the database. You could solve this by making sure you commit the transaction before returning the json response.
For example:
if ($codPeca->save()) {
    \DB::commit();
    return response()->json('salvo', 200);
} else {
    ...


text:
Q: Footnotes repeated erroneously in Beamer (when compiled with notes) Consider the following MWE:
\documentclass{beamer}
%\setbeameroption{show notes on second screen}

\begin{document}
    \begin{frame}{Why are \protect\emph{we}\footnote[frame]{The Steering Council} here?}
    \note{A few presenter's notes.}
        \begin{itemize}
            \item We are looking for \emph{new ways} to ...
\pause      \item We search for strategies, which ...
\pause      \item The Steering Council is the body that coordinates ...
        \end{itemize}
    \end{frame}
\end{document}

Works as expected, until I uncomment the option to show notes on the second screen:

Can anybody explain?


text:
Q: How do I generate a table similar to this and fit to page
I was wondering how I would generate a table similar to one shown and fit it to the page.

A: For a more practical MWE, I add the two longest cells to test. I chose the first column to be p{6em}, that's, large enough for two words like power control and use tabularx and ragged2e as also suggested by others.
\documentclass[a4paper]{article}
\usepackage{tabularx,ragged2e}
\usepackage{booktabs,array,times}
\usepackage[margin=1in]{geometry}
\begin{document}

\newcolumntype{L}{>{\RaggedRight\arraybackslash}X}

\begin{table}\centering
\caption{My caption}
\label{my-label}
\begin{tabularx}{\linewidth}{@{}p{6em}LL@{}}
\toprule
        & \multicolumn{1}{c}{Conventional Power Plant} & \multicolumn{1}{c}{Wind Power Plant}                                                                                \\ \midrule
Topology                                               & One or a few large generating units, each unit could be rated at 40 to 1000 MW+ & Typically hundreds of small generators deployed over a large area, each unit could be rated at 1 to 5 MW Wind turbines                   \\
. . .                                                  & . . .                & . . .                                                                                \\
Reactive power control & Units are equipped with an automatic voltage regulator, typically set for voltage control & Reactive power is managed at the plant level, through coordinated control of wind turbine control and/or plant-level reactive compensation\\ \bottomrule
\end{tabularx}
\end{table}

\end{document}

A: Using the packages tabularx, booktabs and, as an option, ragged2e you can easily achieve the desired result.
\documentclass{article}

\usepackage{tabularx}
\usepackage{booktabs}
\usepackage{ragged2e}

\newcolumntype{L}{>{\RaggedRight\arraybackslash}X}

\begin{document}

\begin{flushleft}
\begin{tabularx}{\linewidth}{lLL}
\toprule
&
\multicolumn{1}{c}{Conventional Power Plant} &
\multicolumn{1}{c}{Wind Power Plant} \\
\midrule
Topology &
Once or a few large generating units, each unit could be rated \dots &
Typically hundreds of small generators deployed over a large area, each unit \dots \\
Prime mover &
\dots &
\dots \\
\bottomrule
\end{tabularx}
\end{flushleft}

\end{document}

A: Load tabularx and booktabs and use
\begin{tabularx}{\linewidth}{@{}l*{2}{>{\arraybackslash}X}@{}}
\toprule\midrule
.................................................... \\
\midrule
....................................................
....................................................
.................................................... \\
\midrule\bottomrule

You can add some padding between rules with
\\
\addlinespace

A: Like all the preceding answers do, I would highly recommend you look into using the tabularx environment and its main column type, called X, which allows automatic line-wrapping and expands in width as needed to fill up the available (horizontal) space. And, like the other answers do, I would load the booktabs package to generate well-spaced horizontal rules.
Looking at the template provided, I think there's one thing that's missing: automatic hanging indentation of lines beyond the first line. This idea is implemented below. Separately, I also wouldn't center the two headers; left-alignment works just as well (and, arguably, even better).

\documentclass{article}
\usepackage[english]{babel}
\usepackage[letterpaper,margin=1in]{geometry} % set page size parameters

\usepackage{tabularx,booktabs,ragged2e,
            newtxtext,newtxmath}
\newcolumntype{Y}{>{\RaggedRight\arraybackslash
     \hangafter1\hangindent1em}X}
\newcolumntype{q}[1]{>{\raggedright
     \hangafter1\hangindent1em}p{#1}}

\newlength\mylen
\settowidth\mylen{Reactive power} % width of first column

\begin{document}

\noindent
\begin{tabularx}{\textwidth}{@{} q{\mylen} YY @{}}
\toprule
& Conventional Power Plant
& Wind Power Plant \\
\midrule
Topology
& One of a few large generating units. Each unit could be rated at 40 to 1000$+$~MW.
& Typically hundreds of small generators deployed over a large area. Each unit could be rated at 1 to 5~MW. \\
Prime Mover &
\dots &
\dots \\
Dispatch
& \dots
& \dots \\
Real power control
& Units have speed governors and are typically capable of \dots
& Real power follows the wind speed generation \\
Reactive power control
& Units are equipped with an automatic voltage regulator, typically set for voltage control
& Reactive power is managed at the plant level, through \dots\\
Location &
\dots &
\dots \\
Generator
& Synchronous generators
&  Type 1---Fixed speed, induction generator; \\
&& Type 2---Variable slip, induction generators with variable rotor resistance; \\
&& \dots \\
\bottomrule
\end{tabularx}
\end{document}


text:
Q: Change Tracking Delete vs Insert and Update I am working on a system which logs alle data manipulation actions centrally.
Currently SQL Server CHange Tracking is applied, but there is a problem in the data it tracks.
E.g. if I Insert a row in TableX, Update the same row and then Delete it, it seems like only the Delete action is being recorded. Does anyone know how to view the previous actions?
DECLARE
@synchronization_version bigint,
@last_synchronization_version bigint;;

-- Obtain the current synchronization version. This will be used next time that changes are obtained.
SET @synchronization_version = CHANGE_TRACKING_CURRENT_VERSION();

-- Obtain initial data set.
SELECT T.*
FROM TableX AS T;

SELECT DTC.commit_time, CT.*, T.*
FROM TableX AS T
RIGHT OUTER JOIN CHANGETABLE(CHANGES TableX, @last_synchronization_version) AS CT ON T.fldId = CT.fldId
JOIN sys.dm_tran_commit_table DTC ON CT.sys_change_version = DTC.commit_ts;

A: As pointed out by @AlwaysLearning the solution was to use Change Data Capture (CDC) (Microsoft Docs) instead of Change Tracking (CT).


text:
Q: How can I do a command like this in Notepad ++ Basically I have thousands of separate titles, they end with something like:
  - Graphite, Graphite",Hotpoint
To combat this and make the title start with Graphite Hotpoint, I do this:
Find    ^(.*) - Graphite, Graphite",Hotpoint$
Replace Graphite Hotpoint \1"

This is great as it sorts these ones out, however I have all the commands wrote down, and it takes forever to individually do it for each colour/brand. Is there a way I can somehow submit all of them to find / replace. Rather than going through them all the time.
Basically to simply things. I wouldnt have to do find / replace for ^(.*) - Graphite, Graphite",Hotpoint$   and then find and replace for   ^(.*) - White, White",Hotpoint$, and then on and on and on, I have them all wrote so I could somehow insert all the commands into notepad++ and then they would all be done.

A: Have you considered using the Python programming language to solve this issue. Here is a Python Script plug in for Notepad++. For automating your find and replace writing a small script to complete it for you will save you lots of time. Here is an example of using regex.
Looks like this could be what you're after:
editor.rereplace(r"^([A-Z]{3,5})--\1", r"CODE: \1")

Link in comments because I don't have enough rep
You could use a dictionary to store the regex to find with the regex to replace it with
As far as I am aware there is no way natively to achieve what you are asking.

A: How about:
Find what: ^(.*) - (\w+), \w+",(\w+)$
Replace with: $2 $3 $1
You may want to use .+  instead of \w+  if there are other characters than [a-zA-Z0-9_]


text:
Q: Relations between finite Hecke algebras and affine Hecke algebras. A finite Hecke algebra $H_n(q)$ of type $A$ is an associated algebra generated by $T_1, \ldots, T_{n-1}$ with relations
\begin{align}
& T_i T_j = T_j T_i, |i-j|>1, \\
& T_i T_{i+1} T_i = T_{i+1} T_i T_{i+1}, \\
& (T_i-q)(T_i+1) = 0.
\end{align}
An affine Hecke algebra $\widehat{H_n}(q)$ of type $A$ is an associated algebra generated by $T_1, \ldots, T_{n-1}, X_1^{\pm 1}, \ldots, X_n^{\pm 1}$ with relations
\begin{align}
& T_i T_j = T_j T_i, |i-j|>1, \\
& T_i T_{i+1} T_i = T_{i+1} T_i T_{i+1}, \\
& (T_i-q)(T_i+1) = 0, \\
& X_i^{\pm 1} X_k^{\pm 1} = X_k^{\pm 1} X_i^{\pm 1}, 1 \leq i, k \leq n, \\
& X_k X_k^{-1} = X_k^{-1} X_k =1, \\
& T_i X_k = X_k T_i, |i-k|>1, \\
& X_{i+1} = q^{-1} T_i X_i T_i, 1 \leq i < n.
\end{align}
Is $H_n(q)$ a subalgebra of $\widehat{H_n}(q)$? Thank you very much.


text:
Q: Python moving average on web data Relatively new to python so apologies if I ask a stupid question.
I just want to check if this is possible and if it is how complex.
I would like to calculate the moving average from share data on this web page
https://uk.finance.yahoo.com/q/hp?a=&b=&c=&d=11&e=16&f=2015&g=d&s=LLOY.L%2C+&ql=1

A: You can use this sample code.
import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')
html = urllib.urlopen(url).read()

soup = BeautifulSoup(html)
# Retrieve all of the anchor tags
tags = soup('span')
for tag in tags:
   # Look at the parts of a tag
   #calculate whatever you wanto

A: Try it:
from urllib import request
from bs4 import BeautifulSoup

url = "https://uk.finance.yahoo.com/q/hp?a=&b=&c=&d=11&e=16&f=2015&g=d&s=LLOY.L%2C+&ql=1"
html_contents = request.urlopen(url).read()

page = BeautifulSoup(html_contents, "html.parser")
el_list = page.find_all("span", {"id": "yfs_p43_lloy.l"})
print(el_list[0])


text:
Q: remove last line(s) if they are empty from a bunch of files Some hosting provider I work with is very strict, if the last line(s) of a php file are empty it throws a fatal error and the site is broken.
The problem is that I've got a lot of php files where the last line might be empty and now I am looking for a way to automatically remove those lines...
I've tried to use sed:
sed -i '${/^$/d}' bla.php

but all i get is an error
sed: 1: "bla.php": extra characters at the end of d command

btw: i am using iTerm on the Mac

A: You can do something like this within your loop.
file_put_contents('[target_file]', implode('', file('[file_being_processed]', FILE_SKIP_EMPTY_LINES)));

The target_file would be your new copy of the file you're processing and the file_being_processed is self explanatory. You would need to add more logic into the loop to keep the same names.
Bare in mind the above code will exclude all blank lines no matter where they are, so you will also need to add some logic to only apply the above code to the last line of the file.

A: Have you tried turning off error_reporting?
Insert the following on the first line of your php files
<?php error_reporting(0); ?>


text:
Q: Can you not combine a variable with a string to look up another variable? I have a script that I'm creating to create new users and add publickeys when I boot up a new node. However I'm running into issues when trying to pull from (user)_PUBLIC_KEYS array.
#!/bin/sh

USERS=(
    User1
    User2
)
User1_PUBLIC_KEYS=(
    "ssh-rsa ..."
    "ssh-rsa ..."
)

User2_PUBLIC_KEYS=(
    "ssh-rsa ..."
)

for user in "${USERS}"; do
    USERNAME="${user}"
    ...
    # Add provided public keys
    for key in "${USER}_PUBLIC_KEYS[@]"; do
        echo "${key}" >> "${home_directory}/.ssh/authorized_keys"
    done
    ...
done

I've even tried testing
user+="_PUBLIC_KEYS[@]"
    # Add provided public keys
    for key in "${user}"; do
        echo "${key}"
    done

This results in
User1
User1_PUBLIC_KEYS[@]
User2
User2_PUBLIC_KEYS[@]


text:
Q: How can I make an item display fake CanPlaceOn/CanDestroy data? In Minecraft Java Edition, I am experimenting with using CanPlaceOn and CanDestroy NBT tags in items to control which blocks that the player can place their items on.
Now I am making a troll map, where nothing is what it seems, and everything is tricking you into going off-track from the right answer. One of the ways I plan on tricking players is by making it seem like an item can be placed on red wool, when really it can be placed on lime wool instead.
I am already aware that by manipulation of the HideFlags tag, some aspects of an item can be hidden. For example, I can hide the fact that the item can be placed on lime wool. This means the player will think the item is useless, but really it can be placed on lime wool.
But, I am stumped on how I can do the second part to this gimmick: add a fake item to the list displayed on the item's hover text. For this part, I want to make the item look like it can be placed on red wool, when really it can't.
How can I accomplish this?

A: 1.14 makes this possible without having to modify the language files.
The answer lies in the item's lore.
The lore text is displayed on the item's hover text. And with 1.14, you can now style your lore text using JSON text components, meaning you can make your lore text look just like the CanPlaceOn list.

For these advanced commands, I recommend using a command generator to get your command right and avoid NBT syntax errors.

*

*Set the HideFlags NBT tag to hide AttributeModifiers, Unbreakable, and the CanPlaceOn and CanDestroy list. These items will be shown below the lore if not hidden.
The number you need is 30 to hide just these four.

*Set the Lore tag to the following lines:

*

*An empty line. This empty line needs to be in place so that a space is displayed between the item name and the fake block list for CanPlaceOn. This is because this space appears when genuinely using the real l.ist.

*The heading for the CanPlaceOn list.
[{"text":"Can be placed on:","color":"gray","italic":false}]

*Your first fake list item. Replace Stone with the block name.
[{"text":"Stone","color":"dark_gray","italic":false}]

*Your second fake list item. Repeat with any other items you want to add to the fake list.
[{"text":"Gold Block","color":"dark_gray","italic":false}]

*Add the real items to the CanPlaceOn list using the normal tags. Don't worry about it showing, because you already hid it using step 1.


text:
Q: How to invoke the method fun of an abstract class in the following code? I am trying to figure out how to call the method fun of an abstract class by a derived class object?
Could you please spent sometime to help me out.
class A {
    void fun (){
        System.out.println("In A");
    }
}

      // An abstract class with a final method
abstract class Base extends A {
    void fun(){
        System.out.println("Base fun() called");
    }
}

class Derived extends Base {
    void fun(){
        System.out.println("Derived fun() called");
    }
}

Glad to receive an answer

A: If what you want is for the fun() method of Derived to call the Base version of fun() internally, then put super.fun() somewhere in the Derived class's fun() method. Similarly, the fun() method of Base can use super.fun() to invoke the fun() method of A.
What you cannot do is, for an object of class Derived, "skip past" the Derived implementation of fun() and instead invoke the overridden Base or A version of fun().


text:
Q: Chain rule and conditional probability I know
$$
P(B|A,C) = \frac{P(A,C|B)\cdot P(B)}{P(A,C)}
$$
by Bayes Rule. But how can $P(A, C|B)$ be simplified further?
Will the chain rule for conditional probability also work?

A: To me, the simplest formula for $P(B|A,C)$ is $P(A,B,C)/P(A,C)$. The other expressions are just variations on this one.


text:
Q: strace/ltrace outputs inconsistent info strace pwd:
getcwd("/root"..., 4096)                = 6

ltrace pwd:
getcwd(NULL, 0)                                     = "/root"

Why the 1st parameter is NULL in ltrace?
It eems strace/ltrace both uses the ptrace syscall,but why they get different info?

A: Right, they both use ptrace, and also they get different info. This is because they use ptrace differently.
If you have a look at the ptrace man page, you will see that there exist several 'request' values, which decide the behaviour of ptrace.
More concretely, if you use ptrace to previously set the option PTRACE_O_TRACESYSGOOD, you have a way to distinguish between the traps leading to system calls and the traps that are not leading to system calls.

A: ltrace shows the library call.  In this case, it shows the function from the libc that the source code is calling.
If you see pwd's source, you will see (coreutils-8.13, file lib/xgetcwd.c):
char *cwd = getcwd (NULL, 0);

So, ltrace's output is correct: pwd executes getcwd(NULL, 0).  According to the Linux man page getcwd(3):

getcwd() allocates the buffer dynamically using malloc(3) if buf is NULL.

However, the system call getcwd(2) always needs a first argument different from NULL, to copy there the pathname.  You can see how this is done in the libc source (eglibc-3.13, file sysdeps/unix/sysv/linux/getcwd.c).
The library call getcwd(NULL, 0) executes the system call getcwd(path, alloc_size), where path is the result of a previous malloc(), and alloc_size is the page size (4096).
To confirm this, if you run ltrace -S pwd you will see both the library calls and the system calls: you will see something like:
getcwd(NULL, 0 <unfinished ...>
SYS_getcwd("/root", 4096)                        = 6
<... getcwd resumed> )                           = "/root"

A: Because the system call and the library call are different. Read the manpage for the getcwd function and you'll see that it has the following prototype:
long getcwd(char *buf, unsigned long size);


text:
Q: Python function to Create CSRs with SAN i found the function that creates the CSRs on this thread: Generating a CSR in Python
However it has no mention to how i could add SAN (SubjectAltName) to the CSR which is important for the browsers to consider the certificate generated using this CSR to be secure.
I then found a separate function for adding SAN to the CSR in this thread:
Is it possible to set subjectAltName using pyOpenSSL?
The problem is i am not able to combine both for whatever reason. whenever i add it, it seems like the Microsoft Active Directory Certificate Services doesn't like it and gives me this error:
Certificate Services Error Message
What am i doing wrong? thank you for all the help in advance
here is how my code is looking for reference:
def create_csr(common_name, country=None, state=None, city=None,
       organization=None, organizational_unit=None,
       email_address=None):
"""
Args:
    common_name (str).
    country (str).
    state (str).
    city (str).
    organization (str).
    organizational_unit (str).
    email_address (str).
Returns:
    (str, str).  Tuple containing private key and certificate
    signing request (PEM).
"""
key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)

req = OpenSSL.crypto.X509Req()
req.get_subject().CN = common_name
if country:
    req.get_subject().C = country
if state:
    req.get_subject().ST = state
if city:
   req.get_subject().L = city
if organization:
    req.get_subject().O = organization
if organizational_unit:
req.get_subject().OU = organizational_unit
if email_address:
    req.get_subject().emailAddress = email_address

req.set_pubkey(key)
req.sign(key, 'sha256')

san_list = ["IP:" + common_name, "DNS:" + common_name]
req.add_extensions([
    OpenSSL.crypto.X509Extension(
        "subjectAltName".encode("utf-8"), False, (", ".join(san_list)).encode("utf-8")
    )
])

private_key = OpenSSL.crypto.dump_privatekey(
    OpenSSL.crypto.FILETYPE_PEM, key)

csr = OpenSSL.crypto.dump_certificate_request(
    OpenSSL.crypto.FILETYPE_PEM, req)

return private_key, csr