text:
Q: Typescript - Dynamically extend interface I am trying to type an existing React Native module with the following props:
useComponent1: boolean
useComponent2: boolean

With the following implementation
render(){
    if(useComponent1){
        return <Component1 {...props}/>
    }

    if(useComponent2){
        return <Component2 {...props}/>
    }
}

I have an interface for components 1 & 2, however, I can't extend both as the props are determined by which component is utilised.
Is it possible to dynamically extends an interface?
If not, is there another solution to this issue?

A: There can be intersection/union type:
interface Component1Props { .... }
interface Component2Props { .... }
interface WrapperOwnProps {
  useComponent1: boolean
  useComponent2: boolean
}
type WrapperProps = WrapperOwnProps & (Component1Props | Component2Props);

Props type can be additionally asserted:
class Wrapper extends Component<WrapperProps> {
  render(){
    const { useComponent1, useComponent2, ...props } = this.props;
    if(useComponent1){
      return <Component1 {...props as Component1Props}/>
    }

    if(useComponent2){
      return <Component2 {...props as Component2Props}/>
    }
  }
}


text:
Q: Does MySQL support replicating all databases? I've been doing some investigation into properly configuring MySQL replication.
From what I understand after reading the documentation, you can only replicate specific databases, and each database name must be specified: In the master configuration, in order for the relevant database writes to be written to the binary logs, and in the slave configuration, in order to replay those logs onto the slave.
Is this correct, or is it possible to configure MySQL to replicate any and all databases?

A: To answer your question about how MySQL replicates all databases, here is how it works...

*

*Master has Binary Logging enabled

*Master records completed SQL Statements

*Master will inject 'USE dbname;' among the SQL Statements it records

*Slave connects to Master (IO Thread)

*Slave IO Thread requests next SQL statement from the Binary Logs

*Slave IO Thread copies it to its Relay Logs

*Slave SQL Thread Processes its Relay Log Entries FIFO (Queue)

Once USE dbname; is issued out of the relay logs,  multiple SQL statements will be processes chronologically until another USE dbname; (a different database) is issued from the Relay Logs.
To see this, pick any Binary Log (except the Current One) on the Master, and run this:
mysqlbinlog binarylogname > SQLStatements.sql

To see all the binary logs and the current binary log on the Master, run these:
SHOW BINARY LOGS;
SHOW MASTER STATUS;

Long story short: By default, all DBs are replicated due to the USE dbname; command within the binary logs on the master and the relay logs on the slave.
Abdul's answer shows how to filter in or filter out databases from being processed by the slave.

A: Yes, you can replicate all databases from master to slave.
But sometimes we don't prefer that Mysql databases should be replicated due to security reasons, because all the user related information will also be available to the slave. That can cause security breaches.
You can set which database should be replicated and which one should not by using options in the configuration file.
   replicate-ignore-db=db_name  and replicate-do-db=db_name

It also depends on which type of replication you are using, like statement based or row based.
Please see:
http://dev.mysql.com/doc/refman/5.1/en/replication-options-slave.html

A: From what I have understood from RolandoMySQLDBA answer is you just add to your my.cnf replicate-ignore-db=mysql to skip mysql system database replication.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exporting data from Access to an already existing Excel spreadsheet How can I export a table from MS Access 2007 into an already existing excel spreadsheet? (Not a new spreadsheet)
The idea being that I have several macros set up on other excel sheets which will analyse the data and output graphs that I can't work out how to produce on Access.
I want to export table "Master" to:
Excel file name: "Resource Planning"
Sheet name: "Raw Data"
Thanks in advance

A: You can create Name Ranges in Excel by going to the Formulas tab and providing a name and reference. Make sure the reference, for example: =Sheet1!$A$1; refers to the range where you want your data to be pasted. Try not to have the Excel file open while you run the subroutine. Then when you are exporting from Access you can use a vba module to run the following:
Private Sub ExportMyQueryOtTableToExcel()
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
        "sqYourQueryNameOrTable", "x:\ExcelFile.xls", -1, "NameRangeInExcelWorkBook"
End Sub

If you want to run this from a Module, just change the "Private Sub" part to "Public Function". That way you can call the function from the Macro with the RunCode action (Function name = ExportMyQueryOtTableToExcel()).


text:
Q: 'int' object is not iterable in strings So I was trying to get a list of the numbers 1,2,3... to print out individually on the console but it would always say int object is not iterable.
My code:
def run_seed_code(told_seed):
    for letter in told_seed:
        print(letter)

run_seed_code(1234321)

A: Try converting the number into a string.
for char in "Hello World":
    print(char)

This prints each letter on a new line because it iterates through the string.
An integer is not iterable, you can't loop through it.
Either adding a string caster in the function or just making the argument a string will work fine.
def run_seed_code(told_seed):
    for letter in str(told_seed): # Convert to a string
        print(letter)

run_seed_code("1234321") # Or pass a string into the argument instead.


text:
Q: Expand closest div with class I have structure:

 Click

And it's repeat 3 times.
In Css:
.cp_expanded_view {
  display:none;
}

So I want to expand closest element with cp_expanded_view class.
My jQuery:
jQuery(document).ready(function($) {
  $(".cp_view_card_details").click(function() {

    $(this).next('.cp_expanded_view').slideToggle('2000',
      function() {

      });

  });
});

jQuery code doesn't work and doesn't show any error.
How can I make nearest cp_expanded_view to shown up?

A: Use parent to find next desire class. cp_expanded_view class is next to main-class class.

jQuery(document).ready(function($) {
$(".cp_view_card_details").click(function() {
$(this).parent().next('.cp_expanded_view').slideToggle('2000', function() {

 });

  });
});
.cp_expanded_view {
  display: none;
}

 Click

  Show Hidden info


text:
Q: How do I access a numpy array using the memory index? I'm learning numpy and I came across an example that uses np.nditer:
a = np.arange(6).reshape(2, 3)
for i in np.nditer(a):
    print i,

This prints out:
0 1 2 3 4 5

Which is the memory index of each element. Given these indexes, how can I access each element in the numpy array? Just doing a[i] gives an error, as the array has more than 1 dimension.

A: nditer returns elements of the array, as 0d arrays themselves.  You have to use extra parameters to get the (multi)index.
If I do your iteration, but display information about the i besides it's value, you'll see:
In [132]: a = np.arange(6).reshape(2,3)
In [134]: for i in np.nditer(a):
     ...:     print(i, type(i), i.shape, i.dtype)

0 <class 'numpy.ndarray'> () int32
1 <class 'numpy.ndarray'> () int32
2 <class 'numpy.ndarray'> () int32
3 <class 'numpy.ndarray'> () int32
4 <class 'numpy.ndarray'> () int32
5 <class 'numpy.ndarray'> () int32

Or equivalently, using the repr display:
In [135]: for i in np.nditer(a):
     ...:     print(repr(i))
     ...:
array(0)
array(1)
...

np.nditer isn't a very useful iteration mechanism, especially not at the beginning.  It is best seen as a stepping stone toward using it in advanced cython code.  In other words, study https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html, all the way to the end.

Looks like your example comes from this page.

The most basic task that can be done with the nditer is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface.

There are more direct ways of iterating through an array:
In [136]: for i in a: print(repr(i))   # by rows
array([0, 1, 2])
array([3, 4, 5])

In [139]: for ij in np.ndenumerate(a):   # with value and 2d index
     ...:     print(ij)
((0, 0), 0)
((0, 1), 1)
((0, 2), 2)
((1, 0), 3)
((1, 1), 4)
((1, 2), 5)

The multi_index example on the nditer page provides similar information:
In [141]: it = np.nditer(a, flags=['multi_index'])
     ...: while not it.finished:
     ...:     print("%d <%s>" % (it[0], it.multi_index))
     ...:     it.iternext()
     ...:
0 <(0, 0)>
1 <(0, 1)>
2 <(0, 2)>
3 <(1, 0)>
4 <(1, 1)>
5 <(1, 2)>


text:
Q: Show that it is equal to $\text{Im}f\oplus \ker g$ Let $R$ be a commutative ring with unit and $M$ be a $R$-module.
I want to show that if $f:M\rightarrow N$ and $g:N\rightarrow M$ are $R$-module homomorphisms such that $gf=1_M$ then $N=\text{Im}f\oplus \ker g$.
$$$$
I have done the following:
Let $g(n)=m$.
Let $n=f(m)+(n-f(m))$.
We have that $f(m)\in \text{Im}f$ and that $g(n-f(m))=g(n)-g(f(m))=g(n)-m=m-n=0$, i.e., $n-f(m)\in \ker g$.
Is this correct?
Now it is left to show that $\text{Im}f\cap \ker g=\{0\}$, or not?
Suppose that $x\in \text{Im}f\cap \ker g=$, which is non-zero.
Then $x\in \text{Im}f$, i.e., there is a $y \in M$ such that $f(y)=x$, and $x\in \ker g$, i.e., $g(x)=0$, or not?
Then we have that $g(f(y))=g(x)\Rightarrow gf(y)=0\Rightarrow y=0$.
Is this correct? How could we continue?

A: Yes, your attempt is correct; you have nothing more to do.

Here's an unabridged version of your proof.
Let $x\in N$; then
$$
x=fg(x)+(x-fg(x))
$$
Note that $fg(x)\in\operatorname{Im}(f)$; moreover $g(x-fg(x))=g(x)-gfg(x)=g(x)-g(x)=0$, therefore $x-fg(x)\in\ker g$.
Hence $N=\operatorname{Im}(f)+\ker g$.
Thus we only have to prove that $\operatorname{Im}(f)\cap\ker g=\{0\}$.
Suppose $x\in\operatorname{Im}(f)\cap\ker g$. Then $x=f(y)$ for some $y\in M$; next $0=g(x)=gf(y)=y$, so $x=0$.


text:
Q: Creating DOMDocument: match one certain element in a PHP-parser good evening dear Community,
Well first of all: felize Navidad - I wanna wish you a Merry Christmas!! In my season-break i am workin on a little parser-script.
Today i'm trying to debug a little DOMDocument object in php. Ideally it'd be nice if
I could get DOMDocument to output in a array-like format, to store the data
in a database!
My example: head over to the url - see the example: the target
I want to filter out the data in the block:
Schulart: BBS
Schulnummer:60119
Anschrift: Berufsbildende Schule Boppard Antoniusstr. 21; 56154 Boppard
Telefon: (0 67 42) 80 61-0
Telefax: (0 67 42) 80 61-29
E-Mail: sekretary@bbs-boppard.de
Internet: website
Träger:Kreisverwaltung Rhein-Hunsr�ck-Kreis
letzte Änderung: 08 Feb 2010 14:33:12 von 60119

I have investigated the sourcecode - and found out that the attribute of interest should
be this one:
 class="content"div class="content"><!-- TYPO3SEARCH_begin -->
or even better: wfqbeResults
So if i run the DOMDucument way i can use this like so:
$dom->getElementById('wfqbeResults');

here the code is: - my trails
<?php

$dom = new DOMDocument();
@$dom->loadHTMLFile(' -> here the website goes in<- ');
$divElement = $dom->getElementById('wfqbeResults');

