text:
Q: Is there Factor analysis or PCA for ordinal or binary data? I have completed the principal component analysis (PCA), exploratory factor analysis (EFA), and confirmatory factor analysis (CFA), treating data with likert scale (5-level responses: none, a little, some,..) as a continuous variable. Then, using Lavaan, I repeated the CFA defining the variables as categorical.
I would like to know what types of analyses would be appropriate for and would be equivalent of PCA and EFA when data are ordinal in nature. And when binary.
I would also appreciate suggestions for specific packages or softwares that can be easily implemented for such analyses.

A: Traditional (linear) PCA and Factor analysis require scale-level (interval or ratio) data. Often likert-type rating data are assumed to be scale-level, because such data are easier to analyze. And the decision is sometimes warranted statistically, especially when the number of ordered categories is greater than 5 or 6. (Albeit purely logically the question of the data type and the number of scale levels are distinct.)
What if you prefer to treat polytomous likert scale as ordinal, though? Or you have dichotomous data? Is it possible to do exploratory factor analysis or PCA for them?
There are currently three main approaches to perform FA (including PCA as its special case) on categorical ordinal or binary variables (read also this account about binary data case, and this consideration about what might be done with ordinal scale).

*

*Optimal scaling approach (a family of applications). Also called Categorical PCA (CatPCA) or nonlinear FA. In CatPCA, ordinal variables are monotonically transformed ("quantified") into their "underlying" interval versions under the objective to maximize the variance explained by the selected number of principal components extracted from those interval data. Which makes the method openly goal-driven (rather than theory-driven) and important to decide on the number of principal components in advance. If true FA is needed instead of PCA, usual linear FA can then naturally be performed on those transformed variables output from CatPCA. With binary variables, CatPCA (regrettably?) behaves in the manner of usual PCA, that is, as if they are continuous variables. CatPCA accepts also nominal variables and any mixture of variable types (nice).

*Inferred underlying variable approach. Also known as PCA/FA performed on tetrachoric (for binary data) or polychoric (for ordinal data) correlations. Normal distribution is assumed for the underlying (then binned) continuous variable for every manifest variable. Then
classic FA is applied to analyze the aforesaid correlations. The approach easily allows for a mixture of interval, ordinal, binary data. One disadvantage of the approach is that - at inferring the correlations - it has no clues to the multivariate distribution of the underlying variables, - can "conceive of" at most bivariate distributions, thus bases itself not on full information.

*Item response theory (IRT) approach. Sometimes also called logistic FA or latent trait analysis. A model very close to binary logit (for binary data) or proportional log odds (for ordinal data) model is applied. The algorithm is not tied with decomposing of a correlation matrix, so it is a bit away from traditional FA, still it is a bona fide categorical FA. "Discrimination parameters" closely correspond to loadings of FA, but "difficulties" replace the notion of "uniquenesses" of FA. IRT fitting certainty quickly decreases as the number of factors grows, which is a problematic side of this approach. IRT is extandible in its own way to incorporate mixed interval+binary+ordinal and possibly nominal variables.
Factor scores in approaches (2) and (3) are more difficult to estimate than factor scores in classic FA or in approach (1). However, several methods do exist (expected or maximum aposteriori methods, maximum likelihood method, etc.).
Factor analysis model assumptions is chiefly the same in the three approaches as in traditional FA. Approach (1) is available in R, SPSS, SAS (to my mind). Approaches (2) and (3) are implemented mostly in specialized latent-variable packages - Mplus, LISREL, EQS.

*Polynomial approach. That has not been developed in full yet. Principal components can be modeled as polynomial combinations of variables (using polynomials is a popular way to model nonlinear effects of ordinal regressors.). Also, observed categories in turn can be modeled as discrete manifestations of polynomial combinations of latent factors.

*There exist a flourishing field of nonlinear techniques of dimensionality reduction; some of them can be applied or adopted to work with categorical data (especially binary or after binarizing into a high-dimensional sparse dataset).

*Performing classic (linear) FA/PCA on rank correlations or other associations suited for categorical data (Spearman/Kendall/Somer's etc.). In case of ordinal data, that is purely heuristic approach, lacking theoretical grounds and not recommended at all. With binary data, Spearman rho and Kendall tau-b correlations and Phi association all equal Pearson r correlation, therefore using them is nothing but doing usual linear FA/PCA on binary data (some perils of it here). It is also possible (albeit not unquestionable) doing the analysis on $r$ rescaled wrt its current magnitude bound.
Look also in this, this, this, this, this, this, this, this.


text:
Q: How to Retrieve a List from Firebase using a spinner? So I am trying to retrieve a list  of all the items based on the sector spinner, because some items belong to different sectors, and I want to display the cases that belong in a specific sector

I have two classes one that stores the status and date the other stores the location
Location Class
public class Location {

    public String sector;
    public String area;

    public double longitude;
    public double latitude;

    public String getSector() {
        return sector;
    }

    public String getArea() {
        return area;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }

    public Location()
    {

    }

    public Location(String sector , String area, double longitude, double latitude)
    {
        this. sector = sector;
        this. area = area;
        this.longitude = longitude;
        this.latitude = latitude;
    }

    @Override
    public String toString() {
        return "\n Sector='" + sector + '\'' +
                ",Area Name='" + area + '\'' +
                ",Longitude='" + longitude + '\'' +
                ",Latitude=" + latitude + "\n";

    }

Case Class
public class Case {

    public String date;
    public String caseStatus;

    public String getDate() {
        return date;
    }

    public String getCaseStatus() {
        return caseStatus;
    }

    public Case()
    {

    }

    public Case(String date,String caseStatus)
    {
        this.date = date;
        this.caseStatus = caseStatus;
    }

    @Override
    public String toString() {
        return "\nCase Date='" + date + '\'' +
                ",Case Status='" + caseStatus + "\n";

    }
}

A: Add Location to the Case class. Also you should make variables private.
public class Case {

    private Date date;
    private String status;
    private Location location;

    public Date getDate() {
        return date;
    }

    public String getStatus() {
        return status;
    }

    public Location getLocation() {
        return location;
    }

    public Case() {
    }

    public Case(Date date, String status, Location location) {
        this.date = date;
        this.status = status;
        this.location = location;
    }

    @Override
    public String toString() {
        return "\nCase Date='" + date + '\'' +
                ",Case Status='" + status + "\n";

    }
}

Open Firestore and start a project.
Connect it to Android Studio in Tools > Firebase > Firestore.
Use String for status, Timestamp for date and Map for location

Add this code to your project.
    ArrayList<Case> cases = new ArrayList<>();

    FirebaseFirestore firestore = FirebaseFirestore.getInstance();
    firestore.collection("cases")
    .whereEqualTo("location.sector", "somesector")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Case case = document.toObject(Case.class);
                            cases.add(case);
// now you have list of Case objects where sector equals "somesector"
                        }
                    }
                }
            });

How to add Case to Firestore collection:
Case case = new Case(new Date(), "positive", new Location("somesector", "somearea", 150d, 555d));

FirebaseFirestore firestore = FirebaseFirestore.getInstance();
firestore.collection("cases").add(case);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Renaming Recursively with if-condition I'm having big troubles combining the rename with an if-condition. PS cannot rename when the file has the same name as before and won't do anything afterwards.
Plus it's unable to rename recursively.
I wanna do sth like:
$entrys = Get-ChildItem -Recurse $myPath
foreach ($name in $entrys) {
    $newName=$name.FullName -replace('[\,\/\*\+\#\~\-\=\^\°\$\%\&\<\>\|]','')
    if (-not ($newName -like $name)) {
         Rename-Item $name -NewName $newName
    }
}

I found something similar here but they dont have any conditions there.
So how do I pipe into an if-condition before renaming, so I can pipe directly from get-childitem -recurse to if() then rename()? Or is there another possibility?
Thanks for help

A: When I try your code I have the same issue that it reports it's unable to rename the file. However, I modified a bit of your code, and now it seems to work:
$entrys = Get-ChildItem -Recurse $myPath -File
foreach ($name in $entrys) {
    $newName = $name.Name -replace('[\,\/\*\+\#\~\-\=\^\°\$\%\&\<\>\|]','')
    if ($newName -ne $name.Name) {
         Rename-Item -LiteralPath $name.FullName -NewName $newName
    }
}

First you have to only check for files and not folders. Because once you renamed a folder the files are no longer found when you recurse into a non existing folder name (one that has changed).
If you need to rename folders also. It needs some more work as the folder names might change.
Hope this helps you out.

A: My PowerShell doesn't throw any error on the Rename-Item cmdlet if the file has the same name. But you could try to use -ErrorAction 0.
However, this oneliner works for me:
gci $myPath -r | % { Rename-Item  $_.FullName  ($_.FullName -replace('[\,\/\*\+\#\~\-\=\^\°\$\%\&\<\>\|]','')) }


text:
Q: JQuery $().each exiting too early I'm using the function below to validate several input fields on a web form. The function iterates through the fields using jQuery .each() iteration. The ValidateInput function validates each individal input field, returning a true or false.
function ValidateForm() {
    var result = true;
    $('[data-regex]').each(function() {
        result = result && ValidateInput(this);
        // return true;
    });

    if ( result == false ) {
        $(".alert").show();
    }

    return result;
}

