text:
Q: Implement Custom Filtering based on various parameters in Android I am developing an education based app which lists of subjects and containing courses.
It is implemented using View Pager(which has list of courses in subject) and PagerTabStrip(containing subject name)
class Subject contains List of Courses
public class Subject{
       private int id;
       private String name;
       private ArrayList<Course> courses;
    }

And class Course containing its own Attributes
public class Course {

    private String name;
    private String description;
    private String professorName;
    private String language;
    private boolean isNew;
    private String rating;
    private String imageUrl;
}

How to implement filtering based on Subject Name, Course Language, Course Professor Name and Course Rating ?
As in if course language and subject name are the filters then display only those subjects and containing courses as per set filter.

A: Create your adapter class based on filter logic of ArrayList for your Main Tabs and based on that bind your adapter to this PagerTabStrip.
For detailed answer Post your adapter class code or ArrayList example you want to filter.. so, we can help you more..


text:
Q: Regex password validation combination Need some help with a Regex please, I have accomplished what I need to do but only with a two step process, I have tried multiple rethinks but am unable to make the two regex's into only one.
Could someone please point me in the right direction? (have been through lots of tutorials, builders and what not but do not seem clever enough to figure it out!)
This is for password validation, ensuring at least one char, one number, one uppercase letter and ensuring first and last chars are not digits and password is at least 8 chars long. This is the server side version but I will also be placing the regex on client side too.
private bool ValidatePassword(string input)
{
    bool _return;
    var regEx = new Regex(@"^(?=(.*\d))(?=.*[a-z])(?=.*[A-Z])(?!\d).{8,}$");
    _return = regEx.IsMatch(input);

    if (_return)
    {
        regEx = new Regex(@"[^1](\D*)$");
        _return = regEx.IsMatch(input);
    }

    return _return;
}

A: Would this work?
var regEx = new Regex(@"^(?=(.*\d))(?=.*[a-z])(?=.*[A-Z])(?!\d).{7,}\D$");

Demo here: http://rubular.com/r/xyiSz3RCQr

A: Try this:
^\D{1}((?=(.*\d))(?=.*[a-z])(?=.*[A-Z])(?!\d).{6,})\D{1}$

redpajama_set_name: RedPajamaStackExchange


text:
Q: I have to find a splitting field of $x^{6}-3$ over $\mathbb{F}_{7}$ I want to find a splitting field of $x^{6}-3$ over $\mathbb{F}_{7}$. I learned that Finite field containing $\mathbb{F}_{7}$ is the form of $\mathbb{F}_{7^m}$ and it is normal extension. So I've tried to find smallest m containing a single root of $x^{6}-3$. If  $x^{6}-3$ is irreducible in $\mathbb{F}_{7}$, then $\mathbb{F}_{7^m}$ is splitting field of  $x^{6}-3$. But I don't know where I should start. Even, I cannot prove that $x^{6}-3$ is irreducible. For polynomial of degree less than 3, there is a method to determine whether it is irreducible or not. But this is not the case. And the try using Gauss' Lemma and Eisenstein is failed, because I cannot find ring $R$ of which field fraction is $\mathbb{F}_{7}$. Is it wrong approach for this kind of question?

A: $x^6-3$ has no roots in $\mathbb{F}_7$, since $3$ is not a quadratic residue $\!\!\pmod{7}$. Moreover, in $\mathbb{F}_7[x]$:
$$ \gcd\left(x^6-3,x^{49}-x\right) = \gcd\left(x^6-3,x^{48}-1\right) = \gcd\left(x^6-3,3^8-1\right) = 1 $$
hence there is no quadratic irreducible polynomial over $\mathbb{F}_7$ that is a divisor of $x^6-3$.
In a similar way:
$$ \gcd\left(x^6-3,x^{343}-x\right) = \gcd\left(x^6-3,x^{342}-1\right) = \gcd\left(x^6-3,-1\right) = 1 $$
hence there is no irreducible polynomial over $\mathbb{F}_7$ that divides $x^6-3$, hence $x^6-3$ is an irreducible polynomial over $\mathbb{F}_7$ and its splitting field is isomorphic to $\mathbb{F}_{7^6}$.

A: Yet another approach, which works because of the special nature of your polynomial $X^6-3$. Notice first that $3$ is a primitive element of $\Bbb F_7$, that is, it generates the cyclic group of order six consisting of the nonzero elements of this field. So any $\lambda$ with $\lambda^6=3$ must be a primitive $36$-th root of unity in its field.
Now you want the smallest extension of $\Bbb F_7$ having thirty-sixth roots of unity, in other words, you want the smallest $m$ such that $36|(7^m-1)$, in other words, smallest $m$ with $7^m\equiv1\pmod{36}$, in other words, you want the period of $7$ in the group $(\Bbb Z/36\Bbb Z)^*$. Well, the powers of $7$ in $\Bbb Z/36\Bbb Z$ are $1,7,13,19,25,31,1,\cdots$, so $m=6$ here.

A: I will answer this with more elementary techniques, because I'm not sure of what facts you are familiar with.  If $x^6-3$ factors, then it has a factor of degree $1$, $2$, or $3$ by a degree argument.
We can check that $x^6-3$ does not have factor of degree $1$ because it doesn't have a root in $\mathbb{F}_7$.  This can be done by plugging in all $7$ values in $\mathbb{F}_7$ or by Fermat's little theorem because $a^6\equiv 1$ for all $a\not\equiv0\pmod{7}$.
Since finite fields are uniquely determined by their order, we can follow the following idea: If $x^6$ had a factor of degree $2$, then a root of that factor would generate $\mathbb{F}_{7^2}$.  Since $-1$ is not a square in $\mathbb{F}_7$, we know that $x^2+1$ is irreducible in $\mathbb{F}_7$.  Therefore, let $\alpha$ be a root of $x^2+1$, then $\mathbb{F}_{7^2}=\mathbb{F}[\alpha]$.  We can check if there is a root of $x^6-3$ in this field.  More precisely, consider
$$
a_1\alpha+a_2.
$$
It seems natural to substitute $a_1\alpha+a_2$ for $x$ in $x^6-3$ and this would work, but it is easier to multiply the entire expression by $x$ to consider $x^7-3x$.  Substituting $a_1\alpha+a_2$ into this expression results in
$$
(a_1\alpha+a_2)^7-3(a_1\alpha+a_2)=a_1\alpha^7+a_2-3(a_1\alpha+a_2).
$$
This follows from Fermat's little theorem (and observing that most binomial coefficients have a factor of $7$).  Moreover, we know that $\alpha^2=-1$, so we can substitute this to get $-4a_1\alpha-2 a_2$ for $a_1\alpha+a_2$ to be a root, it must be that both $-4a_1=0$ and $-2a_2=0$, this only happens when $a_1=a_2=0$, but this doesn't satisfy the original equation.
You can continue with this logic for the cubic case as well.

A: I wanna use an easy tool:
1) it is not neccesary to check $3$ is square of not in $\mathbb F_7$. $x^6-1 \equiv 0 \mod 7$ for all $x \in \mathbb F_7^*$ which is well-known.
2) Use same trick again $3^6 \equiv 1 \mod 7$. That means $x^{36}\equiv 1 \mod 7$. Now $36\mid(7^6-1)$ trivially, it is $(7-1)(7^5+\cdots+1)$.  Moreover, $36 \not \mid (7^n-1)$ for $n <6$.  This means it is irreducible.


text:
Q: What is a word for something(like a tradition) which acts as a symbol that points to a particular underlying mindset? This dress code is a mere _______ of underlying chauvinism, mindset of controlling and subjugating women, and misogyny. It is not the dress-code but this mindset which is holding them back.
I want to say that this dress code is only one of the symbols which points to chauvinism, mindset of controlling and subjugating women, and  misogyny. Changing the dress code does not change the underlying mindset.

A: Perhaps "echo" might serve your purpose well.

"a close parallel or repetition of an idea, feeling, style, or event."
  Google search results of 'echo definition'

You might also find the synonyms of echo helpful.

trace, vestige, remnant, ghost, shadow, memory, recollection, remembrance; reminder, sign, mark, token, souvenir, indication, suggestion, hint;
  evidence

A: An appropriate word would be manifestation, which means something illustrative of something else, particularly when that something else is an abstraction.  In your example, there's something we can see (namely the results of a dress code) which serves to illustrate or characterize something we can't see (namely the abstraction of the mindsets of chauvinism and misogyny).

A: You could consider using reflection:

a thing that is a consequence of or arises from something else: Yet if we view the Government's recent behaviour as a collective reflection of what happens to each of us when we are under pressure, then things become clearer.

[Oxford Online Dictionary]

the production of an image by or as if by a mirror

[Merriam-Webster]

Student dress code is a reflection
  of educational,
  behavioral, and professional expectations. Students' behavior is often
  a reflection of what they wear.

A: I would say "subtext" as it means an implied or underlying metaphorical meaning.
But I would also suggest "pretext" which is an underlying or hidden meaning.
But I wouldn't say the dress code is a symbol but I would say it is symbolic of something. That "something" could be chauvinism. Specifically I would say it is a chauvinism carried out politically(high school politics of course but still political).
The books Language As Symbolic Action and Politics As Symbolic Action helped me come to this conclusion.

A: This dress code is a mere indicator of underlying chauvinism...

[noun] a sign that shows the condition or existence of something


text:
Q: How to set dynamic width of div?

     UserName

   CompanyName

In my code UserName can be of dynamic length and same with CompanyName.
I want to set width of div as per name of UserName similarly for the
CompanyName.
Restriction is that I can only use style or css. no jquery.

A: CSS:
#theparent, #divUserName, #divCompanyName {
   display: inline-block;
   width: auto/*not neccessary*/
}

A:

#divUserName,
#divCompanyName {
    left: 0px;
    right: 0px;
}

#divUserName {
    background-color: #f00;
}

#divCompanyName {
    background-color: #0f0;

     UserName

   CompanyName

A: You can do this by using float property. When you use float the width will be set automatically as per data present in that.
so

#divUserName{
    background:green;
    border:1px solid blue;
    float:left;
    margin:5px;
}
#divCompanyName{
    background:yellow;
    border:1px solid blue;
    margin:5px;
    float:left;
}

     UserName

   CompanyName


text:
Q: how to add a link on single option in select tag hello I am trying to create a category select dropdown which consists of some data coming from database I have created a page named addcategory.php and I am trying to add a  in the select tag something like "add new category" I tried several methods like onchange function in javascript but it gets applied to the whole select menu I only want to add a link to the last option of the select tag below I am attaching the code which I am using.
<select class="w-100" id="categoryselect" name="selectcat" required>
  <option value="" disabled selected>Select Category</option>
    <?php
        $sql="SELECT * FROM categories";
        $result=mysqli_query($conn, $sql);
        while($row=mysqli_fetch_array($result))
        {
            echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
        }
    ?>
  <option value="categories" onClick="window.location = 'addcategory.php'">Add New Category</option>
</select>

A: Bind the event handler to select tag instead of bind the event into options tag.
The onchange event occurs when the value of an element has been changed.
<select class="w-100" id="categoryselect" name="selectcat" onChange="if(this.value=='categories') window.location='addcategories.php'">
      <option value="" disabled selected>Select Category</option>
        <?php
            $sql="SELECT * FROM categories";
            $result=mysqli_query($conn, $sql);
            while($row=mysqli_fetch_array($result))
            {
                echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
            }
        ?>
      <option value="categories">Add New Category</option>
    </select>