$innerHTML= '';
$children = $divElement->childNodes;
foreach ($children as $child) {
   $innerHTML .= $child->ownerDocument->saveXML( $child );
}
echo $innerHTML;

<?

Duhh: this outputs lot of garbage. The code spits out a lot of html anyway. I have to
overhaul the code a bit to get the wanted 9 lines out of the parser:
what is aimed: i want to get out the following:
a. 9 lines with nine labels and nine values.
b. I want to prepare the output to store it in a MySQL-DB!
Look forward to some hints
greetings zero

A: Here is the solution return the labels and values in a formatted array ready for input to mysql!
<?php

$dom = new DOMDocument();
@$dom->loadHTMLFile('http://schulen.bildung-rp.de/gehezu/startseite/einzelanzeige.html?tx_wfqbe_pi1%5buid%5d=60119');
$divElement = $dom->getElementById('wfqbeResults');

$innerHTML= '';
$children = $divElement->childNodes;
foreach ($children as $child) {
$innerHTML = $child->ownerDocument->saveXML( $child );

$doc = new DOMDocument();
$doc->loadHTML($innerHTML);
//$divElementNew = $dom->getElementsByTagName('td');
$divElementNew = $dom->getElementsByTagname('td');

    /*** the array to return ***/
    $out = array();
    foreach ($divElementNew as $item)
    {
        /*** add node value to the out array ***/
        $out[] = $item->nodeValue;
    }

echo '<pre>';
print_r($out);
echo '</pre>';

}

?>


text:
Q: JQueryUI Draggable - Issues setting Containment [x1,x2] values I am having trouble setting the containment value of the jqueryUI draggable function when using the [x1,y1,x2,y2] format.  Here is the js:

And the html which the script is interacting with:

I am trying to set the drag containment (of the slideMin div) based on the offset().left of the next div, in this case (slideMax).
In other words, I want the draggable behavior to stop (for the slideMin div) when it reaches the left of the next (slideMax) div.
The x1 seems to be working as the drag is stopping at the position defined, however, it is overlapping and extending beyond the next div, which i do not want to happen.  There must be something wrong with how I am setting the x2 value but I am not sure what it is.
Any advice?

A: Figured it out... I had two divs, both draggable.  The first div was to stop when it reached the next div.  The above code accomplished this until I was to drag either div: once either div was dragged, the draggable range for the other div was not updating, therefore, I received the error where the draggable range was overlapping the other div.  To fix it, I had to re-initiate and set the draggable range for the other div within the draggable function for the div that was being moved.
The new code goes something like this:
$(this).draggable({
    containment: [$(this).position().left, $(this).position().top, $(this).next().position().left - $(this).width()+4, $(this).position().top],
    drag: function(e){
        $(this).next().draggable({
            containment: [parseFloat($(this).position().left) + parseFloat($(this).width())-4, $(this).next().position().top, parseFloat($(this).parent().position().left) + parseFloat($(this).parent().width())-3, $(this).next().position().top]
        });
    }
});
$(this).draggable({
    containment: [parseFloat($(this).prev().position().left) + parseFloat($(this).prev().width())-4, $(this).position().top, $(this).position().left, $(this).position().top],
    drag: function(e){
        $(this).prev().draggable({
            containment: [$(this).parent().offset().left-$(this).prev().width()+5, $(this).prev().position().top, $(this).position().left - $(this).prev().width()+4, $(this).prev().position().top]
        });
    }
});

PS, the numbers -3 -4 +5, etc. were to add spacing for the handles on my draggable divs (4px handles), if you don't have handles you don't need the extra -3 -4 +5 portions of the code.


text:
Q: How to bind data to DataTrigger in Silverlight I populate Silverlight DataGrid like
 grdActivities.ItemsSource = items;

XAML
<datagrid:DataGrid   x:Name="grdActivities" AutoGenerateColumns="False">
   <sdk:DataGrid.RowStyle>
      <Style TargetType="sdk:DataGridRow">
         <iv:Interaction.Triggers>
           <ia:DataTrigger Binding=IsMarkedToDelete" Value="True"  >
              <ia:ChangePropertyAction PropertyName="Visibility" >
                <ia:ChangePropertyAction.Value>
                   <Visibility>Collapsed</Visibility>
                </ia:ChangePropertyAction.Value>
              </ia:ChangePropertyAction>
           </ia:DataTrigger>
         </iv:Interaction.Triggers>
       </Style>
     </sdk:DataGrid.RowStyle>
  <datagrid:DataGrid.Columns>
   // Some columns are here
  </datagrid:DataGrid.Columns>
</datagrid:DataGrid>

What I cannot get working is Binding should it be relative?
Thanks for any help!

A: Your Binding must contain the keyword "Binding".
<ia:DataTrigger Binding="{Binding Path=IsMarkedToDelete}" Value="True">


text:
Q: Terminal printing results at another location? Everyone. I am a beginner programmer, and I can't seem to find this information anywhere on the web, so I am hoping you guys can help. My problem is that sometimes when I try to print a result the terminal spits back something like "" or "", rather than the result. I am actually following very short, very simple lines of code straight out of a book and still getting these results.
Here are some examples to better show what is happening.
In the first example, "potato" is just the file handle name of a random text document.
import nltk
def diversity(potato):
    return len(potato) / len(set(potato))
print diversity(potato)
#prints <function diversity at 0x107b5a848>">

or
import nltk
print bigrams(['make', 'me', 'some', 'bigrams'])
#prints <generator object bigram at 0x1088a4d20>

However in the examples in the text book just show the correct results printing. If it is at all important to know, I am specifically working with the book "Natural Language Processing with Python" by Bird, Klein, and Loper, and I am running Python 2.7.9.
Can anyone explain what is happening and how I can get around this? These are very simple lines of code with very simple answers, so the fact that my terminal seemingly refuses to print the correct answers is irritating and worrisome. Thank you!

A: The second example is very easy to explain.
The return value from the nltk.bigrams function is a generator.
If you want to see the actual values that it returns you need to iterate over it and print its values:
In [11]: for bigram in  nltk.bigrams(['make', 'me', 'some', 'bigrams']):
   ....:     print bigram
   ....:
('make', 'me')
('me', 'some')
('some', 'bigrams')


text:
Q: Google Maps API - GMarker.openInfoWindowHtml() stopped working I have a Google Map that suddenly stopped working for no apparent reason (I hadn't touched the code for months, but the wrapper code from our CMS may have changed without Corporate telling me).
http://www.democratandchronicle.com/section/builder
(sorry about the nasty HTML outside the map, most of that comes from our corporate parent...)
I've narrowed it down to this part of my drawMarker function:
GEvent.addListener(marker, 'click', function() {
  marker.openInfoWindowHtml(html, { maxWidth: 500 });
});

Of note:

*

*alert(html); displays the correct HTML for the infowindow.

*The HTML in the html variable is indeed valid.

*The click event is firing (confirmed by alert('test'); within it)

*Another map I host on the same site works fine, despite similar code.

*No JavaScript errors in Firebug or IE that I can see.

I've been bashing my head against this for a while. What am I missing?

A: I've had random problems with Google Maps API at times and more than once it has been fixed by going back one API version.  i.e. if your google maps API javascript inclusion string is like this http://maps.google.com/maps?file=api&v=2.xd&key=XXXXX
change the 2.x to something a few versions back (back when it was working) like 2.132 or something

A: try:
GEvent.addListener(marker, 'click', function() {
  this.openInfoWindowHtml(html, { maxWidth: 500 });
});

remember the scope of the object "marker" is outside your function

A: I recently had this issue, event handlers definitely ran, etc. Turned out there were two instances of the Google Maps <script> tag on the page. Removing one fixed it.

A: Try forcing JavaScript to make a new variable out of your HTML:
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html+'', { maxWidth: 500 });
});

A: This resolved itself. I suspect an update to the API broke something for a version or two.


text:
Q: C# Sorting ordered dictionary I am working with ordered dictionary (as it is the data structure that gives me functionality to access items by both key and index.)
I am trying to sort it using bubble sort ,
(specially because some legacy code that will be calling this has comparator defined with only one method, How one element is less than the other element.
ILzObjectComparator_Less(ByVal First As Object, _
                                          ByVal Second As Object) As Boolean )
)
While my code kind of works, i.e. it is sorting by value, it is changing key-value mappings.
Here is my method -
    public void SortUsingComparer(LzCollections.ILzObjectComparator Comparator)
    {
        for (int j = 0; j < od.Count; j++)
        {
            for (int i = 0; i < od.Count - 1; i++)
            {
                if(Comparator.Less( od[i+1],od[i]))
                {
                    temp = od[i + 1];
                    od[i + 1] = od[i];
                    od[i] = temp;
                }
            }
        }
    }

There is one similar question , but that used OrderBy which I am not able to map with ILzObjectComparator that our legacy code uses.)
Any help would be highly appreciated.

A: You are referencing not the Elements in the Dictionarybut their Values: od[i]
You could try to use the Elements instead: od.ElementAt(i) but this won't allow you assign anything to it nor can you do an InsertAt().
Note, that I'm not even sure that the order in a Dictionary is guaranteed.
So, I don't think you can do that.
But, of course, there is the OrderedDictionary class.
But since you need to use a custom comparer, I guess you have to switch to another collection class, maybe List<Tuple<>>?
Here is an example
List<Tuple<int, int>> od = new List<Tuple<int,int>>();

After adding a few elements you can sort it, by by either Item:
for (int j = 0; j < od.Count; j++)
{
    for (int i = 0; i < od.Count - 1; i++)
    {
        // insert your custom comparer here:
        if (od.ElementAt(i + 1).Item1 < od.ElementAt(i).Item1)
        {
            var temp0 = od.ElementAt(i);
            var temp1 = od.ElementAt(i + 1);
            od.RemoveAt(i);
            od.RemoveAt(i);
            od.Insert(i, temp1);
            od.Insert(i+1, temp0);
        }
    }
}

Of course a Tuple is less helpful than a Dictionary, uniqueness for example etc..


text:
Q: Crawl webpage which are rendered via JavaScript. PhtantomJs or any other tool? I'm building a tool to crawl a page and store its html locally.
Also load that HTML on a webpage using iframe. So I have unbind and bind events on the crawled page.
I'm using PhantomJS to get the webpage data.
Web pages that render data via JavaScript are not feasible to crawl. Is there any way in PhantomJs to do so ?
Code to get web page data after page has loaded using PhantomJs is :
PHP code to shell execute phantomJs command
$shelldata = exec(PHATOM_JS_PATH."bin/phantomjs ".PHATOM_JS_PATH."/phantomcode.js $WEB_URL > webpage.html 2>&1");

Sample 1
var system = require('system');
var page = require('webpage').create();
var args = system.args;

page.onLoadFinished = function(status) {
//  console.log('Status: ' + status);
    console.log(page.content);
    phantom.exit();
};

if(args.length > 1){
    page.open(args[1], function(status) {
        if(status == "success"){
        }else{
            console.log("Invalid");
            phantom.exit();
        }
    });

}else{
    console.log("Invalid");
    phantom.exit();
}

