text:
Q: Spivak's Calculus Chapter 28-1 (Fields) Question in Textbook
The question defines a set F and then defines the operations on F through a table. In this chapter, Spivak outlines the properties that operators on a field must have. In the example in textbook he says that that the verifications of the conditions are simple, case by case checks. However, would that not be extremely long and tedious going through every case for every element in set F? Is there a simpler way to do this?

A: So, if you know that this field happens to be the field $\mathbb{Z}/3\mathbb{Z}$ (you don't need to know what that means), then maybe you can use the general argument that $\mathbb{Z}/p\mathbb{Z}$ (again, don't need to know what that means) is a field.
However, I don't think the axioms are as hard to verify as you might think they are. For instance, the existence of additive identity means that one of the columns in the addition table looks the same as the column listing the elements being added. The existence of additive inverses is the same as saying that every column in the addition table has a $0$ in it. Commutativity means that flipping the multiplication table along the diagonal gives the same table. So, this is quicker to manually verify than you might think. Does that help?

A: The Field is only !$3$! elements.  It is very easy and short to check everything.
Axiom 1:  Addition is commutative.  If $a = b$ then $a+b= a+a=b+a$ so we only have to check if $a\ne b$ and there are only three such pairs.  $0 + 1 = 1=1+0; 0+2=2=2+0; 1+2=0=2+1$.  That's it.  We checked them all.
Axiom 2: Addition is associative.  The check $(a+b) + c = a+(b+c)$ is $27$ cases of $a,b,c$ but we can cut that down with commons sense. If $a,b$ or $c=0$ then $(a+b) + 0 = a+b = a +(b+0)$ and $(a+0)+c= a+c = a+(0+c)$ and $(0+b) +c = b+c = 0 + (b+c)$. (See axiom 3).  If none of $a,b,c=0$ then that is only $8$ cases but still we must have two of them equal or three of the equal and as addition is commutative:
$(a+a) + a = a+(a+a)$ and $(a+a)+b=a+(a+b)$ can be checked with $4$ cases.  And $(a+b) +a= a+(a+b)=a+(b+a)$.  And $(b+a)+a=(a+b)+a=a+(a+b)=(a+a) + b=b+(a+a)$.  so that associativity.
Axiom 3: $0+a = a+0= a$.  Just three things to check.  $0+0=0;1+0=1;2+0=0$ that's it we checked them ALL.
Axiom 4: even element has an additive inverse.  Only three to check.  $0+0=0$ so $0$ has an inverse.  $1+2 = 0$ so $1$ has an inverse. $2+1=0$ so $2$ has inverse.
Multiplication axioms are similar.
that was not a lot to do.
Showing no order can exist is figure: $0 = 1 + 1 + 1$  If $1 > 0$ then $1+1 > 0+1$ and $1+1+1 > 0+1+1$ and if $1< 0$ .... well same thing.


text:
Q: lightMap / specularMap / shading with meshBasicMaterial I'm currently working on something along the lines of a plugin for another program to add 3D capability to it, so I'm trying to put all the functionality i can from three.js into it, with  the added goal of this being a good way to learn all the functionality of three.js firsthand.
I'm running into an issue now as i implement textures and materials that with mesh basic material, setting some things which the documentation on the main threejs.org site shows are features, doesn't actually do anything.
when i set a texture for either specularmap or lightmap nothing is actually showing up. Im pretty sure its not a mistake im making because setting the texture of the map works, but trying to set this same texture for the specularMap or lightMap is doing nothing. Does a regular texture work for these, or do i have to do something different?
I'd also like to know what the shading property does for mesh basic, because as far as i can see setting it to smoothshading/flatshading/noshading is doing nothing aswell.

A: MeshBasicMaterial does not respond to lights. Change your material to MeshLamberMaterial  or MeshPhongMaterial, for example.
For MeshBasicMaterial and MeshLambertMaterial, the specularMap is used only to modulate the reflection when an environment map is used.
For any material, lightmaps require a second set of UVs. geometry.faceVertexUvs[ 0 ] contains the usual set of UVs; for a lightmap, you need to add geometry.faceVertexUvs[ 1 ], a second set of UVs.
For MeshBasicMaterial, the shading property only applies when an environment map is used. SmoothShading will yield smooth reflections; FlatShading will yield faceted reflections.
three.js r.66

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery parentsUntil not firing in else condition oK, This is strange...I have the same code that will work great in the if statment...but wont fire once it gets to the parentsUntil when it hits the else statement  ????
 if(sArray.length > 400){

 $.each(sArray,  function(key, item){

                    $("!#"+item).parentsUntil(".#jstree").filter(".#jstree-closed").each(function () {
                            $aTree.jstree("close_all", this);
                            });
                  });

else{

 $.each(sArray,  function(key, item){

                    $("!#"+item).parentsUntil(".#jstree").filter(".#jstree-closed").each(function () {
//IT IS NOT MAKING IT HERE
                            $aTree.jstree("close_all", this);
                            });
                  });

}

A: You missed 2 } and what the console give to you with that :
if(sArray.length > 400){

     $.each(sArray,  function(key, item){
        $("#"+item).parentsUntil(".jstree").filter(".jstree-closed").each(function () {
            $aTree.jstree("check_node", this);
        });
    });

}// Was missing
else{

$.each(sArray,  function(key, item){
    console.log($("#"+item).parentsUntil(".jstree").filter(".jstree-closed"));
    $("#"+item).parentsUntil(".jstree").filter(".jstree-closed").each(function () {
            //IT IS NOT MAKING IT HERE
            console.log("pass");
            $aTree.jstree("check_node", this);
        });
    });
}


text:
Q: Forcing a typecast of a custom object in javascript Suppose I have 2 constructors and a member function defined
function A() {}
function B() {}
A.prototype.a = function(){}

And I've instantiated a B. How can I force a conversion to make it an A?
o = new B();
//What should I put here?
o.a();

I'm new to js. And I have a feeling that whether o mentioned above is an A or a B is merely controlled by a reference to a prototype. Therefore, I feel typecast should be possible.
Answers, as well as explanations that can help me understand js objects, are welcomed.

A: You can't change (that is, completely swap-out) the prototype of an object once it's been created (yet; in a future version of JavaScript, it's likely to be possible).
Objects in JavaScript are enormously malleable, though. You can do this, for instance:
o.a = A.prototype.a;

...and then o will have the a function. If you wanted to give it all of the enumerable properties of A.prototype (including any from its prototype):
var name;
for (name in A.prototype) {
    o[name] = A.prototype[name];
}

The prototype property of functions is a completely normal, boring object assigned to a normal, boring property on the function. When you use new to create an object using that function (which is called a "constructor function"), the function's prototype property is assigned to the newly-created object as its underlying prototype (which has no name you can access in code [yet]).
As of ES5 (reasonably supported in Chrome, Firefox, Opera, and IE9; not in IE8 and earlier), you can get the prototype of an object via Object.getPrototypeOf, and you can create objects assigning them a prototype without going through constructor functions by using Object.create, but you can't change what an object's prototype is once it's been created.
Some JavaScript engines (like the one in Firefox) have a currently-non-standard extension called __proto__ which lets you directly access and manipulate the prototype of an object, by treating it as a property. E.g.:
o.__proto__ = A.prototype;

...but that is not standard at present. It may well be part of the next standard, though. If you're interested in information about the upcoming ES6, you can find draft specifications and such here.


text:
Q: How to integrate the Heat Kernel? Let
$P(x, y, t) := (4 \pi t)^{-v/2}\exp\left(\frac{-|x-y|^2}{4t}\right)$, with $x, y \in \mathbb{R}^v$ and $t \in \mathbb{R}$,
denote the Heat Kernel.
QUESTION: How to show that:
$$Q(x, y, t) := \int^t_0 P(x, y, s)\,\mathrm ds$$
behaves like: $|x - y|^\gamma \exp\left(\frac{-|x-y|^2}{4t}\right)$ in the region:
$$A :=\{(x, y) \mid |x-y| \leq 4 \sqrt{t}\}$$
for some suitably chosen $\gamma$?


text:
Q: Symfony 3 routing subdomains I have to bundles, frontend and backend. I want the subdomain "admin.domain.com" to work as "admin.domain.com/whateverpage" and controlled by the backend bundle controllers. All other subdomains should work like "sub1.domain.com/{dynamicwhateverpage}" or "sub2.domain.com/{dynamicwhateverpage}" and be controlled by the frontend bundle controllers.
I got it to work with "admin.domain.com/backend/whateverpage" and "sub1.domain.com/frontend/{dynamicwhateverpage}". The backend and frontend in the URL of course should not be visible to the users. Is there a way to rewrite with htaccess? Or is there even a better way to achieve this kind of rewriting?

A: Symfony can match routing based on host. This should also work when importing routes, though I have not tested it;
/**
 * @Route("/", name="project_page", host="{project}.example.com")
 */
public function projectPageAction($project) {
    // ...
}

Just make sure your none dynamic routes are loaded before the all capturing one, or make sure the project one can't match eg. admin.

Earlier Routes Always Win
Why would you ever care about requirements? If a request matches two routes, then the first route always wins.


text:
Q: Efficiently access property of objects in pandas column Say I have the following DataFrame:
df = pd.DataFrame("x":[pd.Timestamp("2016-03-18")])

How can I access the properties of the datetime object stored in column x? That is, I want e.g.
df.x[0].weekofyear # returns 9

But for the whole column. Clearly, df.x.weekofyear wouldn't work, as df.x is a series and not a datetime object, and df.x.apply(pd.Timestamp.weekofyear) won't work either, as weekofyear is an attribute and not a function.
The solution I could think of was defining a function to access the attribute and then apply this, as:
def get_week(x):
    return x.weekofyear

df.x.apply(get_week) # returns series of weeks

It seems that this is a bit roundabout and verbose, and my experience is that whenever I do something like this, pandas already has a super efficient built-in way to do it - is there one for this case?

A: use vectorised .dt.weekofyear
So df['x'].dt.weekofyear will return for whole column:
In [119]:
df = pd.DataFrame({'dates': pd.date_range(dt.datetime(2016,1,1), dt.datetime(2016,1,20))})
df

Out[119]:
        dates
0  2016-01-01
1  2016-01-02
2  2016-01-03
3  2016-01-04
4  2016-01-05
5  2016-01-06
6  2016-01-07
7  2016-01-08
8  2016-01-09
9  2016-01-10
10 2016-01-11
11 2016-01-12
12 2016-01-13
13 2016-01-14
14 2016-01-15
15 2016-01-16
16 2016-01-17
17 2016-01-18
18 2016-01-19
19 2016-01-20

In [120]:
df['dates'].dt.weekofyear

Out[120]:
0     53
1     53
2     53
3      1
4      1
5      1
6      1
7      1
8      1
9      1
10     2
11     2
12     2
13     2
14     2
15     2
16     2
17     3
18     3
19     3
Name: dates, dtype: int64


text:
Q: UITableViewCell delete does not use proper UITableViewRowAnimation When a row is deleted it always slides to left no matter what animation value I pass. I would like it to slide up similar to many of the stock apps.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        self.tableData = [][[self.tableData mutableCopy] removeObjectAtIndex:indexPath.row] copy];

        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];

    }
}