text: Q: GCC Runtime Library Exception i want to use use gcc compiler (under GPLv3) in my c++ project and libstdc++ that comes with GCC compiler but my project is closed source . there is an exception of Runtime Library but i don't understand  it very well.and i have read (GCC Runtime Library Exception FAQ). can some one explain this exception and if i used libstdc++ can i make my program closed source ?.


text:
Q: Running python script on Microsoft Azure I'll have a linux machine with a virtual machine installed for Microsoft azure soon. I need to run some data mining/graph analysis algorithms on the azure because I work with big data. I don't want to use azure machine learning stuff. just want to run my own python code. What are the steps? If needed, hoe can I install python libraries on azure?

A: There is no additional steps to do in comparison to Your own. local server. Linux on Azure is a standard Linux machine. If You are looking for step-by-step hopw to on running Linux VM on Azure, just search on azure.com and You will find it. I think You will not have any problems even without documentation. Azure portal is very simple to use, also CLI tool for Linux, Mac and Windows. You just need to run Linux VM and SSH-in to it. Nothing more. If You need some help, just write here.


text:
Q: echo orders from items I have items in shopping cart that are presented in shopping cart. For example: I have 3 different items with quantity
I managed to echo it out to shopping cart page, and to write an order to ORDERS table.
 <?php
 ...
 $sql = "SELECT id_item, item, price FROM id_item WHERE id_item IN (";
    foreach ($_SESSION['cart'] as $id => $value) {
       $sql .=$id.",";
    }
$sql = substr($sql, 0, -1).") ORDER BY item ASC";
$query =mysql_query($sql);
$total = 0;
while($row=mysql_fetch_array($query)) {
    $subtotal = $_SESSION['cart'][$row['id_item']]['quantity']*$row['price'];
    $total += $subtotal;
?>

    <?= $row['item'] ?>
    <input type="text" name="quantity[<?= $row['id_item']?>]" size="5" value="<?= $_SESSION['cart'][$row['id_item']]['quantity']?>"
    <?= $row['price']?>
    <?= $_SESSION['cart'][$row['id_item']]['quantity']*$row['price']?> kn

...

So now I want to write an order into table ORD.ITEMS and I'm stuck here because it have multiple items.
table ORDERS and ORD.ITEMS have relation on id_order, table ORD.ITEMS and ITEMS have rel on item & id_item
 ORDERS
 id_order
 user
 date
 status   -> this I'll try on my own, if status is 0 order is open, if 1 order closed, if 2 order

 ORD.ITEMS
 id_order
 id_ord.items
 item
 quantity

 ITEMS
 id_item
 title
 description
 price

so now I want something like this for three differente items:
 ORDERS
 1
 user1
 2014-01-01
 0

 ORD.ITEMS
 1
 1
 10
 5

 ORD.ITEMS
 1
 2
 20
 3

 ORD.ITEMS
 1
 3
 30
 2

How to write SQL query that after finishing order write into table ORD.ITEMS three items?

A: I managed to solve my problem, it was easy. This is a way I solve it:
    $sqlMaxS = "SELECT MAX(id_ord_items) FROM ord.items";
    $resultMaxS = queryDB($sqlMaxS);
    $result = mysql_fetch_row($resultMaxS);
    $id_ord_items = $result['0'];
    $id_ord_items++;

    $sql = "SELECT * FROM items WHERE id_item IN (";

    foreach ($_SESSION['cart'] as $id => $value) {
        $sql .=$id.",";
    }

    $sql = substr($sql, 0, -1).") ORDER BY name ASC";

    $query =mysql_query($sql);

    while($row=mysql_fetch_array($query)) {

        $sql = "INSERT INTO ord.items (id_order, id_ord_items, item, quantity)
                VALUES ('$id_order', '$id_ord_items', {$row['id_item']}, {$_SESSION['cart'][$row['id_item']]['quantity']})";
    $stavka++;
    queryDB($sql);

just as above I used while loop.


text:
Q: Whether to store and retrieve data from a javascript object or a backend database I'm a novice programmer and in the process of building one of my first web apps using Node and Express, while connected to a MongoDB database.
For part of my app the user enters values into a form, and in one part selects from a list of 30 possible Door types.  Upon submitting the form, the Door type is queried in my database, which is pre-loaded, and the Weight value for that Door type is retrieved.  Then the Weight value is used to do a calculation with two other values (height and width) submitted in the form.  I got this to work using callback functions when the form is posted.
My question is:  would this type of process be simpler if I just stored the weights of the different door types in a Javascript object and then retrieve the proper weight using dot notation?  The doors only have three properties: name, weight, and one other.  This way I don't have to take the time to query the database.  Any suggestions for the best way to do this process?

A: Mongodb is largely used for databases where there lot of documents and few relationship. Your type of application will do better with Mongodb as it is easily scalable. Also simple math operations while storing and retrieving documents can be performed using these in-built functions.


text:
Q: Create a composite attribute in My sql ER diagram? I am currently working on a project in mySQL and I was wondering if mySQL makes it possible to create a set of composite attributes for an attribute of an entity. The attribute is not the primary key, it is an address so the composite attributes are supposed to be, street, town, state ECT... A) is this possible? if so which type would I use/ how would I go about doing it. B) is this practical I have about 10 entities and I feel like a couple of them will need composite attributes that was just the best example.