Sample 2
var system = require('system');
var page = require('webpage').create();
var args = system.args;

if(args.length > 1){
    page.open(args[1], function(status) {
        if(status == "success"){
            setTimeout(function() {
                console.log(page.content);
                phantom.exit();
            }, 200);
        }else{
            console.log("Invalid");
            phantom.exit();
        }
    });
}else{
    console.log("Invalid");
    phantom.exit();
}

A: instead of using SetTimeout with 200ms I think it will be better to inject scrolling down a script to the website  you want to download, that's how you avoid cases of sites using windowing
here is an exmaple made with puppeteer  written in node
const puppeteer = require("puppeteer");
const fs = require("fs");

const injectionPath = "scrollInjection.js";

const writeContent = (content)=>{
  fs.writeFile("./test/pageoutput", content, function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
});
}

const delay = time => {
  return new Promise(function(resolve) {
    setTimeout(resolve, time);
  });
};

let run = async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  //wait for page to fully loaded
  await page.goto(
    "URL TO GO TO"
  );

  //inject scrolling down script
  await page
    .evaluate(fs.readFileSync(injectionPath, "utf8"))
    .catch(err => console.log(err));

  //scroll down for x sec
  await delay("HOW MUCH TIME TO SCROLL DOWN THE PAGE ");

  // get page content
  const html = await page.content();
  writeContent(html)
  await browser.close();
};
run();

injectionFile.js
function myTimer() {
  window.scrollTo(0, document.body.scrollHeight);
}
var scroller = setInterval(function() {
    myTimer();
  }, 1000);


text:
Q: Gradiend transparency on input font when text extends over the input I am facing a problem: I am creating some inputs with different states; one of this states is when the text of the input is longer that the input itself: in this case the text that is hidden at the left of the input should fade out with a gradient transparency:

My code for now is this:

.Input {
    position: relative;
    width: 100%;
    border: none;
    width: 200px;
}

.Input:before {
    content: '';
    position: absolute;
    bottom: 0;
    width: 100%;
    transition: border-bottom 0.5s ease;
    border-bottom: 1px solid gainsboro;
}

.Input input {
    margin-top: 20px;
    height: 40px;
    width: 100%;
    padding-left: 0;
    font-size: 16px;
    font-weight: 300;
    background-color: transparent;
    background-image: linear-gradient(to bottom, gainsboro 50%, tomato 50%);
    background-repeat: no-repeat;
    background-size: 0 11%;
    background-position: 50% 100%;
    transition: all 0.5s ease;
    box-shadow: none;
}

.Input h1 {
    font-size: 16px;
    color: gainsboro;
    font-weight: 400;
    position: absolute;
    pointer-events: none;
    left: 0;
    bottom: 0;
    transition: 0.5s ease all;
    width: 100%;
    line-height: unset;
}

.Input:hover:before {
    transition: border-bottom 0.5s ease;
    border-bottom: 1px solid dimgray;
}

input:focus {
    background-color: transparent;
    background-image: linear-gradient(to bottom, transparent 50%, tomato 50%);
    background-repeat: no-repeat;
    background-size: 100% 11%;
    background-position: 50% 100%;
    transition: all 0.5s ease;
}

input:focus,
input:not(:focus):valid {
    border: none;
    outline: none;
}

input:focus ~ h1, input:not(:focus):valid ~ h1 {
    color: tomato;
    transition: all 0.5s ease;
    transform: translateY(-25px);
}

<input type="text" class="Input" name="testInput" value="" data-id="" required>

MyInput

Any help will be welcome…
Thanks in advance!

A: The idea to check if the text reach a particular length, if yes you show a hidden element.
In the example below I simplified to the test but what you need to do is to calculate the width that the text should take and then compare with the input width. You can check this link for some idea
 Calculating text width

$('.Input input').on('keypress change keyup', function() {
  if ($(this).val().length > 10) {
    $(this).parent().find('.grad').css('opacity', '1');
  } else {
    $(this).parent().find('.grad').css('opacity', '0');
  }
})
$('.Input .grad').click(function() {
  $(this).parent().find('input').focus();
})
.Input {
  position: relative;
  width: 100%;
  border: none;
  width: 200px;
}

.grad {
  position: absolute;
  cursor: text;
  top: 25px;
  bottom: 2px;
  left: 0;
  right: 90%;
  opacity: 0;
  transition: 0.5s;
  z-index: 1;
  background-image: linear-gradient(to right, rgba(255, 255, 255, 0.8), transparent);
}
.Input:before {
  content: '';
  position: absolute;
  bottom: 0;
  width: 100%;
  transition: border-bottom 0.5s ease;
  border-bottom: 1px solid gainsboro;
}

.Input input {
  margin-top: 20px;
  height: 40px;
  width: 100%;
  padding-left: 0;
  font-size: 16px;
  font-weight: 300;
  background-color: transparent;
  background-image: linear-gradient(to bottom, gainsboro 50%, tomato 50%);
  background-repeat: no-repeat;
  background-size: 0 11%;
  background-position: 50% 100%;
  transition: all 0.5s ease;
  box-shadow: none;
}

.Input h1 {
  font-size: 16px;
  color: gainsboro;
  font-weight: 400;
  position: absolute;
  pointer-events: none;
  left: 0;
  bottom: 0;
  transition: 0.5s ease all;
  width: 100%;
  line-height: unset;
}

.Input:hover:before {
  transition: border-bottom 0.5s ease;
  border-bottom: 1px solid dimgray;
}

input:focus {
  background-color: transparent;
  background-image: linear-gradient(to bottom, transparent 50%, tomato 50%);
  background-repeat: no-repeat;
  background-size: 100% 11%;
  background-position: 50% 100%;
  transition: all 0.5s ease;
}

input:focus,
input:not(:focus):valid {
  border: none;
  outline: none;
}

input:focus~h1,
input:not(:focus):valid~h1 {
  color: tomato;
  transition: all 0.5s ease;
  transform: translateY(-25px);
}

  <input type="text" class="Input" name="testInput" value="" data-id="" required>

    MyInput


text:
Q: Convert a String to a Type Constructor in Haskell Does anyone know if there's a function in Haskell which does something like this:
"Int" -> Int

"String" -> String

"Bool" -> Bool

ie. it takes a string representation of a type constructor name, and converts it to the actual type constructor, both in an expression and in a pattern.
edit:
My overall goal is to simplify something like:
transExp (Add exp1 exp2) vars
  = transExp exp1 vars ++ transExp exp2 vars ++ [IAdd]

transExp (Sub exp1 exp2) vars
  = transExp exp1 vars ++ transExp exp2 vars ++ [ISub]

Into a single pattern match, so basically convert Add or Sub to a string, add an "I" to the front, and convert it back to a type.

A: In which context? There is Template Haskell and Data.Typeable, but for an actually helpful answer you need to provide more details.

A: There is a much better way to refactor your code here without any Template Haskell or reflection shenanigans by simply joining your Add and Sub cases into one:
data BinOp = Add | Sub | ...

data Expr = ...
          | BinOp BinOp Expr Expr
          | ...

transExp (BinOp op exp1 exp2) vars
    = transExp exp1 vars ++ transExp exp2 vars ++ [transOp op]
...

transOp Add = IAdd
transOp Sub = ISub

This way, we're using the data type to express directly the fact that binary operators are related, and therefore have similar translations. You can still pattern match on BinOp Add exp1 exp2 if you want to make a special case for addition somewhere.

A: Well, here's the problem.
"String" -> String

That's gibberish in Haskell-land, because "String" is a value but String is a type.  So you might try this:
String -> a

This doesn't do what you want.  You should learn how to read type signatures, because if you can't read type signatures, you're going to be badly handicapped at Haskell.  The above type means, "Give me a string and I can give you a value of any type you request."  There is a function in the prelude with this signature, it is called error, which is not what you want.
It sounds like you want something along these lines:
String -> TypeRep

Sorry, no such function.  TypeRep does not instantiate the Read class.
What are you actually trying to do here?  If you tell us what you are actually trying to do, we can help you with that problem rather than try to help with this problem.

A: You can't do it, because strings are runtime data and types have to be entirely resolved at compile time. The best you can probably do with your example is a helper function to eliminate some of the duplication:
helper exp1 exp2 vars op = transExp exp1 vars ++ transExp exp2 vars ++ [op]
transExp (Add exp1 exp2) vars = helper exp1 exp2 vars IAdd
transExp (Sub exp1 exp2) vars = helper exp1 exp2 vars ISub

But this may not actually be very useful in the long term, depending on how many cases you have.
In general, pattern matching is something that runs against type structures, so it has to be spelled out at compile type against concrete type constructors. This is the price you have to pay for having a really solid static type system.


text:
Q: Python - Module level variables vs Function parameter? def doSomething()
   bucket = s3.get_bucket(BUCKET_NAME)
   ...

if __name__=="__main__":
    s3 = boto.connect_s3()
    doSomething()

vs
def doSomething(s3)
   bucket = s3.get_bucket(BUCKET_NAME)
   ...

if __name__=="__main__":
    s3 = boto.connect_s3()
    doSomething(s3)

Is there a best-practice for this kind of a scenario? This is still a simple scenario. Sometimes there are 4-5 such variables which would need to be used on doSomething, and I've never developed a consistent style for dealing with these.

A: i would go with function parameters as it becomes easier to test the functions with easier mocks.
Also documentation and reuse becomes better


text:
Q: jQuery Animations not Displaying So, I have a td element with attribute onclick='edit(this)'.
Everything in this script works fine, except when I try to execute alerts() when a non space or numerical character is typed, absolutely nothing happens to the  element.
<script>
    function edit(s) {
        if(s.innerHTML != " " && s.innerHTML != "<nobr name=\"clear\"> </nobr>") {
            s.innerHTML = "<input onblur='set(this)' id ='select' type='text' value='"+ s.innerHTML[19] +"'>";
        }
        else{
            s.innerHTML = "<input onblur='set(this)' id ='select'type='text'>";
        }
        document.getElementById('select').focus();
    }
    function set(s) {
        if(s.value == "" || (s.value != "1" && s.value != "2" && s.value != "3" && s.value != "4" && s.value != "5" && s.value != "6" && s.value != "7" && s.value != "8" && s.value != "9")){
            if(s.value != "1" && s.value != "2" && s.value != "3" && s.value != "4" && s.value != "5" && s.value != "6" && s.value != "7" && s.value != "8" && s.value != "9") {
                s.parentNode.innerHTML = "<nobr name='clear' id='alert'>&nbsp</nobr>";
                alerts();
            }
            else {
                s.parentNode.innerHTML = "<nobr name='clear'>&nbsp</nobr>";
            }
        }
        else{
            s.parentNode.innerHTML = "<nobr name='clear'>" + s.value + "</nobr>";
        }
    }
    function clears() {
        var g = window.prompt("Remove all values from sudoku:","1");
        if(g != null) {
            $("#sudoku"+g+" [name='clear']").html("");
        }
    }
    function alerts() {
        $("#alert").parent().animate({backgroundColor: 'red'},"fast");
        $("#alert").parent().animate({backgroundColor: 'white'},"slow",killid());
    }
    function killid() {
        $("#alert").removeAttr("id");
    }