Here is the full tableview controller code, it is has a lot in it. That is the reason I didn't post it at first.
@interface FMListViewController ()
@property (strong) NSArray *currentLocations;
@property (assign) BOOL isEditing;
@end

@implementation FMListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UISegmentedControl *viewType = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"List", @"Map", nil]];
    CGRect viewTypeRect = viewType.frame;
    viewTypeRect.size.width = 150.0f;
    viewType.frame = viewTypeRect;
    viewType.selectedSegmentIndex = 0;
    [viewType addTarget:self action:@selector(viewTypeChange:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = viewType;
    self.currentLocations = [[FMLocations sharedManager] allLocations];
    //watch for weather updates
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weatherUpdated) name:@"weatherUpdated" object:nil];
    //watch for changes to saved locations
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(locationsUpdated) name:@"locationsUpdated" object:nil];
    self.isEditing = NO;

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    // this UIViewController is about to re-appear, make sure we remove the current selection in our table view when swiping back occurs
    NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow];
    [self.tableView deselectRowAtIndexPath:tableSelection animated:NO];
    [self.navigationController setToolbarHidden:YES animated:NO];

}

- (void)viewTypeChange:(UISegmentedControl *)segControl{
    NSLog(@"change to map");
    [(FMNavController *)[self navigationController] changeViewType];
    segControl.selectedSegmentIndex = 0;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)weatherUpdated{
    [self.tableView reloadData];
    [self.refreshControl endRefreshing];
}

- (void)locationsUpdated{
    if(self.isEditing){
        self.currentLocations = [[FMLocations sharedManager] savedLocations];
    }else{
        self.currentLocations = [[FMLocations sharedManager] allLocations];
    }
    [self.tableView reloadData];
}

#pragma mark - Table Editing Stuff
- (IBAction)toggleEditing:(id)sender{
    if(self.isEditing){
        self.isEditing = NO;
        self.currentLocations = [[FMLocations sharedManager] allLocations];
        [self.tableView reloadData];
        UIBarButtonItem *newRightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(toggleEditing:)];
        self.navigationItem.rightBarButtonItem = newRightItem;
        [self.tableView setEditing:NO animated:YES];
    }else{
        self.isEditing = YES;
        self.currentLocations = [[FMLocations sharedManager] savedLocations];
        [self.tableView reloadData];
        UIBarButtonItem *newRightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(toggleEditing:)];
        self.navigationItem.rightBarButtonItem = newRightItem;
        [self.tableView setEditing:YES animated:YES];
    }

}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0 && [[FMLocations sharedManager] currentLocation] && !self.isEditing){
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
        NSMutableArray *newLocations;
        int arrayOffset = 0;
        if([[FMLocations sharedManager] currentLocation] && !self.isEditing){
            arrayOffset = -1;
        }
        newLocations = [[[FMLocations sharedManager] savedLocations] mutableCopy];
        int itemToRemove = (int)indexPath.row + arrayOffset;
        if(itemToRemove < 0 || itemToRemove > [newLocations count]){
            NSLog(@"invalid item to remove");
        }else{
            [newLocations removeObjectAtIndex:itemToRemove];
            [[FMLocations sharedManager] saveSavedLocations:[newLocations copy]];
            if(self.isEditing){
                self.currentLocations = [[FMLocations sharedManager] savedLocations];
            }else{
                self.currentLocations = [[FMLocations sharedManager] allLocations];
            }

            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];

        }
    }
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0 && [[FMLocations sharedManager] currentLocation] && !self.isEditing){
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    NSMutableArray *editableLocations = [[[FMLocations sharedManager] savedLocations] mutableCopy];
    if(editableLocations && [editableLocations count] > sourceIndexPath.row && [editableLocations count] > destinationIndexPath.row){
        NSInteger fromIndex = sourceIndexPath.row;
        NSInteger toIndex = destinationIndexPath.row;

        id object = [editableLocations objectAtIndex:fromIndex];
        [editableLocations removeObjectAtIndex:fromIndex];
        [editableLocations insertObject:object atIndex:toIndex];
        [[FMLocations sharedManager] saveSavedLocations:[editableLocations copy]];
    }
}

#pragma mark - Refresh control action
- (IBAction)doRefreshTable:(id)sender{
    [[ForecastManager sharedManager] updateForecasts];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.currentLocations count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //NSLog(@"getting cell");
    FMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FMLocationCell" forIndexPath:indexPath];
    NSDictionary *theLocation = [self.currentLocations objectAtIndex:indexPath.row];
    // Configure the cell...
    cell.locationLabel.text = [[theLocation objectForKey:@"name"] uppercaseString];
    WeatherObject *locationWeather = [[ForecastManager sharedManager] weatherObjectForLocation:[[theLocation objectForKey:@"id"] intValue]];
    [cell setCurrentTemp:locationWeather.currentTemp];

    [cell configureForecastViews:locationWeather.forecastObjects];
    [cell.weatherPreviewContainer setNeedsDisplay];
    return cell;
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if([segue.identifier isEqualToString:@"showLocation"]){
        FMDetailViewController *detailController = [segue destinationViewController];
        NSDictionary *theLocation = [self.currentLocations objectAtIndex:self.tableView.indexPathForSelectedRow.row];
        detailController.navigationItem.title = [theLocation objectForKey:@"name"];
        detailController.detailLocation = theLocation;
    }

}

A: You can try below solutions:
1) Replace your line with the below one
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];

2) Change the code with the below one:
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];

Hope this helps!

A: please  try with that
don't delete cell directly first make its cellheight to zero using.  NSIndexPath *deleteIndexPath;
wirte below code before delete
    [tbl beginUpdates];
    deleteIndexPath = indexPath;
    [tbl reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [tbl endUpdates];

and in set hight method use
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{    if (indexPath == deleteIndexPath) {
    return 0;
}
return 50;
}


text:
Q: Can't access private members of a class despite friend class I am doing a homework assignment on overloading operators. This is my code:
#include<iostream>
#include<cmath>
using namespace std;

class ComplexNumber{
    double real;
    double imaginary;

  public:
    friend class Equation;
};

class Equation{
    ComplexNumber *broevi;
    char *znaci;
    int n;

  public:
    Equation(){
        broevi=new ComplexNumber[0];
        znaci=new char[0];
        n=0;
    }
    friend istream &operator >>(istream &in, Equation &e){
        int k=1;
        while(k){
            char *tmp; ComplexNumber *b;
            tmp=new char[e.n+1];
            for(int i=0; i<e.n; i++)
                tmp[i]=e.znaci[i];
            b=new ComplexNumber[e.n+1];
            for(int i=0; i<e.n; i++)
                b[i]=e.broevi[i];
            in>>e.broevi[e.n].real>>e.broevi[e.n].imaginary;
            in>>tmp[e.n];
            if(tmp[e.n]=='=')
                break;
            delete []e.znaci;
            e.znaci=tmp;
            delete[]e.broevi;
            e.broevi=b;
            ++e.n;
        }
        return in;
    }
    friend class ComplexNumber;
};

This is only a part of my code.
While compiling I get these two following errors:

error: 'double ComplexNumber::imaginary' is private
error: 'double ComplexNumber::real' is private

On this line:
in>>e.broevi[e.n].real>>e.broevi[e.n].imaginary;

Can you please point out where my mistake is?

A: Your operator>> is a friend of Equation, so it can access private fields of Equation.  But, it is not a member of Equation, and it is not a friend of ComplexNumber, so it can't access private fields of ComplexNumber.
The simplest solution is to add a friend operator>> to ComplexNumber, and then use that in Equation's operator>>:
class ComplexNumber {
    double real;
    double imaginary;

public:
    friend istream& operator >>(istream &in, ComplexNumber &cn) {
        in >> cn.real >> cn.imaginary;
        return in;
    }
};

class Equation {
    ...

public:
    ...

    friend istream& operator >>(istream &in, Equation &e) {
        ...
        //in >> e.broevi[e.n].real >> e.broevi[e.n].imaginary;
        in >> e.broevi[e.n];
        ...
    }
};

However, if that is not allowed for your assignment, then you can instead move your stream logic to a member method of Equation for its operator>> to call, and then that method will have access to the private fields of ComplexNumber:
class ComplexNumber {
    double real;
    double imaginary;

public:
    friend class Equation;
};

class Equation {
    ...

    void read(istream &in) {
        // your logic here...
    }

public:
    ...

    friend istream& operator >>(istream &in, Equation &e){
        e.read(in);
        return in;
    }
};


text:
Q: Delimiter List of list I have a list of lists and need to change the delimiter to '|':
my_list_of_lists = [['1001100', 'xxx', '', '1100', 'PAR_200', '21651947694', '0', '0', '20210301', '20210331', '1630,51', '1', ''],
['1001110', 'sss', '', '1110', 'C-200', '20210307', '1630,51', '1', '7252048000136', ''],
['1001115', 'ddd', '', '1115', '21', '', 'NO6520058050362', '0', '08', '110433', '1630,51', '1', '', ''],
['1001120', 'fff', '', '1120', 'MG', '', '', '73895137480', ''],
['101100', 'ees', '', '1100', 'PAR_200', '21653346587', '0', '0', '20210301', '20210331', '1013,84', '1', ''],
['101110', 'fsc', '', '1110', 'C-200', '20210307', '1013,84', '1', '7252048000136', ''],
['101115', 'fer', '', '1115', '1', '', 'LI1600081181694N2K346', '0', '06', '110433', '1013,84', '1', '', ''],
['101120', 'ter', '', '1120', 'MG', '', '', '17651232321', '']]

When I try this with a single list, works:
my_list = ['1001100', 'xxx', '', '1100', 'PAR_200', '21651947694', '0', '0', '20210301', '20210331', '1630,51', '1', '']

delim = "|"

res = ''

for lists in my_list:
    res = res + str(lists) + delim

print(res)

1001100|xxx||1100|PAR_200|21651947694|0|0|20210301|20210331|1630,51|1||

But I think I'm missing something on the list comprehension to do this in a list of lists:
delim = "|"

res = ''

for sub_lst in my_list_of_lists:
    for lists in sub_lst:
        res = res + str(lists) + delim

Desired output:
1001100|xxx||1100|PAR_200|21651947694|0|0|20210301|20210331|1630,51|1||
1001110|sss||1110|C-200|20210307|1630,51|1|7252048000136||
1001115|ddd||1115|21||NO6520058050362|0|08|110433|1630,51|1|||
....

What am I doing wrong?

A: Use join:
lst = [['1001100', 'xxx', '', '1100', 'PAR_200', '21651947694', '0', '0', '20210301', '20210331', '1630,51', '1', ''],
['1001110', 'sss', '', '1110', 'C-200', '20210307', '1630,51', '1', '7252048000136', ''],
['1001115', 'ddd', '', '1115', '21', '', 'NO6520058050362', '0', '08', '110433', '1630,51', '1', '', ''],
['1001120', 'fff', '', '1120', 'MG', '', '', '73895137480', ''],
['101100', 'ees', '', '1100', 'PAR_200', '21653346587', '0', '0', '20210301', '20210331', '1013,84', '1', ''],
['101110', 'fsc', '', '1110', 'C-200', '20210307', '1013,84', '1', '7252048000136', ''],
['101115', 'fer', '', '1115', '1', '', 'LI1600081181694N2K346', '0', '06', '110433', '1013,84', '1', '', ''],
['101120', 'ter', '', '1120', 'MG', '', '', '17651232321', '']]

out = ['|'.join(l) for l in lst]
print(out)

Output
['1001100|xxx||1100|PAR_200|21651947694|0|0|20210301|20210331|1630,51|1|', '1001110|sss||1110|C-200|20210307|1630,51|1|7252048000136|', '1001115|ddd||1115|21||NO6520058050362|0|08|110433|1630,51|1||', '1001120|fff||1120|MG|||73895137480|', '101100|ees||1100|PAR_200|21653346587|0|0|20210301|20210331|1013,84|1|', '101110|fsc||1110|C-200|20210307|1013,84|1|7252048000136|', '101115|fer||1115|1||LI1600081181694N2K346|0|06|110433|1013,84|1||', '101120|ter||1120|MG|||17651232321|']


text:
Q: WPF Databinding: How do I access the "parent" data context? I have a list (see below) contained in a window. The window's DataContext has two properties, Items and AllowItemCommand.
How do I get the binding for the Hyperlink's Command property needs to resolve against the window's DataContext?
<ListView ItemsSource="{Binding Items}">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Action">
        <GridViewColumn.CellTemplate>
          <DataTemplate>
            <StackPanel>
              <TextBlock>

                <!-- this binding is not working -->
                <Hyperlink Command="{Binding AllowItemCommand}"
                           CommandParameter="{Binding .}">
                    <TextBlock Text="Allow" />
                </Hyperlink>

              </TextBlock>
            </StackPanel>
          </DataTemplate>
        </GridViewColumn.CellTemplate>
      </GridViewColumn>
    </GridView>
  </ListView.View>
</ListView>

A: This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

A: You could try something like this:
...Binding="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

A: This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.
RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"


text:
Q: Chrome Developer Tools throwing errors with Xperia inspector We have a number of android devices which we develop web apps for.
When we are developing for Chrome mobile, we fire up the Developer Mode and start inspecting the webpages for the devices. Once all the drivers and RSA keys have been accepted, we are able to see all the devices in chrome://inspect/#devices.
When clicking inspect, the chrome developer tools comes up and we are able to interact with the webpages elements and javascript. << All this is normal..
Except for the Sony Xperia Z1. When I bring up the Developer tool, it is blank. The drivers are fine since I would not have been able to get this far if they had not been, but just in case, I got them again. Still blank. I then did the crazy thing of bringing up the Developers tool page for the Developers tool. (Yeah, this is getting deep).
I was presented with some errors. I have never seen the Dev tool for the Dev tool show errors before and I don't even think I can do anything about them.. but I was hoping someone might be able to suggest what is wrong.. I am presuming it is something to do with the phone and again prob out of my control, but there may be some drivers that WILL do what we need and I just can't find them. The Output for the Dev tool Dev tool is:
Uncaught TypeError: Object #<InspectorFrontendHost> has no method 'zoomFactor' inspector.js:9162
Document was loaded from Application Cache with manifest chrome-devtools://devtools/remote/serve_rev/@170502/170502.manifest devtools.html:1
Application Cache Checking event devtools.html:1
Application Cache NoUpdate event devtools.html:1
Uncaught TypeError: Object #<Object> has no method 'setAttachedWindow'
Uncaught TypeError: Object #<Object> has no method 'setDockSide' VM161:1

I have tried searching for some of these terms on Google, but very little directly related.
Any help would be greatful.


text:
Q: How to show Toast in class which extends Activity I have a Java Class in my Android project, where I wanted to separate facebook authorization from email authorization. Because of this line
 LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "public_profile"));