The problem I'm having is that the .each() is terminating early, as soon as any individual input field fails validation. I know that if function() returns false, the .each() will terminate, but I don't see how I'm doing that. I've even tried adding an explicit return true; as the last line of function(), but this made no difference.
For completeness, here's ValidateInput:
function ValidateInput(thisInput) {
    var fieldName = $(thisInput).attr('name');
    var fieldValue = $(thisInput).val();
    var regex = $(thisInput).attr('data-regex');
    console.log('validating field "' + fieldName + '" value "' + fieldValue + '" with regEx "' + regex + '"';
    var re = new RegExp(regex);
    var result = re.test(fieldValue);
    if ( result ) {
        console.log('- passed');
        $(thisInput.closest(".form-group")).addClass("has-success").addClass("has-feedback")
    } else {
        console.log('- failed');
        $(thisInput.closest(".form-group")).addClass("has-error").addClass("has-feedback")
    };

    return result;
}

The code that calls ValidateForm is as follows:
<input type="submit" name="ct108" value="Save User" onclick="return ValidateForm();" />

What am I missing?

A: Your ValidateInput method stops processing after the first one that doesn't pass validation because this line:
result = result && ValidateInput(this);

The way && works is that if the item on the left side is truthy the value on the right is returned as the value, otherwise the value on the left is returned as the value.
You can guarantee that each one is processed by flipping it around:
result = ValidateInput(this) && result;


text:
Q: Update statement in sqlite Hey what i want to do is update a table if the field exsits or insert the new value as given by the user.
For this what i do is select everything present in the table and check if the name entered by the user exists den update it or else insert it.
However the problem is when there is no data in the table the query fails and no data is inserted in the table.
NSString *query = @"select * from PPM";
sqlite_stmt *statement;

if(sqlite_prepare_v2(database,[query UTF8string],-1,&statement,NULL) == SQLITE_OK)
{
    while (sqlite3_step(statement) == SQLITE_ROW)
     //select data from table
     //if value entered is same as entered by user update the table
     //else insert in the table
}

A: How about INSERT OR REPLACE ?
You can use it with the UNIQUE constraints in your database structure to replace a value if it already exists, and insert it if it not there already.
shell> sqlite3
SQLite version 3.6.23
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> CREATE TABLE user(name UNIQUE, value);
sqlite> INSERT OR REPLACE INTO user VALUES("foo", 123);
sqlite> SELECT * FROM user;
foo|123
sqlite> INSERT OR REPLACE INTO user VALUES("foo", 321);
sqlite> SELECT * FROM user;
foo|321

A: If you use the INSERT OR REPLACE variation of the INSERT command, you don't need to check for existing data, as SQLite will do it for you, as long as there is a column with a UNIQUE constraint.
For example:
CREATE TABLE db.table(id UNIQUE, name);

INSERT OR REPLACE INTO db.table (id, name) VALUES (5, 'exep');

If an id of 5 exists in the table, this command will behave like an update, else it will be an insert.
See http://www.sqlite.org/lang_conflict.html for more details.


text:
Q: Export the outlook 2016 address book Is there a way to save a copy of the company address book to personal contacts in Outlook 2013 or 2016? I am using this method to get the address book onto a Windows phone user's handset!

A: I just wanted to save the company address book to local contacts in Outlook, and I found a quick and dirty way: Open the address book, select all contacts, Right-click and add to contacts!


text:
Q: Reuse result of stochastic python-igraph layout for future plotting I can successfully draw a nice network using the kk layout. Unfortunately, as kk is a stochastic layout, it looks different every time I plot it.
Is there a way to plot it twice with the same vertex and node arrangement but varying the visual style? I would like to visualize changes by changing the vertex colors and showing both plots side-by-side. Of course, in the future I might be interested in modifying edges too but this is not an issue right now.
I'm completely fine with the fact that the layout changes for every run of my programm, it should just plot it consistently within one run.
I can plot it twice if I save the resulting SVG but of course modyfining the underlying graph would be more elegant than just tweaking the raw SVG.
This plots the same layout twice but only as SVG:
s = cairo.SVGSurface(None, 800, 800)
model = ig.plot(g, **visual_style,
    vertex_label=[label_for_title(vertex[1]['title']) for vertex in enumerate(g.vs)],
    edge_color=[color_for_rating(edge[1]['rating']) for edge in enumerate(g.es)],
    target=s,
    mark_groups=action_systems)._repr_svg_()

display(SVG(model))
display(SVG(model))

A: Yes, there is, because igraph lets you store the layout of the vertices as an object: my_layout = g.layout('kk').
So you can plot your graph g multiple times with the same layout:
my_layout = g.layout('kk')
igraph.plot(g,layout=my_layout)
#now change g and/or the visual style
g.delete_edges([0,3,4])
igraph.plot(g,layout=my_layout,vertex_color=['blue' for _ in g.vs])

The new plotted graph will have the same vertex positions but now a few edges will be gone and all the vertices will be blue, naturally.


text:
Q: Redis Public Keys I am working on HackTheBox and have come across a question that Google has yet to answer. The current script looks like so:
#!/bin/bash

rm /root/.ssh/id*

ssh-keygen -t rsa

(echo -e "\n\n";cat "/root/.ssh/id_rsa.pub";echo -e "\n\n") > "/root/Desktop/postmanKey.txt"

redis-cli -h 10.10.10.160 flushall

cat "/root/Desktop/postmanKey.txt" | redis-cli -h 10.10.10.160 -x set bb

redis-cli -h 10.10.10.160 save

redis-cli -h 10.10.10.160 set dbfilename "authorized_keys"

redis-cli -h 10.10.10.160 save

ssh -i "/root/.ssh/id_rsa" redis@10.10.10.160

I understand all of it except for one thing. Why do we do (echo -e "\n\n";cat "/root/.ssh/id_rsa.pub";echo -e "\n\n") > "/root/Desktop/postmanKey.txt"  to generate a public key with 2 trailing and 2 following newlines? I have done some tinkering and quite a few Google searches but I have yet to turn up the reason why this is necessary. If I push the file to the server without the newlines and then attempt to connect via ssh, I am unable to. My only thought is maybe this is something to do with the common format of private keys:
-----BEGIN RSA PRIVATE KEY-----
....
-----END RSA PRIVATE KEY-----
however, we are connecting with a private key, but pushing to the server a public key... hence why I am lost. Thank you for any information!


text:
Q: Word to describe an action you do to relax/de-stress I'm trying to remember an adjective that describes something you do to help yourself relax/de-stress, but I can't think of it. It's similar to therapeutic, but when I checked the synonyms I couldn't find it. I wouldn't say it's a common word either.
Ex: After a long day at work, I enjoy cooking because it's _______ to me.
To many, exercise is ______.

A: The adjectival form of relax is relaxing
Relaxing

Something that is relaxing is pleasant and helps you to relax.

*

*I find cooking very relaxing.

*We come here once a year expecting a quiet, relaxing holiday.

*After a long day at work, I enjoy cooking because it's relaxing to me.

*To many, exercise is relaxing.

A: After a long day at work, I enjoy cooking because it soothes me. To many, exercise is therapeutic.
soothe

To calm or placate (a person, for example).    To ease or relieve
  (pain, for example).
Having or exhibiting healing powers

A: Without further information this is a guess.
I first thought of the word "to unwind", but then realised you said it wasn't common. Then, reading your example sentence I found that "cathartic" may fit. But "cathartic" or "carthasis" goes further than to relax or destress; it has an association with purging inner emotions to release tension and is a form of therapy for oneself. The word goes back to Ancient Greece, I think it was used first by Aristotle, but in regard to drama. It is also commonly used in modern psychology and medicine, hence the therapeutic association. It's also used in ordinary pop culture or layman's terms.
Some examples of the use of "catharsis" are given at Merriam-Webster Dictionary:

Acting is a means of catharsis for her. Painting is a catharsis
  for me.
Merriam-Webster Dictionary

It also has this description about its origin and development:

Catharsis and cathartic both trace to the Greek word kathairein,
  meaning "to cleanse, purge." Catharsis entered English as a medical
  term having to do with purging the body—and especially the bowels—of
  unwanted material. The adjective cathartic entered English with a
  meaning descriptive of such a physically cleansing purge. It didn't
  take long for people to start using these words figuratively in
  reference to emotional release and spiritual cleansing.

So the word has got to do with "release" of emotions, and many people get that from doing certain activities.
If that's not the word you were thinking of let me know I'll delete the answer.


text:
Q: Como fazer um DePARA no SQL |        cliente      |
id  | cpf  | cpf_valido
2   | 1234 |  1
3   | 1234 |  1
5   | 4567 |  0

e preciso montar a tabela assim
|        de_para    |
 id  | id_para | cpf
 2   |    3    |1234
 3   |    3    |1234
 5   |    5    |4567

Resumindo, gerar um depara para os cpfs com o apontamento para o maior id se o cpf for valido
se o cpf for invalido manter o mesmo id

A: Segue uma sugestão para testes utilizando a função Max com a cláusula Over:
select
    id,
    case when cpf_valido = 1
        then max(id) over(partition by cpf)
        else id
    end as id_para,
    cpf
from cliente

A: SELECT t1.id
       CASE cpf_valido
         WHEN 1 THEN (SELECT MAX(t2.id)
                        FROM tabela t2
                       WHERE t2.cpf = t1.cpf)
         ELSE t1.id
       END AS id_para,
       t1.cpf
  FROM tabela t1


text:
Q: error "/clang:-1: linker command failed with exit code 1 (use -v to see invocation)" in Xcode I've installed some pods in my Xcode project and run the pods init and pods update commands to create workspace file. I'm using Xcode 10.1 (because my code is in Swift 3 and no latest Xcode doesn't support that). I've tried searching internet a lot but every time I run the project, I'm getting this error -

ld: symbol(s) not found for architecture x86_64 clang: error: linker
command failed with exit code 1 (use -v to see invocation)

I've installed following libraries in my pod file -

I've tried to to change Bitcode to 'No', and Reflection Metadata Level to 'None' but it doesn't work. And yes, of course, I'm using the .xcworkspace file and not the .xcodeproj file. I did the pod update command too in terminal but that doesn't help either!
This is my podfile -
# Uncomment the next line to define a global platform for your project
# platform :ios, '10.0'

# Pods for myproj
target 'myproj' do
  use_frameworks!
  pod 'Alamofire'
  pod 'AlamofireImage', '~> 3.1'
  pod 'AlamofireObjectMapper'
  pod 'Eureka'
  pod 'Firebase'
  pod 'Firebase/Core'
  pod 'Firebase/RemoteConfig'
  pod 'IQKeyboardManagerSwift', '5.0.0'
  pod 'SideMenuController'
  pod 'SnapKit', '~> 3.2.0'
  pod 'Fabric'
  pod 'Crashlytics'
  pod 'MGSwipeTableCell'
  pod 'SSZipArchive'
  pod 'RealmSwift'
  pod 'Realm'
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'DevSupport',
    'RCTText',
    'CxxBridge',
    'RCTNetwork',
    'RCTImage',
    'RCTAnimation',
    'RCTLinkingIOS',
#    'RCTWebSocket', # needed for debugging
    # Add any other subspecs you want to use in your project
  ]
  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'
  # Explicitly include Yoga if you are using RN >= 0.42.0
  pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'

 end

A: In case anyone is having similar problem, let me tell you that I was able to solve the problem by adding the following frameworks to Pods>React>General>Linked Frameworks and Libraries -
DoubleConversion.framework
glog.framework
folly.framework
Foundation.framework
JavaScriptCore.framework
yoga.framework


text:
Q: cv::bitwise_xor in JavaCV My question may seem silly to some people. But I couldn't find any answer on the internet.
Is there any equivalent function in JavaCv to the OpenCV function cv::bitwise_xor(Mat,Mat,Mat)? Thank you.

A: From the wiki of JavaCV:

If your favorite feature X of OpenCV has both a C API and a C++ API, JavaCV only maps the C API.

From the OpenCV documentation

C++: void bitwise_xor(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray())
C: void cvXor(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL)

So (although not tested) I would expect it's called cvXor.


text:
Q: How to, using the definiton of a limit, calculate the limit, if it exists in the first place, of the sequence $ a_{n} = \frac{n + 1}{3n - 4} $? I've been taught how to evaluate limits in high school, so I know that the limit of the sequence  $ a_{n} = \frac{n + 1}{3n - 4} $ is $ \frac{1}{3} $, but I have no idea how to show that using only the definition of a limit. This is pretty much the first time that I've been exposed to these types of "proof-problems", where, to solve the problem, you have to do more than just manipulate numbers whilst obeying the rules that the teacher had given me, so any kind of help, in whatever form, is most appreciated.

A: You have to prove that for every $\epsilon > 0$ you can find $n_0 \in \mathbb{N}$ s.t. $n > n_0 \implies |a_n - \frac 13| < \epsilon$
So now let's see what the equation on the right looks like. (To avoid any inconvinience with negative numbers you can consider $n \ge 2$). Then we have:
$$a_n - \frac 13 = \frac{n+1}{3n-4} - \frac 13 = \frac{3n+3 - 3n+4}{3(3n-4)} = \frac{7}{9n - 12}$$
Set the last value should be less than $\epsilon$ and now we have that:
$$\frac{7}{9n - 12} < \epsilon  \iff 9n - 12 > \frac 7\epsilon \iff n > \frac{7 +12 \epsilon}{9\epsilon}$$
So therefore you can choose $n_0 = \frac{7 +12 \epsilon}{9\epsilon}$ and it's not hard do see that this will give you a formal $\epsilon - \delta $ proof.


text:
Q: Associativity in Lambda calculus I am working on the exercise questions of book The Lambda calculus. One of the questions that I am stuck is proving the following:
Show that the application is not associative; in fact, x(yz) not equals (xy)z
Here is what I have worked on so far:
Let x = λa.λb. ab
Let y = λb.λc. bc
Let z = λa.λc. ac

(xy)z => ((λa.λb. ab) (λb.λc. bc)) (λa.λc. ac)
=> (λb. (λb.λc. bc) b) (λa.λc. ac)
=> (λb.λc. bc) (λa.λc. ac)
=> (λc. (λa.λc. ac) c)

x(yz) => (λa.λb. ab) ((λb.λc. bc) (λa.λc. ac))
=> (λb. ((λb.λc. bc) (λa.λc. ac)) b)
=> (λb. (λc. (λa.λc. ac) c) b)

Is this correct? Please help me understand.

A: I also think that your counter-example is correct.
You can probably get a simpler counter-example like this:

let x = λa.n and y, z variables then:
(xy)z => ((λa.n) y) z => n z
  x(yz) => (λa.n) (y z) => n

A: The derivations seem fine, at a glance.
Conceptually, just think that x, y, and z can represent any computable functions, and clearly, some of those functions are not associative. Say, x is 'subtract 2', y is 'divide by 2', and z is 'double'. For this example, x(yz) = 'subtract 2' and (xy)z = 'substract 1'.

A: It seems ok, but for simplicity, how about prove by contradiction?
Assume (xy)z = x(yz), and let
x = λa.λb. a     # x = const
y = λa. -a       # y = negate
z = 1            # z = 1

and show that ((xy)z) 0 ≠ (x(yz)) 0.

A: The book you mention by Barendregt is extremely formal and precise (a great book), so it would be nice to have the precise statement of the exercise.
I guess the actual goal was to find instantiations for x, y and z such that
x (y z) reduces to the boolean true = \xy.x and (x y) z reduces to the boolean false = \xy.y
Then, you can take e.g. x = \z.true and z = I = \z.z (y arbitrary).
But how can we prove that true is not convertible with false? You have no way to prove it inside the calculus, since you have no negation: you can only prove equalities and not inequalities. However, let us observe that if true=false then all terms are equal.
Indeed, for any M and N, if true = false then
                         true M N = false M N

but true M N reduces to M, while false M N reduces to N, so
                              M = N

Hence, if true = false all terms would be equal, and the calculus would be trivial. Since we can find not trivial models of the lambda calculus, no such
model may equate true and false (more generally may equate terms with different normal forms, that would require us to talk about the bohm-out technique).


text:
Q: The default value for vm.dirty_background_ratio Wondering why the default value for "vm.dirty_background_ratio" from Linux Server (CentOS and Ubuntu) is set to 40. Is this just a recommendation for safety? Or is there any particular reason why?
If the total system memory is over 32Gb, 40% is just a lot to set free. I googled pretty much all over the place, but we could not find enough rationale to support the ratio.


text:
Q: How do I route all traffic from clients connected to the DD-WRT to its OpenVPN tunnel tun0? I am setting a secondary (DD-WRT) router to act as a OpenVPN client so that all clients would get VPN access simply by connecting to the router. But seems clients traffic is always routed via the main gateway instead of the established VPN tunnel.
SETUP
ISP modem+router(gateway) <--LAN cable--> DD-WRT OpenVPN client <--LAN/WIFI--> clients

This secondary DD-WRT OpenVPN client can connect to the remote OpenVPN server ok.
I can ping hosts in the server side subnet by first telnetting into the DD-WRT.
The OpenVPN server also shows that the DD-WRT client is connected properly.
wget -O - http://icanhazip.com returns the remote server's public IP.
So the tunnel is up properly.
PROBLEM
Traffic from clients connected to my DD-WRT are routed through my gateway router,
not through the VPN tunnel tun0.
I think I need to forward traffic from br0 interface to tun0 interface.
I have tried following iptables rules and checked that IPv4 forward is enabled.
cat /proc/sys/net/ipv4/ip_forward ==> 1
cat /proc/sys/net/ipv4/conf/tun0/forwarding ==> 1
cat /proc/sys/net/ipv4/conf/br0/forwarding ==> 1

# These rules are saved by pressing the 'Save firewall' button
#and rebooting the DD-WRT router.
iptables -I FORWARD -i br0 -o tun0 -j ACCEPT
iptables -I FORWARD -i tun0 -o br0 -j ACCEPT

And separately
# These rules are saved by pressing the 'Save firewall' button
# and rebooting the DD-WRT router.
iptables -I FORWARD -s 192.168.2.0/24 -d 192.168.66.0/24 -j ACCEPT
iptables -I FORWARD -s 192.168.66.0/24 -d 192.168.2.0/24 -j ACCEPT

SETTINGS
ISP modem+gateway router
No settings modified. It is as ISP has set it.

DD-WRT OpenVPN client
- Firmware: DD-WRT v24-sp2 (08/12/10) vpn
- SPI firewall: Disabled
- WAN: Disabled
- Operating mode: Router   (this disables NAT, right?)
- Gateway: 192.168.2.1
- Local DNS: 8.8.8.8
- NTP client: Enabled

I don't post VPN server/client configs because the client can connect to the server without errors and both
ping and wget commands work properly from inside the DD-WRT.
So, my question is:
How do I route all traffic from clients connected to the DD-WRT to its OpenVPN tunnel tun0?
Am I using iptables incorrectly? Add a new route perhaps?
If some info is missing please ask.
Thank you in advance! :)
P.S. Below more info.
ROUTING TABLE (after VPN tunnel is up)
root@DD-WRT:~# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
87.219.xxx.xxx  192.168.2.1     255.255.255.255 UGH   0      0        0 br0
192.168.66.1    192.168.66.5    255.255.255.255 UGH   0      0        0 tun0
192.168.66.5    *               255.255.255.255 UH    0      0        0 tun0
192.168.5.0     192.168.66.5    255.255.255.0   UG    0      0        0 tun0
192.168.2 .0    *               255.255.255.0   U     0      0        0 br0
169.254.0.0     *               255.255.0.0     U     0      0        0 br0
127.0.0.0       *               255.0.0.0       U     0      0        0 lo
default         192.168.66.5    128.0.0.0       UG    0      0        0 tun0
128.0.0.0       192.168.66.5    128.0.0.0       UG    0      0        0 tun0
default         192.168.2.1     0.0.0.0         UG    0      0        0 br0