</script>

The id is added and then removed almost instantly after that. The background color does not change.
Ideas?

A: That's because you are calling the function right when you are starting the animation. Remove the parentheses after the function name to let the animate method call it instead:
$("#alert").parent().animate({ backgroundColor: 'white' }, "slow", killid);


text:
Q: best practice to implement a multi step data validation .NET Web MVC 4 Application Which is the best practice to implement a multi step data validation in a .NET Web MVC 4 Application?
Step 1
<input type="email" name="email"/>

In the controller I check with a RegExp the validity of the email and redirect to step 2
Step 2
<input type="hidden" name="email"/>
<input type="password" name="pwd"/>
<input type="password" name="confirmpwd"/>

In the controller I check the validity of the passwords and create an user
If someone change the email in the input hidden can register an account with a not valid email.
So I can Save the email in the Session?
Or should I encrypt with a 2 way encription the email and pass it to the form as hidden?
Revalidate the email? And in the case of big number of data?
Which is the best practice?

A: Strictly from a best practice perspective you cannot rely on use input, which includes hidden form fields. You could store the email in session, however this has implications if the server crashes, or if the server is on a farm? I would suggest storing the email in a transactional DB so it can later be retrieved.
As far as validation you should use the regex data annotation on your view model for email and if you have minimum requirements for password strength. You can also use data annotation to validate the confirm password matches the password. Finally check Model.IsValid on your controller for the best results.


text:
Q: How to simplify a class without writing methods that are already simple? I have a complex class and I want to simplify it by implementing a facade class (assume I have no control on complex class). My problem is that complex class has many methods and I will just simplify some of them and rest of the will stay as they are. What I mean by "simplify" is explained below.
I want to find a way that if a method is implemented with facade then call it, if not then call the method in complex class. The reason I want this is to write less code :) [less is more]
Example:
Facade facade = // initialize
facade.simplified(); // defined in Facade class so call it

// not defined in Facade but exists in the complex class
// so call the one in the complex class
facade.alreadySimple();

The options that comes to mind mind are:
Option 1: Write a class holding a variable of complex class and implement complex ones then implement simple ones with direct delegation:
class Facade {
    private PowerfulButComplexClass realWorker = // initialize
    public void simplified() {
         // do stuff
    }
    public void alreadySimple() {
         realWorker.alreadySimple();
    }
    // more stuff
}

But with this approach I will need to implement all the simple methods with just a single delegation statement. So I need to write more code (it is simple though)
Option 2: Extend the complex class and implement simplified methods but then both simple and complex versions of these methods will be visible.
In python I can achieve similar behaviour like this:
class PowerfulButComplexClass(object):
    def alreadySimple(self):
        # really simple

    # some very complex methods

class Facade(object):
    def __init__(self):
        self.realworker = PowerfulButComplexClass()
    def simplified(self):
        # simplified version of complex methods in PowerfulButComplexClass

    def __getattribute__(self, key):
    """For rest of the PowerfulButComplexClass' methods use them as they are
    because they are simple enough.
    """
        try:
            # return simplified version if we did
            attr = object.__getattribute__(self, key)
        except AttributeError:
            # return PowerfulButComplexClass' version because it is already simple
            attr = object.__getattribute__(self.data, key)
        return attr