I was obliged to extend my FBLogin class from Activity. Did I do it right or I should have done in other way?
But my main Question is - how to show a Toast message in this FBLogin class? this line shows me errors
Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();

A: Try to use:
Toast.makeText(fblogin.this, "Success", Toast.LENGTH_SHORT).show();

A: For normal Activity:
Toast.makeText(FBLogin.this, "Success", Toast.LENGTH_SHORT).show();

extends Fragment:
Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();

A: Do this
Toast.makeText(YourClassName.this, "Success", Toast.LENGTH_SHORT).show();

Like if your Class Name is MainActivity then you have to do this
Toast.makeText(MainActivity .this, "Success", Toast.LENGTH_SHORT).show();

or you can pass Context of your Application.
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();


text:
Q: React: Why  puts the event object at the end of the argument of the event handler The title may sound vague, so here is a snippet of code to explain what it means...
changeInput = (index, event) => {
 //How come "event" is the second argument?
 //I didn't put "event" (but index) in the code below.
 //Why isn't the argument (event, index)?
}

render() {
    const index = 0;
    return (
        <input type="text"
               onChange={this.changeInput.bind(this,index)} />
      );
    }
}

In React.js, form elements (input, textarea etc) send the event object to the event handler (changeInput).
However, I'm a little confused with the order. Why event is put at the end of the event handler, instead of at the beginning?
It might be nicer to use an anonymous function for onChange.
(i.e. (event) => this.changeInput.bind(event,index) may be better looking)
Before doing so, I'd like to know the reason, but can't find any clue in the official doc.
Any advice will be appreciated.

A: Check the documentation for bind. The first arg you send to bind is thisArg (which is used to determine this inside the function, changeInput in your case), the rest arguments is passed to the function.
this.changeInput.bind(this, arg1, arg2, arg3)

Will result in
this.changeInput(arg1, arg2, arg3)

The reason you've to call .bind is a story itself. You can search for "javascript this context" to learn more about this and how it works, it's worth learning that :)

A: It's because of index here .bind(this, index). Bind passes first arg as a context and all other args will be passed to the function on call
Here is an implementation of bind for better understanding:
Function.prototype.bind = function bind(context, ...bindArgs) {
  return (...args) => {
    return this.call(context, ...bindArgs, ...args);
  };
};


text:
Q: How to swap ctrl+enter and ctrl+shift+enter in Visual Studio 2015? In VS 2015, ctrl + enter puts the cursor above the current line while ctrl + shift + enter puts it below. I find it rather counterintuitive because the usage of the latter is more frequent yet it requires more keystroke. I wonder how can I switch them in the VS settings?

A: These shortcuts map to the Edit.LineOpenAbove and Edit.LineOpenBelow commands. You can reassign them in Visual Studio keyboard options.


text:
Q: My pc cannot boot past grub [Kali Linux] I have Kali Linux installed on my hp envy as the primary Os. No dual boot. I had issues with the bios and got it replaced and reprogrammed. My PC now boots past bios, into grub. It even gives me a Kali Linux selection from the grub. My PC cannot boot into Kali after that. It gives me this error.

[    2.393708] mce : [Hardware Error]: CPU 0: Machine Check Exception: 5 Bank 4: ba00000000060403
[    2.393842] mce : [Hardware Error]: RIP !INEXACT! 10:<ffffffff9b922e45> {intel_idle+0x85/0x130}
[    2.393977] mce : [Hardware Error]: TSC 162c5d0a12 MISC 1e3c
[    2.394103] mce : [Hardware Error] PROCESSOR 0:406e3 TIME 1420096831 SOCKET 0 APIC 0 microcode cc
My pc boots fine when I run Kali Linux on a live CD on fail safe mode but crashes when I run windows from a USB hard drive.

A: The important part is here:
mce: [Hardware Error]: Machine check: Processor context corrupt
Kernel panic - not syncing: Fatal machine check

A machine check is a signal directly from the CPU itself that a serious error has been detected. Unfortunately, the most common reasons for machine checks are various kinds of hardware faults. It might be:

*

*simple CPU overheating (clogged air vents? heat sink not properly attached to CPU?)

*RAM failure (run a memory tester overnight if possible)

*data corruption on system bus (usually requires motherboard replacement, which may or may not be cost-effective on a laptop = warranty replacement of the complete computer might be in order)

*something else (this list is not exhaustive)

Your first goal should be to get any irreplaceable data backed up somewhere outside the laptop. If you don't already have external backups, you might need to do something like removing the SATA HDD/SSD or the M.2 SSD module from the laptop, plugging it to an appropriate external enclosure and copying your data out of the drive that way. If you feel you're out of your depth here, get a professional involved.
The second goal is getting the hardware fault diagnosed and fixed. If the system has detachable RAM memory modules, and there is more than one of them, you might try running with just one module installed. Try each module at a time: if one works and the other fails, you'll know which one of the modules is bad. If there is just one memory module, you'll need to get a second compatible module for testing. If the memory modules are not user-replaceable in that laptop model, that kind of testing will obviously be impossible.
At this point, you will have done essentially everything a skilled amateur can be expected to do with a problem like this one.
Even if the system is still under warranty, the sad reality is that you'll probably first have to prove the problem also exists when using a supported OS, i.e. Windows. But that error looks severe and repeatable enough that it will probably also crash the Windows installer, so be sure to try that, so that you will be able to honestly say you tried. It will probably be proof enough to get the warranty replacement process started.


text:
Q: How to specify directory for image uploader in install script I have an install script that works, but doesn't upload the files where I want them:
$installer->addAttribute('catalog_category', 'category_banner_image',  array(
    'type'     => 'varchar',
    'label'    => 'Category Banner Image',
    'input'    => 'image',
    'backend'  => 'catalog/category_attribute_backend_image',
    'global'   => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'visible'           => true,
    'required'          => false,
    'user_defined'      => true,
    'default'           => '',
    'nullable'          => true,
    'group'             => 'Category Promo'
));

It uploads everything to /media/catalog/category but I would like for them to go to /media/categories/banners.  How can I specify that in the install script?

A: Your attribute code can not describe where to store image,
so you need to add this in your di.xml
    <virtualType name="vendor_name\module_name\BannerImageUpload" type="vendor_name\module_name\Model\ImageUploader">
           <arguments>
        <argument name="baseTmpPath" xsi:type="string">categories/banners</argument>
           <argument name="basePath" xsi:type="string">categories/banner</argument>
           <argument name="allowedExtensions" xsi:type="array">
               <item name="jpg" xsi:type="string">jpg</item>
               <item name="jpeg" xsi:type="string">jpeg</item>
               <item name="gif" xsi:type="string">gif</item>
               <item name="png" xsi:type="string">png</item>
           </argument>
       </arguments>
   </virtualType>


text:
Q: ImportError: libGL.so.1: cannot open shared object file: No such file or directory cv2 When I am trying to migrate file to Heroku master (deploying to Heroku)
These errors comes:
    (test) C:\Users\DELL\Desktop\django-project\imageapi>heroku run python manage.py migrate
           Running python manage.py migrate on ⬢ imageapii... up, run.9341 (Free)
           Traceback (most recent call last):
    File "/app/manage.py", line 22, in <module>
     main()
  File "/app/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line
  File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
    return import_module(self.urlconf_name)
  File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/app/imageapi/urls.py", line 18, in <module>
    from core.views import TextView,fetching
  File "/app/core/views.py", line 3, in <module>
    import cv2 as cv
  File "/app/.heroku/python/lib/python3.9/site-packages/cv2/__init__.py", line 5, in <module>
    from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory

and my pip list :
Package             Version
------------------- ---------
asgiref             3.4.1
certifi             2021.5.30
chardet             4.0.0
dj-database-url     0.5.0
Django              3.2.5
django-cors-headers 3.7.0
django-heroku       0.3.1
djangorestframework 3.12.4
gunicorn            20.1.0
idna                2.10
numpy               1.21.0
opencv-python       4.5.2.54
Pillow              8.3.0
pip                 21.1.3
psycopg2            2.9.1
pytz                2021.1
PyYAML              5.4.1
requests            2.25.1
setuptools          57.0.0
sqlparse            0.4.1
uritemplate         3.0.1
urllib3             1.26.6
wheel               0.36.2
whitenoise          5.2.0

I am doing this on window 10 and not using Docker.I tried many answer regarding this error but none of them was useful.
pls help me :(
Thanks in advance


text:
Q: CSS content script issue in Google Chrome extension I am creating a simple Chrome extension that blocks the "Google" logo image on the Google homepage using a content script. I followed the directions on the content-script page, but it still does not seem to be working. Can anyone spot what I'm doing wrong?

EDIT: I have tested it with other website like flickr.com and it works perfectly. I've also searched through the Google homepage CSS and cannot figure out which CSS rule is overriding my CSS. Any ideas? How can I make a stronger CSS injection so that no other CSS can override mine?

manifest.json:
{
  "manifest_version": 2,
  "name": "Google Logo Blocker",
  "description": "This extension blocks the Google logo image.",
  "version": "1.0",

  "content_scripts": [
   {
     "matches": ["http://www.google.com/"],
     "css": ["blocker.css"]
   }
  ],

  "browser_action": {
    "default_icon": "icon.png"
  }
}

blocker.css:
img {
    display: none !important;
}

A: Your code works for me.  You are using straight USA Google, not an international version, right?
Just in case, change your matches to:
"matches": ["http://*.google.com/", "https://*.google.com/"],

And target the logo more directly.  This will work in most cases:
#hplogo {
    display: none !important;
}

For full-on, international Google support, change the content_scripts portion of your manifest to:
"content_scripts": [ {
    "matches":          ["http://*/*", "https://*/*"],
    "include_globs":    ["http://*.google.*/*", "https://*.google.*/*"],
    "css":              ["blocker.css"]
} ],

Optionally also using exclude_matches and/or exclude_globs as desired.

If it still doesn't work, state the usual:

*

*Exact URL

*Chrome version

*OS

*Other extensions active

A: It is  <img> tag in modern version and  is a <div> tag with background image for international version. Regardless, of the differences they bear same id = hplogo, so this can work for you.
Click for Larger Image

Use
#hplogo{
       display:none !important;
}

it will remove google Logo.


text:
Q: 'undefined likes' twitter like project Recently I started working on a twitter like clone to learn some python and django. I have successfully added "tweets" and got them to display some basic text on my homepage. My issue is with the like button. I am attempting to have a like button that will display the total amount of likes on that "tweet". For now I am using a random int just to display the likes. However the button just displays "undefined Likes". I thought it was going to be pretty straight forward however i am still new to all this so any help pointing me in the right direction would be appreciated. Thanks all.
views.py:
import random
from django.http import HttpResponse, Http404, JsonResponse
from django.shortcuts import render

from .models import Prediction

# Create your views here.
def home_view(request, *args, **kwargs):
    return render(request, "pages/home.html", context={}, status=200)

def prediction_list_view(request, *args, **kwargs):
    """
    REST API VIEW
    Consume by JavaScript or Swift/Java/iOS/Andriod
    return json data
    """
    qs = Prediction.objects.all()
    predictions_list = [{"id": x.id, "content": x.content, "likes": random.randint(0, 122)} for x in qs]
    data = {
        "isUser": False,
        "response": predictions_list
    }
    return JsonResponse(data)

def prediction_detail_view(request, prediction_id, *args, **kwargs):
    """
    REST API VIEW
    Consume by JavaScript or Swift/Java/iOS/Andriod
    return json data
    """
    data = {
        "id": prediction_id,
    }
    status = 200
    try:
        obj = Prediction.objects.get(id=prediction_id)
        data['content'] = obj.content
    except:
        data['message'] = "Not found"
        status = 404
    return JsonResponse(data, status=status) # json.dumps content_type='application/json'

_____________________________________________________________________________________

↓↓↓↓ This is my home.html ↓↓↓↓

_____________________________________________________________________________________

{% extends 'base.html' %}

{% block head_title %}
Welcome
{% endblock head_title%}

{% block content %}
Welcome

    Loading...

{% endblock content %}


text:
Q: Dynamic add new panel to bootstrap accordion I write a function to dynamic add new panel to bootstrap accordion
and it work
My problem is the panel body show inverted
See the image below

And when i try the same code in jsfiddle it work fine
https://jsfiddle.net/Eadhassan/aqpbzcex/1/
This is my HTML code :
<button class="btn btn-default btn-block addPanel" type="button">Add panel</button>

This is my jQuery code :

Any body had this problem before

A: I solved my problem
it was in css file a role for rotate collapse button
many thanks for @Mohamed-Yousef


text:
Q: Regex to match "Item" but not "Items" in JQM Router Plugin I am pretty sure this question is all about regex.
I am using the JQM router plugin found here.  It uses regex to match up pages and bind event handlers. In the docs it states:

A typical mistake is forgetting the $ operator. If you have two pages,
  such as #product and #productList, a hypothetical route "#product"
  would match both pages, leading to unexpected behaviors

Ok.  So I have an #item page and an #items page so I prefixed #item with a $.  But now it doesn't bind the event handler at all.  If i dont use the dollar then the binding for item gets applied to both pages.  This is the actual implementation:
var router = new $.mobile.Router([
    {"#items": {events:"i", handler: items.controller.init}},
    {"#items(?:[?/](.*))?": {events:"bs", handler: items.controller.onPageBeforeShow}},

    {"#item": {events:"i", handler: item.controller.init}},
    {"#item(?:[?/](.*))?": {events:"bs", handler: item.controller.onPageBeforeShow}},

]);

A: The $ matches the end of the string in regex. You don't want to put it at the beginning, you want it at the end.
For example:
#product
  matches
#product
#productList

#product$
  matches
#product

Try this code:
var router = new $.mobile.Router([
    {"#items$": {events:"i", handler: items.controller.init}},
    {"#items(?:[?/](.*))?$": {events:"bs", handler: items.controller.onPageBeforeShow}},

    {"#item$": {events:"i", handler: item.controller.init}},
    {"#item(?:[?/](.*))?$": {events:"bs", handler: item.controller.onPageBeforeShow}},

]);

A: You must postfix, not prefix, i.e.
#items$
#items(?:[?/](.*))?$
#item$
#item(?:[?/](.*))?$


text:
Q: Why does FSharpLint suggest, "In F# code, use 'e1 || e2' instead of 'e1 or e2'" If I write the expression,
if not (expr1 or expr2) then value

I get the following warning from FSharpLint, In F# code, use 'e1 || e2' instead of 'e1 or e2'.
Why is using || preferred over using or? I want to write idiomatic code, but this appears to me to degrade readability. I really like the readability of the not function over !. the above example expression reads nicer and is much more declarative than the C# counterpart,
if (!(expr1 || expr2)) { return value; }

So why regress the readability improvement by suggesting double pipes instead of or?

A: According to the FSharpLint folks, it's not a Lint warning; it's a warning emitted by the F# compiler.
It's probably there because or doesn't have a corresponding and counterpart.  There is an and keyword, but it's not used for boolean operations, so you have to use && anyway, which means its better to use || for consistency.


text:
Q: STM32 SPI Driver Receiving Data Always 0 I'm trying to write an SPI driver using the stm32 LL libraries (for the STML4 system). I'm testing the SPI driver by writing 2 bytes to the MOSI line and listen for 1 byte on the MISO line. Using an oscilloscope I was able to verify the 2 bytes were correctly transmitted and the SPI slave device responds with a byte. See attached screenshot:

In the image, I am probing the SCLK and MISO lines. Clearly, the last 8 bits on the MISO line is 0b01110011 which is the expected data. The driver I wrote does not reflect this and is always reading a 0 from the SPI DR register. I'm having issues trying to run the code in debug mode due to the SPI peripheral (maybe I'm missing something) and can't output values using printf (don't have access to a UART interface). I was hoping for some ideas on what issues there could be.
void spi_transmit_receive( SPI_TypeDef* spi, uint8_t* tx, uint8_t* rx, uint16_t size )
{

    if( !LL_SPI_IsEnabled( spi ) )
    {
        LL_SPI_Enable( spi );
    }

    if( size > 1 )
    {
        LL_SPI_SetRxFIFOThreshold( spi, LL_SPI_RX_FIFO_HALF_FULL );
    }
    else
    {
        LL_SPI_SetRxFIFOThreshold( spi, LL_SPI_RX_FIFO_QUARTER_FULL );
    }

    uint8_t* rx_ptr = rx;
    uint8_t* tx_ptr = tx;

    uint16_t tx_count = size;
    uint16_t rx_count = size;

    while( tx_count > 0 || rx_count > 0 )
    {
        if( tx_count > 0 && LL_SPI_IsActiveFlag_TXE( spi ) )
        {
            if( tx_count > 1 )
            {
                LL_SPI_TransmitData16( spi, *((uint16_t*)tx_ptr) );

                tx_ptr += sizeof( uint16_t );

                tx_count -= 2;
            }
            else
            {
                LL_SPI_TransmitData8( spi, *tx_ptr );

                tx_count -= 1;
            }
        }

        if( rx_count > 0 && LL_SPI_IsActiveFlag_RXNE( spi ) )
        {
            if( rx_count > 1 )
            {
                *((uint16_t*)rx_ptr) = LL_SPI_ReceiveData16( spi );
                rx_ptr += sizeof( uint16_t );
                rx_count -= 2;

                if( rx_count <= 1 )
                {
                    // Switch to 8 bit mode for last 8 bits
                    LL_SPI_SetRxFIFOThreshold( spi, LL_SPI_RX_FIFO_QUARTER_FULL );
                }
            }
            else
            {
                *rx_ptr = LL_SPI_ReceiveData8( spi );
                //rx_ptr += sizeof(uint8_t);
                rx_count -= 1;
            }
        }
    }

    while( LL_SPI_IsActiveFlag_BSY( spi ) ) {}

    LL_SPI_Disable( spi );
}

A: You do not specify the specific STM32 part, so it is not possible to provide a specific user manual reference, there are at least two SPI peripheral variants across the range of STM32 parts, so it is not possible to be definitive for your part, but documentation for the STM32F1xx and STM32F2xx SPI_DR states (my emphasis):