IP ROUTE SHOW
root@DD-WRT:~# ip route show
87.219.xxx.xxx via 192.168.2.1 dev br0
192.168.66.1 via 192.168.66.5 dev tun0
192.168.66.5 dev tun0  proto kernel  scope link  src 192.168.66.6
192.168.5.0/24 via 192.168.66.5 dev tun0
192.168.2.0/24 dev br0  proto kernel  scope link  src 192.168.2.160
169.254.0.0/16 dev br0  proto kernel  scope link  src 169.254.255.1
127.0.0.0/8 dev lo  scope link
0.0.0.0/1 via 192.168.66.5 dev tun0
128.0.0.0/1 via 192.168.66.5 dev tun0
default via 192.168.2.1 dev br0

IP RULE SHOW
root@DD-WRT:~# ip rule show
0:      from all lookup local
32766:  from all lookup main
32767:  from all lookup default

OpenVPN CLIENT LOG
root@DD-WRT:~# cat /var/log/messages | grep openvpn
May 24 15:47:21 DD-WRT daemon.notice openvpn[699]: OpenVPN 2.1.1 mipsel-unknown-linux-gnu [SSL] [LZO2] [EPOLL] built on Aug 12 2010
May 24 15:47:21 DD-WRT daemon.warn openvpn[699]: WARNING: file '/tmp/openvpncl/client.key' is group or others accessible
May 24 15:47:21 DD-WRT daemon.notice openvpn[702]: UDPv4 link local: [undef]
May 24 15:47:21 DD-WRT daemon.notice openvpn[702]: UDPv4 link remote: 87.219.xxx.xxx:1194
May 24 15:47:23 DD-WRT daemon.notice openvpn[702]: [server] Peer Connection Initiated with 87.219.xxx.xxx:1194
May 24 15:47:25 DD-WRT daemon.notice openvpn[702]: TUN/TAP device tun0 opened
May 24 15:47:25 DD-WRT daemon.notice openvpn[702]: /sbin/ifconfig tun0 192.168.66.6 pointopoint 192.168.66.5 mtu 1500
May 24 15:47:26 DD-WRT daemon.notice openvpn[702]: Initialization Sequence Completed

IFCONFIG
root@DD-WRT:~# ifconfig
br0
Link encap:Ethernet  HWaddr 00:1D:73:55:1C:A4
inet addr:192.168.2.160  Bcast:192.168.2.255  Mask:255.255.255.0
UP BROADCAST RUNNING PROMISC MULTICAST  MTU:1500  Metric:1
RX packets:14119 errors:0 dropped:0 overruns:0 frame:0
TX packets:10639 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:2068891 (1.9 MiB)  TX bytes:5382302 (5.1 MiB)

br0:0
Link encap:Ethernet  HWaddr 00:1D:73:55:1C:A4
inet addr:169.254.255.1  Bcast:169.254.255.255  Mask:255.255.0.0
UP BROADCAST RUNNING PROMISC MULTICAST  MTU:1500  Metric:1

eth0
Link encap:Ethernet  HWaddr 00:1D:73:55:1C:A4
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:13136 errors:0 dropped:0 overruns:0 frame:0
TX packets:10847 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2180726 (2.0 MiB)  TX bytes:5517739 (5.2 MiB)
Interrupt:4

eth1
Link encap:Ethernet  HWaddr 00:1D:73:55:1C:A6
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:210 errors:0 dropped:0 overruns:0 frame:198105
TX packets:3683 errors:14 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:41273 (40.3 KiB)  TX bytes:963954 (941.3 KiB)
Interrupt:2 Base address:0x5000

lo
Link encap:Local Loopback
inet addr:127.0.0.1  Mask:255.0.0.0
UP LOOPBACK RUNNING MULTICAST  MTU:16436  Metric:1
RX packets:28 errors:0 dropped:0 overruns:0 frame:0
TX packets:28 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:2034 (1.9 KiB)  TX bytes:2034 (1.9 KiB)

tun0
Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:192.168.66.6  P-t-P:192.168.66.5  Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
RX packets:56 errors:0 dropped:0 overruns:0 frame:0
TX packets:62 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:100
RX bytes:4734 (4.6 KiB)  TX bytes:4428 (4.3 KiB)

vlan0
Link encap:Ethernet  HWaddr 00:1D:73:55:1C:A4
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:13135 errors:0 dropped:0 overruns:0 frame:0
TX packets:10847 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1944080 (1.8 MiB)  TX bytes:5466622 (5.2 MiB)

A: Here I'm assuming that the lan and vpn interfaces on the server are br0 and tun0, respectively.
# Enable IP forwarding.
echo 1 > /proc/sys/net/ipv4/ip_forward

# Allow postrouting to tun0. You may want to use "-s" here to strictly limit forwarding to IPs on your LAN.
iptables -t nat -A POSTROUTING -o tun0  -j MASQUERADE

# Enable forwarding from the LAN to the VPN (and back via related and established connections).
# Again, you may want to use "-s".
iptables -A FORWARD -i br0 -o tun0 -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

It works for me on openwrt rotuer, and comes from @Xyne https://bbs.archlinux.org/viewtopic.php?pid=1208721#p1208721


text:
Q: Call and SMS permission is not given but still getting warning from google play Google Console

Android Manifest File

I have not used any of the call and sms permission but still i'm getting the warning message from google play..what would be the solution? Please suggest me!

A: As you've now posted your gradle file, it turns out the PayUMoney Android SDK is the culprit.
Other people have raised the issue on their GitHub repo, you need to submit a permissions declaration form to Google Play, explaining that you need the permissions to perform SMS verification.
Specifically, this exception from Google's help article:

SMS-based financial transactions (e.g. 5 digit messages), and related activity including OTP account verification for financial transactions and fraud detection


text:
Q: How can I access the value of a XML element using Xdocument I'm trying to edit a record inside a XML document, using C#, with the following structure:
<?xml version="1.0" standalone="yes"?>
<Questionnaire>
  <Record>
    <Pile>1</Pile>
    <Serno>1</Serno>
  </Record>
</Questionnaire>

I'm selecting the record successfully by using:
SernoID=txt_Serno.Text;
XElement xml = XElement.Load("path");
XElement x = xml.Elements().Where(p => p.Element("Serno").Value.Equals(sernoID.ToString())).First();

Now, if the user changes any data in the winform, I want to update it into the xml file, for which I'm using:
x.Element("Pile").Value = txt_pile.Text;
x.Save("path");

However, it keeps only the modified record, and removes all the other existing records. It probably has something to do with the save command?
Can anyone help please?
Thanks!!

A: x is the result of your query, so it is a single Record element. You then save that to your file at the specified path. This has the effect of overwriting your file with just this single element.
Make your changes as before, but change this line:
x.Save("path");

To this:
xml.Save("path");

This will save the whole document, not just a single element.


text:
Q: Count starts at 2 I don't know why but it disregards the first row of the table.
Please help:
    $row = 0;
    $con = mysqli_connect("localhost", "root", "root", "db");
    $query = "select * from user_accounts";
    $result = mysqli_query($con, $query);
    $row = mysqli_fetch_assoc($result);
    while($row = $result->fetch_array())
      {
      echo $row['ID'] . " " . $row['Username'];
      echo "
";
      }

A: $row = mysqli_fetch_assoc($result);
while($row = $result->fetch_array())

So, you fetch one, ignore it and then continue fetching

A: Two things, you're declaring an un-needed variable ($row = 0;)and you're fetching twice, which you shouldn't do:
$con = mysqli_connect("localhost", "root", "root", "db");
$query = "select * from user_accounts";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
  {
  echo $row['ID'] . " " . $row['Username'];
  echo "
";
  }


text:
Q: Shell script to check all the URLs from a file or list I'm looking for a shell script to check a list of URLs and give output. For example:
http://abc.com/index.php
http://abc1.com/index.php

I may place them in a separate file or inside the script. I need a valid HTTP response code for all these URLs. If all the URLs work, the response code must be HTTP OK HTTP/1.1 200 OK.
If any URL from the above URLs fails, I need output with an error message for that particular URL.

A: You will have to install wget is you don't have it already:
#!/bin/bash
IFS='
'
LIST='http://www.google.com
http://www.drk.com.ar/daphne.php
http://www.google.com/this-is-an-error
http://serverfault.com/questions
'
for I in $LIST
do
  wget -q --no-cache --spider $I
  if [ $? != 0 ]; then
    echo Error: $I
  fi
done


text:
Q: C# winFom Send DataTable to stimulsoft report i want to display a data table records that's not connected to any database
in a stimulation report. i try this lines of code but the report page is empty
what can i do?
        factorDT.TableName = "factorDT";
        factorDataSet.Tables.Add("factorDT");

        factorDT.Columns.Add("PCode", typeof(int));
        factorDT.Columns.Add("Title", typeof(string));
        factorDT.Columns.Add("UnitPrice", typeof(int));
        factorDT.Columns.Add("Count", typeof(int));
        factorDT.Columns.Add("TotPrice", typeof(int));

        private void simpleButton1_Click(object sender, EventArgs e)
        {
         stiReport1.RegData("factorDataSet",factorDataSet);
         stiReport1.Dictionary.Synchronize();
         stiReport1.Compile();
         stiReport1.Show(true);
        }

A: I solve this by saving my data table into XML file and load it to my StiReport


text:
Q: Google maps icon color Currently you can use googles chart api to load custom markers with different colors
See here: https://developers.google.com/chart/image/docs/gallery/dynamic_icons
But this has been deprecated. So to ensure that my website works in the future what should I be using?
Or is there some simple way of defining the color of the markers using css or something?

A: instead of using a deprecated library I found http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#StyledMarker which works perfectly :)


text:
Q: How to use a stored FetchRequest with NSFetchedResultsController? NSFetchedResultsController provides a lot of nice stuff free when working with tableViews.  I also understand that storing fetch requests in the model is good form.  Can I use both of these together for super core data goodness?  If so, how so?
This example from Mr. Zarra's excellent book shows the template returning an array and I've failed in my attempts to get a fetchedResultsController back.
- (NSArray*)retrieveBigMeals {

NSManagedObjectContext *moc = [self managedObjectContext];
NSManagedObjectModel *mom = [self managedObjectModel];
NSFetchRequest *request = [mom fetchRequestTemplateForName:@"bigMeals"];

NSError *error = nil;
NSArray *result = [moc executeFetchRequest:request error:&error];

if (error) {
[NSApp presentError:error]; return nil;
} return result;

A: Just use the ios navigation based application template with core data. They already have the code for using NSFetchedResultController there.


text:
Q: How to replace in array not integers number to empty string jQuery I have array with data :
["05:45", "06:00", "06:15", "06:30", "06:45", "07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30", "08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45", "15:00"]

For this data i need to replace numbers which are not equal to zero, so i must have array like this:
["", "06:00", "", "", "", "07:00", "", "", "", "08:00", "", "", "", "09:00", "", "", "", "10:00", "", "", "", "11:00", "", "", "", "12:00", "", "", "", "13:00", "", "", "", "14:00", "", "", "", "15:00"]

For this i create function but for some reason it's not working:

var intervals = ["05:45", "06:00", "06:15", "06:30", "06:45", "07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30", "08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45", "15:00"]

function hideNumbers() {
  for (var i = 0; i < intervals.length; i++) {
    var c = intervals[i].split(':');
    var time = parseInt(c[1])
    var result = (c[0] + ':' + c[1])

    if (time != 00) {
      intervals[i].replace(result, "");
    }
  }
  console.log(intervals)
}

hideNumbers();

So what is the problem?

A: .replace() doesn't replace in-place, it returns the replacement as a new string, so you need:
intervals[i] = intervals[i].replace(result, "");

var intervals = ["05:45", "06:00", "06:15", "06:30", "06:45", "07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30", "08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45", "15:00"]

function hideNumbers() {
  for (var i = 0; i < intervals.length; i++) {
    var c = intervals[i].split(':');
    var time = parseInt(c[1])
    var result = (c[0] + ':' + c[1])

    if (time != 00) {
      intervals[i] = intervals[i].replace(result, "");
    }
  }
  console.log(intervals)
}

hideNumbers();

Extra:
As pointed out in the comments, as you are looking to remove that entry, there's no need for the .replace() at all.
But it's useful to know why x.replace(... doesn't change x and needs to be x = x.replace(....
As an other extra: there's also no need for the parseInt(c[1]) and you can compare directly with if (c[1] === "00")

Extra Extra:
While the question was about your code specifically (with .replace() not replacing), there are other ways to do this, eg:

var intervals = ["05:45", "06:00", "06:15", "06:30", "06:45", "07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30", "08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45", "15:00"]

function hideNumbers() {
  intervals = intervals.map(x => x.split(":")[1]!=="00" ? "" : x);
  console.log(intervals)
}

hideNumbers();


text:
Q: using character R function I'm creating a function in R where I'm asking a letter (or a string). Here is an example with a first function:
fun.1<-function(a=2,b=3,c=4) return(a+b^2+c^3)

and another function using the first one:
fun.2<-function(letter.to.test="a",a=2,b=3,c=4){
   if(letter.to.test=="a") {a=0:10}
   else if(letter.to.test=="b"){b=0:10}
   else {c=0:10}
   return(fun.1(a,b,c))
}

How may I write fun.2 without the if else functions? In my real code, I have 46 parameters to test, so it's ugly to write 46 if else. Thank you

A: More general approach:
fun.2 <- function(letter.to.test="a", a=2, b=3, c=4) {
   if (letter.to.test %in% letters[1:3]) {
      assign(letter.to.test, 1:10)
      fun.1(a,b,c)
   }
}

A: You could substitute the test value into a call to <-. Then evaluate it to change the values.
fun.2 <- function(test = "a", a = 2, b = 3, c = 4) {
    eval(call("<-", as.name(substitute(test)), 0:10))
    fun.1(a, b, c)
}

fun.2()
# [1] 73 74 75 76 77 78 79 80 81 82 83

A: You don't need fun.2
fun.1<-function(a=2,b=3,c=4) return(a+b^2+c^3)

mapply(fun.1, a=1:10, SIMPLIFY = TRUE)
# [1] 74 75 76 77 78 79 80 81 82 83

mapply(fun.1, b=1:10, SIMPLIFY = TRUE)
# [1]  67  70  75  82  91 102 115 130 147 166

A: You want a switch statement.
fun.2<-function(letter.to.test="a",a=2,b=3,c=4){
   switch(letter.to.test,
      a = {a=0:10},
      b = {b=0:10},
      c = c=0:10}
   )
   return(fun.1(a,b,c))
}

A: If you want them all assigned to the same value (e.g., 0:10), try this:
fun.2<-function(letter.to.test="a",a=2,b=3,c=4){
  assign(paste(parse(text = letter.to.test)), 0:10)
  return(fun.1(a,b,c))
}


text:
Q: Merge columns of two DataTables using linq I have two DataTables: dt1 and dt2.
dt1:
ID     | Name     | Address | QTY
-------+----------+---------+-----
A1     | Dog      | C1      | 272
A2     | Cat      | C3      | 235
A3     | Chicken  | C2      | 254
A4     | Mouse    | C4      | 259
A5     | Pig      | C5      | 233

dt2:
ID     | Name     | Address | QTY MAX
-------+----------+---------+--------
A1     | Dog      | C1      | 250
A2     | Cat      | C3      | 200
A3     | Chicken  | C2      | 300
A6     | Rabbit   | C6      | 350

But, I want to merge dt1 and dt2 to dt3 like below:
ID     | Name     | Address | QTY   | QTY MAX
-------+----------+---------+-------+--------
A1     | Dog      | C1      | 272   | 250
A2     | Cat      | C3      | 235   | 200
A3     | Chicken  | C2      | 254   | 300
A4     | Mouse    | C4      | 259   | 0
A5     | Pig      | C5      | 233   | 0
A6     | Rabbit   | C6      | 0     | 350

Can any one help me?

A: This solution is not a linq solution as you could simply use DataTable.Merge & DataTable.PrimaryKey to get the desired output.
Here is a dummy example which you can use:
var dt1 = new DataTable();
var p1 = dt1.Columns.Add("a", typeof(int)); //Use this to add Primary Key constraint
dt1.Columns.Add("b");
dt1.Columns.Add("c");
dt1.Rows.Add("1", "apple", "10");
dt1.Rows.Add("2", "mango", "20");
dt1.Rows.Add("3", "orange", "30");
dt1.Rows.Add("4", "banana", "40");
dt1.PrimaryKey = new DataColumn[] { p1 }; //This removes duplication of rows

var dt2 = new DataTable();
var p2 = dt2.Columns.Add("a", typeof(int)); //Use this to add Primary Key constraint
dt2.Columns.Add("b");
dt2.Columns.Add("d");
dt2.Rows.Add("1", "apple", "50");
dt2.Rows.Add("2", "mango", "60");
dt2.Rows.Add("3", "orange", "70");
dt2.Rows.Add("5", "grapes", "80");
dt2.PrimaryKey = new DataColumn[] { p2 }; //This removes duplication of rows

var dt3 = dt1.Copy();
dt3.Merge(dt2);  // Merge here merges the values from both provided DataTables

Taking your question into consideration:
var dt1 = new DataTable();
var p1 = dt1.Columns.Add("ID", typeof(string));
dt1.Columns.Add("Name", typeof(string));
dt1.Columns.Add("Address", typeof(string));
dt1.Columns.Add("Qty", typeof(int));
dt1.Columns["Qty"].DefaultValue = 0; //Setting default value
dt1.Rows.Add("A1", "Dog", "C1", 100);
dt1.Rows.Add("A2", "Cat", "C3", 200);
dt1.Rows.Add("A3", "Chicken", "C2", 300);
dt1.Rows.Add("A4", "Mouse", "C4", 400);
dt1.Rows.Add("A5", "Pig", "C5", 500);
dt1.PrimaryKey = new DataColumn[] { p1 };

var dt2 = new DataTable();
var p2 = dt2.Columns.Add("ID", typeof(string));
dt2.Columns.Add("Name", typeof(string));
dt2.Columns.Add("Address", typeof(string));
dt2.Columns.Add("Qty Max", typeof(int));
dt2.Columns["Qty Max"].DefaultValue = 0; //Setting default value
dt2.Rows.Add("A1", "Dog", "C1", 600);
dt2.Rows.Add("A2", "Cat", "C3", 700);
dt2.Rows.Add("A3", "Chicken", "C2", 800);
dt2.Rows.Add("A6", "Rabbit", "C6", 900);
dt2.PrimaryKey = new DataColumn[] { p2 };

var dt3 = dt1.Copy();
dt3.Merge(dt2);

Output:

Thanks @shA.t for suggesting to include DataColumn.DefaultValue so that blank cells could be replaced with 0. Also his answer seems to include linq features which I guess is what you are looking for!

A: If your DataTables haven't primary key and you can't or don't want to change those DataTables you can use a code like this:
// At first you need to define your result `DataTable`
// So make it by cloning from first `DataTable`
var dt3 = dt1.Clone();
// Then add extra columns to it
dt3.Columns.Add("Qty Max", typeof(int));

// Second, you need to add rows of first `DataTable`
foreach (DataRow row in dt1.Rows)
{
    // When you don't have a primary key you need a code like this to find same rows:
    var dt2Row = dt2.Rows.OfType<DataRow>().SingleOrDefault(w => w["ID"].Equals(row["ID"]));
    var qtyMax = dt2Row?["Qty Max"] ?? 0;    // Here I set default value to `0`

    dt3.Rows.Add(row["ID"], row["Name"], row["Address"], row["Qty"], qtyMax);
}

// Third, you need to add rows of second `DataTable` that is not in first
var dt2OnlyRows =
    dt2.Rows.OfType<DataRow>().Where(w => dt1.Rows.OfType<DataRow>().All(x => x["ID"] != w["ID"]));
foreach (var row in dt2OnlyRows)
{
    dt3.Rows.Add(row["ID"], row["Name"], row["Address"], 0, row["Qty Max"]);
}


text:
Q: Video.mp4 not found after updating to latest Xcode I've an application that has a video which is running in the background (Like a background video). But after updating to the latest Xcode I'm getting an error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

I'm getting this error after removing the .mp4 file from Xcode and re-added it. Earlier I got an error like

Could not find videoName.mp4 on desktop

The video is placed exactly where it used to be and everything worked just fine till now. The video is located inside Xcode under the folder.
    private func setupView()
{
    let path = URL(fileURLWithPath: Bundle.main.path(forResource: "mydogwalkvideo", ofType: ".mp4")!)

    let player = AVPlayer(url: path)

    let newLayer = AVPlayerLayer(player: player)
    newLayer.frame = self.videoView.frame
    self.videoView.layer.addSublayer(newLayer)
    newLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill

    player.play()
    player.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.videoDidPlayToEnd(notification:)), name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: player.currentItem)

}