obj = Facace()
obj.simplified() # call the one we have defined
obj.alreadySimple( # call the one defined in PowerfulButComplexClass

So what is the Java way to achieve this?
Edit: What I mean by "simplify": A complex method can be either a method with too many arguments
void complex method(arg1, arg2, ..., argn) // n is sufficiently large

or a set of related methods that will almost always called together to achieve a single task
outArg1 = someMethod(arg1, arg2);
outArg2 = someOtherMethod(outArg1, arg3);
actualResult = someAnotherMethod(outArg2);

so we want to have something like this:
String simplified(arg1, arg2, arg3) {
    outArg1 = someMethod(arg1, arg2);
    outArg2 = someOtherMethod(outArg1, arg3);
    return someAnotherMethod(outArg2);
}

A: It's called Inheritence. Consider the following code:
class Complex {
    public function complex() { /* Complex Function */ }
    public function simple() { /* Already simple function */ }
}

class SimplifiedComplex extends Complex {
    public function complex() { /* Simplify Here */ }
}

The simple() method will work on a SimplifiedComplex object.

A: I think you've already called it. I would go with Option 1. It provides the most flexibility given the rigidity of java.
I prefer it because it favors composition over inheritance. Although this creates more code, I find designs like this generally are easier to modify in the long run.
Inheritance should only be used to model strict "is a" relationships where the subclass necessarily has all the properties and behaviors of the base class. If you're using inheritance for anything else your asking for trouble.
Finally, I don't buy into the idea of "Less Is More"(Insert incredibly concise, indecipherable perl example here). I buy into the principle of "Code should be as simple as it needs to be and no simpler".

A: Depending on your use case, you might want to create a facade in front of some of the functionality in complex class by delegating (Option 1), and instead of providing support for the rest of the functionality in complex class, you provide means to access complex class directly (getComplexClass).
This might make the design clearer. Consider, for example, a complex class handling most of the features of a bank system. Creating a class named "Account" that has access to the complex class but only uses the methods relevant for a bank account helps the design. For convenience, the Account class could have a method getBankSystemForAccount or something similar.

A: This is ugly in Java, but you can write a function that takes the name of the method you want to call, and a parameter list, and use reflection to find the appropriate method to call. This will be conceptually similar to how you'd do it in Python, except much uglier.


text:
Q: custom useMediaQuery hook does not appear to work on a phone I am trying to write a custom useMediaQuery hook so I can use this to do things conditionally based on screen size in a react app. The hook I have written appears to be working in my browser, but I did a netlify build and it does not work correctly when I pull it up on my phone. Does anyone see any issues? Thinking this may have something to do with certain functions being used being unsupported by different browsers. I tried safari and chrome on my Iphone and both did not work.
Here is my useMediaQuery hook:
import { useEffect, useState } from "react";

// credit for this hook came from this website: https://usehooks-ts.com/react-hook/use-media-query
// I modified it a bit to remove some deprecated methods not supported by all browsers

export const useMediaQuery = (query) => {
  //returns true/false if window matches our query, if window is undefined returns false
  const getMatches = (query) => {
    // Prevents SSR issues
    if (typeof window !== "undefined") {
      return window.matchMedia(query).matches;
    }
    return false;
  };

  // piece of state telling whether or not our query matches window
  const [matches, setMatches] = useState(getMatches(query));

  // sets our state based on our query, runs initially and with the change event listener
  const handleChange = () => {
    setMatches(getMatches(query));
  }

  useEffect(() => {
    // Triggered at the first client-side load and if query changes
    handleChange();

    window.addEventListener('resize', handleChange);
    // eslint-disable-next-line
  }, [query]);

  return matches;
};

Here is my App.js demo where I output certain text based on a media query:
import './App.css';
import { useMediaQuery } from './hooks/useMediaQuery';

const renderDeviceSizeText = (isTabletOrSmaller, isPhoneScreen) => {
  if(isTabletOrSmaller === false) {
    return
Desktop

  } else if (isTabletOrSmaller === true && isPhoneScreen === false){
    return
Tablet

  } else {
    return
Mobile

  }
}

function App() {

  const isTabletOrSmaller = useMediaQuery('(max-width: 768px');
  const isPhoneScreen = useMediaQuery('(max-width: 480px)');

  return (

      {
        renderDeviceSizeText(isTabletOrSmaller, isPhoneScreen)
      }

  );
}

export default App;

Here is the url for the netlify app I deployed using this react app: https://venerable-dieffenbachia-2cfd8b.netlify.app/


text:
Q: binding and unbinding jquery live functions I'm going to try and explain this the best I can...
I have one page that calls to certain js file with multiple live functions.
JS File #1
$("#1").live("click.1",function() { }
$("#2").live("click.2",function() { }
$("#3").live("click.2",function() { }

JS File #2
$("#4").live("click.3",function() { }
$("#5").live("click.4",function() { }
$("#6").live("click.5",function() { }

Depending on the id I click, It is supposed to activate one js file while inactivating the other js file's functions. The problem I am having is... How do I unbind or die() all js functions from the previous click so when I toggle back it won't cycle through the js more than once? I need to do this on a scalable level rather than unbinding each one individually. Thanks

A: Ideally you should be using on() (http://api.jquery.com/on/) as live() is deprecated. You should update your jQuery src file to the most recent version. You can unbind within each function by doing:
$(this).unbind();

If you are loading this content via ajax then unbind will work but if you are reloading the page then the events will rebind when the DOM is recreated.


text:
Q: How can I find size of the file before POST-ing the data? I just realized that one can only POST about 8 MB of data. I have a form to upload multiple files. This files are sent to a php page through POST method where it gets uploaded. Now, I want to check the size of data which will be posted and give an alert message. How can I do that?  I googled a bit and found that $_SERVER['CONTENT_LENGTH'] can be used to find this. Unfortunately, I can't figure out how to use it?
Here's my form:
<form name="offer" onsubmit="return validateForm()" action="fileupload.php" method="post" enctype="multipart/form-data">

        I9:
         Doc: <input type="file" id="myfile" name="myfile[]">

       Client document:
        Doc: <input type="file" id="myfile" name="myfile[]">

         FCRA :
          Doc: <input type="file" id="myfile" name="myfile[]">

        Insurance Certificate :
         Doc: <input type="file" id="myfile" name="myfile[]">

         Work Order :
          Doc: <input type="file" id="myfile" name="myfile[]">

Also, is it possible to display the size of each uploaded file? I know this can be done by javascript. But how?

A: use this for client side
function findSize() {
    var fileInput =  document.getElementById("_ufile_1");
    try{
        alert(fileInput.files[0].size); // Size returned in bytes.
    }catch(e){
        var objFSO = new ActiveXObject("Scripting.FileSystemObject");
        var e = objFSO.getFile( fileInput.value);
        var fileSize = e.size;
        alert(fileSize);
    }
}


text:
Q: How does the CMB constrain the baryon asymmetry? The CMB contains information about baryon acoustic oscillations in which baryons (I assume protons and electrons) and photons form a plasma exhibiting sound waves. How is information about the baryon asymmetry of the universe contain in this?
Why do we not get some combination of baryon and (charged) lepton asymmetries if there are both electrons and protons in the mix?
Why does the dependence not go as their density but rather the asymmetry?

A: Here is a description:

The acoustic oscillations arise because of a conflict in the photon–baryon plasma in the early universe. The pressure of the photons tends to erase anisotropies, whereas the gravitational attraction of the baryons, moving at speeds much slower than light, makes them tend to collapse to form overdensities. These two effects compete to create acoustic oscillations, which give the microwave background its characteristic peak structure. The peaks correspond, roughly, to resonances in which the photons decouple when a particular mode is at its peak amplitude.

You ask:

How is information about the baryon asymmetry of the universe contain in this?

Please note the correction to the previous version of the answer, as I found a paper where the acoustic oscillations of the CMB are used in order to estimate the baryon asymmetry.
They have a phenomenological model of how more matter and  antimatter annihilation  gamma rays would affect the acoustic oscillations  at photon decoupling to give the CMB

at 380.000 years after the Big Bang, where it says transparency point for light, where the photons of the CMB have their last scatter before reaching our detectors.
These oscillations depend on the density of matter previous to the CMB , according to their model, the existence of an asymmetry can be found from the oscillations. Baryon antibaryon's annihilating would affect by the gamma rays generated the final photon spectrum at photon decoupling time.
The subject is still at a research state.


text:
Q: How to use gohook to bind right and other buttons? package main

import (
    "fmt"

    hook "github.com/robotn/gohook"
)

func main() {

    // out: alt-q
    hook.Register(hook.KeyDown, []string{"alt", "q"}, func(e hook.Event) {
        fmt.Println("alt-q")
    })

    // out: no output
    hook.Register(hook.KeyDown, []string{"up"}, func(e hook.Event) {
        fmt.Println("up")
    })

    // out: no output
    hook.Register(hook.KeyHold, []string{"left"}, func(e hook.Event) {
        fmt.Println("left")
    })

    // out: no output
    hook.Register(hook.KeyUp, []string{"down"}, func(e hook.Event) {
        fmt.Println("down")
    })

    s := hook.Start()
    <-hook.Process(s)
}

I didn't find the relevant instructions, how to use it?
=================================================
I'm sure there is nothing wrong with the keyboard, the following code prints out the keys normally
hook.Register(hook.KeyUp, []string{}, func(e hook.Event) {
    fmt.Println(e)
})

Thank you for your attention.


text:
Q: License Agreement finish button is disabled in Android Studio The license Agreement finish button is disabled in Android Studio.I cannot accept the License

How can I accept the license?

A: You should click on the accept button for each of the three categories of licensing, then the finish button will be enabled.


text:
Q: How to read the dynamic objects data present in JSON? I am obtaining a JSON from another application. I would like to parse that JSON and read the data present in them. The JSON contains some of the user-defined data which are dynamic and the key/value pair can be dynamic so I am a bit confused about how to read these dynamic data and do further processing.
Following is the sample JSON that I would like to process:
{
  "context": [
    {
      "one": "https://example.one.com"
    },
    {
      "two": "https://example.two.com"
    },
    {
      "three": "https://example.three.com"
    }
  ],
  "name": "Batman",
  "age": "30",
  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"
}

I am able to read some of the static/well-defined data directly such as name & age but I am not understanding how to read some of the user-defined/dynamic data from this JSON as it does not have a definite key/value or there is no guarantee that it will appear in the order after the age property.
I am trying to find a way to read/obtain all the user-defined data from this JSON:
  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"

Is there a direct way to achieve this or use some library? I am developing the application using Vuejs/Nuxtjs.

A: I think that's not the best api you are using, you should have constant object parameters that you always know how to find things. If you want to find not known parameters you can parse JSON to object and loop throug it.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

A: You can simply achieve that by iterating over Object.keys().
Demo :

const jsonData = {
  "context": [
    {
      "one": "https://example.one.com"
    },
    {
      "two": "https://example.two.com"
    },
    {
      "three": "https://example.three.com"
    }
  ],
  "name": "Batman",
  "age": "30",
  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"
};

Object.keys(jsonData).forEach(key => {
    if (typeof jsonData[key] === 'object') {
    Object.keys(jsonData[key]).forEach(innerObjKey => {
        console.log(innerObjKey, jsonData[key][innerObjKey])
    })
  } else {
     console.log(key, jsonData[key])
  }
})

A: Combining Object.keys with a recursive function, even if you have multiple nested objects, it will work without having to refactor your code everytime!
const jsonData = {
    context: [
        {
            one: "https://example.one.com",
        },
        {
            two: "https://example.two.com",
        },
        {
            three: "https://example.three.com",
        },
    ],
    name: "Batman",
    age: "30",
    "one:myField": {
        "two:myField2": "Hello",
        "one_nested:myField": {
            another_nested_key: "another_nested_value",
        },
    },
    "three:myField3": "Hello2",
};

recursive(jsonData);

function recursive(nestedKey) {
    if (typeof nestedKey !== "object") return;

    Object.keys(nestedKey).forEach((key) => {
        if (typeof nestedKey[key] === "object") {
            recursive(nestedKey[key]);
        } else {
            console.log(key, nestedKey[key]);

            // add your conditions here

            if (key === "name") {
                // bla bla bla
            }
        }
    });
}


text:
Q: How to pull an array from POST request with-in Django I am trying to extract an Array from a POST request using Django.

def settlements_orders(request):

    database = "####"
    if request.method == 'POST':
        first_date = request.POST.get('first_date', False)
        last_date = request.POST.get('last_date', False)
        brands = request.POST.getlist('brands[]')
    else:
        first_date = '2020-01-01'
        last_date = '2020-05-13'
        brands= ['ICON-APPAREL']

    settlements_orders = SettlementOrders.objects.using(database)\
        .filter(posted_date__date__range=[first_date, last_date]) \
        .filter(sku__brand__in=brands) \
        .select_related('sku').select_related('posted_date') \
        .values('sku__company','sku__brand','sku__department','sku__category','sku__sub_category',
                'sku__parent_asin','sku__asin','sku__vendor', 'sku__color','sku__size','sku__case_pack',
                'posted_date__year', 'posted_date__month'
                )\
        .annotate(count=Count('order_id'),
                  qty_sold=Sum('quantity_sold'),
                  qty_returned=Sum('quantity_returned'),
                  order_revenue=Sum('order_revenue'),
                  refund_revenue=Sum('refund_revenue'),
                  promotion=Sum('promotion'),
                  giftwrap_collected=Sum('giftwrap_collected'),
                  giftwrap_paid=Sum('giftwrap_paid'),
                  shipping_fees_collected=Sum('shipping_fees_collected'),
                  shipping_fees_paid=Sum('shipping_fees_paid'),
                  sales_tax_collected=Sum('sales_tax_collected'),
                  sales_tax_paid=Sum('sales_tax_paid'),
                  shipping_tax_collected=Sum('shipping_tax_collected'),
                  shipping_tax_paid=Sum('shipping_tax_paid'),
                  fulfillment_fees=Sum('fulfillment_fees'),
                  comission_fees=Sum('comission_fees'),
                  closing_fees=Sum('closing_fees'),
                  other_fees=Sum('other_fees'),
                  restock_fees=Sum('restock_fees'),
                  goodwill_paid=Sum('goodwill_paid'),
                  goodwill_reimbursed=Sum('goodwill_reimbursed'),
                  return_fees=Sum('return_fees'),
                  reimbursements=Sum('reimbursements'),
                  margin=Sum('margin')
                  )
    return JsonResponse(settlements_orders[::1], safe=False)

I am using the Array to filter data When I make a GET request I am returned data but on a POST request, I get a 500 response. Any help would be appreciated.


text:
Q: How to make Google Link Chart Dynamic I' am stuck trying to figure out how to make the Google Line Chart dynamic. The error am getting on the console:

Uncaught Error: Not an array

   function pensionDawChart( DataPoints ){
        console.log( [$.trim(DataPoints)] );
        var data = google.visualization.arrayToDataTable( $.trim(DataPoints) );
        var options = {
            title: 'Pension',
            curveType: 'function',
            legend: { position: 'bottom' }
        };
        var chart = new google.visualization.LineChart(document.getElementById('pension-calculator-chartContainer'));
        chart.draw(data, options);
    }

//Plot the chart
function pension_chart(){
    var ageAtRetirement  = 29;
    var GeneralDataPoints, inflatedClosing, DataPoints;
    years = $('#retirement-inputs #years-to-retirement').val();
    DataPoints = [];
    for (year = 1; year <= years; year++){
        inflatedClosing = parseInt($('#lookup-table-preserved #row-' + year + ' .inflated-closing').text());
        GaInflatedClosing = parseInt($('#lookup-table-preserved #row-' + year + ' .ga-inflated-closing').text());
        DataPoints.push([year, inflatedClosing, GaInflatedClosing] + ',');
    }
    google.charts.setOnLoadCallback( pensionDawChart(DataPoints) );
}

Console Log
This the dump on the DataPoints
["1,10994,5248,,2,13988,6498,,3,16983,7747,,4,19977,…,,27,88848,37911,,28,91842,39174,,29,94837,40437,"]0: "1,10994,5248,,2,13988,6498,,3,16983,7747,,4,19977,8996,,5,22971,10247,,6,25966,11499,,7,28961,12752,,8,31956,14005,,9,34950,15258,,10,37944,16512,,11,40939,17767,,12,43933,19022,,13,46928,20277,,14,49922,21534,,15,52916,22791,,16,55910,24048,,17,58905,25306,,18,61899,26564....

A: this is working code, I have used websocket html5 update the graph
$scope.drawGraph= function() {

            var i = 0;
            var data = new google.visualization.DataTable();
            var chart = new google.visualization.LineChart(document
                    .getElementById('container3'));

            data.addColumn('datetime', 'Date');
            data.addColumn('number', 'dataaa');
            data.addColumn({
                type : 'string',
                role : 'tooltip'
            });
            data.addColumn({
                label : 'Style',
                type : 'string',
                role : 'style'
            });

    //You can add timer event here
        webSocket.onmessage = function(event) {
                var point = JSON.parse(event.data);
                if (point.length > 1) {
                    $scope.Contribution = point;
                }

                var currentDate = new Date();
                var dateValue = parseInt(currentDate.getTime());
                var year = new Date(dateValue).getFullYear();
                var month = (new Date(dateValue).getMonth());
                var day = new Date(dateValue).getDate();
                var hours = new Date(dateValue).getHours();
                var minutes = new Date(dateValue).getMinutes();
                var seconds = new Date(dateValue).getSeconds();

                    data.addRow([
                            new Date(year, month, day, hours, minutes,
                                    seconds), (parseFloat(point.anomaly)),
                            (parseFloat(point.anomaly)).toString(),
                            'color: #5E92FF;stroke-color: #FF0000',
                            parseFloat(point.predictive) ]);

                var options = {
                    title : "title",
                    titlePosition : 'left',
                    width : '70%',
                    height : '30%',
                    titleTextStyle : {
                        color : 'white'
                    },
                    legend : {
                        'position' : 'right',
                        textStyle : {
                            color : 'white'
                        }

                    },
                    curveType : 'function',
                    backgroundColor : {
                        fill : 'transparent'
                    },
                    'chartArea' : {
                        'width' : '75%',
                        'height' : '65%',
                        'left' : '10%'
                    },
                    colors : [ '#0080FF', 'gold' ],

                    tooltip : {
                        isHtml : true
                    },
                    vAxis : {
                        textStyle : {
                            color : 'white'
                        }

                    },
                    is3D : true,

                    hAxis : {
                        textStyle : {
                            color : 'white'
                        },
                        format : 'hh:mm:ss',
                        viewWindow : {
                            min : new Date(year, month, day, hours,
                                    minutes, seconds - 100),
                            max : new Date(year, month, day, hours,
                                    minutes, seconds)
                        }
                    },

                }
                chart.draw(data, options);

        }

A: To achieve expected result, split data in string using DataPoints[0].split
DataPoints[0].split(",")


text:
Q: prepare for segue is not letting me set NSString of next viewController I want to set an NSString from viewController A to viewController B. I tried using the code below but it's not working.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"segueSubCat"])
    {
        NSIndexPath *indexPath = [tableViewCat indexPathForSelectedRow];

        ViewControllerSubCat *subCatVC = [segue destinationViewController];
        subCatVC.cellNameCat = [categories objectAtIndex:indexPath.row];
        subCatVC.navigationItem.title = subCatVC.cellNameCat;
    }
}

I tried that, and the app crashed every time I went to the second view. So I replaced it with the following code:
wat = @"wat";
[[segue destinationViewController] setContentsName:wat];

And it did the same thing. i.e. it crashed.
I'm not sure what I'm doing wrong.
Note: When I take away the code inside prepareForSegue, then it works.
Error Message
2014-12-18 15:36:16.382 myApp[1503:42438] -[UINavigationController setCellNameCat:]: unrecognized selector sent to instance 0x7fb9714e7240
2014-12-18 15:36:16.388 myApp[1503:42438] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UINavigationController setCellNameCat:]: unrecognized selector sent to instance 0x7fb9714e7240'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010094cf35 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x00000001005e5bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x000000010095404d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x00000001008ac27c ___forwarding___ + 988
    4   CoreFoundation                      0x00000001008abe18 _CF_forwarding_prep_0 + 120
    5   myApp        0x00000001000b3887 -[ViewController prepareForSegue:sender:] + 343
    6   UIKit                               0x000000010128b71c -[UIStoryboardSegueTemplate _perform:] + 151
    7   UIKit                               0x0000000100e21360 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1242
    8   UIKit                               0x0000000100e214d4 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219
    9   UIKit                               0x0000000100d5c331 _applyBlockToCFArrayCopiedToStack + 314
    10  UIKit                               0x0000000100d5c1ab _afterCACommitHandler + 516
    11  CoreFoundation                      0x0000000100881dc7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    12  CoreFoundation                      0x0000000100881d20 __CFRunLoopDoObservers + 368
    13  CoreFoundation                      0x0000000100877b53 __CFRunLoopRun + 1123
    14  CoreFoundation                      0x0000000100877486 CFRunLoopRunSpecific + 470
    15  GraphicsServices                    0x0000000103f1b9f0 GSEventRunModal + 161
    16  UIKit                               0x0000000100d39420 UIApplicationMain + 1282
    17  myApp        0x00000001000b4523 main + 115
    18  libdyld.dylib                       0x0000000102edc145 start + 1
    19  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

A: First check whether you assigned the UIViewController class as ViewControllerSubCat in storyboard.
EDIT:
From your crash log it's clear that you are getting a UINavigationController as the result of [segue destinationViewController];. So change the code like:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"segueSubCat"])
    {
        NSIndexPath *indexPath = [tableViewCat indexPathForSelectedRow];
        UINavigationController *navController = [segue destinationViewController];
        ViewControllerSubCat *subCatVC = (ViewControllerSubCat *)navController.topViewController;
        subCatVC.cellNameCat = [categories objectAtIndex:indexPath.row];
        subCatVC.navigationItem.title = subCatVC.cellNameCat;
    }
}

A: As the other posters have said, the destination view controller is not your custom class. It sounds like you've got that sorted out.
Another problem you're likely to face:
At the time prepareForSegue is called, the destination VC's view hierarchy hasn't been loaded yet.
This line:
subCatVC.navigationItem.title = subCatVC.cellNameCat;

probably won't work, because I doubt if your new VCs navigationItem has been loaded yet.
Disclaimer: I've actually never tried to manipulate a destination view controller's navigationItem in a prepareForSegue method, so I don't know for sure if it will be defined, but I strongly suspect not. To test this, log the value of subCatVC.navigationIte in prepareForSegue (once you sort out getting a pointer to the correct VC)


text:
Q: Bonus integration problem we got at class: Integrate $\frac {x \sin x}{1+\cos^2x}$ between $0$ and $\pi$ Bonus integration problem we got at class: Integrate $\frac {x \sin x}{1+\cos^2x}$ between $0$ and $\pi$
So the lecturer gave this problem. I tried this really hard but couldn't succeed. It doesn't give me any bonus points at class, he just gave it as a nice challenge and it got me quite frustrated.
Any help will be great!
Thank you.

A: $$
\begin{align}
&\int_0^\pi\frac{x\sin(x)\,\mathrm{d}x}{1+\cos^2(x)}\tag{1}\\
&=\int_0^\pi\frac{(\pi-x)\sin(x)\,\mathrm{d}x}{1+\cos^2(x)}\tag{2}\\
&=\frac\pi2\int_0^\pi\frac{\sin(x)\,\mathrm{d}x}{1+\cos^2(x)}\tag{3}\\
&=\frac\pi2\left[-\arctan(\cos(x))\vphantom{\int}\right]_0^\pi\tag{4}\\[3pt]
&=\frac\pi2\left[\frac\pi4+\frac\pi4\right]\tag{5}\\[3pt]
&=\frac{\pi^2}4\tag{6}
\end{align}
$$
Explanation:
$(2)$: substitute $x\mapsto\pi-x$
$(3)$: average $(1)$ and $(2)$
$(4)$: substitute $u=\cos(x)$; apply arctan integral; undo substitution
$(5)$: evaluate
$(6)$: simplify


text:
Q: Помогите с написанием LINQ запроса Суть такова: есть папки в которых есть файлы, после манипуляций с ними путь к этим файлам записывается в БД (т.е в дальнейшем мне с ними никак взаимодействовать не надо). Мне надо проверить, есть ли уже в БД файлы, которые есть в конкретной директории. Я пытался вот так:
var except = concreteDirFiles.Except(allDbFiles);

concreteDirFiles - файлы из какой-то конкретной директории, а не из всех нужных (т.к может быть вложенность в директориях, а действия над файлами надо производить в соответствии с фильтром по дате и времени)
У меня стоит System.Timers.Timer и проверяет все папки на наличие новых файлов, в результате для папки mydir1 я получу массив string[2], однако, если эти файлы уже есть в БД (допустим БД вернет мне массив string[5]), то код выше просто исключит их текущего контекста LINQ и вернет мне файлы из БД (с удаленным вхождением string[2], получается, что код Except возвращает мне string[3]), которые потом другой код будет обрабатывать и так до бесконечности будет исключать вхождение, но возвращать по сути уже обработанные файлы.
Как правильно написать LINQ, чтобы пропускать уже существующие в бд файлы?
Используется EF Core 5.0.10.

A: Если ваш "директор" ставит задачу слежения за файлами, дабы знать когда какой файл изменился, чтобы определить источник изменения - есть такая штука в Windows, как аудит:
ПКМ на диск/папку/файл -> свойства -> безопасность -> дополнительно -> аудит -> изменить -> добавить -> Пишите "Все" -> ОК -> можете проставить все галочки (хотя хватит и трансфер/создание/удаление) -> И снова ОК -> ОК .. ОК
Потом глобально включаете аудит:
В cmd команда "secpol" -> локальные политики -> политика аудита -> аудит доступа к объектам -> ставите галочки (или только одну на успех) -> применить
Запускаете журнал событий:
В cmd eventvwr -> журналы windows -> безопасность -> создать настраиваемое представление -> выставляете параметры:
Журналы событий - безопасность
Источники - Microsoft Windows security auditing.
Ключевые слова - Аудит отказа, Аудит успеха
Если компьютер в домене или есть доступ - можно указать сетевой
 адрес компьютера на котором находятся файлы и выполняется аудит.

Сохраняете настраиваемое представление с новым именем - всё, теперь сама ОС следит за изменениями конкретных объектов без всяких сканирований сторонним софтом.
Единственное условие - всё это настраивать нужно на том компьютере - где физически находятся файлы, а смотреть уже можно с любого компа (в настраиваемом представлении указать адрес компа, с ходу может не получиться, т.к. безопасность винды, домены, рабочие группы, учётные записи, итд...).
Чтобы убрать отслеживание, так-же через свойства объекта: ПКМ -> свойства -> безопасность -> дополнительно -> аудит -> изменить -> удаляете правило.
https://docs.microsoft.com/ru-ru/microsoft-365/compliance/export-view-audit-log-records?view=o365-worldwide
В статье описано как экспортировать данный журнал и открыть его в Excel. Можно написать батник и засунуть в планировщик чтобы он запускал экспорт и писал файл в отдельную папку, из которой уже читать всё это какой-нибудь утилитой, может даже вашей самописной, в принципе хоть в БД напрямую экспортируй, MSSQL точно такое поддерживает, главное чтобы таблица была, многие другие БД тоже на такое способны.
Если не нужно писать в БД (его роль уже будет играть журнал винды), то в .NET уже есть System.Diagnostics.EventLog, им и можете читать. Прибиндить вывод к формам или wpf за пару кликов - труда не составит.
В итоге хочу сказать: если это нужно для внутренних нужд организации, то лучше использовать уже готовые инструменты, любезно предоставленные самими мелкомягкими, конкретно для данной задачи, данный метод точно работает в Windows 7 - сам пользуюсь, должен работать начиная с Windows server 2003, и может уже и был в Windows XP или ещё раньше, т.к. вопрос информационной безопасности стоял уже очень давно в зарубежных компаниях. Поэтому зачем изобретать велосипед, когда можно настроить уже существующий вылизанный инструмент, которому лет 20. Единственный вопрос: как удобно показать эти данные (binding: forms-datagridview / wpf, да хоть в браузере), если нужно не только в журналах - export в БД через xml или System.Diagnostics.EventLog с реалтайм докидыванием записей в БД, а если приложение было остановлено - дополнительная таблица с последних записанным моментом времени чтобы читать историю System.Diagnostics.EventLog при запуске и фильтровать её. Это лучше чем долбаться с файлами и папками и жарить мозги в попытках продумать алгоритм чтобы узнать что изменилось когда программа была выключена.


text:
Q: Unable to center table in CSS... (Internet explorer) Centering and alignments works just fine on IE and Firefox. I haven't done HTML/CSS for quite some time, so I am unsure as to what I am doing wrong. I have already searched around and no table centering has worked for me.
fiddle: http://jsfiddle.net/y6n7ufL9/

    /* different things I tried to get to work */
    #table {
      display: table;
      text-align: center;
      margin-left: auto;
      margin-right: auto;
      table-layout: auto;
    }

    body {
      background-color: #ececec;
    }
    #navborderline {
      width: 50%;
      margin: auto;
      margin-top: 5px;
      height: 2px;
      background-color: black;
    }
    #navborder ul {
      text-align: center;
    }
    #navborder ul li {
      list-style-type: none;
      display: inline;
      margin-left: 5%;
      margin-right: 5%;
    }
    #navborder a {
      text-decoration: none;
      color: black;
      font-size: 18px;
      border-bottom: 1px solid transparent;
      -webkit-transition: all .3s ease-in-out;
      -moz-transition: all .3s ease-in-out;
      -o-transition: all .3s ease-in-out;
      transition: all .3s ease-in-out;
    }
    #navborder a:hover {
      border-bottom: 1px solid red;
    }
    #navborder {
      margin-top: 10px;
    }
    #table {
      width: 60%;
      margin: auto;
      margin-top: 5px;
      text-align: center;
    }
    #table td,
    tr {
      border: 1px solid black;
      width: 50%;
    }

  <title>Travis' Portfolio</title>
  <link rel="stylesheet" type="text/css" href="css/css.css" />

  <link rel="stylesheet" type="text/css" href="css/reset.css" />