Depending on the data frame format selection bit (DFF in SPI_CR1 register), the data
sent or received is either 8-bit or 16-bit. This selection has to be made before enabling
the SPI to ensure correct operation.

That is it is not valid to change the frame from 16 to 8 bit in the middle of a transaction.  It seems that you should operate this device exclusively in 8 bit mode and simply send two bytes.  I think, the use of a 16 bit frame is appropriate only if all transfers are a multiple of 16 bits.
I imagine what is happening is the device remains in 16 bit mode and the data being sent MSB first ends up in the MSB of SPI_DR.  But since the documentation suggests that this is undefined behaviour, all bets are off.


text:
Q: How can I plot a dataframe in R given in quarterly years? i have a dataset given with:
   Country Time      Value
1   USA    1999-Q1   292929
2   USA    1999-Q2   392023
3.  USA    1999-Q3   9392992
4

.... and so on. Now I would like to plot this dataframe with Time being on the x-axis and y being the Value. But the problem I face is I dont know how to plot the Time. Because it is not given in month/date/year. If that would be the case I would just code as.Date( format = "%m%d%y"). I am not allowed to change the quarterly name. So when I plot it, it should stay that way. How can I do this?
Thank you in advance!

A: Assuming DF shown in the Note at the end, convert the Time column to yearqtr class which directly represents year and quarter (as opposed to using Date class) and use scale_x_yearqtr.   See ?scale_x_yearqtr for more information.
library(ggplot2)
library(zoo)

fmt <- "%Y-Q%q"
DF$Time <- as.yearqtr(DF$Time, format = fmt)
ggplot(DF, aes(Time, Value, col = Country)) +
  geom_point() +
  geom_line() +
  scale_x_yearqtr(format = fmt)

(continued after graphics)

It would also be possible to convert it to a wide form zoo object with one column per country and then use autoplot.  Using DF from the Note below:
fmt <- "%Y-Q%q"
z <- read.zoo(DF, split = "Country", index = "Time",
  FUN = as.yearqtr, format = fmt)
autoplot(z) + scale_x_yearqtr(format = fmt)

Note
Lines <- "
Country Time Value
1 USA 1999-Q1 292929
2 USA 1999-Q2 392023
3 USA 1999-Q3 9392992"
DF <- read.table(text = Lines)

A: Using ggplot2:
library(ggplot2)

ggplot(df, aes(Time, Value, fill = Country)) + geom_col()

A: I know other people have already answered, but I think this more general answer should also be here.
When you do as.Date(), you can only do the beginning. I tried it on your data frame (I called it df), and it worked:
> as.Date(df$Time, format = "%Y")
[1] "1999-11-28" "1999-11-28" "1999-11-28"

Now, I don't know if you want to use plot(), ggplot(), the ggplot2 library... I don't know that, and it doesn't matter. However you want to specify the y axis, you can do it this way.


text:
Q: Vee-validate if/else input field I want to add a class (border 1px solid #ff0000) to an input element if there is an error. Like:
Error:
errors.has(name)

Input:
<input v-validate="validate" v-on:input="updateValue($event)" :type="type" :placeholder="placeholder"
               :name="name" :value="value" :class="classname" :id="id">

How can i achieve that?

A: Bind your class with an errors.has condition
<input v-validate="validate" :name="name" :class="{'classname': errors.has(name)}">


text:
Q: How to bind a Kendo UI Grid to a collection of my model in an editor template using MVC Razor I Have a Grid that is based on a Model Similar to
public class UserModel
{
  ...
  public IList<UserOrgModel> UserOrg {get; set;}
  ...
}

This Grid is set to .Editable(e => e.Mode(GridEditMode.PopUp).TemplateName("...") and open this editorTemplate to edit the row I selected (by pressing Action Button).
This Editor Template contain also a Grid that would be bind to my collection.
I defined my grid this way
@(Html.Kendo().Grid(Model.UserOrg)
  .Name("blabla")
  .Columns(col =>
  {
    col.Bound(c => c.Id);
  })
)

When I do this my grid based on my collection is always empty.
Any Idea how I can use Kendo UI  and its grid to do what I want.  I don't know how to bind my grid with the "collection" of my model.

A: I found my Answer here:
Grid Popup Editing Navigation Property Collection with nested Grid
I Downloaded the demo and All I wanted was there. This is exactly what I was looking for!

A: Honestly, I didn't fully understand your question. But if you are trying to bind the grid to a collection in your model. Here you go:
In the Kendo UI online demos, this example may help you. Scroll to the bottom portion of the page, click on "ASP.NET MVC" then click the "local_data.cshtml". Here is the code example edited to be more like your example:
@model UserModel

@(Html.Kendo().Grid(Model.UserOrg)
    .Name("Grid")
    .Columns(columns =>
    {
        //set up your columns here
        columns.Bound(u => u.Name).Title("Name");
    })
    .Pageable()
    .Sortable()
    .Scrollable(scr=>scr.Height(430))
    .Filterable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .ServerOperation(false)
     )
)

Update
I found another SO article that may help you: Kendoui MVC EditorTemplateName do not work in PopUp edit mode
I think what you want is to create an editor template in the ~\View\Shared\EditorTemplates folder that you reference using the column.EditorTemplateName("..").


text:
Q: Infinispan failover capability I'm trying to leverage Infinispan's distributed task failover and I can't seem to get it to work. A little background on what I am trying to do:
I have two server nodes in a cluster. These two nodes share a distributed cache and the cache contains information used to run a task. I am trying to implement a failover feature on them so that if a task is running on server #1 and it goes down, server #2 will be able to pick up the task and complete it.
1) I first create a DistributedCallable object:
    (MyJob) MyJob myJob = new MyJob(param1, param2);
2) Then I create a DistributedExecutorService and a DistributedTaskBuilder and configure it with the provided Infinispan random node failover policy:
DistributedExecutorService execService =
        new DefaultExecutorService(cacheManager.getCache());
DistributedTaskBuilder<Boolean> taskBuilder =
        execService.createDistributedTaskBuilder(myJob);
taskBuilder = taskBuilder.failoverPolicy(DefaultExecutorService.RANDOM_NODE_FAILOVER);

3) I build the distributedtask and then run it using the DistributedExecutorService:
DistributedTask<Boolean> distTask = taskBuilder.build();
execService.submit(distTask);

During my tests, I do see that the DistributedTask gets sent to either server #1 or server #2, and that the distributed cache is being updated properly by both servers. However, when I try testing for failover, it doesn't seem to work.
For example:
When the task is running on server #1 (I set the task to sleep for about ~20 secs), I kill server #1, yet I don't see the task being re-run or picked up by server #2. Vice versa.
I'm not sure if I'm missing anything, I've done this according to the Infinispan 7.0.x user guide. In order for failover to work do I need to use one of the provided server modules (Hot Rod/Memcached/REST Server/WebSocket Server)? I'm using Infinispan in its embedded mode (in the actual application) and the documentation makes it seem like using the Distributed Execution Framework should provide failover.
Any help would be much appreciated!

A: It seems that in order to apply the failover policy, you need to wait for the result of such task:
DistributedTask distTask = taskBuilder.build();
Future future = execService.submit(distTask);
Object ignoredReturnValue = future.get();

The downside is that also that if the originator node (where you call this code) crashes, the failover policy cannot be applied.