What could possibly gone wrong when I updated to the latest Xcode version? And how comes this error appears? I've a video and I've not changed anything in the code and it worked just fine for months.
Any help would be much appreciated!

A: Make sure the file is actually included in the project with the target membership.
For example:

Hope it helps


text:
Q: Как правильно вытащить данные с class без span внутри него? Подскажите, пожалуйста, как вытащить данные из следующего кода?

Завтра

+9°
      0°

 Завтра +9°
> 0°
> 0° облачно``

А нужно чтобы было так
> Завтра +9° 0° облачно

Понимаю, что проблема возникает из-за спана внутри класса day__temperature. Но как его отбросить не понятно.

A: Можно так решить проблему
import requests
from bs4 import BeautifulSoup

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.2)\
            AppleWebKit/537.36 (KHTML, like Gecko)\
            Chrome/63.0.3239.84 Safari/537.36',
        'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'
        }

url = 'https://pogoda.mail.ru/prognoz/semipalatinsk/'

page = requests.get(url, headers=headers).content

item = BeautifulSoup(page, 'lxml')

date = item.find('div', {'class': 'day__date'}).text

day_temperature = item.find('div', {'class': 'day__temperature'}).text

day_temperature_night = item.find('span', {'class': 'day__temperature__night'}).text

day__description = item.find('div', {'class': 'day__description'}).text

print(date, day_temperature[0:4], day_temperature_night, day__description)

A: Чтобы первую непустую строку напечатать из div.day__temperature элемента:
print(next(soup.find('div', 'day__temperature').stripped_strings))

или
print(next(soup.select_one('div.day__temperature').stripped_strings))

Результат в обоих случаях: +9°.

A: import requests
from bs4 import BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.2)\
        AppleWebKit/537.36 (KHTML, like Gecko)\
        Chrome/63.0.3239.84 Safari/537.36',
    'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'
    }

 url = 'https://pogoda.mail.ru/prognoz/semipalatinsk/'

 page = requests.get(url, headers=headers).content

 item = BeautifulSoup(page, 'lxml')

 presently = item.find('a', {'href': '/prognoz/semipalatinsk/14dney/#day2'}).text

 tomorrow = item.find('a', {'href': '/prognoz/semipalatinsk/14dney/#day3'}).text

 print(presently.replace('\n', ' ').replace('\t', ''))

 print(tomorrow.replace('\n', ' ').replace('\t', ''))


text:
Q: division of two matrices with different domination in python I'm trying to divide a matrix (4**4) over a matrix(4*1) such as:
A= np.array([[4.76169807e-07,0,0,0],
             [0,4.76211146e-07,0,0],
             [0,0,1.86128889e-06, 0],
             [0,0,0,1.88126161e-06]])

B=np.array([[3.95],[ 2.35],[2.35],[2.35]])

C=np.divide(A,B)

In Matlab I use C= A/B and the answer is a matrix(4*1)
C=
 [1.0e+06 *
  8.295360054732532
   8.294639966113035
   1.262565964938776
   1.249161724594699]

but in python is totally different and answer is a matrix (4*4)
C= [[1.20549318e-07 0.00000000e+00 0.00000000e+00 0.00000000e+00]
 [0.00000000e+00 2.02643041e-07 0.00000000e+00 0.00000000e+00]
 [0.00000000e+00 0.00000000e+00 7.92037826e-07 0.00000000e+00]
 [0.00000000e+00 0.00000000e+00 0.00000000e+00 8.00536855e-07]]

How can get the correct answer in python such as matlab?

A: The operation C=B/A is not well defined because matrix multiplication is not commutative (see here), so it can help to frame your problem in terms of matrix multiplication instead of division. That being said: Your MATLAB output appears to be the diagonal elements of matrix A divided element-wise by the by the elements of vector B.
In order to get this same behavior in python you will need to use
A= np.array([[4.76169807e-07,0,0,0], [0,4.76211146e-07,0,0],
[0,0,1.86128889e-06, 0], [0,0,0,1.88126161e-06]])
A = np.diag(A)
B = np.array([3.95,2.35,2.35,2.35])
C = np.divide(B, A)

Now we have the desired value in C:
array([ 8295360.06259213,
        4934785.79772679,
        1262565.96309453,
        1249161.72610358])


text:
Q: Using 7A power cord on 10A laptop Does using a 7A power cord on a laptop that needs 10A damage components or mess something up? I know I need a new one but I have already used the old power cord. This laptop is a Compaq Armada 1500 computer (20+ years old).

A: Assuming the computer really does draw more then 7 amps (which be very unlikely - even at only 100 volts that would be 770 watts  which would drain the battery in seconds to minutes and the laptop would need to disipate an impractical amount if heat ) this could theoretically be dangerous as the cord would heat up and possibly short out - so its a fire risk.
If this is a British plug with a 5 amp or 7 amp fuse in the base, it is ok to use. If not, the risk is very small [but not non existant. It would be a question if " why did the manufacturer specify a 10 amp cable?" My guess us that they were cheap and standard  and not to do with the laptop requirements.


text:
Q: Text node cannot appear in this state (Line 1, position 1) I'm just starting to learn C#, and I am using Koding to develop (since I don't currently have access to my Ubuntu machine). I'm attempting to get the Hello World program to work, but the compiler I'm using (which is Mono) isn't taking it.
This is the code that I'm using for the program:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1{
    class Program{
        static void Main(string[] args){
            Console.WriteLine("Hello, World!");
            Console.ReadLine();
        }
    }
}

I created a file, wrote the code, and attempted to compile it using xbuild program.cs but I got the error message Text node cannot appear in this state (Line 1, position 1).
What am I doing wrong here? Is it the compiler, the OS, the code?

A: xbuild expects a project or solution file (which are xml format), not a c# source file. You should pass that (e.g. xbuild program.sln), or if you don't have one then invoke the compiler directly by mcs program.cs or similar.
PS: You should have mentioned the command line you used in the original question, instead of in a comment later.