Home

Assignments

Contact

Random

          Ello

        Hello
        hello v2

        Hello
        hello v2


text:
Q: Cross compiling libwebsockets with cmake I am trying to cross-compile libwebsockets with cmake, but I am getting the below errors:
root@ubuntu-Latitude-E5450:/home/ubuntu/Downloads/libwebsockets/build# cmake .. -DCMAKE_INSTALL_PREFIX_PATH=/home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/bin/arm-oe-linux-gnueabi/ -DCMAKE_LIBRARY_PATH=/home/ubuntu/toolchain/sysroots/aarch64-oe-linux/usr/lib/ -DCMAKE_SYSROOT=/ubuntu/home/das_toolchain/sysroots/aarch64-oe-linux/ -DCMAKE_TOOLCHAIN_FILE=../cross-arm-oe-linux-gnueabi.cmake -DLWS_WITHOUT_EXTENSIONS=1 -DLWS_WITH_SSL=0 -DLWS_WITH_ZIP_FOPS=0 -DLWS_WITH_ZLIB=0
-- The C compiler identification is GNU 4.9.3
-- Check for working C compiler: /home/ubuntu/das_toolchain/sysroots/x86_64-oesdk-linux/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-gcc
-- Check for working C compiler: /home/ubuntu/das_toolchain/sysroots/x86_64-oesdk-linux/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-gcc -- broken
CMake Error at /usr/local/share/cmake-3.8/Modules/CMakeTestCCompiler.cmake:51 (message):
  The C compiler
  "/home/ubuntu/das_toolchain/sysroots/x86_64-oesdk-linux/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-gcc"
  is not able to compile a simple test program.

  It fails with the following output:

   Change Dir: /home/ubuntu/Downloads/libwebsockets/build/CMakeFiles/CMakeTmp

  Run Build Command:"/usr/bin/make" "cmTC_515b7/fast"

  /usr/bin/make -f CMakeFiles/cmTC_515b7.dir/build.make
  CMakeFiles/cmTC_515b7.dir/build

  make[1]: Entering directory
  `/home/ubuntu/Downloads/libwebsockets/build/CMakeFiles/CMakeTmp'

  Building C object CMakeFiles/cmTC_515b7.dir/testCCompiler.c.o

/home/ubuntu/das_toolchain/sysroots/x86_64-oesdk-linux/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-gcc
  --sysroot=/ubuntu/home/das_toolchain/sysroots/aarch64-oe-linux/ -o
  CMakeFiles/cmTC_515b7.dir/testCCompiler.c.o -c
  /home/ubuntu/Downloads/libwebsockets/build/CMakeFiles/CMakeTmp/testCCompiler.c

  Linking C executable cmTC_515b7

  /usr/local/bin/cmake -E cmake_link_script
  CMakeFiles/cmTC_515b7.dir/link.txt --verbose=1

  /home/ubuntu/das_toolchain/sysroots/x86_64-oesdk-linux/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-gcc
  --sysroot=/ubuntu/home/das_toolchain/sysroots/aarch64-oe-linux/ -rdynamic
  CMakeFiles/cmTC_515b7.dir/testCCompiler.c.o -o cmTC_515b7

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot open crt1.o: No such file or directory

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot open crti.o: No such file or directory

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot open crtbegin.o: No such file or directory

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot open crtend.o: No such file or directory

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot open crtn.o: No such file or directory

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot find -lgcc

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot find -lgcc_s

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot find -lc

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot find -lgcc

  /home/ubuntu/toolchain/sysroots/x86_64-oesdk-linux/usr/libexec/arm-oe-linux-gnueabi/gcc/arm-oe-linux-gnueabi/4.9.3/real-ld:
  error: cannot find -lgcc_s

  collect2: error: ld returned 1 exit status

  make[1]: *** [cmTC_515b7] Error 1

  make[1]: Leaving directory
  `/home/ubuntu/Downloads/libwebsockets/build/CMakeFiles/CMakeTmp'

  make: *** [cmTC_515b7/fast] Error 2

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:146 (project)