text:
Q: How can I Find user that has most orders (include user data) using C# EF and Linq I have an assignment, I have to find the User that has most orders (including user data).
Here is my database diagram.[Database Diagram ](https://i.stack.imgur.com/Ewog2.png)
Here is an example of getting most sold product(not included in the question):
var productsGroup = orders.GroupBy(x => x.Product)
                .ToDictionary(x => x.Key, y => y.Select(z => z.Count).Sum());

var mostSoldProduct = productsGroup.MaxBy(kvp => kvp.Value).Key;

A: Based on what I got from your question and the images you have attached, a linq query like this should work (notice that I assume the DbContext instance is _dbContext) :
_dbContext.OrderData.GroupBy(orderData => orderData.UserId)
.Select(g => new
{
    UserId = g.Key,
    MaxNumberOfOrders = g.Count()
}).OrderByDescending(x => x.MaxNumberOfOrders).FirstOrDefault();

This linq query results :
SELECT TOP(1) [o].[UserId], COUNT(*) AS [MaxNumberOfOrders]
FROM [OrderData] AS [o]
GROUP BY [o].[UserId]
ORDER BY COUNT(*) DESC

Which gives you the userId with the most orders and the number of orders.


text:
Q: A Scrollable div — Stick (or anchor) to bottom when content is added Basically I have a scrollable area, a container div, with loads of items of fixed height (say 50px).
When adding new content, the height of the div is gradually increased (i.e. the new content animates in such that its height increases from zero. All these are CSS transitions.
Now is there a way to 'anchor' the scrollable div to the bottom so that the content area in the scrollable div expands upwards and not downwards.
I would prefer a solution that does not not use setInterval().

Reply to the comment below.
The source is at Download-To-Dropbox/src (They are in Coffee and Stylus).
Try going to http://dtd.heroku.com (That's the live copy). You'll see that directories expand on the right pushing the parent directory to the left (basically it's like the column view in Finder – Mac).
The problem here is that once you drill into multiple dub-directories and the horizontal scrollbar appears, The new directory that opens is hidden to the right of the screen. I'd like it to be visible throughout the transition time.

A: Suppose your div's ID is scrolldiv. Here's the basic function that adds content to the div:
var dv = document.getElementById("scrolldiv");
dv.innerHTML += "
New Entry
";
animateAdd(1000); //animation lasts for 1000 ms (1 s)

Here's a prototype of the function animateAdd:
function animateAdd(duration) {
    var stepDur = duration / 50;
    var curHeight = 0;
    var dv = document.getElementById("scrolldiv");
    var lstDv = dv.getElementsByTagName("div");
    var newDv = lstDv[lstDv.length - 1];
    function doAnim() {
        if(curHeight >= 50) {
             //we're done!
             return;
        }
        curHeight ++;
        dv.scrollTop ++;
        newDv.style.height = curHeight + "px";
        setTimeout(doAnim, stepDur);
    }
    doAnim();
}

Demo: little link.
Hope that helped you in any manner!


text:
Q: Using UIAccessibilityAction:accessibilityPerformEscape Apple's docs for this protocol says of accessibilityPerformEscape
"Implement this method on an element or containing view that can be revealed modally or in a hierarchy. When a VoiceOver user performs a dismiss action, this method dismisses the view. For example, you might implement this method for a popover in order to give users a deliberate dismiss action to perform that closes the popover."
I can't find any information on what the dismiss action is.  Anybody have any clues?

A: Never mind, just found it here:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Accessibility/AccessibilityfromtheViewControllersPerspective.html
It's a two-fingered Z shape.


text:
Q: Can the locally 5-prism graphs be classified? What it says on the label, pretty much.
If some graph $\Gamma$ is locally a 3-prism for all $ x\in\Gamma $, then it's easy to prove $\Gamma$ is the triangular graph $T(5)$.
If $\Gamma$ is locally the 4-prism (ie: the cube), it's not quite as easy to prove there's two different possibilities: the 24-cell, or the complement of a $3\times5$ grid (this only got done in 1983).
http://www.sciencedirect.com/science/article/pii/0012365X83901164
There's at least one graph that's locally an 5-prism: let $G=\mathbb{Z}_{31}$ (additively), $S=\pm\{1,2,4,8,16\}$mod $31$ and $ \Gamma = Cay(G,S) $. It has $v=31$, $k=10$, diameter $2$, and is symmetric but not strongly regular.
More generally, let $q=2^n-1$, $G=\mathbb{Z}_q$ and $S=\pm\{1,2, \dots 2^{n-1}\}$ mod $q$. Then $ Cay(G,S) $ is locally an $n$-prism for $n\geq4$. For $n=3$ this construction gives the complete graph $K_7$; for $n=4$ it gives the smaller locally cubic graph. (The 24-cell is exceptional, not for the first time.)
For composite $q$ (most Mersenne numbers are), if $r$ is a sufficiently large factor of $q$ the same construction also defines a smaller graph which is locally an n-prism. (Use $G=\mathbb{Z}_r$ and $S$ mod $r$.) (This is probably gonna end up as a different question, so here's a taster; $n=8$ and $r=51$ gives a 51-vertex graph that is locally an 8-prism, and there's generally a lot of graphs for each $n$.)
However, $2^5-1=31$ is prime (a Mersenne prime), so there's only one graph here. Are there more, smaller or bigger? If it's unique, can it be proven?


text:
Q: Disk partion problems while installing ubuntu I have quite problem with disk partions while installing ubuntu basically I am confused how to recognize the *C:* disk in ubuntu as windows showing it 68gb and when i see in ubuntu while installing it doesn't show any such thing i know it come in mb but no similar came pls help I have 2 hard drives and have important data in those so can't just wipe out all howvee i wanna fresh install ubuntu

A: welcome to Linux!
All Unix based Operating systems (like Ubuntu) use a different File and Disk Layout than what Windows uses. Under Linux, you don't have drive Letters like C:, D:, etc. but instead there's a Filesystem root (displayed as "/") and all other Devices are just a File (e.g. /dev/sda1) that can be mounted to a Directory.
I know it's a bit confusing for Windows users, but basically, it means that in this case you will have to orientate yourself by the size of the Disk.
If you would like to learn more about this, there's a great Video from thiojoe about this topic: https://youtu.be/zZV4jSeBvFs
It talks a lot about why there typically is no A: or B: Drive in Windows, but at 3:12 he also explains how Linux handles Drives.


text:
Q: Behavioral difference between Gradient Desent and Hill Climbing I'm trying to understand the difference between these two algorithms and how they differ in solving a problem. I have looked at the algorithms and the internals of them. It would be good to hear from others who already experienced with them. Specially, I would like to know how they would behave differently on the same problem.
Thank you.

A: In addition to radbrawler's answer, they are however similar in the greedy approach that both use to find local minima/maxima. I may consider Gradient descent as the continuous version of the discrete Hill climbing technique.

A: Difference
The main difference between the two is the direction in which they move to reach the local minima (or maxima).

*

*In Hill Climbing we move only one element of the vector space, we then calculate the value of function and replace it if the value improves. we keep on changing one element of the vector till we can't move in a direction such that position improves. In 3D sapce the move can be visualised as moving in any one of the axial direction along x,y or z axis.

*In Gradient Descent we take steps in the direction of negative gradient of current point to reach the point of minima (positive in case of maxima). For eg, in 3D Space the direction need not to be an axial direction.


text:
Q: Delete Item - Doubly Linked list using Tail Recursion I am currently learning Doubly Linked Lists.
I have managed to convert write a doubly linked list that was nearly 100% functional. However I need to learn how to write it with tail recursion.
Below is my DLLNode code:
public class DLLNode
{
    private DLLNode previous;
    public DLLNode next;
    private String value;

    public DLLNode(String value)
    {
        this.value = value;
        this.previous = previous;
        this.next = next;
    }

    public DLLNode(String value, DLLNode next, DLLNode previous)
    {
        this.value = value;
        this.next = next;
        this.previous = previous;
    }

    public String GetDataItem()
    {
        return value;
    }

    public void setDataItem()
    {
        this.value = value;
    }

    public DLLNode GetPreviousNode()
    {
        return previous;
    }

    public void setPrevious(DLLNode previous)
    {
        this.previous = previous;
    }

    public DLLNode GetNextNode()
    {
        return next;
    }

    public void setNextNode(DLLNode next)
    {
        this.next = next;
    }

    public void addItem(String value) {
        if(this.next == null) {
            // Stopping condition
            DLLNode newNode = new DLLNode(value);
            this.next = newNode;
        } else {
            // Recurse
            this.next.addItem(value);
        }
    }

}

I have managed to get my AddItem working using tail recursion and I'm now looking into getting delete Item working. I'm guessing that like addItem I need deleteItem adding to my DLLNode.
Below is my DoublyLinkedList class:
public class DoublyLinkedList
{
    private int noOfItems;
    private DLLNode head;
    private DLLNode tail;

    // Default constructor
    public DoublyLinkedList()
    {
        head = null;
        tail = null;
        this.noOfItems = 0;
    }

    public void DeleteItem(int index)
    {
        if (index ==0)
        {
            System.out.println("Out of Bounds");
        }
        if (index > noOfItems)
        {
            System.out.println("Out of Bounds");
        }
        if (head == null)
        {
            System.out.println("No Item to remove");
        }
        else if (index == 1)
        {
            head = head.GetNextNode();
            noOfItems--;
        }
        else
        {
            int position = 0;
            DLLNode currentNode = head;

            while (currentNode != null) {
                if (position == index-1) {
                    currentNode.setNextNode(
                            currentNode.GetNextNode().GetNextNode());
                    noOfItems--;
                    break;
                }
                currentNode = currentNode.GetNextNode();
                position++;
            }
        }
    }
}

Any tips on where I can get started with converting this code would be greatly appreciated.
Kind Regards,
Ben.
P.S. Apologies for the way the code has formatted - I've tried to fix it but it won't seem to sort. Can anyone good at formatting code on her please try and sort it out?

A: private void DeleteItemHelper(final int indexToDelete, int curIndex, DLLNode curNode) {
    if (curIndex == indexToDelete) {
        // Handle removing a node with both a previous and next nodes.
    }

    else {
        DeleteItemHelper(indexToDelete, curIndex + 1, curNode.getNextNode());
    }
}

public void DeleteItem(int index) {
    DeleteItemHelper(index, 0, head);
}

A: Without further testing I think that you are forgetting to re-set the head reference of the node following the removed node:
if (position == index-1) {
    // Tail of currentNode is set to the node following
    // next node, but head of that node still points to the
    // node which should be removed from list
    currentNode.setNextNode(
        currentNode.GetNextNode().GetNextNode());
    noOfItems--;
    break;
}


text:
Q: ¿Como restar horas de un DateTime? Tengo un DateTime y necesito restar horas de una columna a la otra. Por ejemplo, quiero restar 12:45:00 - 12:25:00 y que el resultado sea 20.
Este el codigo que estoy usando
        for (int i=0; i<n; i++)
        {
            DateTime fecha1 = Convert.ToDateTime(inicio[i].ToString("HH:mm:ss"));
            DateTime fecha2 = Convert.ToDateTime(arrayhrllegada[i].ToString("HH:mm:ss"));
            //var duration = Math.Round(fecha1 - fecha2, 1);
            double horas = Math.Round(fecha2.Subtract(fecha1).TotalMinutes,1);

            dataGridView1.Rows[i].Cells[7].Value = horas.ToString();
        }

Es Inicio menos Llegada y el resultado es Tiempo de Espera

A: Para restar fechas puedes usar el Subtract() del DateTime
DateTime.Subtract Method
un ejemplo seria
DateTime fecha1 = Convert.ToDatetime("12:45:00");
DateTime fecha2 = Convert.ToDatetime("12:25:00");

double horas = fecha2.Subtract(fecha1).TotalHours;

TimeSpan.TotalHours Property

A: Puedes usar el TimeSpan para la diferencia de horas de la siguiente manera:
TimeSpan diferenciaHoras = new TimeSpan();
DateTime fechaInicio = new DateTime();
fechaInicio = DateTime.Parse("12:25:00");

DateTime fechaLlegada = new DateTime();
fechaLlegada = DateTime.Parse("13:30:00");

diferenciaHoras = fechaLlegada - fechaInicio;
int horas = diferenciaHoras.Hours;
double horasTotales = diferenciaHoras.TotalHours;

En este ejemplo, entre las 12:25 y las 13:30 hay una hora con 5 minutos. La propiedad TotalHours te dará el resultado de 1.083 que es la hora mas 0.083 horas que equivalen a los 5 minutos.
Si lo necesitas en minutos, entonces utilizas la propiedad TotalMinutes o multiplicas las horas obtenidas por 60.
double minutos = diferenciaHoras.TotalMinutes;

O
double minutos = horasTotales * 60;


text:
Q: FlatList is not rerendering upon data change I have an array of conversations and a function that checks if the recipient is online. However when that function changes its return value (boolean), the flatlist does NOT rerender. I tried extraData but with no luck. My code is:
flatList
        <FlatList
              data={conversations}
              extraData={isRefreshing}
              renderItem={(conversation) => (
                <TouchableOpacity
                  onPress={() => selectConversation(conversation.item)}
                  style={{
                    flexDirection: "row",
                    justifyContent: "space-between",
                    alignItems: "center",
                    borderBottomWidth: 1,
                    padding: 5,
                    marginBottom: 5,
                  }}
                >
                  <View>
                    <Text>{getRecipient(conversation.item).displayName}</Text>
                    <Text>{conversation.item.latestMessage}</Text>
                  </View>
                  {isUserOnline(conversation.item) && (
                    <Text style={{ color: "green" }}>ONLINE</Text>
                  )}
                </TouchableOpacity>
              )}
              keyExtractor={(item) => item._id}
            />

useEffect
  useEffect(() => {
    let handler = (data) => {
      console.log(data);
      setOnlineUsers((prevState) => {
        return data;
      });
      setRefreshing(!isRefreshing);
    };
    const unsubscribe = navigation.addListener("focus", () => {
      console.log("focused");
      socket.on("online-users-data", handler);
      socket.emit("join-online-users");
      getConversations();
    });

    return () => {
      socket.emit("leave-online-users");
      socket.off("online-users-data", handler);
      unsubscribe();
    };
  }, []);

isUserOnline()
  function isUserOnline(conversation) {
    const user = getRecipient(conversation);
    const onlineUser = onlineUsers.find((u) => u.userId === user._id);

    return (
      user && onlineUser && user._id.toString() === onlineUser.userId.toString()
    );
  }

A: I have solved this by adding onlineUsers to extraData. Damn it was confusing.


text:
Q: "Manifest merger failed with multiple errors, see logs" error, Arcore using Unity I'm a total beginner using unity and recently I've been looking into arcore. More specifically, I've been trying to get this example "HelloAR" up and running on unity version 2019.4.18f1 (https://developers.google.com/ar/develop/unity/quickstart-android)
I've followed the steps completely however I keep getting the same error, "Manifest merger failed with multiple errors, see logs".
After looking into the errors it seems that the problem was related to the gradle.
Here are the errors:

I've tried downloading gradle 6.6.1 and making it the custom gradle in unity,
I've checked the boxes shown in this manual : (https://developers.google.com/ar/develop/unity/android-11-build),
I've added the following code to both launchertemplate and maintemplate:
I've tried using other solutions but have not been able to fix it.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        // Must be Android Gradle Plugin 3.6.0 or later. For a list of
        // compatible Gradle versions refer to:
        // https://developer.android.com/studio/releases/gradle-plugin
        classpath 'com.android.tools.build:gradle:6.6.1'
    }
}