text:
Q: Debugging Random JavaScript Errors in CRM 2015 Turbo Forms I'm receiving random errors in multiple forms/entities for my CRM 2015.1 Online instance.  I recently reset my site map, hoping that would help, and it hasn't.  What is causing these errors, and how do I fix it?
<CrmScriptErrorReport>
  <ReportVersion>1.0</ReportVersion>
  <ScriptErrorDetails>
   <Message>Cannot read property 'firstChild' of null</Message>
   <Line>0</Line>
   <URL>/form/page.aspx?lcid=1033&themeId=b03aadd8-2a2a-406f-4365-9d9e69561feb&tstamp=70515986&updateTimeStamp=635742898971441709&userts=130912363895311265&ver=-682775896#etc=112&extraqs=%3f_gridType%3d112%26etc%3d112%26id%3d%257bE3257540-4327-E511-80F8-FC15B428DC1C%257d%26rskey%3d%257b00000000-0000-0000-00AA-000010001028%257d&pagemode=iframe&pagetype=entityrecord&rskey=%7b00000000-0000-0000-00AA-000010001028%7d&counter=1446763863308</URL>
   <PageURL>/form/page.aspx?lcid=1033&themeId=b03aadd8-2a2a-406f-4365-9d9e69561feb&tstamp=70515986&updateTimeStamp=635742898971441709&userts=130912363895311265&ver=-682775896#etc=112&extraqs=%3f_gridType%3d112%26etc%3d112%26id%3d%257bE3257540-4327-E511-80F8-FC15B428DC1C%257d%26rskey%3d%257b00000000-0000-0000-00AA-000010001028%257d&pagemode=iframe&pagetype=entityrecord&rskey=%7b00000000-0000-0000-00AA-000010001028%7d&counter=1446763863308</PageURL>
   <Function>anonymous(){var$v_0=this.$8q_1.toDictionary();var$$dict_3=$v_0;for(var$$key_4in$$dict_3){var$v_2={key:$$key_4,value:$$dict_3[$$key_4]};var$v_3=$v_2.value;if(!$v_3.$5Y_2){$v_3.initialize();}}var$v_1=this.get_viewMap().toDictionary();var$$dict_9=$v_1;for(va</Function>
   <FunctionRaw>function () {
        var $v_0 = this.$8q_1.toDictionary();
        var $$dict_3 = $v_0;
        for (var $$key_4 in $$dict_3) {
            var $v_2 = { key: $$key_4, value: $$dict_3[$$key_4] };
            var $v_3 = $v_2.value;
            if (!$</FunctionRaw>
   <CallStack>
    <Function>anonymous(){var$v_0=this.$8q_1.toDictionary();var$$dict_3=$v_0;for(var$$key_4in$$dict_3){var$v_2={key:$$key_4,value:$$dict_3[$$key_4]};var$v_3=$v_2.value;if(!$v_3.$5Y_2){$v_3.initialize();}}var$v_1=this.get_viewMap().toDictionary();var$$dict_9=$v_1;for(var$$key_Ain$$dict_9){var$v_4={key:$$key_A,value:$$dict_9[$$key_A]};var$v_5=$v_4.value;try{$v_5.bind();}catch($v_6){Mscrm.CrmDebug.fail(String.format('Exceptionencounteredbinding{0}:{1}',$v_5.getKey(),$v_6.message));catchError($v_6.message,window.location.href,0,true);}}}</Function>
    <Function>anonymous(){this.$9B_1=true;this.ui.bindUI();if(this.$4B_1.toArray().length>0){Mscrm.TurboForm.Control.PageManager.get_instance().startUIUpdate();}}</Function>
    <Function>anonymous(){this.$N_1.bindUI();}</Function>
    <Function>anonymous($p0,$p1,$p2){var$v_0=$p0._error;if(!IsNull($v_0)){var$v_1=Mscrm.ErrorInformation.createErrorInfo($v_0.Code,$v_0.DisplayText,$v_0.SerializedException);var$v_2=Mscrm.Utilities.createCallbackFunctionObject('errorDialogCallback',Mscrm.TurboForm.Control.PageBootstrapper,null,false);openErrorDlg($v_0.Code,$v_0.DisplayText,$v_1,0,0,$v_2);return;}else{for(var$$arr_6=$p0.Descriptor.FormDescriptor,$$len_7=$$arr_6.length,$$idx_8=0;$$idx_8<$$len_7;++$$idx_8){var$v_C=$$arr_6[$$idx_8];Mscrm.TurboForm.Control.PageBootstrapper.$Fo($v_C);}var$v_3='TODO:Handlelayouttemplatenotfound.';var$v_4=Mscrm.TurboForm.Control.PageBootstrapper.$3n();$v_4.descriptors=$p0.Descriptor.FormDescriptor;$v_4.ProcessControlRule=$p0.processControlRule;$v_4.primaryFormId=newMicrosoft.Crm.Client.Core.Framework.Guid($p0.Descriptor.PrimaryFormId);$v_4.entityMetadata=Mscrm.TurboForm.Control.PageBootstrapper.$Gl($p0.entityMetadata);$v_4.InlineEditSubGrids=Mscrm.TurboForm.Control.PageBootstrapper.$Gm($p0.InlineEditSubGrids);var$v_5=$p0.header;$v_4.applicationInitDeferredStatements=$p0.header.ApplicationInitDeferredStatements;$v_4.sfaTabsInitDeferredStatements=$p0.header.SFATabsInitDeferredStatements;$v_4.caseSFATabsInitDeferredStatements=$p0.header.CaseSFATabsInitDeferredStatements;var$v_6=Xrm.Internal.startMetricsStopwatch('InjectLayoutIncludestoPage');$v_6.start();Sys.Application.beginCreateComponents();eval($v_5.TurboApplicationInitStatements);Sys.Application.endCreateComponents();Mscrm.TurboForm.Control.PageBootstrapper.$FS($v_5.StyleIncludes);Mscrm.TurboForm.Control.PageBootstrapper.$F4($v_5.TurboScriptIncludes);Mscrm.TurboForm.Control.DisposalManager.clearExistingDataClientVariables();Mscrm.TurboForm.Control.DisposalManager.clearExistingLayoutClientVariables();Mscrm.TurboForm.Control.PageBootstrapper.$FR($v_5.ClientVariables);$v_6.stop();var$v_7=Xrm.Internal.startMetricsStopwatch('RenderFormLayout');$v_7.start();var$v_8=$v_5.JQueryTemplates;$v_4.templates=$v_8;for(var$v_D=0;$v_D<$v_8.length;$v_D++){var$v_E=$v_8[$v_D];if($v_E.Key==='rootJQueryTemplate'){$v_3=$v_E.Value;break;}}Mscrm.TurboForm.Control.PageBootstrapper.$H1($v_3);$v_7.stop();var$v_9=Xrm.Internal.startMetricsStopwatch('InitializeApplicationComponents');$v_9.start();Sys.Application.beginCreateComponents();eval(createFormControlLite);eval(createPageManager);eval(createEventManager);eval(SubGridCommandBarData);Sys.Application.endCreateComponents();$v_9.stop();if($v_4.formType!==7&&!$v_4.recordId.equals(Microsoft.Crm.Client.Core.Framework.Guid.get_empty())){var$v_F=Xrm.Internal.startMetricsStopwatch('RequestSubgridsData');$v_F.start();Mscrm.TurboForm.Control.PageBootstrapper.$H3();$v_F.stop();}var$v_A=Xrm.Internal.startMetricsStopwatch('InitializeXrmControlsandData');$v_A.start();Mscrm.TurboForm.Control.PageManager.get_instance().initialize();$v_A.stop();var$v_B=Xrm.Internal.startMetricsStopwatch('BindXrmtoHTML');$v_B.start();Mscrm.TurboForm.Control.PageManager.get_instance().bindUI();$v_B.stop();Mscrm.TurboForm.Control.PageManager.get_instance().initializeProcessControl($v_4);$v_4.layoutReady=true;Xrm.XrmPerformance.measureTime('OnLayoutReadyhandlers',function(){returnMscrm.TurboForm.Control.PageBootstrapper.$8D('OnLayoutReady');});Mscrm.Performance.PerformanceMarkerManager.get_instance().addMarker('PageReadyforDataBind',1);Mscrm.TurboForm.Control.PageBootstrapper.$DR($p1,$p2);}}</Function>
    <Function>anonymous($p1_0){$v_0.stop();var$v_1=Xrm.Internal.startMetricsStopwatch('ParseFormLayoutResponseJson');$v_1.start();var$v_2=Mscrm.TurboForm.Control.PageBootstrapper.$CS($p1_0);$v_1.stop();if($v_2){var$v_3=Mscrm.TurboForm.Control.PageBootstrapper.$EL($p1);var$v_4=Mscrm.TurboForm.Control.PageBootstrapper.$EK($p1);var$v_5=Xrm.Internal.startMetricsStopwatch('ProcessFormLayout');$v_5.start();Mscrm.TurboForm.Control.PageBootstrapper.$Go($v_2,$v_3,$v_4);$v_5.stop();}}</Function>
    <Function>anonymous(){if($v_0.readyState!==4){return;}$v_0.onreadystatechange=null;if($v_0.status!==200){}successCallback($v_0.responseText);$v_0=null;}</Function>
    <Function>requestPage(requestUrl,successCallback,asynchronous,headers)</Function>
    <Function>anonymous($p0,$p1){var$v_0=Xrm.Internal.startMetricsStopwatch('RequestFormLayout');$v_0.start();setLoadingText(Xrm.Internal.getResourceString('LOCID_PAGE_LOADING_REQUEST_DATA'));requestPage($p0,function($p1_0){$v_0.stop();var$v_1=Xrm.Internal.startMetricsStopwatch('ParseFormLayoutResponseJson');$v_1.start();var$v_2=Mscrm.TurboForm.Control.PageBootstrapper.$CS($p1_0);$v_1.stop();if($v_2){var$v_3=Mscrm.TurboForm.Control.PageBootstrapper.$EL($p1);var$v_4=Mscrm.TurboForm.Control.PageBootstrapper.$EK($p1);var$v_5=Xrm.Internal.startMetricsStopwatch('ProcessFormLayout');$v_5.start();Mscrm.TurboForm.Control.PageBootstrapper.$Go($v_2,$v_3,$v_4);$v_5.stop();}},false,$p1);}</Function>
    <Function>anonymous($p0,$p1){Mscrm.TurboForm.Control.PageBootstrapper.$EA();Mscrm.TurboForm.Control.PageManager.get_instance().$B_1=Mscrm.TurboForm.Control.PageBootstrapper.$3;Mscrm.TurboForm.Control.PageBootstrapper.$3.layoutReady=false;Mscrm.TurboForm.Control.DisposalManager.setLastFormLoadTimeoutIntervalJobId();var$v_0=[];Mscrm.TurboForm.Control.PageBootstrapper.$53($v_0,'x-crm-mismatch',$p0);Mscrm.TurboForm.Control.PageBootstrapper.$Cc($p1.toString(),$v_0);}</Function>
    <Function>anonymous($p0,$p1){var$v_0=null;if(IsNull($p1)||!$p1||IsNull(Mscrm.TurboForm.Control.PageBootstrapper.$3.formDataResponseAfterParse)){var$v_1=Mscrm.TurboForm.Control.PageBootstrapper.$Et();if(IsNullOrEmptyString($v_1)){setLoadingText(Xrm.Internal.getResourceString('LOCID_PAGE_LOADING_REQUEST_DATA'));window.setTimeout(function(){returnMscrm.TurboForm.Control.PageBootstrapper.$DR($p0);},15);return;}$v_0=Mscrm.TurboForm.Control.PageBootstrapper.$CS($v_1);var$v_2=$v_0._error;if(!IsNull($v_2)){var$v_3=Mscrm.ErrorInformation.createErrorInfo($v_2.Code,$v_2.DisplayText,$v_2.SerializedException);var$v_4=Mscrm.Utilities.createCallbackFunctionObject('errorDialogCallback',Mscrm.TurboForm.Control.PageBootstrapper,null,false);openErrorDlg($v_2.Code,$v_2.DisplayText,$v_3,0,0,$v_4);return;}else{Mscrm.TurboForm.Control.PageBootstrapper.$3.formDataResponseAfterParse=$v_0;}}else{$v_0=Mscrm.TurboForm.Control.PageBootstrapper.$3.formDataResponseAfterParse;}setLoadingText(Xrm.Internal.getResourceString('LOCID_PAGE_LOADING_PROCESSING_DATA'));$v_0.formData._formId=newMicrosoft.Crm.Client.Core.Framework.Guid($v_0.formData._formId.toString());Mscrm.TurboForm.Control.PageBootstrapper.$3.formData=$v_0.formData;Mscrm.TurboForm.Control.PageBootstrapper.$3.commandBarData=$v_0.commandBarData;Mscrm.TurboForm.Control.PageBootstrapper.$3.wrpcTokenData=$v_0.tokenData;Mscrm.TurboForm.Control.PageBootstrapper.$3.businessRulesVersion=$v_0.businessRulesVersion;Mscrm.TurboForm.Control.PageBootstrapper.$3.FormVersion=$v_0.formVersion;Mscrm.TurboForm.Control.PageBootstrapper.$3.attributeMappingXml=$v_0.mappedXmlString;Mscrm.TurboForm.Control.PageBootstrapper.$3.entityDisplayName=$v_0.entityDisplayName;Mscrm.TurboForm.Control.PageBootstrapper.$3.isCustomImagePresentInDatabase=$v_0.isCustomImagePresentInDatabase;Mscrm.TurboForm.Control.PageBootstrapper.$8Q=false;if(Mscrm.TurboForm.Control.PageBootstrapper.$3.formData&&Mscrm.TurboForm.Control.PageBootstrapper.$3.layoutReady){Mscrm.Performance.PerformanceMarkerManager.get_instance().addMarker('DataReady',1);var$v_5=Xrm.Internal.startMetricsStopwatch('BindDataandCreateControls');$v_5.start();var$v_6=Xrm.Internal.startMetricsStopwatch('ProcessCachedLayout');$v_6.start();var$v_7=Mscrm.TurboForm.Common.LayoutUrlCache.get_instance().getUrl(Mscrm.TurboForm.Control.PageBootstrapper.$3.etc,Mscrm.TurboForm.Control.PageBootstrapper.$3.navigationFormId,Mscrm.TurboForm.Control.PageBootstrapper.$3.processId,Mscrm.TurboForm.Control.PageBootstrapper.$3.formType);var$v_8=Mscrm.CrmUri.create(Mscrm.TurboForm.Control.PageBootstrapper.$3.formData._formlayoutUrl);var$v_9=Mscrm.TurboForm.Control.PageBootstrapper.$3.navigationFormId.equals(Microsoft.Crm.Client.Core.Framework.Guid.get_empty());var$v_A=!$v_7;var$v_B=!Mscrm.TurboForm.Control.PageBootstrapper.$3.navigationFormId.equals(Mscrm.TurboForm.Control.PageBootstrapper.$3.formData._formId);if($v_B){Mscrm.TurboForm.Control.PageBootstrapper.$3.navigationFormId=Mscrm.TurboForm.Control.PageBootstrapper.$3.formData._formId;Mscrm.TurboForm.Control.PageBootstrapper.$3.primaryFormId=Mscrm.TurboForm.Control.PageBootstrapper.$3.formData._formId;}Mscrm.TurboForm.Control.PageBootstrapper.$Hs();var$v_C=!Mscrm.TurboForm.Control.ProcessControlBootstrapper.bindProcessId(Mscrm.TurboForm.Control.PageBootstrapper.$3);Mscrm.TurboForm.Common.LayoutUrlCache.get_instance().addUrl(Mscrm.TurboForm.Control.PageBootstrapper.$3.etc,Microsoft.Crm.Client.Core.Framework.Guid.get_empty(),Mscrm.TurboForm.Control.PageBootstrapper.$3.processId,Mscrm.TurboForm.Control.PageBootstrapper.$3.formType,$v_8);Mscrm.TurboForm.Common.LayoutUrlCache.get_instance().addUrl(Mscrm.TurboForm.Control.PageBootstrapper.$3.etc,Mscrm.TurboForm.Control.PageBootstrapper.$3.navigationFormId,Mscrm.TurboForm.Control.PageBootstrapper.$3.processId,Mscrm.TurboForm.Control.PageBootstrapper.$3.formType,$v_8);if($v_A&&($v_9||!$v_B)&&!$v_C){var$v_J=[];Mscrm.TurboForm.Control.PageBootstrapper.$53($v_J,'x-crm-duplicate',$p0);requestPage($v_8.toString(),function(){},true,$v_J);}else{var$v_K=$v_A||$v_7.toString()!==$v_8.toString();if($v_K){Mscrm.TurboForm.Control.PageBootstrapper.$H7($p0,$v_8);return;}}$v_6.stop();Mscrm.TurboForm.Control.DisposalManager.clearExistingDataClientVariables();Mscrm.TurboForm.Control.PageBootstrapper.$FQ($v_0.clientVariables);Sys.Application.initialize();var$v_D=Xrm.Internal.startMetricsStopwatch('LoadPBLWebresource');$v_D.start();var$v_E=Mscrm.CrmUri.create('/_forms/formscript.js.aspx');$v_E.get_query()['formname']='crmform';$v_E.get_query()['airenabled']=true;$v_E.get_query()['businessrulesversion']=Mscrm.TurboForm.Control.PageBootstrapper.$3.businessRulesVersion;$v_E.get_query()['formid']=Mscrm.TurboForm.Control.PageBootstrapper.$3.navigationFormId;$v_E.get_query()['fver']=Mscrm.TurboForm.Control.PageBootstrapper.$3.FormVersion;Mscrm.TurboForm.Control.CustomScriptsManager.get_instance().loadWebResource($v_E);Mscrm.TurboForm.Control.CustomScriptsManager.get_instance().executeHandler('Mscrm.BusinessRulesScript.Initialize','',null);$v_D.stop();var$v_F=Xrm.Internal.startMetricsStopwatch('CreateCommonControls');$v_F.start();Mscrm.TurboForm.Control.PageBootstrapper.$E1();$v_F.stop();Mscrm.TurboForm.Control.PageManager.get_instance().bindData(Mscrm.TurboForm.Control.PageBootstrapper.$3);Xrm.XrmPerformance.measureTime('OnDataBoundhandler',function(){returnMscrm.TurboForm.Control.PageBootstrapper.$8D('OnDataBound');});var$v_G=Xrm.Internal.startMetricsStopwatch('CreateQuickForm');$v_G.start();if(Mscrm.TurboForm.Control.PageBootstrapper.$3.formType===7){Mscrm.GlobalQuickCreate.GlobalQuickCreateBehavior.showGlobalQuickCreate();Mscrm.GlobalQuickCreate.GlobalQuickCreateBehavior.showGlobalQuickCreateContainer(window.frameElement.id,true);}$v_G.stop();var$v_H=Xrm.Internal.startMetricsStopwatch('CreateRecordSetControl');$v_H.start();Mscrm.TurboForm.Control.PageBootstrapper.$E6();$v_H.stop();var$v_I=Xrm.Internal.startMetricsStopwatch('AddItemtoMRU');$v_I.start();Mscrm.Utilities.addEntityToRecent(Mscrm.TurboForm.Control.PageBootstrapper.$3.formData._entity);$v_I.stop();Mscrm.Utilities.showHideHierarchyButton(Mscrm.TurboForm.Control.PageBootstrapper.$3.get_isFormHierarchyEnabled());$v_5.stop();}}</Function>
    <Function>anonymous(){returnMscrm.TurboForm.Control.PageBootstrapper.$DR($p0);}</Function>
   </CallStack>
  </ScriptErrorDetails>
  <ClientInformation>
   <BrowserUserAgent>Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36</BrowserUserAgent>
   <BrowserLanguage>undefined</BrowserLanguage>
   <SystemLanguage>undefined</SystemLanguage>
   <UserLanguage>undefined</UserLanguage>
   <ScreenResolution>1920x1080</ScreenResolution>
   <ClientName>Web</ClientName>
   <ClienState>Online</ClienState>
   <ClientTime>2015-11-05T17:51:08</ClientTime>
  </ClientInformation>
  <ServerInformation>
    <OrgLanguage>1033</OrgLanguage>
    <OrgCulture>1033</OrgCulture>
    <UserLanguage>1033</UserLanguage>
    <UserCulture>1033</UserCulture>
    <OrgID>{8925BAEE-9186-419B-A1B4-422FE0539E27}</OrgID>
    <UserID>{31CBF85A-DF03-E511-80F5-FC15B428AD68}</UserID>
    <CRMVersion>7.1.1.3157</CRMVersion>
  </ServerInformation>
</CrmScriptErrorReport>


text:
Q: how to convert full date into short type date in javascript? I get full date in JavaScript. -> "Sun Feb 23 2020 10:12:46 GMT+0800 (CST)"
I'd like to convert this into short date(date type, not string) -> "2020-02-23"
How can I convert this?

A: There are a number of ways this can be achieved, however a simple approach that doesn't require a third-party library would be as follows:

const inputString = "Sun Feb 23 2020 10:12:46 GMT+0800 (CST)";

/* Parse date object directly from string of supplied format */
const date = new Date(inputString);

/* Define helper function that pads a zero to front on string, if
number less that 10 */
const padNumber = n => `${n < 10 ? '0' : ''}${n}`

/* Format desired output string, and use padNumber help on date parts
as needed */
const outputString = `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}`

console.log(outputString);

A: its not a build in function but you can always

iterate the string until the first number comes.
you start recording a 'date' string then,
then replace the whitespaces with dashes
and stop recording your date string at the first ':'
you could make a function out of this, or search for a built-in

A: You  can use a moment package to fulfil your purpose. Here is the small example.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import moment from 'moment';

export default class App extends React.Component {

constructor(props) {
    super(props);
    this.state = {
      dateText: '',
    };
  }

    onDOBDatePicked = (date) => {
      this.setState({
        dateText: moment(date).format('DD-MMM-YYYY')
      });
    }
    componentDidMount () {
      const date = "Sun Feb 23 2020 10:12:46 GMT+0800 (CST)";
      this.onDOBDatePicked(date);
    }

  render() {
    return (
      <View>
        <Text style={{ padding : 50 }}>
          {this.state.dateText}
        </Text>
      </View>
    );
  }
}


text:
Q: Include angular-Material Dependency Bower In CMD ,following command works fine.
bower install angular-material
I am trying to include angular-material dependency in bower.json.I added following line in json file.
 "angular-material": "~0.11.1",

But this is not working .I am not able to figure it out how to proceed.

A: To save the dependecy to the bower.json file you need to add --save.
Try this
bower install angular-material --save
--EDIT--
The error message is clear. You don't have git installed.
Bower needs the following to work-

*

*node

*npm

*git

Verify if you have all these 3 installed like so...

*

*node -v

*npm -v

*git --version

You can get more info here

A: I used following command which updates bower.json file automatically.
bower install bootstrap --save


text:
Q: Div aligned in the middle of another div I am trying to make a layout with a div which have some text in the middle, and bellow that text, 4 social media icons. So I have made a div with another div inside of it, but I can't center the last one vertically...
So, how do I center div "sec10_content" in the middle of div "section10"?
I know that this question has been asked before, but I can't manage the code in my case...
Here's the code:
HTML:

CSS:
.section10
{
    width:100%;
    height:320px;
    vertical-align: middle;
    background-color:#222222;
}
.sec10_content
{
    width: 50%;
    height: 100px;
    margin: auto;
    border: 1px solid white;
}

A: I think that adding display inline-flex would work.
.section10
{
    width:100%;
    height:320px;
    vertical-align: middle;
    background-color:#222222;
    display: inline-flex;
}

A: The way I like is to add these 3 lines of css on inner div
 position: relative;
 top: 50%;
 transform: translateY(-50%);

See JSFiddle.
Source: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/


text:
Q: Testing & Analysis of Shell (Bash) Scripts? I'm working on a project where we deploy our software to Linux machines. This involves a whole load of Bash, for example, the init scripts (e.g. service foo start for SysVinit. My big concern is that we don't test these the way we test the application layer code with JUnit, FindBugs etc as part of our CI pipeline. What solutions are usually relied upon here? Is it possible to test and analyse these low level Linux scripts the way we would the app layer code?

A: I don't know of any Bash unit test setup, but I did work with a man who was a old-school uber-scripter. He would write tests for his scripts. They consisted of turning on the xtrace (set -x) feature in the script being tested. He would then capture the output from xtrace (+ ...) from each test run/test case and he could grep through that, or parse it otherways, to ensure the correct operations were being performed. Hope that helps.


text:
Q: Extract part of the string elements in an array using jq I'm trying to extract part of the string in elements of an array, and create a new array with these extractions.
[
  "local/binaries/app-2.21.0.tar.gz",
  "local/binaries/app-2.20.0.tar.gz",
  "local/binaries/app-2.19.1.tar.gz",
  "local/binaries/app-2.19.0.tar.gz",
  "local/binaries/app-2.18.0.tar.gz"
]

Desired output
[
  "app-2.21.0",
  "app-2.20.0",
  "app-2.19.1",
  "app-2.19.0",
  "app-2.18.0"
]

A: You can use jq's capture function with regular expressions.
jq '[.[] | capture("(?<captured>app-[0-9]+\\.[0-9]+\\.[0-9]+)") | .[]]'

Try it out on jq playground.
Documentation: https://stedolan.github.io/jq/manual/#RegularexpressionsPCRE


text:
Q: Unable to start embedded container; nested exception is java.lang.IllegalArgumentException: Invalid  */ in servlet mapping Spring boot I am developing an application in spring boot with jersey. I'm new to Spring boot.When i try to deploy the war in tomcat7.0,I'm getting the following errors
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/leasing-management-spring]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:945)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1768)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.IllegalArgumentException: Invalid  */ in servlet mapping
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:687)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
    at org.springframework.boot.context.web.SpringBootServletInitializer.run(SpringBootServletInitializer.java:133)
    at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:124)
    at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:81)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5156)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 10 more