-- Configuring incomplete, errors occurred!
See also "/home/ubuntu/Downloads/libwebsockets/build/CMakeFiles/CMakeOutput.log".
See also "/home/ubuntu/Downloads/libwebsockets/build/CMakeFiles/CMakeError.log".

I have specified the CMAKE_SYSROOT in the toolchain file and also specified the same in my command line while building. Where am I going wrong with this?
Your help would be appreciated.
Below is my toolchain file:
#
# CMake Toolchain file for crosscompiling on ARM.
#
# This can be used when running cmake in the following way:
#  cd build/
#  cmake .. -DCMAKE_TOOLCHAIN_FILE=../cross-arm-oe-linux-gnueabi.cmake
#

set(CROSS_COMPILER_PATH /home/ubuntu/das_toolchain/sysroots/x86_64-oesdk-linux/usr/bin/arm-oe-linux-gnueabi/)
set(CROSS_PATH /ubuntu/home/das_toolchain/sysroots/aarch64-oe-linux/)
set(TOOLCHAIN_PREFIX arm-oe-linux-gnueabi-)
#set(SYSROOT --sysroot=/ubuntu/home/das_toolchain/sysroots/aarch64-oe-linux/)
set(CMAKE_SYSROOT /ubuntu/home/das_toolchain/sysroots/aarch64-oe-linux/)

# Target operating system name.
#set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_NAME Arm)

# Name of C compiler.
#set(CMAKE_C_COMPILER "${CROSS_PATH}/bin/arm-linux-gnueabihf-gcc")
#set(CMAKE_CXX_COMPILER "${CROSS_PATH}/bin/arm-linux-gnueabihf-g++")
#set(CMAKE_C_COMPILER "${CROSS_PATH}${TOOLCHAIN_PREFIX}gcc ${SYSROOT}")
#set(CMAKE_CXX_COMPILER "${CROSS_PATH}${TOOLCHAIN_PREFIX}g++ ${SYSROOT}")
set(CMAKE_C_COMPILER "${CROSS_COMPILER_PATH}${TOOLCHAIN_PREFIX}gcc")
set(CMAKE_CXX_COMPILER "${CROSS_COMPILER_PATH}${TOOLCHAIN_PREFIX}g++")
#set(CMAKE_C_FLAGS ${SYSROOT})
#set(CMAKE_CXX_FLAGS ${SYSROOT})

# Where to look for the target environment. (More paths can be added here)
set(CMAKE_FIND_ROOT_PATH "${CROSS_PATH}")

# Adjust the default behavior of the FIND_XXX() commands:
# search programs in the host environment only.
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)

# Search headers and libraries in the target environment only.
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

A: In my experience, using CMAKE_SYSROOT can cause issues like this sometimes since it passes the --sysroot flag to the compiler, which can confuse it.  To tell CMake where to find libraries, without affecting the actual compiler options, just set CMAKE_PREFIX_PATH instead of CMAKE_SYSROOT.


text:
Q: C# UpdateModel with custom data instead of FormCollection For reference this is in a C# MVC2 website.
I'm looking to save a data using a Model in my database, but I need to do it with custom data rather than the FormCollection I am used to.  Here is how I typically do it:
TryUpdateModel(userToUpdate, new string[] { "ID", "Name", "Age", "Gender" }, form.ToValueProvider());

// Model Validation is here, no need to see it so removed to save space

if (ModelState.IsValid)
{
     dbu.SaveChanges();
}

How do I go about replacing the form.ToValueProvider() with custom data?  How should it be created/formatted?

A: You can create your own source by creating a NameValueCollection with your values, then using that to create a FormCollection, and then you can use that form collection as the value provider directly.
Also, FormCollection has an Add method, where you can just add values directly.
var values = new NameValueCollection { { "ID", "1" }, {"Name": "Bob"} }; // etc.
var collection = new FormCollection(values);

// or...
// var collection = new FormCollection();
// collection.Add("ID", "1");
// collection.Add("Name", "Bob");
// etc.

TryUpdateModel(userToUpdate, new string[] { "ID", "Name", "Age", "Gender" }, form);

If you are binding a flat model (say, User in this example), the above sample will be enough. However, if your fields have a prefix (this might be the case if you are doing a deep model binding), separate the prefix with a dot:
var collection = new FormCollection();
collection.Add("User.ID", "1");
collection.Add("User.Name", "Bob");

// Binds to fields with the prefix "User"
TryUpdateModel(userToUpdate, "User", new string[] { "ID", "Name", "Age", "Gender" }, null, form);

A: you can use updateModel() provided by asp.net mvc to get all model values  from formcollection key value pair and map to your database model provided your formcollection key matches the model parameters i.e
public ActionResult CreateUser(FormCollection fc)
 {

    UserModel usermodel= new UserModel ();

    if(TryUpdateModel(usermodel,fc.ToValueProvider()))

        UpdateModel(usermodel, fc.ToValueProvider());

  return View("UserView");
}


text:
Q: Openquery where clause using multiple like I'm trying to run an Openquery with multiple Where clause NOT LIKE but is giving me the error

"Error: MALFORMED_QUERY, ERROR at Row:15:Column:16 unexpected token:
  like".