However, I've had no luck getting rid of these errors. Any help would be greatly appreciated!

A: For Unity 2019.3 and above
Enable Custom Base Gradle Template

Then go to it's location Assets -> Plugins -> Android -> baseProjectTemplate.gradle
Change your gradle to classpath 'com.android.tools.build:gradle:3.4.3'
Stay with Unity's recommended gradle

For Unity 2018
Enable custom main template

Go your mainTemplate.gradle and change your gradle version to classpath 'com.android.tools.build:gradle:3.4.3'
Stay with Unity's recommended gradle version aswell.


text:
Q: Nested ngFor Loop in Angular 13 Could not Work I have tried To loop in angular like shown in the images. but nothing worked.Here i showed my html & Ts Code . Here I have using Bootstrap5 to Style the template part. I'm new to angular please help me out to solve this issue. Thanks in Advance
This Is My Html Code

        {{job.ID}}{{job.Name}}

                {{mjob.MisscoId}}{{mjob.DescriptionOfTheProfession}}

                        {{smjob.MisscoId}}{{smjob.DescriptionOfTheProfession}}

this is My TypeScript
this.allJobSubMajorGroup = [
      {
        MisscoId: '001',
        Code: 'BA',
        DescriptionOfTheProfession: 'SubMajor1',
      },
      {
        MisscoId: '002',
        Code: 'LDC',
        DescriptionOfTheProfession: 'SubMajor2',
      },
      {
        MisscoId: '003',
        Code: 'ED',
        DescriptionOfTheProfession: 'SubMajor3',
      },
      {
        MisscoId: '004',
        Code: 'ESS',
        DescriptionOfTheProfession: 'SubMajor4',
      },
      {
        MisscoId: '005',
        Code: 'MSC',
        DescriptionOfTheProfession: 'SubMajor5',
      },
    ];
this.allJobFamily = [
      {
        MisscoId: 0,
        ID: '0',
        JobFamilyID: '28',
        Code: 'BA',
        Name: 'Edited',
      },
      {
        MisscoId: 1,
        ID: '1',
        JobFamilyID: '28',
        Code: 'BA',
        Name: 'Business And Administrative Services',
      },
      {
        MisscoId: 2,
        JobFamilyID: '1',
        ID: '2',
        Code: 'LDC',
        Name: 'CLerk',
      },
      {
        MisscoId: 3,
        JobFamilyID: '30',
        ID: '3',
        Code: 'ED',
        Name: 'Educational Service',
      },
      {
        MisscoId: 4,
        JobFamilyID: '2',
        ID: '4',
        Code: 'ESS',
        Name: 'Elementary, Secretarial and Skilled Service',
      },
      {
        MisscoId: 5,
        JobFamilyID: '33',
        ID: '5',
        Code: 'MSC',
        Name: 'Graduate',
      },
    ];
this.allJobSubMajorGroup = [
      {
        MisscoId: '001',
        Code: 'BA',
        DescriptionOfTheProfession: 'SubMajor1',
      },
      {
        MisscoId: '002',
        Code: 'LDC',
        DescriptionOfTheProfession: 'SubMajor2',
      },
      {
        MisscoId: '003',
        Code: 'ED',
        DescriptionOfTheProfession: 'SubMajor3',
      },
      {
        MisscoId: '004',
        Code: 'ESS',
        DescriptionOfTheProfession: 'SubMajor4',
      },
      {
        MisscoId: '005',
        Code: 'MSC',
        DescriptionOfTheProfession: 'SubMajor5',
      },
    ];

this.allJobMajorGroup = [
      {
        MisscoId: '00',
        Code: 'BA',
        DescriptionOfTheProfession: 'majorGroup1',
      },
      {
        MisscoId: '01',
        Code: 'LDC',
        DescriptionOfTheProfession: 'majorGroup2',
      },
      {
        MisscoId: '02',
        Code: 'ED',
        DescriptionOfTheProfession: 'majorGroup3',
      },
      {
        MisscoId: '03',
        Code: 'ESS',
        DescriptionOfTheProfession: 'majorGroup4',
      },
      {
        MisscoId: '04',
        Code: 'MSC',
        DescriptionOfTheProfession: 'majorGroup5',
      },
    ];

I want to show like this
the first image show the final output when all div get opened

the second image show when one div is opened


text:
Q: Angular Nested FormArray I'm trying to create a dynamic form with nested formArray using the following method but I'm getting this error "Failed to execute 'setAttribute' on 'Element': ']' is not a valid attribute name."
I not sure where i did wrong, could someone advise me on this?
TS:
createProductForm() {
this.productForm = this.formBuilder.group({
  variations: this.formBuilder.array([this.createVariation()])
});
}

createVariation() {
return this.formBuilder.group({
  variName: '',
  variOptions: this.formBuilder.array([this.createOptions()])
});
}

addVariation(): void {
(this.productForm.controls['variations'] as FormArray).push(this.createVariation());
}

createOptions() {
return this.formBuilder.group({
  optName: '',
  optStock: '',
  optSku: '',
  optDisPrice: '',
  optActPrice: ''
});
}

addOption(): void {
(this.productForm.controls['variOptions'] as FormArray).push(this.createOptions());
}

HTML:

            <button type="button" class="btn btn-primary" (click)="addVariation()">Add Variation</button>

                    <clr-input-container>
                      Variation Name
                      <input clrInput type="text" formControlName="variName"/>
                    </clr-input-container>

                        <clr-input-container>
                          Option Name
                          <input clrInput type="text" formControlName="optName"/>
                          <button type="button" class="btn btn-primary" (click)="addOption()">Add Tion</button>
                        </clr-input-container>

A: There is a typing mistake in your code, an extra square bracket is added

,
change it to

A: Typo fix -

  // Remove `]` from EOL


text:
Q: Pronouncing the Greek Alphabet for use in Mathematics I've noticed that sometimes when I am writing out equations and saying the symbols in my head I will slip up and say "p" for "$ \rho $" or mix the pronunciation between letters say "$ \eta $" for "$ \xi $" possibly because the latter symbol looks like a cursive "e" where the former sounds like the pronunciation of "e". I was worried that I was practicing bad habits and so decided to try to learn the alphabet with the correct pronunciation for use in mathematics once and for all.
Modern Greek pronunciation differs significantly from how I've heard the alphabet pronounced and so I think it is clear that living in the United States I should follow the American English pronunciation. However, there still seem to be considerable differences in pronunciation, or perhaps I am just obsessing over it. For example, two different American English pronunciations of zeta:
http://www.merriam-webster.com/dictionary/zeta
http://www.oxfordlearnersdictionaries.com/definition/english/zeta?q=zeta


text:
Q: Python: Get caret position in Linux I want to get gloval caret position in x;y coordinates of sreen. If it is posible, i want to use some python library. If no, maybe you can describe method to do it, that you know (command, c library, c++ library). All, that you know.
I want to have something like this: solution on Windows, but in Linux


text:
Q: Finding a given VTK module with CMake I am currently trying to add a clipping plane to my dataset on vtk for android.
No problem on the code so far but I have issues building the .apk as my program will not compile.
In order to be able to use the clipping plane as I intend to I have the following includes:
#include <vtkTransformPolyDataFilter.h>
#include <vtkClipPolyData.h>
#include <vtkSampleFunction.h>
#include <vtkPlane.h>
#include <vtkImplicitPlaneWidget2.h>
#include <vtkImplicitPlaneRepresentation.h>

Yet when I try to compile (thanks to a Cmake generated Makefile) I get:
error: vtkImplicitPlaneWidget2.h: No such file or directory
 #include <vtkImplicitPlaneWidget2.h>

So I thought that I should try and add the vtkInteractionWidgets component to my find_package() in my CMakeLists.txt to obtain this:
find_package(VTK COMPONENTS
  vtkInteractionStyle
  vtkRenderingOpenGL2
  vtkRenderingVolumeOpenGL2
  vtkRenderingFreeType
)

Yet when I do so, I get:
Requested modules not available:
vtkInteractionWidgets

So I checked my modules list in my vtkbin/lib/cmake/vtk-7.1/Modules and I can clearly see: vtkInteractionWidgets.cmake
Any help would be appreciated, thanks in advance :).

EDIT:
I did check VTKConfig.cmake which has: set(VTK_MODULES_DIR "/Users/.../VTK/vtkbin/lib/cmake/vtk-7.1/Modules"). This directory as stated above does contain the vtkInteractionWidgets.cmake.
However I noticed that my /Users/.../VTK/vtkbin/CMakeExternals/Install/vtk-android/lib does not contain the equivalent lib. The only lib that I have containing the keyword interaction is: libvtkInteractionStyle-7.1.a