Caused by: java.lang.IllegalArgumentException: Invalid  */ in servlet mapping
    at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3075)
    at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3050)
    at org.apache.catalina.core.ApplicationServletRegistration.addMapping(ApplicationServletRegistration.java:192)
    at org.springframework.boot.context.embedded.ServletRegistrationBean.configure(ServletRegistrationBean.java:211)
    at org.springframework.boot.context.embedded.ServletRegistrationBean.onStartup(ServletRegistrationBean.java:195)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:222)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:84)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:206)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 20 more
web.xml

  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    Restful Web Application

          org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener

<filter>
    <filter-name>metricFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>metricFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextAttribute</param-name>
        <param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

pom.xml

http://maven.apache.org/maven-v4_0_0.xsd">
      4.0.0
      in.vit.leasing
      springBootCore
      war
      1.0-SNAPSHOT
      Leasing Maven Webapp
      http://maven.apache.org

<properties>
    <project.java.version>1.8</project.java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <jetty.version>9.3.0.v20150612</jetty.version>
    <jersey.version>1.19</jersey.version>
    <spring-boot.version>1.2.6.RELEASE</spring-boot.version>
    <slf4j.version>1.6.6</slf4j.version>
    <logback.version>1.0.9</logback.version>
    <hibernate.version>4.3.6.Final</hibernate.version>
    <spring.version>3.2.3.RELEASE</spring.version>
    <atomikos.version>3.8.0</atomikos.version>
    <sql.driver.version>4.0</sql.driver.version>