What I'm trying to run is something like this
SELECT  *   from openquery(Server, 'Select Id
        , BodyLength
        , ContentType
        , CreatedById
        , CreatedDate
        , Description
        , IsPrivate
        , LastModifiedById
        , LastModifiedDate
        , Name
        , OwnerId
        , ParentId
        from Attachment
        where LastModifiedDate > 2018-11-16T00:00:00Z
        and (Name NOT like (''SML -%'') and
        Name NOT like (''EARLY -%'') and
        Name NOT like (''DELAYED -%'') and
        Name NOT like (''CLOSED -%'') and
        Name NOT like (''CLOSURE -%'') and
        Name NOT like (''OUTAGE -%'') and
        Name NOT like (''MISC -%'') and
        Name NOT like (''TIME AS A CONTROL%'') and
        Name NOT like (''TEMPORARY -%''))
        order by Id
        LIMIT 10000') x

What I want is to exclude all the records that by Name starting like that.
It runs smoothly when not excluded by name, but I really need it. Any ideas?

A: Probably the issue is your date constant, not like.  It needs delimiters:
where LastModifiedDate > ''2018-11-16T00:00:00Z'' and
      (Name NOT like ''SML -%'' and
       Name NOT like (''EARLY -%'') and
       . . .
      )


text:
Q: what dependencies to add for HTTP in gradle file android; ByteArrayBody, HttpMultipartMode, StringBody does not resolve I have added the following in gradle file
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"
    useLibrary  'org.apache.http.legacy'
    useLibrary  'org.apache.http.entity.mime.content'

    defaultConfig {
        applicationId "com.example.swuljcityconductor"
        minSdkVersion 24
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

Also I have added the following to Manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

I want to send image files over HTTP POst.
Anything else should I do?
The keywords
ByteArrayBody, HttpMultipartMode, StringBody does not resolve.
What else should I add?

A: Retrofit is best one for http in android, have some  caching and more features, u can read in https://square.github.io/retrofit/ and https://github.com/square/retrofit


text:
Q: Pass-by-Reference Error I have a hook system setup... which is working on localhost... I put it live and get an error saying "Warning: Call-time pass-by-reference has been deprecated".
Now, apparently the work around is to remove all "&" from your function calls, ie foo(&$me) to foo($me) and then in foo's function definition do "function foo(&$me)".
However, I can not do this... because my hooks accept an array as arguments, I need a work around for this. Like I can use "run_hooks ( 'hook-name', $me );" or "run_hooks ( 'hook-name', array ( $me, $another_var, etc... ) )";
So this means I can not use "function run_hooks ( $hook_name, &$arguments )" because I'll get an error in php saying it can not pass "array()" as reference...
Any ideas an a work around?
Thanks.

A: I guess you want to use a reference in order to prevent unnecessary copies of data. But that's not what you should use them for (in php5). Simply pass the array.
function foo($x /* not a reference */) {
  echo $x['bar'], "\n";
}
$p = array('bar'=>12345);
foo($p);
// or
foo( array('bar'=>12345) );

This invokes no deep copy of the array that is passed as parameter - as long as you don't change the array. This mechanism is called copy-on-write and the php implementation is explained in http://www.research.ibm.com/trl/people/mich/pub/200901_popl2009phpsem.pdf

A: Pass an array of references around - this array itself doesn't need to be a reference:
 function foo($args) {
    modify $args[0]...
    modify $args[1]...
 }

 $someVar = ...
 $anotherVar = ...

 foo(array(&$someVar, &$anotherVar));

A: I think I found a viable workaround, no errors, and it does work without modifying anything in my classes... could help anyone else... ArrayObject solved it, seince objects are already 'referenced'.
function test ( $var, $foo )
{
    $var    = 3;
    $foo    = 3;
}

$var    = 1;
$foo    = 1;
call_user_func_array ( 'test', new ArrayObject ( array ( &$var, &$foo ) ) );

print $foo;
print $var;

// Output is 3 3 like expected :)


text:
Q: Twitch API - can't get auth token using PHP Hello stackoverflow members.
I'm not a person who likes to ask for a help but in this case it's IMO the only way to solve my problem. Google didn't help me much.
So. My problem:
I want to get some data using Twitch API. Sounds easy? I wish it was. Below I'm posting my actual code (it's small but it was modified various of times and now it look like...):
$user = json_decode(file_get_contents('https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=MY_CORRECT_CLIENT_ID&redirect_uri=http://localhost/php/twitch.php&scope=user_read'), true);
print_r($user); // returns nothing

$token = $user['access_token'];
print_r($token); // same as above

$ch = curl_init();

// some stupid curls
curl_setopt($ch, CURLOPT_URL, 'https://api.twitch.tv/kraken/streams/followed');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Authorization: OAuth '.$token );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$retval = curl_exec($ch);

curl_close($ch);

$result = json_decode($retval, true);

It returns... Nothing. So I used ready solution from discussions.twitch. (I wish I could write the name of the author of this code but I'm too tired to search it again. Either way thanks!):
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
    'client_id' => 'blablabla_correct',
    'client_secret' => 'blablabla_also_correct',
    'grant_type' => 'authorization_code',
    'redirect_uri' => 'http://localhost/php/twitch.php',
    'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
$response = json_decode($data, true);
//var_dump($response);
$access_token = $response["access_token"];
echo $access_token;

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $returnobj = curl_exec($ch);
    curl_close($ch);
    return $returnobj;
}

$testobj = json_decode(get_data("https://api.twitch.tv/kraken/user?oauth_token=".$access_token."&client_id=".$fields['client_id']));
echo "
Data: ";

print_r($testobj);

This code above is a bit better. Only a bit. It returns Error 401. Why? Because it can't get auth token. Well, it's something but not what I wanted to get. What should I do now? Maybe it's fault of localhost address?
FAQ(?):
Yes, I'm using correct data from my Twitch application settings page.
Yes, I'm confused

A: You're making two calls to the Twitch API, and you need to debug them independently.
For now, just skip the second call.  Focus on the one where you grab your access token.
Try this:
// to start, just use the code you've already got:
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
    'client_id' => 'blablabla_correct',
    'client_secret' => 'blablabla_also_correct',
    'grant_type' => 'authorization_code',
    'redirect_uri' => 'http://localhost/php/twitch.php',
    'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);

// Now, here we believe the first error comes into play, so let's check it out
print_r($data); // confirm that this is not what we want
$info = curl_getinfo($ch); // let's get some details about that last request
// print it out and see what we get
echo '
';
print_r($info);
echo '
';

... that should give you a starting point to figure out what's going on.  If you see an auth token, then you're not accessing it in the right way.  If you don't, the info will give you some information about why.
I don't know what redirect_uri is (can you link to docs that explain it?) so I can't know if the localhost reference is a problem there.


text:
Q: Canvas reference I want to add a canvas to my application which I should be able to paint on. Sadly, I already fail at adding the reference. The MSDN page says the reference is System.Windows.Controls but I only can add the System.Windows.Controls.Ribbon reference.
How do I find the reference and am I even looking for the correct thing?

A: The Canvas class is in the PresentationFramework assembly.
You can find such information on MSDN.
Find the class you are looking for, in this case System.Windows.Controls.Canvas (just type this in Google). Then you will find this page:

Namespace:   System.Windows.Controls
Assembly:  PresentationFramework (in PresentationFramework.dll)

So you need to add a reference to the assembly PresentationFramework in your project, and create a using System.Windows.Controls in your code file.

A: you can right click on your "references" and click "Add Reference...".
from Window that opens for you, click on "Assemblies => Framework => PresentationFramework " and add it to your project.
Maybe Helps You.


text:
Q: Why do we prefer the Schauder basis over the Hamel basis in functional analysis? Our functional analysis instructor mentioned in the class that the Hamel basis is not so important in the context of Banach spaces. Instead, we prefer the Schauder basis. However, he did not specify the reason why it is so. I tried to think about it myself, but could not find a satisfactory answer. Can someone illustrate why the Hamel basis is not important in the context of Banach spaces, and what motivated mathematicians to work with the Schauder basis?

A: Some common Banach spaces such as $\ell^p$ for $p \in [1,+\infty\rangle$ and $c_0$, the space of all sequences converging to $0$, have a simple Schauder basis consisting of canonical vectors $(e_n)_{n=1}^\infty$.
On the other hand, their algebraic dimension is equal to $c$, so a Hamel basis is necessarily uncountable and hence more complicated. Not to mention that we cannot even provide an explicit example of a Hamel basis for these spaces as its existence relies on the axiom of choice.

A: A Schauder basis captures the topology of a Banach space (or other topological vector space). It's that topology that makes the space useful and interesting.
A Hamel basis captures only the algebraic properties.
From wikipedia

In mathematics, a Schauder basis or countable basis is similar to the
usual (Hamel) basis of a vector space; the difference is that Hamel
bases use linear combinations that are finite sums, while for Schauder
bases they may be infinite sums. This makes Schauder bases more
suitable for the analysis of infinite-dimensional topological vector
spaces including Banach spaces.


text:
Q: How do I parse a long number string to just a number? I have some Ids I need converted from strong to numbers however whenever I use parseInt() or Number(), I get a double type decimal
1.01038295007818e+016.0

I need to just convert the string to just a number.

A: The maximum integer that can be represented in javascript, without losing any precision, is 9007199254740991. See the javascript docs for more info. If you want to use integers bigger than that, you will need to use a third party library like Big Integer.

A: There are 5 different ways to convert string to number as below:
parseInt(num); // default way (no radix)
parseInt(num, 10); // parseInt with radix (decimal)
parseFloat(num) // floating point
Number(num); // Number constructor
~~num //bitwise not
num / 1 // diving by one
num * 1 // multiplying by one
num - 0 // minus 0
+num // unary operator "+"
You will find thye explanation Here
for
var s = parseInt("101038295007818e0160",10);
alert(s);

O/P: 101038295007818e0160 .
and for:
 var s = parseInt(101038295007818e0160,10);
alert(s);

O/P:1
for
 var s = parseInt("101038295007818e0160");
alert(s);

O/P: 101038295007818e0160 .
and for:
 var s = parseInt(101038295007818e0160);
alert(s);

O/P:1
Hope it will help you.

A: The parseInt() function takes the first number of the string and removes decimal places, it returns an integer:

var a = parseInt("1.000350001");
var b = parseInt("456789.1");
var c = parseInt("20");

console.log(a);
console.log(b);
console.log(c);

The Math.floor() method rounds a number downward to its nearest integer:

var d = Math.floor("1234.00101");

console.log(d);

The Number() function converts the string to a number that represents the strings value:

var e = Number("1000.12");

console.log(e);

For your question, I believe either parseInt or Math.floor would work just fine, unless your number is greater than JavaScripts largest available number

A: What you're getting is scientific notation, because the number you've tried to parse it too big.
The largest integer accurately represented in Javascript is
9007199254740991

However your number 1.01038295007818e+016.0 is
10103829500781800


text:
Q: Developing environment sync Is there any way to sync the code between two systems like cloud services(Google docs/Sky drive) in Eclipse/Android Studio IDE's ? Is there any plugin for eclipse to do this ? or Any other IDE which supports this ?
while searching i got something like this

A: Your question is a bit unclear. If you want to sync code between different machines asyncronously then you only need to use a version control system.
If you want to edit the exact same document in eclipse with multiple people, then all answers are in Is there an Eclipse plugin for collaborative editing?.
Cloud9 is just for coding in the browser and storing the project in the cloud. You probably don't want that.


text:
Q: Trying to add a point to a SRSS 2005 chart I have created a line chart using Reporting Services that charts the number of accidents per month.  That works great.
The problem is that now I need to add a marker to the chart that indicates when new safety procedures were put in place.  This will just be a single date that is in a separate table.  Ideally, it would show up as a line on the date axis showing the date the the new procedures were implemented.  Is there a way to do this?
Edit: I may have oversimplified this.  There is a chart like this for each of our locations, so the conversion date will be different for each.  Therefore, I can't just add it in as a value.

A: Add a new value element to your chart. Set it's value expression to the date/value that you want. This will create a horizontal line.
edit: Then create a formula / modify your query to get the desired value. The process shouldn't change.