A: So it turns this has to be done manually in the vtkAndroid.cmake file in VTK_SOURCE/CMake/vtkAndroid.cmake. There should be inside some lines to manually add each needed modules:
# Now cross-compile VTK with the android toolchain
set(android_make_flags
  -DANDROID_NDK:PATH=${ANDROID_NDK}
  #...
  -DModule_vtkFiltersCore:BOOL=ON
  #...

In my case I needed to add: -DModule_vtkInteractionWidgets:BOOL=ON


text:
Q: How to get the current working directory with os library and write a .txt file on it? I want to find the current working directory (cwd) with os library and write .txt file on it.
Something like this:
import os

data=["somedatahere"]
#get_the_current_directory
#if this_is_the_current_directory:
  new_file=open("a_data.txt", "a")
  new_file.write(data)
  new_file.close()

A:
import os

You're halfway there!
The rest of it is:
print(os.getcwd())

Of course, you don't need to know that value,
as a_data.txt or ./a_data.txt suffices.
As a side note, you'd be better off closing with a with handler:
with open('a_data.txt', 'a') as new_file:
    new_file.write(data)

Habitually using a Resource Manager means
never having to say, "sorry, forgot to close it!"

A: It can be done using the os library, but the new pathlib is more convenient if you are using Python 3.4 or later:
import pathlib
data_filename = pathlib.Path(__file__).with_name('a_data.txt')
with open(data_filename, 'a') as file_handle:
    file_handle.write('Hello, world\n')

Basically, the with_name function said, "same dir with the script, but with this name".


text:
Q: Validation issue when upgrading to state_machines gem I wanted to change from state_machine to state_machines.  As I started to do this I encountered that the state was no longer changing from the initial state.
reviewed some stackoverflow and other guides: -

*

*https://teamtreehouse.com/community/statemachines-usage

*state-machines/state_machines-activerecord#33

*Validation before persistance on state_machine gem
So changes i have made:

*

*using state-machines-activerecord gem

*add def initialize...
(see below)

*I am now getting a rake setup error on my data.  it
seems to have an issue with the validation the Contact ( a related
model that gets created first).  Regardless of state, the Contact is
always created first.  This ran fine before changing the gem.

any ideas?  i think i have included all relevant code.
gem-file:
ruby "2.2.2"
gem "rails", "4.2.1"
gem "pg", "0.17.1" # postgresql database
gem "state_machines-activerecord"

gem-lock file
state_machines (0.4.0)
state_machines-activemodel (0.3.0)
  activemodel (~> 4.1)
  state_machines (>= 0.4.0)
state_machines-activerecord (0.3.0)
  activerecord (~> 4.1)
  state_machines-activemodel (>= 0.3.0)`

lead.rb (model) is:
`class Lead < ActiveRecord::Base
  belongs_to :created_by_user, class_name: "User", inverse_of: :leads_created
  belongs_to :contact
  belongs_to :user
  accepts_nested_attributes_for :contact
  validates :contact, presence: true
state_machine :state, initial: :new_lead do
    state :claimed
    state :referred
    state :broadcast
    state :unclaimed`

    `event :claim! do
      transition all => :claimed
    end

    event :unclaim! do
      transition claimed: :unclaimed
    end

    event :refer! do
      transition new_lead: :referred
    end

    event :broadcast! do
      transition all => :broadcast
    end`

`def initialize(*)
    super() # NOTE: This *must* be called, otherwise states won't get
    initialized
  end`

CONTROLLER
def lead_attributes
    params.require(:lead).permit(   :claimed,
      :contact_id,
      :status,
      :state,
      :user_id

setup_acceptance.rake
def create_contact(options={})
  user               = User.find_by(last_name: "Smith")
  contact_attributes = { created_by_user: user, user: user }
  attributes         = contact_attributes.merge options
  contact = Contact.create! attributes
  contact.save!
  contact
end
def create_lead(options={})
  user              = User.find_by(last_name: "Smith")
  client_attributes = { user: user, created_by_user: user }
  attributes        = client_attributes.merge options
  Lead.create! attributes  ****(LINE 1311 where error message occurs)****
end

rake.setup
Lead.transaction do #(NOTE: THIS IS LINE 435)
    create_lead(  #(NOTE: THIS IS LINE 436)
      user: User.find_by(last_name: "Smith"),
      contact: Contact.find_by(last_name: "Lozar"),
      status: 0,
      state: "claimed"
        }
      ]
    )

error:
rake aborted!
ActiveRecord::RecordInvalid: Validation failed: Contact Please enter a value
/Users/workspace/ab/lib/tasks/setup_acceptance.rake:1311:in `create_lead'
/Users/workspace/ab/lib/tasks/setup.rake:436:in `block (2 levels) in <top (required)>
/Users/workspace/ab/lib/tasks/setup.rake:435:in `block in <top (required)>'
Tasks: TOP => setup_sample_data
(See full trace by running task with --trace)

A: with great thanks @avdi
The solution was to change:
super()

...which discards all the initialization arguments
to:
super

...which retains them implicitly.


text:
Q: Game Center doesn't accept my code after I updated to Swift 2 This is my code:
if GKLocalPlayer.localPlayer().authenticated {
            if mode == 60 {
                var scoreReporter2 = GKScore(leaderboardIdentifier: "countrymaster60") //leaderboard id here

                scoreReporter2.value = Int64(score) //score variable here (same as above)
                var scoreArray: [GKScore] = [scoreReporter2]
                GKScore.reportScores(scoreArray, withCompletionHandler: {(error : NSError!) -> Void in
                    if error != nil {
                        print("error")
                    }

The error message it gives:

Cannot invoke 'reportScores' with an argument list of type
  '([GKScore], withCompletionHandler: (NSError!) -> Void)'

Any suggestions?

A: The documentation says that the method signature is:
class func reportScores(_ scores: [GKScore], withCompletionHandler completionHandler: ((NSError?) -> Void)?)

So you need to make the error variable in the completion handler an Optional.
Change
GKScore.reportScores(scoreArray, withCompletionHandler: {(error : NSError!) -> Void in

for
GKScore.reportScores(scoreArray, withCompletionHandler: {(error : NSError?) -> Void in


text:
Q: Python MySQLdb/mysqlclient: bind a named set (or tuple or list) as parameter Background: Not much documentation on MySQLdb Connector
Maybe I'm looking in the wrong places, but there's not much documentation about Python's MySQLdb family of connectors. Perhaps PEP249 is meant to do the job. Oracle's MySQL/Python connector seems to have much better docs, but at the moment I'm working with mysqlclient (the 3.x version of MySQLdb, which wraps around the C connector).
Named Parameters in MySQLdb: working for single values
After much searching, I stumbled upon beautiful syntax for binding named parameters, so long as they are a single value. For instance (made-up query to simplify the case):
query = """
        SELECT...
        WHERE
             name = %(name)s AND
             gender = %(gender)s
        """
parameters = {'name': name, 'gender': gender}
cursor.execute(query, parameters)

This properly escapes the parameters. Terrific.
Named Parameters in MySQLdb: how to use iterables?
Now I'd like to use a set, list or tuple to build queries with IN. Something like:
query = """
        SELECT...
        WHERE
        gender = %(gender)s AND
        name IN %(nameset)s
        """

I found a similar question here but that query doesn't use named parameters (the placeholder is named, but not the iterable).
What am I missing? Would someone know the magic syntax to make this work?
I see in the MySQLdb code that paramstyle is set to format rather than pyformat, but pyformat does work for single values.
To clarify,

*

*I am not interested in an answer that just builds a string like ('sophie', 'jane', 'chloe') and concatenates it to the query. I need bound parameters to guarantee proper escaping.

*I am also not interested in concatenating a join that uses db.escape_string(), although I may end up going that route if nothing else works.

What I'm really after is a clean idiom that binds named iterable parameters, if there is one.

A: Don't love answering my own question, but it's been a day...
Having looked inside the MySQLdb code, it looks like I won't get my wish. The quoting function will always add one set of quotes too many.
This is where I've ended up (the fallback option I had mentioned):
idset = ('Chloe', 'Zoe', "Noe';drip dautobus")

quoted_ids = [mdb.escape_string(identifier).decode('utf-8') for identifier in idset]
sql_idset = "('" + "', '".join(quoted_ids) + "')"

query = """
        SELECT ...
            FROM ...
            JOIN ...
            WHERE
              someid = %(someid)s AND
              namae IN """ + sql_idset

parameters = {'someid': someid}
cursor.execute(query, parameters)

Only one of the parameters is bound. The set in the IN clause is pre-quoted.
Not my favorite thing to have to do, but at least each value is run through the MySQLdb quoting function in order to quote any potentially harmful stuff.
The decode is there because escape_string prepares a byte string, but the query being built with the bound parameter someid is a string. Maybe there is an easier way. If you find one, let me know.

A: I don't know how to express it specifically in MySQLdb but it just works out of the box with the MySQL connector library (version: 1.4.4, MySQL 5.7.x) as suggested in this other answer:
cursor.execute('SELECT * FROM test WHERE id in %(l)s', {'l': (1,2,3)})

If MySQLdb messes it up then I suggest acquiring direct cursor somehow.


text:
Q: Extetions Tab Not on GNOME Tweak I am trying to install themes to my system so I can have the look I want. Everywhere I looked seems to point to GNOME Tweak, and so far the app has worked fine. However, the Shell option is locked due to it saying I haven't enabled the User Theme extension. I have tried installing the theme, as well as all of the extensions I have been told, however the Extensions tab still seems to not exist. How would I fix this so I can enable the User Theme option?

A: If you are now using 22.04 LTS with GNOME v40 matters have changed.
You should search for Extension Manager (use left Windows key) and when open you should see an extension listed called User Themes.
Select Install


text:
Q: How to allow users to see a document's metadata but not its contents I would like to create a permission level that allows users to see the metadata of documents in a document library but disallows them to open and read the document. I naively thought this would be accomplished by enabling the "View Items" permission and disabling the "Open Items" permission. But obviously the meaning of these permissions is different from what I assumed. The "View Items" permission by itself seems to enable users not only to see the document metadata but also to open and read the document.
Is there any way to achieve the desired permission level?

A: I discovered this by accident.
We have a document library with PDFs and metadata. If you allocate the permission 'view only' the users can see the list with metadata, but when they open the pdf they get access denied.
We have office web application but for this particular site they are turned off. However I believe that a word, excel or pp document it would be opened in read only. Pdfs behaves differently.


text:
Q: AttributeError: 'GoogleImageScraper' object has no attribute 'driver' So, i'm trying to make a face comparision with python and a google image scaper but I don't know why I'm getting this error:
Traceback (most recent call last):
  File "c:\Users\..\Desktop\face_recognition\main.py", line 79, in find_image_urls
    self.driver.get(self.url)
AttributeError: 'GoogleImageScraper' object has no attribute 'driver'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\..\Desktop\face_recognition\main.py", line 189, in <module>
    image_urls = image_scrapper.find_image_urls()
  File "c:\Users\..\Desktop\face_recognition\main.py", line 81, in find_image_urls
    self.driver.get(url=self.url)
AttributeError: 'GoogleImageScraper' object has no attribute 'driver'

My main.py file
Please help me this is very important.


text:
Q: Is Fubini's theorem the right way to solve this? I was given this integral: $$\int_{0}^1 \int_{0}^\infty \frac{y\arctan(xy)}{(1+y^2)(1+x^2y^2)} dy dx $$
I tried using Fubini to change the integration order and what I got was:
$$\int_{0}^\infty \frac{(\arctan(y^2) - \arctan(0))}{2(1+y^2)}dy $$ and I cannot integrate further, is this how I should have solved this integral?

A: The second integral should have the square outside the arctan. And $\arctan(0)$ is $0$, so your answer is
$$
\frac{1}{2}\int_0^\infty \frac{\arctan(y)^2}{1+y^2}dy = \frac{1}{6}(\arctan(\infty)^3-\arctan(0)^3) = \frac{1}{6}\left(\frac{\pi}{2}\right)^3
$$


text:
Q: How to add listener to Firestore Geoquery? I'm following along with the official Firestore docs to create an app using geohashes and geoqueries (https://firebase.google.com/docs/firestore/solutions/geoqueries#query_geohashes)
I'm trying to add a listener to that query but I get the following error:
Declared closure result 'ListenerRegistration' is incompatible with contextual type 'Query'. I'm stumped because XCode recommends I replace "Query" with "Query" :D
All I did was add this listener to the sample code I linked above:
var queries = queryBounds.map { bound -> Query in
  return db.collection("cities")
    .order(by: "geohash")
    .start(at: [bound.startValue])
    .end(at: [bound.endValue])
    .addSnapshotListener { querySnapshot, error in
            guard let documents = queries?.documents else {
                print("Error fetching documents: \(error!)")
                return
            }
            let cities = documents.map { $0["name"]! }
            print("Current cities in CA: \(cities)")
        }
    }