</properties>
<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey.contribs</groupId>
        <artifactId>jersey-guice</artifactId>
        <version>${jersey.version}</version>
    </dependency>

    <!-- <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId>
        <version>${jersey.version}</version> </dependency> -->

    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.6.0</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-xml-provider</artifactId>
        <version>2.6.0</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>2.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jersey</artifactId>
        <version>${spring-boot.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
        <version>${spring-boot.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>${spring-boot.version}</version>
        <scope>test</scope>
    </dependency>
    <!-- Spring boot Tomcat Dependency -->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <version>${spring-boot.version}</version>
        <scope>provided</scope>
    </dependency>
  <repositories>
    <repository>
        <id>java.net</id>
        <url>http://download.java.net/maven/2/</url>
    </repository>
</repositories>

<build>
    <finalName>leasing-management-spring</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${project.java.version}</source>
                <target>${project.java.version}</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>${jetty.version}</version>

            <configuration>
                <reload>automatic</reload>
                <scanIntervalSeconds>20</scanIntervalSeconds>
                <stopKey>todostop</stopKey>
                <stopPort>9999</stopPort>
            </configuration>

          </plugin>
       </plugins>
    </build>

</project>

Spring Boot Code
@SpringBootApplication
    public class Application extends SpringBootServletInitializer {
  @Override
    protected SpringApplicationBuilder configure
     (SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

public static void main(String[] args) throws Exception{
    SpringApplication.run(Application.class, args);

}

@Bean
public ServletRegistrationBean jerseyServlet(){
    ServletRegistrationBean register =
    new ServletRegistrationBean(new ServletContainer(),"*/");
    register.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyInitialization.class.getName());
    return register;
}}

Jersey Configuration
public class JerseyInitialization extends ResourceConfig{

public JerseyInitialization(){
    this.packages("in.vit.leasing.core.api");

}

}

A: The exception (or rather its cause) tells you exactly what's wrong:

Invalid */ in servlet mapping

In your Java code you try to instantiate the ServletRegistrationBean like this:
ServletRegistrationBean register =
new ServletRegistrationBean(new ServletContainer(),"*/");

As the exception says */ is not a valid servlet mapping. You
probably want /* instead.
From the Java Servlet Specification:

In the Web application deployment descriptor, the following syntax is used to define  mappings:

*

*A string beginning with a  ' / '  character and ending with a  ' /* '
  suffix is used for  path mapping.

*A string beginning with a  ' *. '  prefix is used as an extension mapping.

*The empty string ("") is a special UR L pattern that exactly maps to the  application's context root, i.e., requests  of the form http://host:port//. In this case the path info is  ' / '  and the servlet path and context path is  empty string ("").

*A string containing only the  '/ '  character indicates the "default" servlet of the  application. In this case the servlet path  is the request URI minus the context path and the path info is null.

*All other strings are used for exact matches only.


text:
Q: Reading local file via pyspark connected to Spark-Cluster managed by docker-compose I would like to host a spark cluster (a spark master and at least two workers) on my local machine with docker-compose running on Windows Subsystem on Linux (WSL).
I am running spark with the following docker-compose.yml from
https://raw.githubusercontent.com/bitnami/containers/main/bitnami/spark/docker-compose.yml

:
`
version: '2'

services:
  spark:
    image: docker.io/bitnami/spark:3.3
    environment:
      - SPARK_MODE=master
      - SPARK_RPC_AUTHENTICATION_ENABLED=no
      - SPARK_RPC_ENCRYPTION_ENABLED=no
      - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no
      - SPARK_SSL_ENABLED=no
    ports:
      - '8080:8080'
      - '7077:7077'
    volumes:
      - ./data:/tmp
  spark-worker:
    image: docker.io/bitnami/spark:3.3
    environment:
      - SPARK_MODE=worker
      - SPARK_MASTER_URL=spark://spark:7077
      - SPARK_WORKER_MEMORY=4G
      - SPARK_WORKER_CORES=1
      - SPARK_RPC_AUTHENTICATION_ENABLED=no
      - SPARK_RPC_ENCRYPTION_ENABLED=no
      - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no
      - SPARK_SSL_ENABLED=no
    volumes:
      - ./data:/tmp

`
Now I connect to the spark master with pyspark and try to read a local csv file from my Windows machine.
`
import pyspark
from pyspark.sql import SparkSession

conf = pyspark.SparkConf().setMaster('spark://localhost:7077')

spark = SparkSession \
    .builder.config(conf=conf) \
    .appName("Python") \
    .getOrCreate()

path = "C:\\Users\\user\\data\\data_1.csv"

df = spark.read.format("csv") \
    .option('header', True) \
    .option('multiLine', True) \
    .load(path)

df.show()

`
This returns the following error:
`
Traceback (most recent call last):
  File "connect.py", line 48, in <module>
    df = spark.read.format("csv") \
  File "Python\Python38\lib\site-packages\pyspark\sql\readwriter.py", line 177, in load
    return self._df(self._jreader.load(path))
  File "Python\Python38\lib\site-packages\py4j\java_gateway.py", line 1321, in __call__
    return_value = get_return_value(
  File "Python\Python38\lib\site-packages\pyspark\sql\utils.py", line 190, in deco
    return f(*a, **kw)
  File "Python\Python38\lib\site-packages\py4j\protocol.py", line 326, in get_return_value
    raise Py4JJavaError(
py4j.protocol.Py4JJavaError: An error occurred while calling o97.load.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 1.0 failed 4 times, most recent failure: Lost task 0.3 in stage 1.0 (TID 4) (172.30.0.2 executor 0): java.io.FileNotFoundException: File file:/C:/Users/user/data/data_1.csv does not exist

`
Reading the local file via pandas on the same path works as expected, so the file exists in this exact location. Converting the pandas df to a spark df works for smaller files, but that seems to be another, memory-related issue I guess. When mounting the file into the worker container, I can open a python shell inside the container and read the csv file via pyspark.
How can I read the local csv file from my machine and process it with spark running in docker-compose?


text:
Q: Cropping rectangle arround a face/coordinates I looking for a way to calculate a rectangle (x,y,width & height) which can be used for cropping an image around the coordinates of a selected face.
I have an image 995x1000 (https://tourspider.blob.core.windows.net/img/artists/original/947a0903-9b64-42a1-8179-108bab2a9e46.jpg) by which the center of the  face is located at 492x325. I can find this information using various services so even for multiple faces in an image I'm ableto find the most prominent - hence a single coordinate.
Now i need to make various sized cropped images from the source image (200x150, 200x200 & 750x250). Now I can't seem to solve how to best calculate a rectangle around the center coordinates while taking into account the edges of the images. The face should be as central as possible in the image.
Even after experimenting with various services (https://www.microsoft.com/cognitive-services/en-us/computer-vision-api) the result are pretty poor as the face, mainly in the 750x250, is sometimes not even present.
I'm also experimenting with the ImageProcessor (http://imageprocessor.org/) library with which you can use anchors for resizing but can't get the desired result.
Does anybody has an idea on how best crop around predefined coordinates?

A: Using Imageprocessor I created the following solution. It is not yet perfect but goes a long way ;)
public static void StoreImage(byte[] image, int destinationWidth, int destinationHeight, Point anchor)
    {
        using (var inStream = new MemoryStream(image))
        using (var imageFactory = new ImageFactory())
        {
            // Load the image in the image factory
            imageFactory.Load(inStream);

            var originalSourceWidth = imageFactory.Image.Width;
            var originalSourceHeight = imageFactory.Image.Height;

            // Resizes the image until the shortest side reaches the set given dimension.
            // This will maintain the aspect ratio of the original image.
            imageFactory.Resize(new ResizeLayer(new Size(destinationWidth, destinationHeight), ResizeMode.Min));

            var resizedSourceWidth = imageFactory.Image.Width;
            var resizedSourceHeight = imageFactory.Image.Height;

            //Adjust anchor position
            var resizedAnchorX = anchor.X/(originalSourceWidth / resizedSourceWidth);
            var resizedAnchorY = anchor.Y/(originalSourceHeight/resizedSourceHeight);

            if (anchor.X > originalSourceWidth || anchor.Y > originalSourceHeight)
            {
                throw new Exception($"Invalid anchor point. Image: {originalSourceWidth}x{originalSourceHeight}. Anchor: {anchor.X}x{anchor.Y}.");
            }

            var cropX = resizedAnchorX - destinationWidth/2;
            if (cropX < 0)
                cropX = 0;

            var cropY = resizedAnchorY - destinationHeight/2;
            if (cropY < 0)
                cropY = 0;
            if (cropY > resizedSourceHeight)
                cropY = resizedSourceHeight;

            imageFactory
                .Crop(new Rectangle(cropX, cropY, destinationWidth, destinationHeight))
               .Save($@"{Guid.NewGuid()}.jpg");
        }

    }