A: No, MySQL doesn't support "composite" attributes.
You could "break out" the components of the "composite" attribute into a separate table. Or, you can keep them as individual columns in the same table.
I use the column name to "identify" the attributes that make up a composite attribute. You gave a good example with "address". It really is one attribute, with several components.
Here's a (neutered) example of one of my table definitions:
CREATE TABLE `foo` (
`id`              COMMENT 'PK'
`category_id`     COMMENT 'FK to ...'
`display_name`
...
`address_street`
`address_street2`
`address_city`
`address_state`
`address_country`
`address_postal_code`
...
`country_code`    COMMENT 'ISO 3166-1-alpha-2 code'
`latitude`
`longitude`
...

Bottom line, MySQL doesn't support composite attributes. But I can use a naming convention to somewhat "relate" the components together.


text:
Q: How to use JavaScript variable in CSS style? Actually I want something like that:
var color = #000;

$(".div").find("li").css({"border-left": '5px solid [`I want to add this variable (color) here`]});

Please help me.
Thank you.

A: If you can use ES6 then a template literal is a good choice here. It uses backticks instead of other types of quotes.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
var color = "#000"; //change this to be a string as @Nikos mentioned

$(".div").find("li").css({"border-left": `5px solid  ${color}`});

A: $(".div").find("li").css({"border-left": `5px solid ${color}`});

A:

var color = "#00f";
$("#button").click(function(){
  $("div").css({"border": "5px solid " + color});
});

<button id="button">Add Border</button>

Hi, I am a div


text:
Q: WSO2 Governance REGDB I have configured my WSO2 Governance repository to MySQL by following the steps in https://docs.wso2.com/display/ADMIN44x/Changing+to+MySQL.
Is there a document which explains the REGDB schema? For e.g. which table stores the asset's association information and etc.
Thanks in advance.
Rgds,
neo

A: You can find the major tables like the following, used for mounting the registry and its resources in the documentation available here
REG_RESOURCE
REG_CONTENT
REG_RESOURCE_HISTORY

Also the detailed steps to setup the registry using MySQL, find here.
https://docs.wso2.com/display/Governance520/Setting+up+MySQL


text:
Q: React native use a local font on snack.expo.io How can I use a local font on snack.expo.io?
I have a ttf font, which I would like to use as evidence on snack.expo.io, but I do not quite understand how I could do it.
Some advice?

A: When you are creating your snack you can import files. You can see beside Project there are three vertical dots, click that takes you to the import menu.

Selecting Import files will take you to this screen where you can either browse or drag and drop your files. I prefer to drag and drop.

You can then drag the files to the folder that you wish them to be located in.
Then to use your custom font you can follow the guide in the documentation.
https://docs.expo.io/versions/latest/guides/using-custom-fonts/
Here is a quick code example.
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants, Font } from 'expo';

// You can import from local files

export default class App extends React.Component {
  // <- use the button on the left, three vertical dots to import files

  // set the initial state
  state = {
    fontLoaded: false
  }

  async componentDidMount() {
    // load fonts
    await this.loadFonts();
  }

  loadFonts = async () => {
    // load the font
    await Font.loadAsync({
      'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
    });
    this.setState({fontLoaded: true})
  }

  render() {
    // use the font in your text components
    // only render the Text component when the font has been loaded.
    return (
      <View style={styles.container}>
        {this.state.fontLoaded ? (<Text style={{ fontFamily: 'open-sans-bold', fontSize: 56 }}>
          Hello, world!
        </Text>) : null}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  }
});

And an accompanying snack to show it working, notice I have stored my fonts in the folder ./assets/fonts/ https://snack.expo.io/@andypandy/custom-font


text:
Q: How to select all class that is above certain tag using CSS Selector in Selenium + Python? Here I want to get all the class = "result-row" which are above the "h4" tag, not the ones which are below "h4" tag.

My current code selects all of them:
section = driver.find_element_by_css_selector("[class='rows']")
result_rows = section.find_elements_by_css_selector("li.result-row")

so how can i get the desired result here?

A: You could try the following css which uses :not to filter out h4's  general siblings based on class
li.result-row:not(h4.ban ~ li.result-row)

which might be simplified to:
.result-row:not(.ban ~ .result-row)

A: If CSS is not obligatory, you can use XPath:
driver.find_element_by_xpath("//h4/previous-sibling::li")


text:
Q: Running Matlab Command From Tcl From my TCL script I like to open Matlab command window and display if its Matlab win32 or win64.
Therefore I use the following command:
exec {*}matlab -nodisplay -nosplash -nodesktop -r  "arch = computer; fprintf('%s \n', arch')";

However I keep getting error:
arch = computer; fprintf('%s
                          |
Error: String is not terminated properly.

If I run the same in Matlab no issues.
Could some kindly advice.
Thanks
Anj.

A: Tcl is substituting the \n before handing the command to matlab. Escape it:
exec matlab ... -r  "arch = computer; fprintf('%s \\n', arch')"

Or use braces
exec matlab ... -r  {arch = computer; fprintf('%s \n', arch')}


text:
Q: How to get Winmerge to recognize that code can move around? How to have Winmerge recognize similar code blocks instead of comparing line to line?
Or is there a way to highlight and skip a region to compare to?


text:
Q: What does the symbol `?` mean in the expression `maxY = (maxY > pt.Y) ? maxY : pt.Y;` What does the symbol ? mean in the following code:
  for(int i = 0 ; i < Hpts.BranchCount;i++)
    { foreach(Point3d pr in Hpts.Branches[i]){
        minX = (minX > pt.X) ? pt.X : minX;
        minY = (minY > pt.Y) ? pt.Y : minX;
        maxX = (maxX > pt.X) ? maxX : pt.X;
        maxY = (maxY > pt.Y) ? maxY : pt.Y;
      }
    }

A: It is called conditional operator.See documentation

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
condition ? first_expression : second_expression;

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

So in your case for example:
minX = (minX > pt.X) ? pt.X : minX;

*

*minX > pt.X is condition

*pt.X is first_expression

*minX is second_expression
Which means that if condition is true value of minX will be equal to pt.X, otherwise it doesn't change because second expression is variable itself.

A: This is equivalent to:
if (minX > pt.X)
{
    minX = pt.X;
}
else
{
    minX = minX;
}

A: ?: is a shorthand for if statement.
So here: minX = (minX > pt.X) ? pt.X : minX, minX will be set to pt.X if minX is larger than pt.X

A: The conditional operator, so instead of writing this:
if (minX > pt.X)
    minX = pt.X;
else
    minX = minX;

You can write it like this:
minX = (minX > pt.X) ? pt.X : minX;

A: The question mark (?), along with the colon (:) together form the ternary conditional expression. It is supported by most languages (I know C, C++, C#, Java, JavaScript, Ruby all do that... feel free to correct me about the exceptions), and has the following syntax:
(condition) ? (code if true) : (code if false)

It is called ternary as it accepts 3 arguments, as shown above.
So to make a more concrete example, let's use the first line of your foreach loop to demonstrate
minX = (minX > pt.X) ? pt.X : minX;

This is equivalent to writing
if (minX > pt.X) {
  minX = pt.X;
} else {
  minX = minX;
}

As you can see, the 4 lines of code can be reduced into a single line without the loss of clarity, which is quite a powerful language construct. You will usually see this used quite heavily in recursive functions, e.g. function for calculating factorials:
int factorial(int n) {
  return (n == 1) ? 1 : factorial(n-1) * n
}


text:
Q: variable value in class is not getting loaded properly Below is my code snippet,this piece of code will be called from a workitem with the needed input parameters.The problem which Iam facing is the value of ExcpStatus variable is not getting loaded properly,my workitems will fail sometime and the value of finalOpStatus will be fail making the value of  ExcpStatus to YES.Now second time if i call this code (after ExcpStatus is changed to YES) the value of ExcpStatus should be reloaded as NO but it takes the previous changed value YES...Can someone help me in this....
     public abstract class SampleWorkItemHandler implements WorkItemHandler {

                public SampleWorkItemHandler()
                    {
                        this.sb_serviceTaskName="default";
                    }

                    public SampleWorkItemHandler(String taskName)
                    {
                        this.sb_serviceTaskName=taskName;
                    }
                    protected String ExcpStatus="NO";
                    protected String loggerCorrelationId = "";
                    private String  startLoggerInsertStr="";
               public void executeWorkItem(WorkItem workitem, WorkItemManager manager) {
            try{
                logger.info("the exception staus is::"+ExcpStatus);
                logger.info("the loggerCorrelationId is::"+loggerCorrelationId);
                String finalOpStatus=SyntBotsBPMOutputValidatorUtil.validateResponse(handlerResponseParams);
                if(finalOpStatus.equalsIgnoreCase("Fail"))
                {
                    ExcpStatus="YES";
                }
              }catch(Exception e){
              System.out.println("Exception Stack Trace:::"+e.getMessage());
       }
   }


text:
Q: Sorting an array into a 2nd array in Java I need to make 2 arrays and sort one into the other in ascending order and display it. I've managed to move ar[] into sorted[], but I can't get it to actually sort.
Here's what I have so far:
public class SortArray
{
    public static void main(String argv[])
    {
        int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
        int sorted[] = new int[7];

        for (int i=0; i<ar.length-1; i++)
        {
            int smallest = 1000000;
            int index    = 0;

            for (int j=i+1; j<sorted.length; j++)
            {
                if (ar[i] < smallest)
                {
                    smallest=i;

                    int tmp = ar[i];
                    ar[i] = sorted[j];
                    sorted[j] = tmp;
                }
            }
        }

        for(int i=0; i<sorted.length; i++)
        {
            System.out.println("sorted[" + i + "] = " + sorted[i]);
        }
    }
}

A: Just try to understand and use java algorithms here. If you have problems with understanding the idea please do not hesitate to ask.
http://www.java2novice.com/java-sorting-algorithms/
They are more efficient and they are not error prone.
Assuming that you are trying to learn sorting algorithms and coding, here is what you are trying to; Please be aware that if there are identical values it will get only one of them.
    int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
    int sorted[] = new int[6];

    int smallestFound=-1;
    for (int i=0; i<ar.length-1; i++)
    {
        int smallest = 1000000;
        for (int j=0; j<sorted.length; j++)
        {
            if (ar[j] < smallest && ar[j]>smallestFound) {
                smallest = ar[j];
            }
        }
        smallestFound=smallest;
        sorted[i] = smallest;
    }

    for(int i=0; i<sorted.length; i++)
    {
        System.out.println("sorted[" + i + "] = " + sorted[i]);
    }

A: you can use  a TreeSet , it sort the element naturally:
public class SortArray
{
    public static void main(String argv[])
    {
        int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
  int sorted[] = new int[7];
List<Integer> sortedList = new TreeSet<Integer>();
for (int i=0; i<ar.length-1; i++) {
    sortedList.add(ar[i]);
}

// transform into array

for(int i = 0; i< sortedList.size(); i++) {
 sorted[i] = sortedList.get(i)
}

        for(int i=0; i<sorted.length; i++)
        {
            System.out.println("sorted[" + i + "] = " + sorted[i]);
        }
    }
}


text:
Q: How long does it take for Google Analytics Goals to start show some data? I am testing Google Analytics Goals but I am not sure if I have it set up correctly. I set up a basic 3 step goal just as a test. I then went to my website and performed those three steps. Should that immediately show up in Google Analytics under the Goal reports or does it take a few days? I need to know so I can know if I need to be troubleshooting or not.

A: You can see goals appear instantly in the Real Time Conversions report.
One other thing to bear in mind when testing: make sure you aren't filtering out your IP address as you won't see any results from testing.

A: It can take 24 - 48 hours to show up in the standard reports (Conversions -> Goals -> ...)
Data processing latency

Processing latency is 24-48 hours. Standard accounts that send more
  than 200,000 visits per day to Google Analytics will result in the
  reports being refreshed only once a day. This can delay updates to
  reports and metrics for up to two days. To restore intra-day
  processing, reduce the number of visits you send to < 200,000 per day.
  For Premium accounts, this limit is extended to 2 billion hits per
  month.

Basic Goal Data can be found almost instantly in the Real-time -> Conversions report

A: Yes, it can take 24 - 48 hours to show up in the standard reports.But I could not wait to make sure if it is sending the right data so I used chrome extension. You can check the Analytics tracking code by using  Chrome extension Google Analytics Debugger.


text:
Q: What is the etymology of the "dot" operator for string concatenation? Some languages have a . operator for string concatenation. The oldest language I could find that supports it is Perl. Was Perl the first to use it? Why was it chosen?

A: If you want to stick with a single non-alphanumeric non-whitespace ASCII character for operators, there really aren't that many. I can only see a couple of alternative choices: !, ~, #, ,, and $. Of those, only . and , can be reached without ⇧ on a US keyboard, # is the comment character. Comma makes kind of sense, but it is already used for a different purpose in C and C-like languages, with which a lot of Perl programmers would also be familiar, and so has the same meaning in Perl.
This leaves you only with the dot. Note that a middle dot (·) is used in maths to denote function composition (and Haskell uses the ASCII dot as an approximation for that), which can be kinda-sorta related to concatenation.
There is, in fact, no standard operator symbol for concatenation in maths, some suggestions are the double plus ⧺ (Haskell uses ++ for concatenation) or the frown ⌢.
Some languages use + for concatenation, which is a terrible choice, because concatenation lacks several of the properties that we normally associate with an addition-like operation. Most importantly, concatenation is noncommutative.


text:
Q: How to get tweets on certain dates using Tweepy? How to get tweets on certain dates using Tweepy
The code I wrote is like this(jupyter):
import tweepy as tw
import xlsxwriter
import datetime
import pandas as pd
consumer_key="#"
consumer_secret="#"
access_key="#"
access_secret="#"
try:
 auth = tw.OAuthHandler(consumer_key, consumer_secret)
 auth.set_access_token(access_key, access_secret)
 auth.get_authorization_url()
 api = tw.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True,compression=True,retry_count=3,retry_delay=10,timeout=15)
except tw.TweepError:
 print ('Error')

name="mahfiegilmez"

startDate = datetime.datetime(2018, 6, 24, 0, 0, 0)
endDate =   datetime.datetime(2018, 12, 31, 23, 59, 59)

say=0
tweets = []
from time import sleep
tmpTweets = api.user_timeline(name,count=200,tweet_mode="extended",lang="tr")

for tweet in tmpTweets:
        if tweet.created_at < endDate and tweet.created_at > startDate:
            tweets.append(tweet)

lastTweet = tmpTweets[-1].id
while (tmpTweets[-1].created_at > startDate):
    print("Sonraki Tweet @", tmpTweets[-1].created_at,say)

    tmpTweets = api.user_timeline(name,max_id = tmpTweets[-1].id,tweet_mode="extended")
    if lastTweet == tmpTweets[-1].id:
        print("lastTweet")
        sleep(15)
    else:
        for tweet in tmpTweets:
            if tweet.created_at < endDate and tweet.created_at > startDate:
                tweets.append(tweet)
    lastTweet = tmpTweets[-1].id
    say+=1

next section:
tweets2=[]
tweets.reverse()
for x in tweets:
    if(x.in_reply_to_status_id==None) or (x.in_reply_to_screen_name==name):
        if (not x.retweeted) and ("RT @" not in x.full_text):
            tweets2.append(x)

Like:

*

*Next Tweet @ 2019-02-15 13:33:26 1095106703098605568 157

*Next Tweet @ 2019-02-11 23:45:58 1094442196500209666 158

*Next Tweet @ 2019-02-10 03:45:28 1094441678889463809 159

*Next Tweet @ 2019-02-10 03:43:24 1094441678889463809 160

*Next Tweet @ 2019-02-10 03:43:24 1094441678889463809 161

*Next Tweet @ 2019-02-10 03:43:24 1094441678889463809 162

*Next Tweet @ 2019-02-10 03:43:24 1094441678889463809 163
.....

How am I gonna solve this?
And finally gives this error.
> IndexError                                Traceback (most recent call
> last) <ipython-input-9-46264abdd8ef> in <module>
>       9         tweets.append(tweet)
>      10
> ---> 11 while (tmpTweets[-1].created_at > startDate):
>      12     print("Last Tweet @", tmpTweets[-1].created_at, " - fetching some more")
>      13     tmpTweets = api.user_timeline(username, max_id = tmpTweets[-1].id)
>
> IndexError: list index out of range

A: A better way to do this would be to use the since_id and max_id parameters for the API.user_timeline method / GET statuses/user_timeline endpoint, instead of making lots of unnecessary requests to loop through tons of Tweets outside the time range. You should also look into using a Cursor instead.
The error you're encountering is likely because the account in question has more than 3200 Tweets since the time specified with startDate.

This method can only return up to 3,200 of a user's most recent Tweets.

https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
So once it's gone through the most recent 3200 Tweets, the next call to the method/endpoint will assign an empty list to tmpTweets. It would then error when you attempt to index tmpTweets in the print statement. Your traceback seems to have different code than your snippet. If that print statement isn't there, then it would error when you attempt to index tmpTweets in the while condition, as in your traceback.


text:
Q: VSCode - How to typehint node_modules types in JSDoc? If i'm writing JavaScript (not TypeScript) in the VSCode editor, it seems like it isn't able to find the types of many modules.
For example, I'm trying to typehint ExpressContext of ApolloServer (apollo-server-express), it can't find ExpressContext:

And yet, if I check the parameters of a function that uses ExpressContext, Intellisense can find it there:

So how do I make it so that I can Cmd+Click on ExpressContext in the @param JSDoc and it brings me to the correct type definition?


text:
Q: display data attribute element of the current slider I'm a beginner in JS, I made a carousel with a data attribute and I want to display it and it have to change when we go the next or previous slider.
For the moment I made a small script and I can display only the data attribute of the first slider
HTML :

{#    Content #}

{#    Content #}

{#    Content #}

{#    Content #}

JS :

How can I improve my code to display the data attribute according to the good slider ?
should I make a loop ? or something with a event click ?
Thanks for answer

A: If you have only one active slide you can do it without loop:
  var carousel = document.querySelector('.el-carousel2parts');
  var spanLegend = document.querySelector('#legend');

  // Find which is active and get its attribute:
  var currentSlide = document.querySelector('.slick-active');
  var currentData = currentSlide.getAttribute('data-legend');

  var dataLegend = currentData;
  spanLegend.innerHTML = dataLegend;

I do not see you full code, so just a guess.You can make onClick function and call new two lines of code. Put onClick on button which updates the slides. Imagine we have several buttons that scroll through the slides.
<button class="turn">Left</button>
<button class="turn">Right</button>

In that case we can have something like this:
  var spanLegend = document.querySelector('#legend');
  var btnsTurn = document.querySelectorAll('.turn');
  btnsTurn.forEach(item => {
      item.addEventListener("click", () => {
          var currentSlide = document.querySelector('.slick-active');
          var currentData = currentSlide.getAttribute('data-legend');
          spanLegend.innerHTML = currentData;
      });
  })

But I assume that you already have a function which add Class 'slick-active' and remove it from another slide. So you can just add some code inside it without new forEach for the same buttons.
PS You take an Attribute from your DOM which can be edited by any user. In general, be careful innerHTML is a dangerous function.
Hope this helps! Regards,


text:
Q: plain text in XML in scala If I make a variable like this:
val x = Hi!

how does Scala represent the text objects? If I were making the system, you'd have some List of elements that looks something like this:
L(0): TextElement = TextElement("h")
L(1): BElement    = BElement(TextElement("i"))
L(2): TextElement = TextElement("!")

But I don't see anything about text elements in any documentation (or really very much about how this works at all.)
How is it implemented in Scala?

A: it is xml.Text :
scala> x.child.map(_.getClass).foreach(println)
class scala.xml.Text
class scala.xml.Elem
class scala.xml.Text

http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/scala/xml/package.html


text:
Q: Using google drive to host my jquery mobile webapp: why is the viewport zoomed out on iphone? My problem is with display of my webapp. I would like to use google drive to host my webapp (j query mobile) so I can test it out. I followed the google drive instructions and uploaded my index.html, my js folder and my css folder to a public shared folder on my gdrive. The test site displays well on the iOS Simulator only if I load the index.html directly from my google drive folder on my laptop. But if the index.html is loaded from the web, the page appears very zoomed out (but otherwise functional). The site is http://gdriv.es/whatname
I have the viewport content="width=device-width, initial-scale=1, minimal-ui"
The jquery and jquery mobile js is hosted on a CDN if that is relevant.
I have tried copying all files from another jquery mobile site which I have hosted elsewhere and which I know displays well on iphone etc - but interestingly it also displays this zoomed out behaviour on google drive...

A: Your problem is not in your files, viewport is also correct.
Unfortunately your content is shown inside a frame thus your viewport is not taken into consideration. Frame is built to cover available space so you can't see it, unless you view page source.
This is what your final page looks like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

        <title>a title</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta name="description" content="GDrives whatname on Google Drive Site Publishing web hosting" />
        <meta property="og:image" content="/logo.png" />
        <link rel="shortcut icon" href="/favicon.ico" />

    <frameset rows="100%">
        <frame src="https://googledrive.com/host/0B5HUb04HaxoSWEtnMVI4TzBmZFk/" />
        <noframes>

Go to Whatname on Google Drive Site Publishing web hosting

        </noframes>
    </frameset>

Your content is linked here:
<frame src="https://googledrive.com/host/0B5HUb04HaxoSWEtnMVI4TzBmZFk/" />


text:
Q: Standalone PowerPoint/Impress replacement? I often use AbiWord for word processing, since it has a better UI than OpenOffice. Considering that there's also a standalone spreadsheet - gnumeric, is there a standalone presentation editor/viewer in the vein of PowerPoint or Impress?
Only installing Impress seems wasteful since I have to install much of the OpenOffice backend as well. PowerPoint Viewer is fine unless I find I need to edit a slide - I'm aware of these alternatives.
Portable, or low-dependency software would be preferred. The question is primarily for Windows systems (though I'd upvote any good Linux-based answers), and compatability with at least classic Office PowerPoint slides would be essential.


text:
Q: mysql: how to optimize this when condition search + more? I have been trying to debug my search MYSQL search speeds and they are horrible (a couple of seconds to 2 minutes).
This is an example code for the search. Search complexity can become really complicated depending on the user requirements.
SELECT Device,Input,`W(m)`,`L(m)`,VDD,`Temp(C)`,Param,Value
FROM `TABLE_NAME`
WHERE (`Temp(C)`='110' OR `Temp(C)`='125' )
    AND (Device='ngear' )
    AND (Input='a' OR Input='b' OR Input='a' OR Input='b' OR Input='c' OR Input='b' )
    AND (Param='speed' OR Param='leakage' )

Please note this table has no indices and no primary key. This data isn't really relational as it contains statistical simulation data that is stored in MYSQL. This table has about 1 million rows of data.
Should I start indexing every column? Any thoughts would be appreciated.
id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  TABLE_NAME  ALL     NULL    NULL    NULL    NULL    12278640    Using where

A: You need a composite index, and properly require some redefine of your data type,
here is some general advice :
alter table MQUAL__TSMC_20G_v0d1_Robert_02122011
add index ( `Temp(C)`, Device, Input, Param);

And your query can be change to :-
where `Temp(C)` in(110, 125)
AND Device='ngear'
AND Input in('a','b','c')
AND Param in('speed', 'leakage');

Due to lack of information of your schema,
so, data type should be :-
`Temp(C)` <-- int

A: My suggestion is to add an index with the 'where' clause that narrows the data the most. As a guess temp should be the first column in the index. You want a compound index as well. The general rule of columns should start with the column that reduces the result set the most to the last being the most common value.


text:
Q: scanning until EOF in c I am writing a decryption program and I need to scan in an unknown number of strings and decode each string as it is entered.  The program must end once it reaches EOF.
I am having difficulty getting the program to end.  when I scan in the first char in the string in my while loop condition statement, it is doing this but when I scan in the actual string bellow the condition statement the string is missing the first char. Should I scan in the first char and then somehow put that char at the beginning of the string?
How do I properly test for EOF in my situation?
#include <stdio.h>
#include<string.h>

int main(void)
{
    int i;
    char code[300];

    while(scanf("%c", &code[0])!=EOF)
    {
        scanf("%s", code);

        for(i=0; i<strlen(code); i++)
        {
            decrypt message one char at a time
        }
        printf("\n");
    }
    return 0;
}

A: while (scanf("%s", code) == 1)
{
    // no need for second scanf call
    ...

A: while (scanf("%c", &code[0]) == 1)
{   scanf("%s", &code[1]);
    ...

A: Using scanf at all is a bad idea for this particular problem.
while(scanf("%c", &code[0])!=EOF)

This scanf call reads a single character. Just use getchar().
scanf("%s", code);

for(i=0; i<strlen(code); i++)
{
    decrypt message one char at a time
}

The scanf call can read arbitrarily many characters (after skipping whitespace; are you sure you want to skip whitespace?). That means that if there are too many characters to be read from stdin, you have a buffer overflow, one that you can't avoid unless you have complete control over what appears on stdin.
You then loop over the code array, calling strlen() for each character you process. Since strlen() generally has to scan from the beginning of the array to the terminating '\0', this is inefficient. If you need to traverse the characters of a string, either call strlen() once and save the value, or look for the terminating '\0' character.
But you're just processing one character at a time, so just read one character at a time:
while ((c = getchar()) != EOF) {
    /* process a character */
}

Don't worry about reading one character at a time being inefficient; buffering will take care of that.


text:
Q: Graph API via Facebook (Android SDK) This is a two part question.
1: Why do I need the user's access token to get the graph object for a public url? Why isn't the facebook app's id sufficient?
2: When requesting the number of likes on a url, including share count and comments, I am only getting the number of shares and comments and not the number of likes. the code being used is as below
new GraphRequest().newGraphPathRequest(
    AccessToken.getCurrentAccessToken(),
    "http://cnn.com/",
    new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            JSONObject graphResponseJSON = response.getJSONObject();
            Log.i(TAG, "FACEBOOK GRAPH RESPONSE: " + graphResponseJSON);
        }
    }
}).executeAsync();

What should I do to get the number of likes for a url?

A: As @WizKid suggested, we can use app's access token to perform such operations.
eg:
Bundle params = new Bundle();
params.putString("access_token", "facebook_app_id|facebook_app_secret");
        params.putBoolean("summary", true);
        new GraphRequest(
                null,
                "/" + objectId + "/likes",
                params,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        Log.i(TAG, "FACEBOOK GRAPH RESPONSE FOR LIKES: " + response);
                    }
                }
        ).executeAsync();

Here facebook_app_id and facebook_app_secret are to be replaced with their relevant values.
It's important to NOT directly paste the values in the code as it can be decompiled and the key's can be recovered by any third party.
Rather store it in strings.xml or preferably server side.


text:
Q: I want to set condition on filter that only login user data is load or public data will load. But private data will also be loaded Here is my query:
$maps = Mapdata::where('userid', Auth::user()->id)->ORwhere('public', 1)->whereBetween('from', array($request->from, $request->to))->orderBy('id', 'DESC')->get();

A: Let your controller do the check. Presuming that you need data that matches the logged-in user if he is logged & else case the public data. Try the following:
if(Auth::id()) {
  $maps = Mapdata::where('userid', Auth::id())->whereBetween('from', array($request->from, $request->to))->orderBy('id', 'DESC')->get();
} else {
  $maps = Mapdata::where('public', 1)->whereBetween('from', array($request->from, $request->to))->orderBy('id', 'DESC')->get();
}

Note: I don't have a clear idea of your DB & model structure. Please update your question with the same for a precise answer from me or someone else out here.

A: You can use when method to write more clear code:
where method gets 3 parameters boolean to check, callback1 executed if boolean is true and callback2 executed if boolean is false.
In your case it will be:
$maps = Mapdata::query()
  ->when(Auth::check(), function($q){
    $q->where(function($q){
      $q->where('userid', Auth::user()->id)->orWhere('public', 1);
    });
  }, function($q){
    $q->where('public', 1);
  })
  ->whereBetween('from', array($request->from, $request->to))
  ->orderBy('id', 'DESC')->get();

Generated sql:
When Authed: SELECT * FROM mapdata WHERE (userid = ? OR public = 1) AND ...
When Guest: SELECT * FROM mapdata WHERE public = 1 AND ...

A: Solved by this query.
$q->where('userid', Auth::user()->id)->orWhere('public', 1);
})->where(function($q) use ($request) {
$q->whereBetween('from', array($request->from, $request->to))->orWhereBetween('to', array($request->from, $request->to));
})->orderBy('id', 'DESC')->get();


text:
Q: Creating a DJVU file from scanned BMPs Recently I have been scanning some of my hand written notes.  Each page ends up as a .bmp file (300 DPI A4).  I wish to combine/compress these too a DJVU file for easy reading.
Hence,

*

*Does anyone know of any programs/utilities for OS X/Linux that can do this.

*If so, what settings can be considered optimal (lined paper, some coloured ink used).

*Are there any practical means of tagging pages/regions (to create an outline).

A: There is some help available here:
http://commons.wikimedia.org/wiki/Help:Creating_a_DjVu_file
The package for doing it is DjVuLibre, which has a utility to create a DJVU file from a TIFF or PBM file. If you need something to easily convert your BMPs to TIFFs, try ImageMagick.
Ad far as outline tagging, I'm entirely lost on how you'd do that.

A: Any2Djvu is a good utility :
Any2Djvu
If you want to convert into pdf , ImageMagick is a good one. ( It's mainly an image processing utility . )
ImageMagick
For more info , go to here


text:
Q: MSBUILD failing with error MSB4236: The SDK 'Microsoft.NET.Sdk' specified could not be found I have a net48 SDK project (library), and on my build machine it has suddenly stopped building (and re-running prior commits fail).
Where does MSBuild look for the Microsoft.NET.Sdk for a .net framework (not core) project? I think it may have actually have been deleted, but I can't be sure since I don't know where to check....
Update: server needed updates installed, rebooted and installed updates,  and now everything is working again.

A: You need dotnet sdk installed on your build machine.
SDK-style projects - even when targeting full FW - need dotnet. See https://learn.microsoft.com/en-us/dotnet/core/project-sdk/overview for more details.
Btw. Binlog viewer and binary MSBuild log (produced via -bl option) is a great tool to troubleshoot your build issues.


text:
Q: How to solve python: OSError: [Errno 123] other os error when I'm trying to add the time to the name of a file using the datetime.datetime.now(), i get: 'OSError: [Errno 123] other os error'
I tried using time.time(), but i feel like that's unnecessary as datetime.datetime.now() can give the time...
shot.save(path+'//'+str(datetime.datetime.now())+'.png')

the error:
    Unhandled exception in listener callback
Traceback (most recent call last):
  File "C:\Users\SQ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\SQ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\keyboard\_win32.py", line 240, in _process
    self.on_press(key)
  File "C:\Users\SQ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
    if f(*args) is False:
  File "C:\Users\SQ\Desktop\Screenshot\02.pyw", line 8, in on_press
    check_key(key)
  File "C:\Users\SQ\Desktop\Screenshot\02.pyw", line 25, in check_key
    shot.save(path+'//'+str(datetime.datetime.now())+'.png')
OSError: [Errno 123] other os error
Traceback (most recent call last):
  File "C:\Users\SQ\Desktop\Screenshot\02.pyw", line 40, in <module>
    listener.join()
  File "C:\Users\SQ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 210, in join
    six.reraise(exc_type, exc_value, exc_traceback)
  File "C:\Users\SQ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\six.py", line 692, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\SQ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\SQ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\keyboard\_win32.py", line 240, in _process
    self.on_press(key)
  File "C:\Users\SQ\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
    if f(*args) is False:
  File "C:\Users\SQ\Desktop\Screenshot\02.pyw", line 8, in on_press
    check_key(key)
  File "C:\Users\SQ\Desktop\Screenshot\02.pyw", line 25, in check_key
    shot.save(path+'//'+str(datetime.datetime.now())+'.png')
OSError: [Errno 123] other os error
[Finished in 5.6s with exit code 1]
[shell_cmd: python -u "C:\Users\SQ\Desktop\Screenshot\02.pyw"]


text:
Q: How to fix "build failed error with openCL" when using hashcat I am trying to crack hash+salt with hashcat. But I kept running into this issue, and could not figure out a possible way to solve it.
clBuildProgram(): CL_BUILD_PROGRAM_FAILURE

Error returned by cvms_element_build_from_source
* Device #3: Kernel /usr/local/Cellar/hashcat/6.1.1/share/hashcat/OpenCL/m00010_a0-pure.cl build failed.

I am using a 15inch Macbook Pro, 2018 with specs as below:
* Device #1: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz, skipped
* Device #2: Intel(R) UHD Graphics 630, 1472/1536 MB (384 MB allocatable), 24MCU
* Device #3: AMD Radeon Pro 560X Compute Engine, 4032/4096 MB (1024 MB allocatable), 16MCU

How could I fix this openCL problem with my mac?


text:
Q: How to call my web API and display data in GridView? Here is my API localhost:51549/API/student/
I want it to be displayed in my form when the button is clicked as a data grid.
I have tried:
private  void button1_Click_1(object sender, EventArgs e)
{
    HttpClient client = new HttpClient();

    client.BaseAddress = new Uri("http://localhost:51549/");
    HttpResponseMessage response = client.GetAsync("api/student").Result;

    dataGridView1.DataSource = response;
}

Note: my student controller basically calls a DLL to do the operations.

A: You have to write the content of the response to the DataSource:
dataGridView1.DataSource = response.Content.ReadAsStringAsync().Result;


text:
Q: Pacman does not install the most recent version of a package I'm trying to install Gradle on my Manjaro machine. I need to use it with Java 12, which implies that I need Gradle 5.6.x. On this page it is said that version 5.6.2 is available, which is good news.
However, when I run
$ sudo pacman -S gradle

only version 5.5.1 gets installed, which seems to make no sense.
I have tried to remove the package, then upgrade my system with -Syu flag and then install it again but I still have the exact same problem.
Is there anything I can do to prevent this from happening ? Thanks


text:
Q: strongly connected $L$, then what are the eigenvalues of $L+L^T$? I asked a similar question before. Now things become a bit different here.
Suppose $L$ is a non-symmetric Laplacian matrix, of which the corresponding graph is strongly connected. Is it true that $L+L^T$ (note that $L+L^T$ is symmetric) has at most one negative eigenvalue? I try many examples using Matlab numerically to find out that there is at most one negative eigenvalues, but I am not sure it is true or not.

Preliminaries on Graph Theory:
$\textit{Graph}$ is essentially a concept from the set theory. A graph containing $n$ nodes can be denoted by $\mathcal{G}_n = (\mathcal{V}_n, \mathcal{E}_n)$, where $\mathcal{V}_n=\{v_1,\dots,v_n\}$ is the $\textit{node set}$ and $\mathcal{E}_n \subseteqq \mathcal{V}_n \times \mathcal{V}_n$ is the $\textit{edge set}$. $\epsilon_{ij}=(v_i,v_j), ~i,j \in \{1,\dots,n\}$ represents an $\textit{edge}$ connecting nodes $v_i$ and $v_j$. When the elements in the edge set $\mathcal{E}_n$ are ordered pairs, $\mathcal{G}_n$ is a $\textit{directed graph}$ (or $\textit{digraph}$). Node $i$ of $\epsilon_{ij}$ is called the $\textit{parent node}$ and node $j$ is the $\textit{child node}$. A  $\textit{directed path}$ is an ordered set of edges such that the child node of the previous edge is the parent node of the next edge, such as ${(v_1, v_2), (v_2, v_3),\dots}$. A directed graph is called $\textit{strongly connected}$ if for every pair of nodes there is a directed path between them. The corresponding $\textit{adjacent matrix}$ to graph $\mathcal{G}_n = (\mathcal{V}_n, \mathcal{E}_n)$ is denoted by $A_n=[a_{ij}] \in M_n, i,j \in {1,\dots, n}$. It represents whether there is an edge between any two nodes, that is, $a_{ji} > 0$ when the edge $(i,j) \in \mathcal{E}_n$ and $a_{ji} = 0$ when the edge $(i,j) \notin \mathcal{E}_n$. The $\textit{Laplacian matrix}$ is denoted by $L_n=[l_{ij}] \in M_n$, where $l_{ij} = \sum_{k=1, k \ne i}^{n}a_{ik}, i=j; ~ l_{ij} = -a_{ij}, i \ne j$.
To generate a random strongly directed graph, one can image a graph where every two nodes are connected. However, the weights of the edges are different. For example, the weight of the edge from node $i$ to node $j$ is $1$ while that of the edge from node $j$ to node $i$ is $10$. So the ajacency matrix can be something like: $\begin{bmatrix}0 & 1 & 2 \\ 10 & 0 & 3 \\ 3 & 4 & 0\end{bmatrix}$ and the corresponding Laplacian matrix is $\begin{bmatrix}3 & -1 & -2 \\ -10 & 13 & -3 \\ -3 & -4 & 7\end{bmatrix}$

A: I do not think there is a reason for this property to be true. I was playing around and I think I found a counterexample. Consider the Laplacian matrix
 $$L=\left[\matrix{1 & 0 & -1&  0&  0\\-2 &2 & 0 &  0 & 0\\ 0 & -2 & 3 & -1 & 0\\-5 & 0 & 0 & 6 & -1\\0 & 0 & -150 & 0 &150}\right]$$
It is easy to see that the associated graph is strongly connected but the eigenvalues of $L+L^T$ are $-57.1216$, $-0.7257$, $4.6800$, $14.1430$ and $363.0243$ i.e. the matrix $L+L^T$ has two negative eigenvalues.


text:
Q: emulate human using open source browser I want to emulate some human(not for spam use) for some my daily works. I don't want to use some curl/wget solution because it will include some works to analyze the HTTP package sent by browser. So, basically:

*

*I will use the browser(eg. chrome) to login the system, so I have login state in that browser.

*I open the search page for the system, and by any way I start the script.

*The script will input some string into the  input, and submit the form.

*The browser redirects to the result page, and my script will analyze the result page and get the things I want.

Is there any existing solutions that I can use to write such script? The functionality should include:

*

*fill in some  and submit the form

*in the result page the script can analyze the webpage and get the desired data.

I was trying to do it in  but the domain for my program and the system that I want to run in is not in the same domain.

A: You may be interested in famous Selenium:

Selenium automates browsers. That's it. What you do with that power is
  entirely up to you. Primarily it is for automating web applications
  for testing purposes, but is certainly not limited to just that.
  Boring web-based administration tasks can (and should!) also be
  automated as well.

See its DEMO here.

Or you may be interested in iMacros addon of Firefox depending on your requirements.


text:
Q: In Android Textview within a Scrollview, not displaying all the text(which it gets from strings.xml) I am developing a game and need a popup for the rules. I write the text in the string.xml file and display in a textview within a Scrollview, but all the Text is not getting displayed. Only the last few lines of the text is getting displayed. Please help me!!
Here is the layout popup xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/dialogbg1"
android:gravity="center"
android:id="@+id/howto"
android:orientation="vertical">

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/scrollView"
    android:layout_gravity="right"
    android:layout_weight="1"
    android:nestedScrollingEnabled="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/rule"
        android:layout_gravity="center"
        android:textColor="#fffff7f4"
        android:id="@+id/rules"
        android:textStyle="italic"
        android:outlineProvider="paddedBounds" />
</ScrollView>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/done"
    android:id="@+id/done"
    android:layout_marginTop="5dp"
    android:layout_weight="1"
    android:textColor="#fffff7f4"
    android:background="@drawable/buttbg1"
    android:clickable="true"/>

and the "rule" variable in the strings.xml file
<string name="rule">Rules to play Mancala!!!\n\nMancala is an ancient family of board games, and there are numerous variants.\n
    This is a version of the basic game, known as two-rank Mancala and also known as Kalah.\n
    1.The Mancala board is made up of two rows of six holes, or pits, each.\n\n
    2.Four playing pieces are placed in each of the 12 holes.\n\n
    3.Each player has a store to the right side of the Mancala board.\n\n
    4.The game begins with one player picking up all of the pieces in any one of the holes on his side.\n\n
    5.Moving counter clockwise, the player deposits one of the stones in each hole until the stones run out.\n\n
    6.If you run into your own store, deposit one piece in it. If you run into your opponent\'s store, skip it.\n\n
    7.If the last piece you drop is in your own store, you get a free turn.\n\n
    8.If the last piece you drop is in an empty hole on your side, you capture that piece and any pieces in the hole directly opposite.\n\n
    9.Always place all captured pieces in your store.\n\n
    10.The game ends when all six spaces on one side of the Mancala board are empty.\n\n
    11.The player who still has pieces on his side of the board when the game ends captures all of those pieces.\n\n
    12.Count all the pieces in each store. The winner is the player with the most pieces.</string>

I'm not able to figure out why all the text is not getting displayed. only text from 4 is getting displayed. If I change the layout screensize, then it gets displayed from 3. Please help me!!!

A: Drop your line android:layout_gravity="center" from TextView.

A: Add android:maxLines="50" in your <TextView /> tag. This will make your TextView to add maximum 50 lines.

A: Inside your TextView Tag Use :
android:layout_gravity="top"


text:
Q: Basic javascript Fahrenheit/Celsius calculator I'm trying to do a Celsius/Fahrenheit conversion calculator, with a button for each conversion and the result being displayed in the appropriate textbox.  I must be missing something obvious here... I'm brand new to javascript and am just not getting it.  Here's what I have done so far:
<!DOCTYPE html>

        <meta charset = "utf-8"/>
        <title>Convert Fahrenheit and Celsius</title>

    <form name="conversionForm">

        Fahrenheit
        <input name="fTemp" type="text"/>
        <button onclick="convertToC">Convert to Celsius</button>

        Celsius
        <input name="cTemp" type="text"/>
        <button onclick="convertToF">Convert to Fahrenheit</button>

    </form>

A: You have a few errors. See this corrected jsFiddle example.

*

*Your input boxes were missing IDs that you were trying to reference with document.getElementById

*Your HTML was improperly closed.

*Your buttons were missing types which makes them default to submit when you really wanted just button

*To prevent the form from actually being submitted you should return false.

JavaScript
    function convertToC() {
        var fTempVal = parseFloat(document.getElementById('fTemp').value);
        var cTempVal = (fTempVal - 32) * (5 / 9);
        document.getElementById('cTemp').value = cTempVal;
        return false;
    }

    function convertToF() {
        var cTempVal = parseFloat(document.getElementById('cTemp').value);
        var fTempVal = (cTempVal * (9 / 5)) + 32;
        console.log(fTempVal);
        document.getElementById('fTemp').value = fTempVal;
        return false;
    }

HTML
<form name="conversionForm">

                Fahrenheit

                    <input name="fTemp" id="fTemp" type="text" />

                    <button type="button" onclick="convertToC();return false">Convert to Celsius</button>

                Celsius

                    <input name="cTemp" id="cTemp" type="text" />

                    <button type="button" onclick="convertToF();return false">Convert to Fahrenheit</button>

</form>

A: You are querying the DOM with the document.getElementById() function, but both input elements don't currently have an id attribute only a name attribute. So in your example, there are no elements that actually match the IDs you're passing to the function.
You should set the id attributes of both elements like so:
<input id="fTemp" name="fTemp" type="text">

<input id="cTemp" name="cTemp" type="text">


text:
Q: Conversion cloud module not found Hello Stack Overflow friends!
I'm trying to use this conversion cloud module (https://github.com/groupdocs-conversion-cloud/groupdocs-conversion-cloud-python), but it's returning the module error: ModuleNotFoundError: No module named 'groupdocs_conversion_cloud'
I've installed the packaged through the terminal with no problem, even though the error keeps returning.
Here's my code:

import groupdocs_conversion_cloud

# Get your app_sid and app_key at https://dashboard.groupdocs.cloud (free registration is required).
app_sid = "3e9***ca"
app_key = "f0***ad407e1"

# Create instance of the API
convert_api = groupdocs_conversion_cloud.ConvertApi.from_keys(app_sid, app_key)
file_api = groupdocs_conversion_cloud.FileApi.from_keys(app_sid, app_key)

try:

        #upload soruce file to storage
        filename = 'FT_Manteiga virgem de cacau.pdf'
        remote_name = 'FT_Manteiga virgem de cacau.pdf'
        output_name= 'FT_Manteiga virgem de cacau.docx'
        strformat='docx'

        request_upload = groupdocs_conversion_cloud.UploadFileRequest(remote_name,filename)
        response_upload = file_api.upload_file(request_upload)
        #Convert PDF to Word document
        settings = groupdocs_conversion_cloud.ConvertSettings()
        settings.file_path =remote_name
        settings.format = strformat
        settings.output_path = output_name

        loadOptions = groupdocs_conversion_cloud.PdfLoadOptions()
        loadOptions.hide_pdf_annotations = True
        loadOptions.remove_embedded_files = False
        loadOptions.flatten_all_fields = True

        settings.load_options = loadOptions

        convertOptions = groupdocs_conversion_cloud.DocxConvertOptions()
        convertOptions.from_page = 1
        convertOptions.pages_count = 1

        settings.convert_options = convertOptions

        request = groupdocs_conversion_cloud.ConvertDocumentRequest(settings)
        response = convert_api.convert_document(request)

        print("Document converted successfully: " + str(response))
except groupdocs_conversion_cloud.ApiException as e:
        print("Exception when calling get_supported_conversion_types: {0}".format(e.message))

I've installed this lib using pip install groupdocs_conversion_cloud


text:
Q: understanding $\int_{F} E[X|\mathcal{F}]dP=\int_F E[X]dP$ in the definition of conditional expectation In the definition of conditional expectation, we require $\int_{F} E[X|\mathcal{F}]dP=\int_F X dP$ for all $F \in \mathcal{F}$, where $\mathcal{F}$ is a sub $\sigma$-algebra, and this condition implies $E[E[X|\mathcal{F}]]=E[X]$. What can go wrong if we alternatively define a conditional expectation to be a measurable random variable that satisfies $E[E[X|\mathcal{F}]]=E[X]$? Existence is definitely still true, so I think it is uniqueness is what we need to worry about, but I am having trouble thinking of a $\mathcal{F}$-measurable random variable satisfying $E[E[X|\mathcal{F}]]=E[X]$ that is not the conditional expectation using the correct definition.

A: Let$(\Omega, \mathcal A, P)$ be a probability space and $\mathcal F$ a sub-$\sigma$-algebra of $\mathcal A$. If $X:\Omega \to \mathbb R$ is a random variable, the conditional expectation $E[X|\mathcal F]$ is the "best $\mathcal F$-measurable function that approximates $X$" in the sense of the integral, that is, for all $F\in \mathcal F$ we have $$\int_FE[X|\mathcal F] dP = \int_F X dP$$
This idea is what my teacher uses to provide myself with an intuitive idea when I studied probability. It is supported by some examples: if you take $\mathcal F=\{\varnothing, \Omega\}$, then $E[X|\mathcal F]$ is a number (because every function that is $\{\varnothing, \Omega\}$-measurable must be a constant), and that constant is precisely $E[X]$. Thus we recover the idea that "the best number that can be used to summarize certain data is the mean".

*

*It is not difficult to think of a random variable $Y$ so that $E[Y]=E[X]$ but $Y \neq E[X|\mathcal F]$. For example, take $Y=E[X]$.
To be more specific, let $$X:([0,1], \mathcal B, m) \to ([0,1], \mathcal B) \quad , \quad X(x)=x$$
where $\mathcal B$ is the Borel $\sigma$-algebra and $m$ is the Lebesgue measure. Pick $\mathcal F$ any sub-$\sigma$-algebra of $\mathcal B$. If $Y=\frac12$, then $E[X]=E[Y]$ but $\int_F Y dP \neq \int_F X dP$ for any interval $F=[0,a]$, $0<a<1$.


text:
Q: Group by two colums that match when altered I have a table in database named Message and this is how the table looks like:

I need to find the last message of conversation gomez had with every user from the table. So, I want to make a column that combines sender and receiver username and group by with that column. However, how do i validate

Lucy+Gomez == Gomez+Lucy

My code so far:
SELECT sender+receiver, content, dateSent
FROM MESSAGE
WHERE sender = 'Gomez' OR receiver = 'Gomez'
GROUP BY sender+receiver
ORDER BY dateSent desc;

A: Use NOT EXISTS instead of GROUP BY:
SELECT m1.*
FROM MESSAGE m1
WHERE 'Gomez' IN (m1.sender, m1.receiver)
AND NOT EXISTS (
  SELECT 1
  FROM MESSAGE m2
  WHERE (m1.sender, m1.receiver) IN ((m2.sender, m2.receiver), (m2.receiver, m2.sender))
    AND m2.dateSent > m1.dateSent
)
ORDER BY m1.dateSent DESC;

Or, if your version of MySql is 8.0+, use ROW_NUMBER() window function:
SELECT sender, receiver, content, dateSent
FROM (
  SELECT *, ROW_NUMBER() OVER (
              PARTITION BY LEAST(sender, receiver), GREATEST(sender, receiver)
              ORDER BY dateSent DESC
            ) rn
  FROM MESSAGE
  WHERE 'Gomez' IN (sender, receiver)
) m
WHERE rn = 1
ORDER BY dateSent DESC;

See the demo.

A: If you want to keep your original concatenation approach, consider always concatenating in alphabetical order:
SELECT
  case
    when sender < receiver
    then concat(sender, receiver)
    else concat(receiver, sender)
  end,
  dateSent
FROM MESSAGE
WHERE sender = 'Gomez' OR receiver = 'Gomez'
GROUP BY case when sender < receiver then concat(sender, receiver) else concat(receiver, sender) end
ORDER BY dateSent desc;

Which can be easily modified further if the sender/receiver values need to be treated in a case-insensitive manner.


text:
Q: How would one go about solving this limit : $\lim_{x\to+0} ((x+9)^x-9^x)^x$ $\displaystyle \tag*{} \lim \limits _{x\to+0} ((x+9)^x-9^x)^x$
Hi everyone ! Sorry in advance for any formatting and grammatical errors !
My attempt to solve this limit went something like this :

*

*Write the limit as $\displaystyle \lim \limits_{x\to+0} e^{x \ln((x+9)^x-9^x)} $

*Move the limit to the power . Now I have to solve : $ \displaystyle \lim \limits _{x\to+0} x \ln((x+9)^x-9^x) $ .

*I realize this is $ 0 \cdot (-\infty)$ so I write it as : $\displaystyle \lim \limits _{x\to+0} \frac{\ln((x+9)^x-9^x)}{1/x} $.

*Now it's $-\frac{\infty}{\infty}$ and so I use L'Hôpital's rule.

*I get :  $\displaystyle \lim \limits _{x\to+0} \frac{((x+9)^x\left(\frac{x}{x+9}+\ln(x+9)\right)-9^x\ln9)(-x^2)}{(x+9)^x-9^x)} $

*Sad because this is $\frac{0}{0}$ and the only thing that I can do is apply L'Hôpital's rule again which would ( I think ) make things worse.

Wolfram Alpha gives 1 as the answer but no Step-by-Step solution sadly.
Any help appreciated !

A: $\newcommand{\d}{\mathrm{d}}$As you say, we need to evaluate the logarithmic limit. Let's first try L'Hopital: $$\lim_{x\to0}\frac{\ln[(x+9)^x-9^x]}{1/x}=\lim_{x\to0}(-x^2)\cdot\frac{[\ln(x+9)+\frac{x}{x+9}](x+9)^x-\ln(9)\cdot 9^x}{(x+9)^x-9^x}$$No... this is horrible and very possibly many never resolve. But there is more to limits than L'Hopital (there is even a tag dedicated to this on the forum). Let's try: $$\ln[(x+9)^x-9^x]=\ln(9^x)+\ln\left[\left(\frac{x}{9}+1\right)^x-1\right]$$And let's recall that for $|x|\lt1$, $(1+x)^y=\sum_{n=0}^\infty\binom{y}{n}x^n$ Where appear the more generalised binomial coefficients. Notice that the first term is $1$ so the $-1$ cancels. I then can write the above as (for small $x$, but we want $x\to0$ anyway): $$x\cdot\ln(9)+\ln\left[\sum_{n=1}^\infty\binom{x}{n}\frac{x^n}{9^n}\right]$$Multiplying by $x$ and taking the limit, L'Hopital becomes useful again (I am casually splitting the limit across the addition and multiplication - this is because all individual limits exist, as I will show): $$\begin{align}\lim_{x\to0}x^2\cdot\ln(9)+\lim_{x\to0}x\cdot\ln\sum_{n=1}^\infty\binom{x}{n}\frac{x^n}{9^n}&=0+\lim_{x\to0}\frac{\ln(x^2/9+x^3(x-1)/162+\cdots)}{1/x}\\&\overset{\text{L.H.}}{=}\lim_{x\to0}(-x^2)\cdot\frac{2x/9+x^2(x-1)/54+\cdots}{x^2/9+x^3(x-1)/162+\cdots}\\&=\lim_{x\to0}\frac{x^3\cdot(-2/9)+O(x^4)}{x^2\cdot(1/9)+O(x^3)}\\&=0\end{align}$$Why zero at the end there? It is a standard limit fact that since the numerator polynomial dominates ($x^3\ll x^2$ as $x\to0$) the limiting behaviour is thus determined. Divide through by $x^2$ if you don't believe me!
Since the limit of the logarithm was $0$, the limit of the whole thing is $e^0=1$.
The $9$ was quite irrelevant here, by the way. Any positive constant would have done.

A: Let's start from understanding how $(x+9)^x-9^x$ behaves for $x\to 0$. You have
$$(x+9)^x-9^x = 9^x\left(\left(1+\frac{x}{9}\right)^x-1\right) = 9^x \left(e^{x\log(1+\frac{x}{9})}-1\right)\,.$$
Now $\log(1+\frac{x}{9}) = \frac{x}{9}+o(x)$ and so $$e^{x\log(1+\frac{x}{9})}= e^{\frac{x^2}{9}+o(x^2)} = 1 + \frac{x^2}{9}+o(x^2)\,.$$
On the other hand $9^x = 1+O(x)$ and so
$$(x+9)^x-9^x = \frac{x^2}{9}+o(x^2)\,.$$
Now we are left with studying the limit
$$\lim_{x\to 0}\left(\frac{x}{3}\right)^{2x}\,.$$
Clearly $3^{2x}\to 1$, so we just need to worry about $x^{2x} = e^{2x\log x}$. Now you have that $x\log x$ is a case of $0\times\infty$, as you said. However, from now it should be easier to use De L'Hôpital and conclude. Can you do it?


text:
Q: SQL query to filter combination of 3 tables I have 3 tables
Student
1 ABC
2 XYZ
3 PQR

Subject
10 Maths
11 Science
12 English

Marks
SID SBID    MARKS
1   10  60
1   11  80
1   12  90
2   10  50
2   11  40
2   12  30
3   10  45
3   11  49
3   12  25

I need to get a result with the columns considering 50 and above is Pass mark.
StudentName, Maths_Marks, Science_Marks, English_Marks, Total, Status(P/F)
ie.
ABC   60  80  90  250  P
XYZ   50  40  30  120  F
PQR   45  49  25  119  F

A: This is what you are looking for :
DECLARE @Student TABLE(
            ID  int,
            Name  VARCHAR(100)
    )

    INSERT INTO @Student SELECT '1','ABC'
    INSERT INTO @Student SELECT '2','XYZ'
    INSERT INTO @Student SELECT '3','PQR'

    DECLARE @Subject TABLE(
            ID  int,
            Name  VARCHAR(100)
    )

    INSERT INTO @Subject SELECT '10','Maths'
    INSERT INTO @Subject SELECT '11','Science'
    INSERT INTO @Subject SELECT '12','English'

        DECLARE @Marks TABLE(
            SID   int,
            SBID    int,
            MARKS   int
    )

    INSERT INTO @Marks SELECT '1','10','60'
    INSERT INTO @Marks SELECT '1','11','80'
    INSERT INTO @Marks SELECT '1','12','90'
    INSERT INTO @Marks SELECT '2','10','50'
    INSERT INTO @Marks SELECT '2','11','40'
    INSERT INTO @Marks SELECT '2','12','30'
    INSERT INTO @Marks SELECT '3','10','45'
    INSERT INTO @Marks SELECT '3','11','49'
    INSERT INTO @Marks SELECT '3','12','25'

        DECLARE @FinalResult TABLE(
            Name  VARCHAR(100),
            Maths_Marks int,
            Science_Marks int,
            English_Marks int
            )

    INSERT INTO @FinalResult
        select
        S.name,
        M.MARKS as Maths_Marks,
        (
    select M2.MARKS as 'Science_Marks' from @Student S2
    join @Marks M2 on M2.SID = S2.ID
    join @Subject SB2 on SB2.ID = M2.SBID
    where SB2.Name ='Science'
    and S2.ID = S.ID
        ) as Science_Marks,
        (
    select M2.MARKS as 'English_Marks' from @Student S2
    join @Marks M2 on M2.SID = S2.ID
    join @Subject SB2 on SB2.ID = M2.SBID
    where SB2.Name ='English'
    and S2.ID = S.ID
        ) as English_Marks

        from @Student S
    join @Marks M on M.SID = S.ID
    join @Subject SB on SB.ID = M.SBID
    where SB.Name ='Maths'

    SELECT  *,fn2.Maths_Marks + fn2.English_Marks +fn2.Science_Marks as Total  ,
    CASE WHEN fn2.Maths_Marks > 50 THEN 'P'
    ELSE 'F'
END AS Status
    from @FinalResult fn2

And finally the Result looks like :

A: you can use pivot. Of course, you did not tag the name of the database and I got the output in sql server.
select StudentName,
       Maths as Maths_Marks,
       Science as Science_Marks,
       English as English_Marks,
      (Maths+Science+English) as Total,
      case when Maths > 50 then 'P' else 'F' end as Status
from
(
   select s.Name as StudentName,m.Marks,sb.Name as sbname
   from Marks m join Subject sb on m.SBID = sb.ID join Student s on m.SID = s.ID
) as SourceTable
pivot (
    max (Marks)
    for sbname
    in (Maths,Science,English)
) as piv

demo in db<>fiddle


text:
Q: Why, speaking of a colonoscopy, does it say "they put it UP your bottom"? This is a piece of dialogue about a colonoscopy from the series "Outnumbered" s03e03:

— Yes, but how does it get inside your insides?
— Well, they put it up your bottom.

A: The phrase "up your bottom" is a standard phrase, perhaps an idiom, in UK English for "inserted anally". The phrase "up your rear" is perhaps more common in US English.  Compare "up the spout" for a bullet in the chamber of a gun, ready to fire (although this phrase has other senses as well).
As with many other idioms, the phrase is not entirely logical, and could be phrased otherwise, but commonly is not. That is just how it is said.


text:
Q: Does an étale equivalence relation of schemes induce an equivalence relation on points? Let $R \rightrightarrows U \to X$ be a presentation of an algebraic space by schemes.
Does this induce an exact sequence $|R| \rightrightarrows |U| \to |X|$ on underlying points?
The reason I ask is that this is stated as a lemma in the Stack Project (Lemma 33.4.4). However, the proof uses:
"Since $j = (s,t):R \to U \times U$ is a monomorphism we see that $|R| \to |U|\times|U|$ is injective."
But this can't be true in general. For instance $|U \times U| \to |U|\times|U|$ is not injective when $U$ is the affine line since all generic points in $|U\times U|$ corresponding to dimension 1 curves map to the same pair of generic points. Of course, this equivalence relation is not étale. The question is: Does étaleness prevent such collapses to happen? In that case, how?
Edit: It is pretty clear that $|R| \rightrightarrows |U|$
becomes a pre-equivalence relation with $|U| \to |X|$ as quotient.
In fact, I think this is the only property used later in the text, which makes the error unproblematic.
Then the only question is: Is $|R| \to |U| \times_{|X|}|U|$ injective?


text:
Q: button или input Можно ли использовать <button type="submit"/> , как <input type="submit/>. И какая между ними разница?

A: button по умолчанию имеет type="submit", если находится в теге form, разница в том, что button можно лучше стилизировать (хочешь картинкой, хочешь фоном и т. д.), ну и у button, как нового элемента HTML5, поддержка чуть хуже, хотя сейчас уже не критично .

A: В дополнение к соседнему ответу:

*

*input элемент по умолчанию имеет display:inline, в то время, как button - display:block в FF input по умолчанию имеет display:inline, в остальных браузерах, значение display совпадает с button: display:inline-block

*Кроме этого, button может быть контейнером для других элементов, в отличие от input.

span {
  font-weight: bold;
  color: red;
}

.green {
  color: green;
}
<form>
  <input type="submit" value="1" />
  <input type="submit" value="2" />
  <input type="submit" value="3" />
  <input type="submit" value="4" />
</form>

<form>
  <button type="submit">1 11</button>
  <button type="submit">2 22</button>
  <button type="submit">3 22</button>
  <button type="submit">4 33</button>
</form>

A: Если используется длинное слово или целое предложение на кнопке - лучше использовать button вместо input, т.к input по умолчанию white-space: nowrap.
Также button поддерживает работу с псевдоэлементами

* {
  box-sizing: border-box;
  font-family: sans-serif;
}

[type="submit"] {
  /*display: block;*/
  padding: 15px 35px;
  width: 100%;
  font-size: 18px;
  position: relative;
}

[type="submit"]:before,
[type="submit"]:after {
  content: 'i';
  position: absolute;
  top: 50%;
  left: 0;
  width: 30px;
  height: 30px;
  line-height: 30px;
  background: tomato;
  color: #fff;
  margin-top: -15px;
}

[type="submit"]:after {
  left: auto;
  right: 0;
}

input type="submit"

<input type="submit" value="Submit text text tetx text text text tetx text text text tetx text text text tetx text text text tetx text text text tetx text">

button type="submit"

<button type="submit">Submit text text tetx text text text tetx text text text tetx text text text tetx text text text tetx text text text tetx text</button>


text:
Q: Xamarin forms iOS changed AppIcons but remains showing old default Starting from a standard Xamarin forms app template and changing the app icons in assets.xcassets, I am unable to make this take effect. The initial xamarin icon keeps showing when deployed to physical devices.
In assets.xcassets, I added all the required image sized.
I ensured that in plist info this asset was set as app icons source.
I have tried cleaning, rebuilding and deleting from the ipad and iphone I am testing with. No success.
I tried deleting the default asset and creating a new one, and make pinfo point to this, and still the old Xamarin icon shows up. This makes me think that there is a cache somewhere on either my windows pc, on which I am developing using vs2019, or on the mac which VS is connected to for doing the actual build, and this is not getting updated, since otherwise that old icon should not exist any longer.
I did read this answer
Xamarin forms: Launcher icon for ios
Which indicates that the OP has a problem with a mismatched path to the asset, but that does not seem to be the case for me. The xcasset folder is at the root of the ios project. As this is simply the default test project it is app1/App1.ios/Fawk.xcassets and the entry in pinfo is
XSAppIconAssets
Fawk.xcassets/AppIcons.appiconset
Does this make any kind of sense?
Edit: Tried vs2019, xamarin forms template. Deleted default asset in assetcatalogs under ios, created a new one, set all my custom icon images (png), updated info.plist/visual assets/appicon to my new asset and then ran it on a physical device. The default xamarin icon is what shows up. This seems to indicate it is not a cache issue, as I suspected, but... something else...

A: *

*You can right-click Assets.xcassets and view it in the folder, there is a json file in it, please check if the file name is correct.

*According to the official documentation, if you are not connected to a Mac, it will only display the original image. For more information, you can check: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/deploy-test/hot-restart#limitations


text:
Q: Can someone look at my gulp file and tell me why it might be so slow to run? It takes far too long usually. On my laptop it literally never finishes. The PHP watch is supposed to be checking for PHP saves in the root and in any sub-directories. I'm not sure if I have the glob correct there, and maybe that's what's causing the problem?
    var gulp = require('gulp');
    var sass = require('gulp-sass');
    var browserSync = require('browser-sync');
    var mmq = require('gulp-merge-media-queries');
    var phpConnect = require('gulp-connect-php');
    var autoPrefixer = require('gulp-autoprefixer');

    gulp.task('sass', function() {
      return gulp.src('assets/css/**/*.scss')
        .pipe(sass()) // Converts Sass to CSS with gulp-sass
        .pipe(autoPrefixer({
                browsers: ['last 2 versions'],
                cascade: false
            }))
        .pipe(gulp.dest('assets/css'));
    });

    gulp.task('connect-sync', function() {
      phpConnect.server({}, function (){
        browserSync({
          proxy: '127.0.0.1:8000'
        });
      });
    });

    gulp.task('mmq', ['sass'], function () {
      gulp.src('assets/css/styles.css')
        .pipe(mmq({
          log: true
        }))
        .pipe(gulp.dest('assets/css'))
        .pipe(browserSync.reload({
          stream: true
    }));
    });

    gulp.task('watch', ['connect-sync', 'sass', 'mmq'], function(){
     gulp.watch('assets/css/**/*.scss', ['sass', 'mmq']);
     gulp.watch('/**/*.php', browserSync.reload);
     gulp.watch('assets/js/**/*.js', browserSync.reload);
      // Other watchers
    });

A: Could be that gulp checks your node_modules folder? This is known to slow gulptasks down.
Try running each gulp statement from the console, i.e. First try gulp sass, then gulp connect.
Can you post the output from your console plz?


text:
Q: ParseJSON Error for HTTPPost - SSJS Unable to retrieve security descriptor In my marketing cloud, landing page.  Getting the error "System.InvalidOperationException: Unable to retrieve security descriptor for this frame" while trying to Parse the JSON response in a HTTP Post call.
The response is received perfectly in respContent shown below. The response has shortLink - unable to parse it to extract the shortLink. The issue is with Platform.Function.ParseJSON(result.Response);
I did try other solutions provided on SFSE but didn't work too.
Code
var url = 'xxxxxx';
var contentType = 'application/json';
var payload = '{"longDynamicLink": "https://xxxxx/?link='+encoded';
var headerNames = ["name"];
var headerValues = ["application/json"];
var result = HTTP.Post(url, contentType, payload, headerNames, headerValues);
var content = Platform.Function.ParseJSON(result.Response);

Write("
respContent :" + result.Response +"
");
Write("
shortLink :" + content.shortLink+"
");

Output
respContent :{ "shortLink": "https://xxx.link/89eQ",
 "previewLink": "https://xxx.link/89eQ?d=1" }

    The error is :{"message":"Unable to retrieve security descriptor for this frame.",
"description":"System.InvalidOperationException: Unable to retrieve security descriptor for this frame. - from mscorlib\r\n\r\n"}

A: Found the fix.
Had to use [0] for the response.
var content = Platform.Function.ParseJSON(result.Response[0]);


text:
Q: cómo compartir variables de javascript a php? Estoy haciendo un proyecto pero necesito que se comparta una variable de js a php, ya puedo compartirlas pero no se comparan con un if, aunque son las mismas.
?>
<script>
    var va = prompt('desea continuar, escriba ok para continuar');
</script>
<?php

$va = "<script>document.writeln(va)</script>";
echo $va;
if ($va =='ok') {
    echo('1');
}else {
    echo('2');
}

El resultado sale ok 2 al escribir ok, pero lo que quiero es que salga el 1, ya intente con trim para limpiar los espacios, pero no sale.
Que tengo mal?

A: Podrías pasar un parámetro vía get y recargar la página:
<?php

if (isset($_GET['resultado']) and ($_GET['resultado'] == 'ok')) {
  // lo que quieras hacer
}
else {
?>

  <script>
    var va = prompt('desea continuar, escriba ok para continuar');
    var url = window.location.href;
    if (url.indexOf('?') > -1){
      url += '&resultado=' + va
    }
    else {
      url += '?resultado=' + va
    }
    window.location.href = url;
  </script>

No he podido validar el código pero debería funcionarte sin problemas.

A: No puedes pasar variables del código JavaScript de la página actual al código PHP de la página actual ... El código PHP se ejecuta en el lado del servidor y no sabe nada sobre lo que está sucediendo en el lado del cliente.
Debes pasar variables al código PHP desde el formulario HTML utilizando otro mecanismo, como enviar el formulario utilizando los métodos GET o POST.
Si lo que quieres es poder ejecutar cosas en PHP sin tener que recargar la página se puede hacer usando $.ajax( o $.GET(
Segun las necesidades que tengas puedo modificar la respuesta para ampliar información.


text:
Q: Merger app.config from custom location I have a scenario where I need to read an environment variable on start, then depending on the value of the ENV variable I need to merge a config file with the App.config file.
E.g.
MyApp.exe
MyApp.exe.config
Stage\MyApp.exe.config
Live\MyApp.exe.config

On start
-if the Environment variable = Stage, then Merge the config file in the Stage folder
-if the Environment variable = Live, then Merge the config file in the Live folder
If I had the following in the default MyApp.exe.config
<appSettings>
 <add key="SomeKey" value="SomeValue">
</appSettings>

and then had the following in the Stage\MyApp.exe.config
<appSettings>
  <add key="SomeKey" value="Some NEW Value">
</appSettings>

I'd expect my application to read the value for SomeKey as "Some NEW Value".
I can't seem to find a clean way to implement this exact approach.
Thanks
Warrick

A: You might want to use Build Events in Visual Studio.
http://msdn.microsoft.com/en-us/library/42x5kfw4(v=vs.90).aspx
You can use the variable to copy the overwrite the app.config in the pre-build event:
$(ConfigurationName)

If the config name is DEV, then copy the app.config.DEV over the app.config
If the config name is PROD, then copy the app.config.PROD over the app.config


text:
Q: Event Tracking code for multiple links in one banner I have a banner on my sites home page, It has multiple links and the html code is written within  tag and does not contains any anchor links, instead it has a href link only.
My IT heads says its not possible to embedd a onclick event tracking code to track all the links.
Please let me know how will i track this?

A: A pure unobtrusive javascript solution (derived from Googles example, working but not necessarily the most complete or beatiful code) :
function addListener(element, type, callback) {
 if (element.addEventListener) element.addEventListener(type, callback);
 else if (element.attachEvent) element.attachEvent('on' + type, callback);
}

links = document.getElementsByTagName('a');
for(i=0,cnt=links.length;i<cnt;i++) {
    addListener(links[i], 'click', function() {
      ga('send', 'event', 'button', 'click', 'nav-buttons');
    });
}

If you put that in an external js file or an inline script it will "decorate" all links in the page (you would need a more specific selector instead of "all links") with a click event that fire google event tracking when somebody clicks the link. No embedded click code in the link tags necessary (that's bad practice in any case).
If you are already using jQuery (since that's probably the most popular javascript library) you can simply do
$( "a" ).click(function() {
  ga('send', 'event', 'button', 'click', 'nav-buttons');
});

(again, choose a more specific selecor).
Both examples assume Universal Analytics, for classic you'd need to change the event tracking code (see DalmTos answer for examples).

A: The following examples will depend on if you are running classic VS universal analytics.
For Classic Analtyics look for ga.js in your tracking code:
Play

For Universal Analytics look for Analtyics.js in your tracking code:
Play

I don't see any reason why you wouldn't be able to track it in your banner.


text:
Q: What determines the limit on voicemail storage on an iPhone 7? My iPhone 7 stopped taking voicemails. I dialed it from a different number and got the automated message, "voice mailbox is full." I contacted my carrier, Credo Mobile, and they explained that voicemail storage occurs on the iPhone, not in my carrier account.
On the iPhone 7, I went into Settings, General, iPhone Storage, Phone, and saw that Voicemails took up only 12.3MB. (This was after I had deleted some voicemails and was again able to leave a message.)
Is there, then, some constant, fixed, number of bytes that my phone can store as voicemail? Or is it a fixed number of messages? Or if I reduce the amount stored by some other app---say, Voice Memos, which today uses a whopping 14.86GB---will there be more room for voicemails?
These are not several questions, it is a single question with several possible suggested answers.
(Because of spam phone calls and robocalls, there is a steady drizzle of unwanted voicemails into my iPhone 7 so that even if no one calls me that I care about, the voice mailbox will get full.)
Note that one response to Can I devote more room to my voicemails? states, in the context of Verizon,

Voicemail is handled by the carrier. The size of your mailbox depends on the plan & features you have with Verizon, not on the free space available on your phone.

But Credo Mobile customer service---a live human being speaking with me---unequivocally stated the opposite for their service. In addition, when I logged into my account on Credo Mobile, https://www.credomobile.com/customer/account/login,
I found no option to set or change the amount of voicemail storage. Also, there are no voicemails in my online account. For instance, I cannot go online and listen to voicemails. There is no list of voicemails online.

A: Whoever you spoke to one the phone was wrong, your carrier limits the number of voice mails you can have stored.


text:
Q: how to check if user is authenticated with passport (get user from token using laravel-passport) I am using Passport to log in users to a Laravel API endpoint, users get authenticated using their social accounts (google, facebook) using laravel-socialite package.
the workflow of logging users in and out works perfectly (generating tokens...Etc). The problem is I have a controller that should return data based on whether there is a user logged in or not.
I do intercept the Bearer token from the HTTP request but I couldn't get the user using the token (I would use DB facade to select the user based on the token but I am actually looking whether there is a more clean way already implemented in Passport)
I also don't want to use auth:api middleware as the controller should work and return data even if no user is logged in.
this is the api route:
Route::get("/articles/{tag?}", "ArticleController@get_tagged");

this is the logic I want the controller to have
public function get_tagged($tag = "", Request $request)
{
    if ($request->header("Authorization"))
        // return data related to the user
    else
        // return general data
}

A: Assuming that you set your api guard to passport, you can simply call if (Auth::guard('api')->check()) to check for an authenticated user:
public function get_tagged($tag = "", Request $request)
{
    if (Auth::guard('api')->check()) {
        // Here you have access to $request->user() method that
        // contains the model of the currently authenticated user.
        //
        // Note that this method should only work if you call it
        // after an Auth::check(), because the user is set in the
        // request object by the auth component after a successful
        // authentication check/retrival
        return response()->json($request->user());
    }

    // alternative method
    if (($user = Auth::user()) !== null) {
        // Here you have your authenticated user model
        return response()->json($user);
    }

    // return general data
    return response('Unauthenticated user');
}

This would trigger the Laravel authentication checks in the same way as auth:api guard, but won't redirect the user away. In fact, the redirection is done by the Authenticate middleware (stored in vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php) upon the failure of the authentication checking.
Beware that if you don't specify the guard to use, Laravel will use the default guard setting in the config/auth.php file (usually set to web on a fresh Laravel installation).
If you prefer to stick with the Auth facade/class you can as well use Auth::guard('api')->user() instead or the request object.

A: thanks to @mdexp answer
In my case I can resolve my problem with using
if (Auth::guard('api')->check()) {
    $user = Auth::guard('api')->user();
}

In my controller.